/
dcr.go
3054 lines (2763 loc) · 109 KB
/
dcr.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
// This code is available on the terms of the project LICENSE.md file,
// also available online at https://blueoakcouncil.org/license/1.0.0.
package dcr
import (
"bytes"
"context"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"decred.org/dcrdex/client/asset"
"decred.org/dcrdex/dex"
"decred.org/dcrdex/dex/calc"
dexdcr "decred.org/dcrdex/dex/networks/dcr"
"decred.org/dcrwallet/v2/rpc/client/dcrwallet"
walletjson "decred.org/dcrwallet/v2/rpc/jsonrpc/types"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/chaincfg/v3"
"github.com/decred/dcrd/dcrec/secp256k1/v3"
"github.com/decred/dcrd/dcrec/secp256k1/v3/ecdsa"
"github.com/decred/dcrd/dcrjson/v3"
"github.com/decred/dcrd/dcrutil/v4"
"github.com/decred/dcrd/gcs/v3"
"github.com/decred/dcrd/gcs/v3/blockcf2"
chainjson "github.com/decred/dcrd/rpc/jsonrpc/types/v3"
"github.com/decred/dcrd/rpcclient/v7"
"github.com/decred/dcrd/txscript/v4"
"github.com/decred/dcrd/txscript/v4/sign"
"github.com/decred/dcrd/txscript/v4/stdaddr"
"github.com/decred/dcrd/wire"
)
const (
// The implementation version. This considers the dex/networks package too.
version = 0
// BipID is the BIP-0044 asset ID.
BipID = 42
// defaultFee is the default value for the fallbackfee.
defaultFee = 20
// defaultFeeRateLimit is the default value for the feeratelimit.
defaultFeeRateLimit = 100
// defaultRedeemConfTarget is the default redeem transaction confirmation
// target in blocks used by estimatesmartfee to get the optimal fee for a
// redeem transaction.
defaultRedeemConfTarget = 1
// splitTxBaggage is the total number of additional bytes associated with
// using a split transaction to fund a swap.
splitTxBaggage = dexdcr.MsgTxOverhead + dexdcr.P2PKHInputSize + 2*dexdcr.P2PKHOutputSize
// RawRequest RPC methods
methodGetCFilterV2 = "getcfilterv2"
methodListUnspent = "listunspent"
methodListLockUnspent = "listlockunspent"
methodSignRawTransaction = "signrawtransaction"
)
var (
requiredWalletVersion = dex.Semver{Major: 8, Minor: 5, Patch: 0}
requiredNodeVersion = dex.Semver{Major: 7, Minor: 0, Patch: 0}
)
var (
// blockTicker is the delay between calls to check for new blocks.
blockTicker = time.Second
configOpts = []*asset.ConfigOption{
{
Key: "account",
DisplayName: "Account Name",
Description: "dcrwallet account name",
},
{
Key: "username",
DisplayName: "RPC Username",
Description: "dcrwallet's 'username' setting for JSON-RPC",
},
{
Key: "password",
DisplayName: "RPC Password",
Description: "dcrwallet's 'password' setting for JSON-RPC",
NoEcho: true,
},
{
Key: "rpclisten",
DisplayName: "RPC Address",
Description: "dcrwallet's address (host or host:port) (default port: 9110)",
DefaultValue: "127.0.0.1:9110",
},
{
Key: "rpccert",
DisplayName: "TLS Certificate",
Description: "Path to the dcrwallet TLS certificate file",
DefaultValue: filepath.Join(dcrwHomeDir, "rpc.cert"),
},
{
Key: "fallbackfee",
DisplayName: "Fallback fee rate",
Description: "The fee rate to use for fee payment and withdrawals when " +
"estimatesmartfee is not available. Units: DCR/kB",
DefaultValue: defaultFee * 1000 / 1e8,
},
{
Key: "feeratelimit",
DisplayName: "Highest acceptable fee rate",
Description: "This is the highest network fee rate you are willing to " +
"pay on swap transactions. If feeratelimit is lower than a market's " +
"maxfeerate, you will not be able to trade on that market with this " +
"wallet. Units: DCR/kB",
DefaultValue: defaultFeeRateLimit * 1000 / 1e8,
},
{
Key: "redeemconftarget",
DisplayName: "Redeem confirmation target",
Description: "The target number of blocks for the redeem transaction " +
"to get a confirmation. Used to set the transaction's fee rate." +
" (default: 1 block)",
DefaultValue: defaultRedeemConfTarget,
},
{
Key: "txsplit",
DisplayName: "Pre-size funding inputs",
Description: "When placing an order, create a \"split\" transaction to " +
"fund the order without locking more of the wallet balance than " +
"necessary. Otherwise, excess funds may be reserved to fund the order " +
"until the first swap contract is broadcast during match settlement, or " +
"the order is canceled. This an extra transaction for which network " +
"mining fees are paid. Used only for standing-type orders, e.g. " +
"limit orders without immediate time-in-force.",
IsBoolean: true,
},
}
// WalletInfo defines some general information about a Decred wallet.
WalletInfo = &asset.WalletInfo{
Name: "Decred",
Units: "atoms",
Version: version,
DefaultConfigPath: defaultConfigPath,
ConfigOpts: configOpts,
}
)
// rpcClient is an rpcclient.Client, or a stub for testing.
type rpcClient interface {
EstimateSmartFee(ctx context.Context, confirmations int64, mode chainjson.EstimateSmartFeeMode) (*chainjson.EstimateSmartFeeResult, error)
GetBlockChainInfo(ctx context.Context) (*chainjson.GetBlockChainInfoResult, error)
SendRawTransaction(ctx context.Context, tx *wire.MsgTx, allowHighFees bool) (*chainhash.Hash, error)
GetTxOut(ctx context.Context, txHash *chainhash.Hash, index uint32, tree int8, mempool bool) (*chainjson.GetTxOutResult, error)
GetBalanceMinConf(ctx context.Context, account string, minConfirms int) (*walletjson.GetBalanceResult, error)
GetBestBlock(ctx context.Context) (*chainhash.Hash, int64, error)
GetBlockHash(ctx context.Context, blockHeight int64) (*chainhash.Hash, error)
GetBlockVerbose(ctx context.Context, blockHash *chainhash.Hash, verboseTx bool) (*chainjson.GetBlockVerboseResult, error)
GetBlockHeaderVerbose(ctx context.Context, blockHash *chainhash.Hash) (*chainjson.GetBlockHeaderVerboseResult, error)
GetRawMempool(ctx context.Context, txType chainjson.GetRawMempoolTxTypeCmd) ([]*chainhash.Hash, error)
GetRawTransactionVerbose(ctx context.Context, txHash *chainhash.Hash) (*chainjson.TxRawResult, error)
LockUnspent(ctx context.Context, unlock bool, ops []*wire.OutPoint) error
GetRawChangeAddress(ctx context.Context, account string, net stdaddr.AddressParams) (stdaddr.Address, error)
GetNewAddressGapPolicy(ctx context.Context, addrType string, gap dcrwallet.GapPolicy) (stdaddr.Address, error)
DumpPrivKey(ctx context.Context, address stdaddr.Address) (*dcrutil.WIF, error)
GetTransaction(ctx context.Context, txHash *chainhash.Hash) (*walletjson.GetTransactionResult, error)
WalletLock(ctx context.Context) error
WalletPassphrase(ctx context.Context, passphrase string, timeoutSecs int64) error
AccountUnlocked(ctx context.Context, account string) (*walletjson.AccountUnlockedResult, error)
LockAccount(ctx context.Context, account string) error
UnlockAccount(ctx context.Context, account, passphrase string) error
Disconnected() bool
RawRequest(ctx context.Context, method string, params []json.RawMessage) (json.RawMessage, error)
WalletInfo(ctx context.Context) (*walletjson.WalletInfoResult, error)
ValidateAddress(ctx context.Context, address stdaddr.Address) (*walletjson.ValidateAddressWalletResult, error)
}
// The rpcclient package functions will return a rpcclient.ErrRequestCanceled
// error if the context is canceled. Translate these to asset.ErrRequestTimeout.
func translateRPCCancelErr(err error) error {
if errors.Is(err, rpcclient.ErrRequestCanceled) {
err = asset.ErrRequestTimeout
}
return err
}
// outPoint is the hash and output index of a transaction output.
type outPoint struct {
txHash chainhash.Hash
vout uint32
}
// newOutPoint is the constructor for a new outPoint.
func newOutPoint(txHash *chainhash.Hash, vout uint32) outPoint {
return outPoint{
txHash: *txHash,
vout: vout,
}
}
// String is a human-readable string representation of the outPoint.
func (pt outPoint) String() string {
return pt.txHash.String() + ":" + strconv.Itoa(int(pt.vout))
}
// output is information about a transaction output. output satisfies the
// asset.Coin interface.
type output struct {
pt outPoint
tree int8
value uint64
}
// newOutput is the constructor for an output.
func newOutput(txHash *chainhash.Hash, vout uint32, value uint64, tree int8) *output {
return &output{
pt: outPoint{
txHash: *txHash,
vout: vout,
},
value: value,
tree: tree,
}
}
// Value returns the value of the output. Part of the asset.Coin interface.
func (op *output) Value() uint64 {
return op.value
}
// ID is the output's coin ID. Part of the asset.Coin interface. For DCR, the
// coin ID is 36 bytes = 32 bytes tx hash + 4 bytes big-endian vout.
func (op *output) ID() dex.Bytes {
return toCoinID(op.txHash(), op.vout())
}
// String is a string representation of the coin.
func (op *output) String() string {
return op.pt.String()
}
// txHash returns the pointer of the outPoint's txHash.
func (op *output) txHash() *chainhash.Hash {
return &op.pt.txHash
}
// vout returns the outPoint's vout.
func (op *output) vout() uint32 {
return op.pt.vout
}
// wireOutPoint creates and returns a new *wire.OutPoint for the output.
func (op *output) wireOutPoint() *wire.OutPoint {
return wire.NewOutPoint(op.txHash(), op.vout(), op.tree)
}
// auditInfo is information about a swap contract on the blockchain, not
// necessarily created by this wallet, as would be returned from AuditContract.
// auditInfo satisfies the asset.AuditInfo interface.
type auditInfo struct {
output *output
secretHash []byte
contract []byte
recipient stdaddr.Address
expiration time.Time
}
// Recipient is a base58 string for the contract's receiving address. Part of
// the asset.AuditInfo interface.
func (ci *auditInfo) Recipient() string {
return ci.recipient.String()
}
// Expiration is the expiration time of the contract, which is the earliest time
// that a refund can be issued for an un-redeemed contract. Part of the
// asset.AuditInfo interface.
func (ci *auditInfo) Expiration() time.Time {
return ci.expiration
}
// Contract is the contract script.
func (ci *auditInfo) Contract() dex.Bytes {
return ci.contract
}
// Coin returns the output as an asset.Coin. Part of the asset.AuditInfo
// interface.
func (ci *auditInfo) Coin() asset.Coin {
return ci.output
}
// SecretHash is the contract's secret hash.
func (ci *auditInfo) SecretHash() dex.Bytes {
return ci.secretHash
}
// convertAuditInfo converts from the common *asset.AuditInfo type to our
// internal *auditInfo type.
func convertAuditInfo(ai *asset.AuditInfo, chainParams *chaincfg.Params) (*auditInfo, error) {
if ai.Coin == nil {
return nil, fmt.Errorf("no coin")
}
op, ok := ai.Coin.(*output)
if !ok {
return nil, fmt.Errorf("unknown coin type %T", ai.Coin)
}
recip, err := stdaddr.DecodeAddress(ai.Recipient, chainParams)
if err != nil {
return nil, err
}
return &auditInfo{
output: op, // *output
recipient: recip, // btcutil.Address
contract: ai.Contract, // []byte
secretHash: ai.SecretHash, // []byte
expiration: ai.Expiration, // time.Time
}, nil
}
// swapReceipt is information about a swap contract that was broadcast by this
// wallet. Satisfies the asset.Receipt interface.
type swapReceipt struct {
output *output
contract []byte
signedRefund []byte
expiration time.Time
}
// Expiration is the time that the contract will expire, allowing the user to
// issue a refund transaction. Part of the asset.Receipt interface.
func (r *swapReceipt) Expiration() time.Time {
return r.expiration
}
// Coin is the contract script. Part of the asset.Receipt interface.
func (r *swapReceipt) Contract() dex.Bytes {
return r.contract
}
// Coin is the output information as an asset.Coin. Part of the asset.Receipt
// interface.
func (r *swapReceipt) Coin() asset.Coin {
return r.output
}
// String provides a human-readable representation of the contract's Coin.
func (r *swapReceipt) String() string {
return r.output.String()
}
// SignedRefund is a signed refund script that can be used to return
// funds to the user in the case a contract expires.
func (r *swapReceipt) SignedRefund() dex.Bytes {
return r.signedRefund
}
// fundingCoin is similar to output, but also stores the address. The
// ExchangeWallet fundingCoins dict is used as a local cache of coins being
// spent.
type fundingCoin struct {
op *output
addr string
}
// Driver implements asset.Driver.
type Driver struct{}
// Setup creates the DCR exchange wallet. Start the wallet with its Run method.
func (d *Driver) Setup(cfg *asset.WalletConfig, logger dex.Logger, network dex.Network) (asset.Wallet, error) {
return NewWallet(cfg, logger, network)
}
// DecodeCoinID creates a human-readable representation of a coin ID for Decred.
func (d *Driver) DecodeCoinID(coinID []byte) (string, error) {
txid, vout, err := decodeCoinID(coinID)
if err != nil {
return "", err
}
return fmt.Sprintf("%v:%d", txid, vout), err
}
// Info returns basic information about the wallet and asset. WARNING: An
// ExchangeWallet instance may have different DefaultFeeRate set, so use
// (*ExchangeWallet).Info when possible.
func (d *Driver) Info() *asset.WalletInfo {
return WalletInfo
}
func init() {
asset.Register(BipID, &Driver{})
}
// ExchangeWallet is a wallet backend for Decred. The backend is how the DEX
// client app communicates with the Decred blockchain and wallet. ExchangeWallet
// satisfies the dex.Wallet interface.
type ExchangeWallet struct {
// 64-bit atomic variables first. See
// https://golang.org/pkg/sync/atomic/#pkg-note-BUG
tipAtConnect int64
ctx context.Context // the asset subsystem starts with Connect(ctx)
client *rpcclient.Client
node rpcClient
chainParams *chaincfg.Params
log dex.Logger
acct string
tipChange func(error)
fallbackFeeRate uint64
feeRateLimit uint64
redeemConfTarget uint64
useSplitTx bool
tipMtx sync.RWMutex
currentTip *block
// Coins returned by Fund are cached for quick reference.
fundingMtx sync.RWMutex
fundingCoins map[outPoint]*fundingCoin
findRedemptionMtx sync.RWMutex
findRedemptionQueue map[outPoint]*findRedemptionReq
}
type block struct {
height int64
hash *chainhash.Hash
}
// findRedemptionReq represents a request to find a contract's redemption,
// which is added to the findRedemptionQueue with the contract outpoint as
// key.
type findRedemptionReq struct {
ctx context.Context
contractP2SHScript []byte
contractOutputScriptVer uint16
resultChan chan *findRedemptionResult
}
func (frr *findRedemptionReq) canceled() bool {
return frr.ctx.Err() != nil
}
// findRedemptionResult models the result of a find redemption attempt.
type findRedemptionResult struct {
RedemptionCoinID dex.Bytes
Secret dex.Bytes
Err error
}
type walletClient = dcrwallet.Client
type combinedClient struct {
*rpcclient.Client
*walletClient
}
// ValidateAddress disambiguates the node and wallet methods.
func (cc *combinedClient) ValidateAddress(ctx context.Context, address stdaddr.Address) (*walletjson.ValidateAddressWalletResult, error) {
return cc.walletClient.ValidateAddress(ctx, address)
}
// Check that ExchangeWallet satisfies the Wallet interface.
var _ asset.Wallet = (*ExchangeWallet)(nil)
// NewWallet is the exported constructor by which the DEX will import the
// exchange wallet. The wallet will shut down when the provided context is
// canceled.
func NewWallet(cfg *asset.WalletConfig, logger dex.Logger, network dex.Network) (*ExchangeWallet, error) {
// loadConfig will set fields if defaults are used and set the chainParams
// package variable.
walletCfg, chainParams, err := loadConfig(cfg.Settings, network)
if err != nil {
return nil, err
}
dcr, err := unconnectedWallet(cfg, walletCfg, chainParams, logger)
if err != nil {
return nil, err
}
logger.Infof("Setting up new DCR wallet at %s with TLS certificate %q.",
walletCfg.RPCListen, walletCfg.RPCCert)
dcr.client, err = newClient(walletCfg.RPCListen, walletCfg.RPCUser,
walletCfg.RPCPass, walletCfg.RPCCert, logger)
if err != nil {
return nil, fmt.Errorf("DCR ExchangeWallet.Run error: %w", err)
}
// Beyond this point, only node
dcr.node = &combinedClient{dcr.client, dcrwallet.NewClient(dcrwallet.RawRequestCaller(dcr.client), chainParams)}
return dcr, nil
}
// unconnectedWallet returns an ExchangeWallet without a node. The node should
// be set before use.
func unconnectedWallet(cfg *asset.WalletConfig, dcrCfg *Config, chainParams *chaincfg.Params, logger dex.Logger) (*ExchangeWallet, error) {
// If set in the user config, the fallback fee will be in units of DCR/kB.
// Convert to atoms/B.
fallbackFeesPerByte := toAtoms(dcrCfg.FallbackFeeRate / 1000)
if fallbackFeesPerByte == 0 {
fallbackFeesPerByte = defaultFee
}
logger.Tracef("Fallback fees set at %d atoms/byte", fallbackFeesPerByte)
// If set in the user config, the fee rate limit will be in units of DCR/KB.
// Convert to atoms/byte & error if value is smaller than smallest unit.
feesLimitPerByte := uint64(defaultFeeRateLimit)
if dcrCfg.FeeRateLimit > 0 {
feesLimitPerByte = toAtoms(dcrCfg.FeeRateLimit / 1000)
if feesLimitPerByte == 0 {
return nil, fmt.Errorf("Fee rate limit is smaller than smallest unit: %v",
dcrCfg.FeeRateLimit)
}
}
logger.Tracef("Fees rate limit set at %d atoms/byte", feesLimitPerByte)
redeemConfTarget := dcrCfg.RedeemConfTarget
if redeemConfTarget == 0 {
redeemConfTarget = defaultRedeemConfTarget
}
logger.Tracef("Redeem conf target set to %d blocks", redeemConfTarget)
return &ExchangeWallet{
log: logger,
chainParams: chainParams,
acct: cfg.Settings["account"],
tipChange: cfg.TipChange,
fundingCoins: make(map[outPoint]*fundingCoin),
findRedemptionQueue: make(map[outPoint]*findRedemptionReq),
fallbackFeeRate: fallbackFeesPerByte,
feeRateLimit: feesLimitPerByte,
redeemConfTarget: redeemConfTarget,
useSplitTx: dcrCfg.UseSplitTx,
}, nil
}
// newClient attempts to create a new websocket connection to a dcrwallet
// instance with the given credentials and notification handlers.
func newClient(host, user, pass, cert string, logger dex.Logger) (*rpcclient.Client, error) {
certs, err := ioutil.ReadFile(cert)
if err != nil {
return nil, fmt.Errorf("TLS certificate read error: %w", err)
}
config := &rpcclient.ConnConfig{
Host: host,
Endpoint: "ws",
User: user,
Pass: pass,
Certificates: certs,
DisableConnectOnNew: true,
}
ntfnHandlers := &rpcclient.NotificationHandlers{
// Setup an on-connect handler for logging (re)connects.
OnClientConnected: func() {
logger.Infof("Connected to Decred wallet at %s", host)
},
}
cl, err := rpcclient.New(config, ntfnHandlers)
if err != nil {
return nil, fmt.Errorf("Failed to start dcrwallet RPC client: %w", err)
}
return cl, nil
}
// Info returns basic information about the wallet and asset.
func (dcr *ExchangeWallet) Info() *asset.WalletInfo {
return WalletInfo
}
// var logup uint32
// func rpclog(log dex.Logger) {
// if atomic.CompareAndSwapUint32(&logup, 0, 1) {
// rpcclient.UseLogger(log)
// }
// }
// Connect connects the wallet to the RPC server. Satisfies the dex.Connector
// interface. WARNING: Once stopped, it cannot reconnect, requiring NewWallet to
// construct a new ExchangeWallet to Connect again.
func (dcr *ExchangeWallet) Connect(ctx context.Context) (*sync.WaitGroup, error) {
// rpclog(dcr.log)
dcr.ctx = ctx
err := dcr.client.Connect(ctx, false)
if err != nil {
return nil, fmt.Errorf("Decred Wallet connect error: %w", err)
}
// The websocket client is connected now, so if any of the following checks
// fails and we return with a non-nil error, we must shutdown the rpc client
// or subsequent reconnect attempts will be met with "websocket client has
// already connected".
var success bool
defer func() {
if !success {
dcr.client.Shutdown()
dcr.client.WaitForShutdown()
}
}()
// Check the required API versions.
versions, err := dcr.client.Version(ctx)
if err != nil {
return nil, fmt.Errorf("DCR ExchangeWallet version fetch error: %w", err)
}
ver, exists := versions["dcrwalletjsonrpcapi"]
if !exists {
return nil, fmt.Errorf("dcrwallet.Version response missing 'dcrwalletjsonrpcapi'")
}
walletSemver := dex.NewSemver(ver.Major, ver.Minor, ver.Patch)
if !dex.SemverCompatible(requiredWalletVersion, walletSemver) {
return nil, fmt.Errorf("dcrwallet has an incompatible JSON-RPC version: got %s, expected %s",
walletSemver, requiredWalletVersion)
}
ver, exists = versions["dcrdjsonrpcapi"]
if !exists {
return nil, fmt.Errorf("dcrwallet.Version response missing 'dcrdjsonrpcapi'")
}
nodeSemver := dex.NewSemver(ver.Major, ver.Minor, ver.Patch)
if !dex.SemverCompatible(requiredNodeVersion, nodeSemver) {
return nil, fmt.Errorf("dcrd has an incompatible JSON-RPC version: got %s, expected %s",
nodeSemver, requiredNodeVersion)
}
curnet, err := dcr.client.GetCurrentNet(ctx)
if err != nil {
return nil, fmt.Errorf("getcurrentnet failure: %w", err)
}
// Initialize the best block.
dcr.tipMtx.Lock()
dcr.currentTip, err = dcr.getBestBlock(ctx)
dcr.tipMtx.Unlock()
if err != nil {
return nil, fmt.Errorf("error initializing best block for DCR: %w", err)
}
atomic.StoreInt64(&dcr.tipAtConnect, dcr.currentTip.height)
dcr.log.Infof("Connected to dcrwallet (JSON-RPC API v%s) proxying dcrd (JSON-RPC API v%s) on %v",
walletSemver, nodeSemver, curnet)
success = true
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
dcr.monitorBlocks(ctx)
dcr.shutdown()
}()
return &wg, nil
}
// OwnsAddress indicates if an address belongs to the wallet.
func (dcr *ExchangeWallet) OwnsAddress(address string) (bool, error) {
a, err := stdaddr.DecodeAddress(address, dcr.chainParams)
if err != nil {
return false, err
}
va, err := dcr.node.ValidateAddress(dcr.ctx, a)
if err != nil {
// Work around a bug with dcrwallet that prevents validateaddress for
// locked accounts.
if isAccountNotEncryptedErr(err) {
return false, nil
}
return false, err
}
return va.IsMine && dcr.acct == va.Account, nil
}
// Balance should return the total available funds in the wallet. Note that
// after calling Fund, the amount returned by Balance may change by more than
// the value funded. Part of the asset.Wallet interface. TODO: Since this
// includes potentially untrusted 0-conf utxos, consider prioritizing confirmed
// utxos when funding an order.
func (dcr *ExchangeWallet) Balance() (*asset.Balance, error) {
balances, err := dcr.node.GetBalanceMinConf(dcr.ctx, dcr.acct, 0)
if err != nil {
return nil, translateRPCCancelErr(err)
}
locked, err := dcr.lockedAtoms()
if err != nil {
return nil, err
}
var balance asset.Balance
var acctFound bool
for i := range balances.Balances {
ab := &balances.Balances[i]
if ab.AccountName == dcr.acct {
acctFound = true
balance.Available = toAtoms(ab.Spendable) - locked
balance.Immature = toAtoms(ab.ImmatureCoinbaseRewards) +
toAtoms(ab.ImmatureStakeGeneration)
balance.Locked = locked + toAtoms(ab.LockedByTickets)
break
}
}
if !acctFound {
return nil, fmt.Errorf("account not found: %q", dcr.acct)
}
return &balance, err
}
// FeeRate returns the current optimal fee rate in atoms / byte.
func (dcr *ExchangeWallet) feeRate(confTarget uint64) (uint64, error) {
// estimatesmartfee 1 returns extremely high rates on DCR.
if confTarget < 2 {
confTarget = 2
}
estimateFeeResult, err := dcr.node.EstimateSmartFee(dcr.ctx, int64(confTarget), chainjson.EstimateSmartFeeConservative)
if err != nil {
return 0, translateRPCCancelErr(err)
}
atomsPerKB, err := dcrutil.NewAmount(estimateFeeResult.FeeRate) // atomsPerKB is 0 when err != nil
if err != nil {
return 0, err
}
// Add 1 extra atom/byte, which is both extra conservative and prevents a
// zero value if the atoms/KB is less than 1000.
return 1 + uint64(atomsPerKB)/1000, nil // dcrPerKB * 1e8 / 1e3
}
// feeRateWithFallback attempts to get the optimal fee rate in atoms / byte via
// FeeRate. If that fails, it will return the configured fallback fee rate.
func (dcr *ExchangeWallet) feeRateWithFallback(confTarget, feeSuggestion uint64) uint64 {
feeRate, err := dcr.feeRate(confTarget)
if err == nil {
dcr.log.Tracef("Obtained local estimate for %d-conf fee rate, %d", confTarget, feeRate)
return feeRate
}
if feeSuggestion > 0 && feeSuggestion < dcr.fallbackFeeRate && feeSuggestion < dcr.feeRateLimit {
dcr.log.Tracef("feeRateWithFallback using caller's suggestion for %d-conf fee rate, %d. Local estimate unavailable (%q)",
confTarget, feeSuggestion, err)
return feeSuggestion
}
dcr.log.Warnf("Unable to get optimal fee rate, using fallback of %d: %v",
dcr.fallbackFeeRate, err)
return dcr.fallbackFeeRate
}
type amount uint64
func (a amount) String() string {
return strconv.FormatFloat(dcrutil.Amount(a).ToCoin(), 'f', -1, 64) // dec, but no trailing zeros
}
// MaxOrder generates information about the maximum order size and associated
// fees that the wallet can support for the given DEX configuration. The fees are an
// estimate based on current network conditions, and will be <= the fees
// associated with nfo.MaxFeeRate. For quote assets, the caller will have to
// calculate lotSize based on a rate conversion from the base asset's lot size.
// lotSize must not be zero and will cause a panic if so.
func (dcr *ExchangeWallet) MaxOrder(lotSize, feeSuggestion uint64, nfo *dex.Asset) (*asset.SwapEstimate, error) {
_, est, err := dcr.maxOrder(lotSize, feeSuggestion, nfo)
return est, err
}
// maxOrder gets the estimate for MaxOrder, and also returns the
// []*compositeUTXO and network fee rate to be used for further order estimation
// without additional calls to listunspent.
func (dcr *ExchangeWallet) maxOrder(lotSize, feeSuggestion uint64, nfo *dex.Asset) (utxos []*compositeUTXO, est *asset.SwapEstimate, err error) {
if lotSize == 0 {
return nil, nil, errors.New("cannot divide by lotSize zero")
}
utxos, err = dcr.spendableUTXOs()
if err != nil {
return nil, nil, fmt.Errorf("error parsing unspent outputs: %w", err)
}
var avail uint64
for _, utxo := range utxos {
avail += toAtoms(utxo.rpc.Amount)
}
// Start by attempting max lots with a basic fee.
basicFee := nfo.SwapSize * nfo.MaxFeeRate
lots := avail / (lotSize + basicFee)
for lots > 0 {
est, _, err := dcr.estimateSwap(lots, lotSize, feeSuggestion, utxos, nfo, dcr.useSplitTx)
// The only failure mode of estimateSwap -> dcr.fund is when there is
// not enough funds, so if an error is encountered, count down the lots
// and repeat until we have enough.
if err != nil {
lots--
continue
}
return utxos, est, nil
}
return nil, &asset.SwapEstimate{}, nil
}
// estimateSwap prepares an *asset.SwapEstimate.
func (dcr *ExchangeWallet) estimateSwap(lots, lotSize, feeSuggestion uint64, utxos []*compositeUTXO,
nfo *dex.Asset, trySplit bool) (*asset.SwapEstimate, bool /*split used*/, error) {
var avail uint64
for _, utxo := range utxos {
avail += toAtoms(utxo.rpc.Amount)
}
val := lots * lotSize
sum, inputsSize, _, _, _, err := dcr.tryFund(utxos, orderEnough(val, lots, nfo))
if err != nil {
return nil, false, err
}
reqFunds := calc.RequiredOrderFunds(val, uint64(inputsSize), lots, nfo)
maxFees := reqFunds - val
estHighFunds := calc.RequiredOrderFundsAlt(val, uint64(inputsSize), lots, nfo.SwapSizeBase, nfo.SwapSize, feeSuggestion)
estHighFees := estHighFunds - val
estLowFunds := calc.RequiredOrderFundsAlt(val, uint64(inputsSize), 1, nfo.SwapSizeBase, nfo.SwapSize, feeSuggestion)
estLowFunds += dexdcr.P2SHOutputSize * (lots - 1) * feeSuggestion
estLowFees := estLowFunds - val
// Math for split transactions is a little different.
if dcr.useSplitTx {
extraFees := splitTxBaggage * nfo.MaxFeeRate
splitFees := splitTxBaggage * feeSuggestion
if avail >= reqFunds+extraFees {
return &asset.SwapEstimate{
Lots: lots,
Value: val,
MaxFees: maxFees + extraFees,
RealisticBestCase: estLowFees + splitFees,
RealisticWorstCase: estHighFees + splitFees,
Locked: val + maxFees + extraFees,
}, true, nil
}
}
// No split transaction.
return &asset.SwapEstimate{
Lots: lots,
Value: val,
MaxFees: maxFees,
RealisticBestCase: estLowFees,
RealisticWorstCase: estHighFees,
Locked: sum,
}, false, nil
}
// PreSwap get order estimates based on the available funds and the wallet
// configuration.
func (dcr *ExchangeWallet) PreSwap(req *asset.PreSwapForm) (*asset.PreSwap, error) {
// Start with the maxOrder at the default configuration. This gets us the
// utxo set, the network fee rate, and the wallet's maximum order size.
// The utxo set can then be used repeatedly in estimateSwap at virtually
// zero cost since there are no more RPC calls.
// The utxo set is only used once right now, but when order-time options are
// implemented, the utxos will be used to calculate option availability and
// fees.
utxos, maxEst, err := dcr.maxOrder(req.LotSize, req.FeeSuggestion, req.AssetConfig)
if err != nil {
return nil, err
}
if maxEst.Lots < req.Lots {
return nil, fmt.Errorf("%d lots available for %d-lot order", maxEst.Lots, req.Lots)
}
// Get the estimate for the requested number of lots.
est, _, err := dcr.estimateSwap(req.Lots, req.LotSize, req.FeeSuggestion, utxos, req.AssetConfig, dcr.useSplitTx)
if err != nil {
return nil, fmt.Errorf("estimation failed: %v", err)
}
return &asset.PreSwap{
Estimate: est,
}, nil
}
// PreRedeem generates an estimate of the range of redemption fees that could
// be assessed.
func (dcr *ExchangeWallet) PreRedeem(req *asset.PreRedeemForm) (*asset.PreRedeem, error) {
feeRate := dcr.feeRateWithFallback(dcr.redeemConfTarget, req.FeeSuggestion)
// Best is one transaction with req.Lots inputs and 1 output.
var best uint64 = dexdcr.MsgTxOverhead
// Worst is req.Lots transactions, each with one input and one output.
var worst uint64 = dexdcr.MsgTxOverhead * req.Lots
var inputSize uint64 = dexdcr.TxInOverhead + dexdcr.RedeemSwapSigScriptSize
var outputSize uint64 = dexdcr.P2PKHOutputSize
best += inputSize*req.Lots + outputSize
worst += (inputSize + outputSize) * req.Lots
return &asset.PreRedeem{
Estimate: &asset.RedeemEstimate{
RealisticWorstCase: worst * feeRate,
RealisticBestCase: best * feeRate,
},
}, nil
}
// orderEnough generates a function that can be used as the enough argument to
// the fund method.
func orderEnough(val, lots uint64, nfo *dex.Asset) func(sum uint64, size uint32, unspent *compositeUTXO) bool {
return func(sum uint64, size uint32, unspent *compositeUTXO) bool {
reqFunds := calc.RequiredOrderFunds(val, uint64(size+unspent.input.Size()), lots, nfo)
// needed fees are reqFunds - value
return sum+toAtoms(unspent.rpc.Amount) >= reqFunds
}
}
// FundOrder selects coins for use in an order. The coins will be locked, and
// will not be returned in subsequent calls to FundOrder or calculated in calls
// to Available, unless they are unlocked with ReturnCoins.
// The returned []dex.Bytes contains the redeem scripts for the selected coins.
// Equal number of coins and redeemed scripts must be returned. A nil or empty
// dex.Bytes should be appended to the redeem scripts collection for coins with
// no redeem script.
func (dcr *ExchangeWallet) FundOrder(ord *asset.Order) (asset.Coins, []dex.Bytes, error) {
// Consumer checks dex asset version, so maybe this is not our job:
// if ord.DEXConfig.Version != dcr.Info().Version {
// return nil, nil, fmt.Errorf("asset version mismatch: server = %d, client = %d",
// ord.DEXConfig.Version, dcr.Info().Version)
// }
if ord.Value == 0 {
return nil, nil, fmt.Errorf("cannot fund value = 0")
}
if ord.MaxSwapCount == 0 {
return nil, nil, fmt.Errorf("cannot fund a zero-lot order")
}
// Check wallet's fee rate limit against server's max fee rate
if dcr.feeRateLimit < ord.DEXConfig.MaxFeeRate {
return nil, nil, fmt.Errorf(
"%v: server's max fee rate %v higher than configured fee rate limit %v",
ord.DEXConfig.Symbol,
ord.DEXConfig.MaxFeeRate,
dcr.feeRateLimit)
}
coins, redeemScripts, sum, inputsSize, err := dcr.fund(orderEnough(ord.Value, ord.MaxSwapCount, ord.DEXConfig))
if err != nil {
return nil, nil, fmt.Errorf("error funding order value of %s DCR: %w",
amount(ord.Value), err)
}
// Send a split, if preferred.
if dcr.useSplitTx && !ord.Immediate {
splitCoins, split, err := dcr.split(ord.Value, ord.MaxSwapCount, coins,
inputsSize, ord.FeeSuggestion, ord.DEXConfig)
if err != nil {
if errRet := dcr.returnCoins(coins); errRet != nil {
dcr.log.Warnf("Failed to unlock funding coins %v: %v", coins, errRet)
}
return nil, nil, err
} else if split {
return splitCoins, []dex.Bytes{nil}, nil // no redeem script required for split tx output
}
return splitCoins, redeemScripts, nil // splitCoins == coins
}
dcr.log.Infof("Funding %s DCR order with coins %v worth %s", amount(ord.Value), coins, amount(sum))
return coins, redeemScripts, nil
}
// unspents fetches unspent outputs for the ExchangeWallet account using rpc
// RawRequest.
func (dcr *ExchangeWallet) unspents() ([]walletjson.ListUnspentResult, error) {
var unspents []walletjson.ListUnspentResult
// minconf, maxconf (rpcdefault=9999999), [address], account
params := anylist{0, 9999999, nil, dcr.acct}
err := dcr.nodeRawRequest(methodListUnspent, params, &unspents)
return unspents, err
}
// fund finds coins for the specified value. A function is provided that can
// check whether adding the provided output would be enough to satisfy the
// needed value. Preference is given to selecting coins with 1 or more confs,
// falling back to 0-conf coins where there are not enough 1+ confs coins.
func (dcr *ExchangeWallet) fund(enough func(sum uint64, size uint32, unspent *compositeUTXO) bool) (
coins asset.Coins, redeemScripts []dex.Bytes, sum, size uint64, err error) {
// Keep a consistent view of spendable and locked coins in the wallet and
// the fundingCoins map to make this safe for concurrent use.
dcr.fundingMtx.Lock() // before listing unspents in wallet
defer dcr.fundingMtx.Unlock() // hold until lockFundingCoins (wallet and map)
utxos, err := dcr.spendableUTXOs()
if err != nil {
return nil, nil, 0, 0, err