forked from lightninglabs/pool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpcserver.go
2946 lines (2510 loc) · 88.9 KB
/
rpcserver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package pool
import (
"bytes"
"context"
"encoding/hex"
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"github.com/davecgh/go-spew/spew"
"github.com/lightninglabs/lndclient"
"github.com/lightninglabs/pool/account"
"github.com/lightninglabs/pool/auctioneer"
"github.com/lightninglabs/pool/auctioneerrpc"
"github.com/lightninglabs/pool/chaninfo"
"github.com/lightninglabs/pool/clientdb"
"github.com/lightninglabs/pool/event"
"github.com/lightninglabs/pool/funding"
"github.com/lightninglabs/pool/order"
"github.com/lightninglabs/pool/poolrpc"
"github.com/lightninglabs/pool/poolscript"
"github.com/lightninglabs/pool/sidecar"
"github.com/lightninglabs/pool/terms"
"github.com/lightningnetwork/lnd/chanbackup"
lndFunding "github.com/lightningnetwork/lnd/funding"
"github.com/lightningnetwork/lnd/input"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/lnwallet/chainfee"
"github.com/lightningnetwork/lnd/lnwire"
)
const (
// getInfoTimeout is the maximum time we allow for the initial getInfo
// call to the connected lnd node.
getInfoTimeout = 5 * time.Second
)
// rpcServer implements the gRPC server on the client side and answers RPC calls
// from an end user client program like the command line interface.
type rpcServer struct {
started uint32 // To be used atomically.
stopped uint32 // To be used atomically.
// bestHeight is the best known height of the main chain. This MUST be
// used atomically.
bestHeight uint32
// Required by the grpc-gateway/v2 library for forward compatibility.
// Must be after the atomically used variables to not break struct
// alignment.
poolrpc.UnimplementedTraderServer
server *Server
lndServices *lndclient.LndServices
lndClient lnrpc.LightningClient
auctioneer *auctioneer.Client
accountManager account.Manager
orderManager order.Manager
marshaler Marshaler
quit chan struct{}
wg sync.WaitGroup
blockNtfnCancel func()
recoveryMutex sync.Mutex
recoveryPending bool
// wumboSupported is true if the backing lnd node supports wumbo
// channels.
wumboSupported bool
}
// accountStore is a clientdb.DB wrapper to implement the account.Store
// interface.
type accountStore struct {
*clientdb.DB
}
var _ account.Store = (*accountStore)(nil)
func (s *accountStore) PendingBatch() error {
_, err := s.DB.PendingBatchSnapshot()
return err
}
// newRPCServer creates a new client-side RPC server that uses the given
// connection to the trader's lnd node and the auction server. A client side
// database is created in `serverDir` if it does not yet exist.
func newRPCServer(server *Server) *rpcServer {
accountStore := &accountStore{server.db}
lndServices := &server.lndServices.LndServices
return &rpcServer{
server: server,
lndServices: lndServices,
lndClient: server.lndClient,
auctioneer: server.AuctioneerClient,
accountManager: account.NewManager(&account.ManagerConfig{
Store: accountStore,
Auctioneer: server.AuctioneerClient,
Wallet: lndServices.WalletKit,
Signer: lndServices.Signer,
ChainNotifier: lndServices.ChainNotifier,
TxSource: lndServices.Client,
TxFeeEstimator: lndServices.Client,
TxLabelPrefix: server.cfg.TxLabelPrefix,
}),
orderManager: order.NewManager(&order.ManagerConfig{
Store: server.db,
AcctStore: accountStore,
Lightning: lndServices.Client,
Wallet: lndServices.WalletKit,
Signer: lndServices.Signer,
}),
marshaler: NewMarshaler(&marshalerConfig{
GetOrders: server.db.GetOrders,
Terms: server.AuctioneerClient.Terms,
}),
quit: make(chan struct{}),
}
}
// Start starts the rpcServer, making it ready to accept incoming requests.
func (s *rpcServer) Start() error {
if !atomic.CompareAndSwapUint32(&s.started, 0, 1) {
return nil
}
rpcLog.Infof("Starting trader server")
ctx := context.Background()
lndCtx, lndCancel := context.WithTimeout(ctx, getInfoTimeout)
defer lndCancel()
info, err := s.lndClient.GetInfo(lndCtx, &lnrpc.GetInfoRequest{})
if err != nil {
return fmt.Errorf("error in GetInfo: %v", err)
}
_, s.wumboSupported = info.Features[uint32(lnwire.WumboChannelsRequired)]
if !s.wumboSupported {
_, s.wumboSupported = info.Features[uint32(lnwire.WumboChannelsOptional)]
}
rpcLog.Infof("Connected to lnd node %v with pubkey %v", info.Alias,
info.IdentityPubkey)
var blockCtx context.Context
blockCtx, s.blockNtfnCancel = context.WithCancel(ctx)
chainNotifier := s.lndServices.ChainNotifier
blockChan, blockErrChan, err := chainNotifier.RegisterBlockEpochNtfn(
blockCtx,
)
if err != nil {
return err
}
var height int32
select {
case height = <-blockChan:
case err := <-blockErrChan:
return fmt.Errorf("unable to receive first block "+
"notification: %v", err)
case <-ctx.Done():
return nil
}
s.updateHeight(height)
// Start the auctioneer client first to establish a connection.
if err := s.auctioneer.Start(); err != nil {
return fmt.Errorf("unable to start auctioneer client: %v", err)
}
// Start managers.
if err := s.accountManager.Start(); err != nil {
return fmt.Errorf("unable to start account manager: %v", err)
}
if err := s.orderManager.Start(); err != nil {
return fmt.Errorf("unable to start order manager: %v", err)
}
if err := s.server.fundingManager.Start(); err != nil {
return fmt.Errorf("unable to start funding manager: %v", err)
}
if err := s.server.sidecarAcceptor.Start(blockErrChan); err != nil {
return fmt.Errorf("unable to start sidecar acceptor: %v", err)
}
s.wg.Add(1)
go s.serverHandler(blockChan, blockErrChan)
rpcLog.Infof("Trader server is now active")
return nil
}
// Stop stops the server.
func (s *rpcServer) Stop() error {
if !atomic.CompareAndSwapUint32(&s.stopped, 0, 1) {
return nil
}
var returnErr error
rpcLog.Info("Trader server stopping")
if err := s.server.sidecarAcceptor.Stop(); err != nil {
rpcLog.Errorf("Error stopping sidecar acceptor: %v", err)
returnErr = err
}
if err := s.server.fundingManager.Stop(); err != nil {
rpcLog.Errorf("Error stopping funding manager: %v", err)
}
s.accountManager.Stop()
s.orderManager.Stop()
if err := s.auctioneer.Stop(); err != nil {
rpcLog.Errorf("Error closing server stream: %v", err)
}
close(s.quit)
s.wg.Wait()
s.blockNtfnCancel()
rpcLog.Info("Stopped trader server")
return returnErr
}
// serverHandler is the main event loop of the server.
func (s *rpcServer) serverHandler(blockChan chan int32, blockErrChan chan error) {
defer s.wg.Done()
for {
select {
case msg := <-s.auctioneer.FromServerChan:
// An empty message means the client is shutting down.
if msg == nil {
continue
}
rpcLog.Debugf("Received message from the server: %v", msg)
err := s.handleServerMessage(msg)
// Only shut down if this was a terminal error, and not
// a batch reject (should rarely happen, but it's
// possible).
if err != nil && !errors.Is(err, order.ErrMismatchErr) {
rpcLog.Errorf("Error handling server message: %v",
err)
interceptor.RequestShutdown()
}
case err := <-s.auctioneer.StreamErrChan:
// If the server is shutting down, then the client has
// already scheduled a restart. We only need to handle
// other errors here.
if err != nil && err != auctioneer.ErrServerShutdown {
rpcLog.Errorf("Error in server stream: %v", err)
err := s.auctioneer.HandleServerShutdown(err)
if err != nil {
rpcLog.Errorf("Error closing stream: %v",
err)
}
}
rpcLog.Error("Unknown server error: %v", err)
case height := <-blockChan:
rpcLog.Infof("Received new block notification: height=%v",
height)
s.updateHeight(height)
case err := <-blockErrChan:
if err != nil {
rpcLog.Errorf("Unable to receive block "+
"notification: %v", err)
interceptor.RequestShutdown()
}
// In case the server is shutting down.
case <-s.quit:
return
}
}
}
func (s *rpcServer) updateHeight(height int32) {
// Store height atomically so the incoming request handler can access it
// without locking.
atomic.StoreUint32(&s.bestHeight, uint32(height))
}
// handleServerMessage reads a gRPC message received in the stream from the
// auctioneer server and passes it to the correct manager.
func (s *rpcServer) handleServerMessage(
rpcMsg *auctioneerrpc.ServerAuctionMessage) error {
switch msg := rpcMsg.Msg.(type) {
// A new batch has been assembled with some of our orders.
case *auctioneerrpc.ServerAuctionMessage_Prepare:
// Parse and formally validate what we got from the server.
rpcLog.Tracef("Received prepare msg from server, batch_id=%x: %v",
msg.Prepare.BatchId, spew.Sdump(msg))
batch, err := order.ParseRPCBatch(msg.Prepare)
if err != nil {
// If we aren't able to parse the batch for some
// reason, then we'll send a reject message.
log.Error("unable to parse batch: %v", err)
return s.sendRejectBatch(batch, err)
}
rpcLog.Infof("Received PrepareMsg for batch=%x, num_orders=%v",
batch.ID[:], len(batch.MatchedOrders))
// Let's store an event for each order in the batch that we did
// receive a prepare message.
if err := s.server.db.StoreBatchEvents(
batch, order.MatchStatePrepare,
poolrpc.MatchRejectReason_NONE,
); err != nil {
rpcLog.Errorf("Unable to store order events: %v", err)
}
// The prepare message can be sent over and over again if the
// batch needs adjustment. Clear all previous shims and channels
// that will never complete because the funding TX they refer to
// will never be published.
if s.orderManager.HasPendingBatch() {
pendingBatch := s.orderManager.PendingBatch()
err = s.server.fundingManager.RemovePendingBatchArtifacts(
pendingBatch.MatchedOrders, pendingBatch.BatchTX,
)
if err != nil {
// The above method only returns hard errors
// that justify us rejecting the batch.
rpcLog.Errorf("Error clearing previous batch "+
"artifacts: %v", err)
return s.sendRejectBatch(batch, err)
}
// Clear our staging area for the new batch proposal. We
// consider any errors as a hard failure and reject the
// batch.
err = s.server.fundingManager.DeletePendingBatch()
if err != nil {
rpcLog.Errorf("Error clearing previous "+
"pending batch: %v", err)
return s.sendRejectBatch(batch, err)
}
}
// Do an in-depth verification of the batch.
bestHeight := atomic.LoadUint32(&s.bestHeight)
err = s.orderManager.OrderMatchValidate(batch, bestHeight)
if err != nil {
// We can't accept the batch, something went wrong.
rpcLog.Errorf("Error validating batch: %v", err)
return s.sendRejectBatch(batch, err)
}
// Before we accept the batch, we'll finish preparations on our
// end which include applying any order match predicates,
// connecting out to peers, and registering funding shim.
err = s.server.fundingManager.PrepChannelFunding(
batch, s.server.db.GetOrder,
)
if err != nil {
rpcLog.Warnf("Error preparing channel funding: %v",
err)
return s.sendRejectBatch(batch, err)
}
// Accept the match now.
err = s.sendAcceptBatch(batch)
if err != nil {
rpcLog.Errorf("Error sending accept msg: %v", err)
return s.sendRejectBatch(batch, err)
}
case *auctioneerrpc.ServerAuctionMessage_Sign:
// We were able to accept the batch. Inform the auctioneer,
// then start negotiating with the remote peers. We'll sign
// once all channel partners have responded.
batch := s.orderManager.PendingBatch()
channelKeys, err := s.server.fundingManager.BatchChannelSetup(
batch,
)
if err != nil {
rpcLog.Errorf("Error setting up channels: %v", err)
return s.sendRejectBatch(batch, err)
}
rpcLog.Infof("Received OrderMatchSignBegin for batch=%x, "+
"num_orders=%v", batch.ID[:], len(batch.MatchedOrders))
// Sign for the accounts in the batch.
sigs, err := s.orderManager.BatchSign()
if err != nil {
rpcLog.Errorf("Error signing batch: %v", err)
return s.sendRejectBatch(batch, err)
}
err = s.sendSignBatch(batch, sigs, channelKeys)
if err != nil {
rpcLog.Errorf("Error sending sign msg: %v", err)
return s.sendRejectBatch(batch, err)
}
// The previously prepared batch has been executed and we can finalize
// it by opening the channel and persisting the account and order diffs.
case *auctioneerrpc.ServerAuctionMessage_Finalize:
rpcLog.Tracef("Received finalize msg from server, batch_id=%x: %v",
msg.Finalize.BatchId, spew.Sdump(msg))
rpcLog.Infof("Received FinalizeMsg for batch=%x",
msg.Finalize.BatchId)
// Before finalizing the batch, we want to know what accounts
// were involved so we can start watching them again. Query the
// pending batch now as BatchFinalize below will set it to nil.
batch := s.orderManager.PendingBatch()
var batchID order.BatchID
copy(batchID[:], msg.Finalize.BatchId)
err := s.orderManager.BatchFinalize(batchID)
if err != nil {
return fmt.Errorf("error finalizing batch: %v", err)
}
// We've successfully processed the finalize message, let's
// store an event for this for all orders that were involved on
// our side.
if err := s.server.db.StoreBatchEvents(
batch, order.MatchStateFinalized,
poolrpc.MatchRejectReason_NONE,
); err != nil {
rpcLog.Errorf("Unable to store order events: %v", err)
}
// If we were the provider for any sidecar channels, we want to
// update our own state of the tickets to complete now.
for ourOrderNonce := range batch.MatchedOrders {
if err := s.setTicketStateForOrder(
sidecar.StateCompleted, ourOrderNonce,
); err != nil {
rpcLog.Errorf("Unable to update our sidecar "+
"ticket after completing batch: %v",
err)
}
}
// Accounts that were updated in the batch need to start new
// confirmation watchers, now that we expect a batch TX to be
// published.
matchedAccounts := make(
[]*btcec.PublicKey, len(batch.AccountDiffs),
)
for idx, acct := range batch.AccountDiffs {
matchedAccounts[idx] = acct.AccountKey
}
return s.accountManager.WatchMatchedAccounts(
context.Background(), matchedAccounts,
)
default:
return fmt.Errorf("unknown server message: %v", msg)
}
return nil
}
func (s *rpcServer) QuoteAccount(ctx context.Context,
req *poolrpc.QuoteAccountRequest) (*poolrpc.QuoteAccountResponse, error) {
// Determine the desired transaction fee.
confTarget := req.GetConfTarget()
if confTarget < 1 {
return nil, fmt.Errorf("confirmation target must be " +
"greater than 0")
}
feeRate, totalFee, err := s.accountManager.QuoteAccount(
ctx, btcutil.Amount(req.AccountValue), confTarget,
)
if err != nil {
return nil, err
}
return &poolrpc.QuoteAccountResponse{
MinerFeeRateSatPerKw: uint64(feeRate),
MinerFeeTotal: uint64(totalFee),
}, nil
}
func (s *rpcServer) InitAccount(ctx context.Context,
req *poolrpc.InitAccountRequest) (*poolrpc.Account, error) {
bestHeight := atomic.LoadUint32(&s.bestHeight)
// Determine the desired expiration value, can be relative or absolute.
var expiryHeight uint32
switch {
case req.GetAbsoluteHeight() != 0 && req.GetRelativeHeight() != 0:
return nil, fmt.Errorf("you must set only one of the relative " +
"and absolute height parameters")
case req.GetAbsoluteHeight() != 0:
expiryHeight = req.GetAbsoluteHeight()
case req.GetRelativeHeight() != 0:
expiryHeight = req.GetRelativeHeight() + bestHeight
default:
return nil, fmt.Errorf("either relative or absolute height " +
"must be specified")
}
var feeRate chainfee.SatPerKWeight
switch {
case req.GetFeeRateSatPerKw() > 0 && req.GetConfTarget() > 0:
return nil, fmt.Errorf("you must set only one of the sats/kw " +
"and confirmation target parameters")
case req.GetFeeRateSatPerKw() > 0:
feeRate = chainfee.SatPerKWeight(req.GetFeeRateSatPerKw())
case req.GetConfTarget() > 0:
// Determine the desired transaction fee.
value := btcutil.Amount(req.AccountValue)
confTarget := req.GetConfTarget()
var err error
feeRate, _, err = s.accountManager.QuoteAccount(
ctx, value, confTarget,
)
if err != nil {
return nil, fmt.Errorf("unable to estimate on-chain fees: "+
"%v", err)
}
// If the fee estimation ever returns a value too small
// we set it to a valid minimum
if feeRate < chainfee.FeePerKwFloor {
feeRate = chainfee.FeePerKwFloor
}
log.Infof("Estimated total chain fee of %v for new account with "+
"value=%v, conf_target=%v", feeRate, value, confTarget)
default:
return nil, fmt.Errorf("either sats/kw or confirmation target " +
"must be specified")
}
if feeRate < chainfee.FeePerKwFloor {
return nil, fmt.Errorf("fee rate of %d sat/kw is too low, "+
"minimum is %d sat/kw", feeRate, chainfee.FeePerKwFloor)
}
acct, err := s.accountManager.InitAccount(
ContextWithInitiator(ctx, req.Initiator),
btcutil.Amount(req.AccountValue), feeRate,
expiryHeight, bestHeight,
)
if err != nil {
return nil, err
}
return MarshallAccount(acct)
}
func (s *rpcServer) ListAccounts(ctx context.Context,
req *poolrpc.ListAccountsRequest) (*poolrpc.ListAccountsResponse, error) {
accounts, err := s.server.db.Accounts()
if err != nil {
return nil, err
}
validAccounts := make([]*account.Account, 0, len(accounts))
for _, acct := range accounts {
// Filter out inactive accounts if requested by the user.
if req.ActiveOnly && !acct.State.IsActive() {
continue
}
validAccounts = append(validAccounts, acct)
}
rpcAccounts, err := s.marshaler.MarshallAccountsWithAvailableBalance(
ctx, validAccounts,
)
if err != nil {
return nil, fmt.Errorf("unable to list marshalled accounts: "+
"%v", err)
}
return &poolrpc.ListAccountsResponse{
Accounts: rpcAccounts,
}, nil
}
// MarshallAccount returns the RPC representation of an account.
func MarshallAccount(a *account.Account) (*poolrpc.Account, error) {
var rpcState poolrpc.AccountState
switch a.State {
case account.StateInitiated, account.StatePendingOpen:
rpcState = poolrpc.AccountState_PENDING_OPEN
case account.StatePendingUpdate:
rpcState = poolrpc.AccountState_PENDING_UPDATE
case account.StateOpen:
rpcState = poolrpc.AccountState_OPEN
case account.StateExpired:
rpcState = poolrpc.AccountState_EXPIRED
case account.StatePendingClosed:
rpcState = poolrpc.AccountState_PENDING_CLOSED
case account.StateClosed:
rpcState = poolrpc.AccountState_CLOSED
case account.StateCanceledAfterRecovery:
rpcState = poolrpc.AccountState_RECOVERY_FAILED
case account.StatePendingBatch:
rpcState = poolrpc.AccountState_PENDING_BATCH
default:
return nil, fmt.Errorf("unknown state %v", a.State)
}
// The latest transaction is only known after the account has been
// funded.
var latestTxHash chainhash.Hash
if a.LatestTx != nil {
latestTxHash = a.LatestTx.TxHash()
}
return &poolrpc.Account{
TraderKey: a.TraderKey.PubKey.SerializeCompressed(),
Outpoint: &auctioneerrpc.OutPoint{
Txid: a.OutPoint.Hash[:],
OutputIndex: a.OutPoint.Index,
},
Value: uint64(a.Value),
ExpirationHeight: a.Expiry,
State: rpcState,
LatestTxid: latestTxHash[:],
}, nil
}
// DepositAccount handles a trader's request to deposit funds into the specified
// account by spending the specified inputs.
func (s *rpcServer) DepositAccount(ctx context.Context,
req *poolrpc.DepositAccountRequest) (*poolrpc.DepositAccountResponse, error) {
rpcLog.Infof("Depositing %v into acct=%x",
btcutil.Amount(req.AmountSat), req.TraderKey)
// Ensure the trader key is well formed.
traderKey, err := btcec.ParsePubKey(req.TraderKey, btcec.S256())
if err != nil {
return nil, err
}
// Enforce a minimum fee rate of 253 sat/kw.
feeRate := chainfee.SatPerKWeight(req.FeeRateSatPerKw)
if feeRate < chainfee.FeePerKwFloor {
return nil, fmt.Errorf("fee rate of %d sat/kw is too low, "+
"minimum is %d sat/kw", feeRate, chainfee.FeePerKwFloor)
}
bestHeight := atomic.LoadUint32(&s.bestHeight)
// If provided, determine new expiration value.
var expiryHeight uint32
switch {
case req.GetAbsoluteExpiry() != 0 && req.GetRelativeExpiry() != 0:
return nil, errors.New("relative and absolute height cannot " +
"be set in the same request")
case req.GetAbsoluteExpiry() != 0:
expiryHeight = req.GetAbsoluteExpiry()
case req.GetRelativeExpiry() != 0:
expiryHeight = req.GetRelativeExpiry() + bestHeight
}
// Proceed to process the deposit and map its response to the RPC's
// response.
modifiedAccount, tx, err := s.accountManager.DepositAccount(
ctx, traderKey, btcutil.Amount(req.AmountSat), feeRate,
bestHeight, expiryHeight,
)
if err != nil {
return nil, err
}
rpcModAccounts, err := s.marshaler.MarshallAccountsWithAvailableBalance(
ctx, []*account.Account{modifiedAccount},
)
if err != nil {
return nil, err
}
txHash := tx.TxHash()
return &poolrpc.DepositAccountResponse{
Account: rpcModAccounts[0],
DepositTxid: txHash[:],
}, nil
}
// WithdrawAccount handles a trader's request to withdraw funds from the
// specified account by spending the current account output to the specified
// outputs.
func (s *rpcServer) WithdrawAccount(ctx context.Context,
req *poolrpc.WithdrawAccountRequest) (*poolrpc.WithdrawAccountResponse, error) {
rpcLog.Infof("Withdrawing from acct=%x", req.TraderKey)
// Ensure the trader key is well formed.
traderKey, err := btcec.ParsePubKey(req.TraderKey, btcec.S256())
if err != nil {
return nil, err
}
// Ensure the outputs we'll withdraw to are well formed.
if len(req.Outputs) == 0 {
return nil, errors.New("missing outputs for withdrawal")
}
outputs, err := s.parseRPCOutputs(req.Outputs)
if err != nil {
return nil, err
}
// Enforce a minimum fee rate of 253 sat/kw.
feeRate := chainfee.SatPerKWeight(req.FeeRateSatPerKw)
if feeRate < chainfee.FeePerKwFloor {
return nil, fmt.Errorf("fee rate of %d sat/kw is too low, "+
"minimum is %d sat/kw", feeRate, chainfee.FeePerKwFloor)
}
bestHeight := atomic.LoadUint32(&s.bestHeight)
// If provided, determine new expiration value.
var expiryHeight uint32
switch {
case req.GetAbsoluteExpiry() != 0 && req.GetRelativeExpiry() != 0:
return nil, errors.New("relative and absolute height cannot " +
"be set in the same request")
case req.GetAbsoluteExpiry() != 0:
expiryHeight = req.GetAbsoluteExpiry()
case req.GetRelativeExpiry() != 0:
expiryHeight = req.GetRelativeExpiry() + bestHeight
}
// Proceed to process the withdrawal and map its response to the RPC's
// response.
modifiedAccount, tx, err := s.accountManager.WithdrawAccount(
ctx, traderKey, outputs, feeRate, bestHeight, expiryHeight,
)
if err != nil {
return nil, err
}
rpcModAccounts, err := s.marshaler.MarshallAccountsWithAvailableBalance(
ctx, []*account.Account{modifiedAccount},
)
if err != nil {
return nil, err
}
txHash := tx.TxHash()
return &poolrpc.WithdrawAccountResponse{
Account: rpcModAccounts[0],
WithdrawTxid: txHash[:],
}, nil
}
// RenewAccount updates the expiration of an open/expired account. This
// will always require a signature from the auctioneer, even after the account
// has expired, to ensure the auctioneer is aware the account is being renewed.
func (s *rpcServer) RenewAccount(ctx context.Context,
req *poolrpc.RenewAccountRequest) (
*poolrpc.RenewAccountResponse, error) {
rpcLog.Infof("Updating account expiration for account %x", req.AccountKey)
// Ensure the account key is well formed.
accountKey, err := btcec.ParsePubKey(req.AccountKey, btcec.S256())
if err != nil {
return nil, err
}
// Determine the desired expiration value, can be relative or absolute.
bestHeight := atomic.LoadUint32(&s.bestHeight)
var expiryHeight uint32
switch {
case req.GetAbsoluteExpiry() != 0:
expiryHeight = req.GetAbsoluteExpiry()
case req.GetRelativeExpiry() != 0:
expiryHeight = req.GetRelativeExpiry() + bestHeight
default:
return nil, errors.New("either relative or absolute height " +
"must be specified")
}
// Enforce a minimum fee rate of 253 sat/kw.
feeRate := chainfee.SatPerKWeight(req.FeeRateSatPerKw)
if feeRate < chainfee.FeePerKwFloor {
return nil, fmt.Errorf("fee rate of %d sat/kw is too low, "+
"minimum is %d sat/kw", feeRate, chainfee.FeePerKwFloor)
}
// Proceed to process the expiration update and map its response to the
// RPC's response.
modifiedAccount, tx, err := s.accountManager.RenewAccount(
ctx, accountKey, expiryHeight, feeRate, bestHeight,
)
if err != nil {
return nil, err
}
rpcModAccounts, err := s.marshaler.MarshallAccountsWithAvailableBalance(
ctx, []*account.Account{modifiedAccount},
)
if err != nil {
return nil, err
}
txHash := tx.TxHash()
return &poolrpc.RenewAccountResponse{
Account: rpcModAccounts[0],
RenewalTxid: txHash[:],
}, nil
}
// BumpAccountFee attempts to bump the fee of an account's transaction through
// child-pays-for-parent (CPFP). Since the CPFP is performed through the backing
// lnd node, the account transaction must contain an output under its control
// for a successful bump. If a CPFP has already been performed for an account,
// and this RPC is invoked again, then a replacing transaction (RBF) of the
// child will be broadcast.
func (s *rpcServer) BumpAccountFee(ctx context.Context,
req *poolrpc.BumpAccountFeeRequest) (*poolrpc.BumpAccountFeeResponse, error) {
traderKey, err := btcec.ParsePubKey(req.TraderKey, btcec.S256())
if err != nil {
return nil, err
}
feeRate := chainfee.SatPerKWeight(req.FeeRateSatPerKw)
err = s.accountManager.BumpAccountFee(ctx, traderKey, feeRate)
if err != nil {
return nil, err
}
return &poolrpc.BumpAccountFeeResponse{}, nil
}
// CloseAccount handles a trader's request to close the specified account.
func (s *rpcServer) CloseAccount(ctx context.Context,
req *poolrpc.CloseAccountRequest) (*poolrpc.CloseAccountResponse, error) {
rpcLog.Infof("Closing acct=%x", req.TraderKey)
traderKey, err := btcec.ParsePubKey(req.TraderKey, btcec.S256())
if err != nil {
return nil, err
}
// Ensure a valid fee expression was provided.
var feeExpr account.FeeExpr
switch dest := req.FundsDestination.(type) {
// The fee is expressed as a combination of an output along with a fee
// rate.
case *poolrpc.CloseAccountRequest_OutputWithFee:
// Parse the output script if one was provided and ensure it's
// valid.
var pkScript []byte
if dest.OutputWithFee.Address != "" {
var err error
pkScript, err = s.parseOutputScript(
dest.OutputWithFee.Address,
)
if err != nil {
return nil, err
}
}
// Parse the provided fee rate.
var feeRate chainfee.SatPerKWeight
switch feeExpr := dest.OutputWithFee.Fees.(type) {
case *poolrpc.OutputWithFee_ConfTarget:
var err error
feeRate, err = s.lndServices.WalletKit.EstimateFee(
ctx, int32(feeExpr.ConfTarget),
)
if err != nil {
return nil, err
}
case *poolrpc.OutputWithFee_FeeRateSatPerKw:
feeRate = chainfee.SatPerKWeight(feeExpr.FeeRateSatPerKw)
}
// Enforce a minimum fee rate of 253 sat/kw.
if feeRate < chainfee.FeePerKwFloor {
return nil, fmt.Errorf("fee rate of %v is too low, "+
"minimum is %v", feeRate, chainfee.FeePerKwFloor)
}
feeExpr = &account.OutputWithFee{
PkScript: pkScript,
FeeRate: feeRate,
}
// The fee is expressed as implicitly defined by the total output value
// of the provided outputs.
case *poolrpc.CloseAccountRequest_Outputs:
if len(dest.Outputs.Outputs) == 0 {
return nil, errors.New("no outputs provided")
}
outputs, err := s.parseRPCOutputs(dest.Outputs.Outputs)
if err != nil {
return nil, err
}
feeExpr = account.OutputsWithImplicitFee(outputs)
case nil:
return nil, errors.New("a funds destination must be specified")
}
dbOrders, err := s.server.db.GetOrders()
if err != nil {
return nil, err
}
var openNonces []order.Nonce
for _, dbOrder := range dbOrders {
orderDetails := dbOrder.Details()
nonce := orderDetails.Nonce()
// There's no need to query for an order in a terminal state
// from our PoV as it can't transition back to active.
if dbOrder.Details().State.Archived() {
continue
}
// To ensure we have the latest order state, we'll consult with
// the auctioneer's state.
orderStateResp, err := s.auctioneer.OrderState(ctx, nonce)
if err != nil {
return nil, err
}
orderState, err := rpcOrderStateToDBState(orderStateResp.State)
if err != nil {
return nil, err
}
// If the order isn't in the base state, then we'll skip it as
// it isn't considered an "active" order.
if orderState.Archived() {
continue
}
if bytes.Equal(orderDetails.AcctKey[:], req.TraderKey) {
openNonces = append(openNonces, orderDetails.Nonce())
}
}
// We don't allow an account to be closed if it has open orders so they
// don't dangle in the order book on the server's side.
if len(openNonces) > 0 {
return nil, fmt.Errorf("acct=%x has open orders, cancel them "+
"before closing: %v", req.TraderKey, openNonces)
}
// Proceed to close the requested account with the parsed fee
// expression.
closeTx, err := s.accountManager.CloseAccount(
ctx, traderKey, feeExpr, atomic.LoadUint32(&s.bestHeight),
)
if err != nil {
return nil, err
}
closeTxHash := closeTx.TxHash()
return &poolrpc.CloseAccountResponse{
CloseTxid: closeTxHash[:],