-
Notifications
You must be signed in to change notification settings - Fork 84
/
dcr.go
4846 lines (4347 loc) · 173 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"
"math"
"net/http"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"decred.org/dcrdex/client/asset"
"decred.org/dcrdex/dex"
"decred.org/dcrdex/dex/calc"
"decred.org/dcrdex/dex/config"
dexdcr "decred.org/dcrdex/dex/networks/dcr"
walletjson "decred.org/dcrwallet/v2/rpc/jsonrpc/types"
_ "decred.org/dcrwallet/v2/wallet/drivers/bdb"
"github.com/decred/dcrd/blockchain/stake/v4"
"github.com/decred/dcrd/blockchain/v4"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/chaincfg/v3"
"github.com/decred/dcrd/dcrec"
"github.com/decred/dcrd/dcrec/secp256k1/v4"
"github.com/decred/dcrd/dcrec/secp256k1/v4/ecdsa"
"github.com/decred/dcrd/dcrutil/v4"
chainjson "github.com/decred/dcrd/rpc/jsonrpc/types/v3"
"github.com/decred/dcrd/txscript/v4"
"github.com/decred/dcrd/txscript/v4/sign"
"github.com/decred/dcrd/txscript/v4/stdaddr"
"github.com/decred/dcrd/txscript/v4/stdscript"
"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
walletTypeDcrwRPC = "dcrwalletRPC"
walletTypeLegacy = "" // dcrwallet RPC prior to wallet types
walletTypeSPV = "SPV"
// confCheckTimeout is the amount of time allowed to check for
// confirmations. If SPV, this might involve pulling a full block.
confCheckTimeout = 4 * time.Second
// acctInternalBranch is the child number used when performing BIP0044 style
// hierarchical deterministic key derivation for the internal branch of an
// account.
acctInternalBranch uint32 = 1
// externalApiUrl is the URL of the external API in case of fallback.
externalApiUrl = "https://explorer.dcrdata.org/insight/api"
// testnetExternalApiUrl is the URL of the testnet external API in case of
// fallback.
testnetExternalApiUrl = "https://testnet.dcrdata.org/insight/api"
// freshFeeAge is the expiry age for cached fee rates of external origin,
// past which fetchFeeFromOracle should be used to refresh the rate.
freshFeeAge = time.Minute
)
var (
// ContractSearchLimit is how far back in time AuditContract in SPV mode
// will search for a contract if no txData is provided. This should be a
// positive duration.
ContractSearchLimit = 48 * time.Hour
// blockTicker is the delay between calls to check for new blocks.
blockTicker = time.Second
peerCountTicker = 5 * time.Second
conventionalConversionFactor = float64(dexdcr.UnitInfo.Conventional.ConversionFactor)
walletBlockAllowance = time.Second * 10
walletOpts = []*asset.ConfigOption{
{
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,
DefaultValue: false,
},
{
Key: "apifeefallback",
DisplayName: "External fee rate estimates",
Description: "Allow fee rate estimation from a block explorer API. " +
"This is useful as a fallback for SPV wallets and RPC wallets " +
"that have recently been started.",
IsBoolean: true,
DefaultValue: false,
},
}
rpcOpts = []*asset.ConfigOption{
{
Key: "account",
DisplayName: "Account Name",
Description: "Primary dcrwallet account name for trading. If automatic mixing of trading funds is " +
"desired, this should be the wallet's mixed account and the other accounts should be set too. " +
"See wallet documentation for mixing wallet setup instructions.",
},
{
Key: "unmixedaccount",
DisplayName: "Change Account Name",
Description: "dcrwallet change account name. This and the 'Temporary Trading Account' should only be " +
"set if mixing is enabled on the wallet. If set, deposit addresses will be from this account and will " +
"be mixed before being available to trade.",
},
{
Key: "tradingaccount",
DisplayName: "Temporary Trading Account",
Description: "dcrwallet account to temporarily store split tx outputs or change from chained swaps in " +
"multi-lot orders. This should only be set if 'Change Account Name' is set.",
},
{
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: defaultRPCCert,
},
}
spvOpts = []*asset.ConfigOption{{
Key: "walletbirthday",
DisplayName: "Wallet Birthday",
Description: "This is the date the wallet starts scanning the blockchain " +
"for transactions related to this wallet. If reconfiguring an existing " +
"wallet, this may start a rescan if the new birthday is older. This " +
"option is disabled if there are currently active DCR trades.",
DefaultValue: defaultWalletBirthdayUnix,
MaxValue: "now",
// This MinValue must be removed if we start supporting importing private keys
MinValue: defaultWalletBirthdayUnix,
IsDate: true,
DisableWhenActive: true,
IsBirthdayConfig: true,
}}
// WalletInfo defines some general information about a Decred wallet.
WalletInfo = &asset.WalletInfo{
Name: "Decred",
Version: version,
SupportedVersions: []uint32{version},
UnitInfo: dexdcr.UnitInfo,
AvailableWallets: []*asset.WalletDefinition{
{
Type: walletTypeSPV,
Tab: "Native",
Description: "Use the built-in SPV wallet",
ConfigOpts: append(spvOpts, walletOpts...),
Seeded: true,
},
{
Type: walletTypeDcrwRPC,
Tab: "External",
Description: "Connect to dcrwallet",
DefaultConfigPath: defaultConfigPath,
ConfigOpts: append(rpcOpts, walletOpts...),
},
},
}
swapFeeBumpKey = "swapfeebump"
splitKey = "swapsplit"
redeemFeeBumpFee = "redeemfeebump"
client http.Client
)
// 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.
type auditInfo struct {
output *output
secretHash []byte
contract []byte
recipient stdaddr.Address // unused?
expiration time.Time
}
// Expiration is the expiration time of the contract, which is the earliest time
// that a refund can be issued for an un-redeemed contract.
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.
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{}
// Check that Driver implements asset.Driver.
var _ asset.Driver = (*Driver)(nil)
var _ asset.Creator = (*Driver)(nil)
// Open creates the DCR exchange wallet. Start the wallet with its Run method.
func (d *Driver) Open(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 "<invalid>", err
}
return fmt.Sprintf("%v:%d", txid, vout), err
}
// Info returns basic information about the wallet and asset.
func (d *Driver) Info() *asset.WalletInfo {
return WalletInfo
}
// Exists checks the existence of the wallet. Part of the Creator interface.
func (d *Driver) Exists(walletType, dataDir string, _ map[string]string, net dex.Network) (bool, error) {
if walletType != walletTypeSPV {
return false, fmt.Errorf("no Decred wallet of type %q available", walletType)
}
chainParams, err := parseChainParams(net)
if err != nil {
return false, err
}
return walletExists(filepath.Join(dataDir, chainParams.Name, "spv"))
}
// Create creates a new SPV wallet.
func (d *Driver) Create(params *asset.CreateWalletParams) error {
if params.Type != walletTypeSPV {
return fmt.Errorf("SPV is the only seeded wallet type. required = %q, requested = %q", walletTypeSPV, params.Type)
}
if len(params.Seed) == 0 {
return errors.New("wallet seed cannot be empty")
}
if len(params.DataDir) == 0 {
return errors.New("must specify wallet data directory")
}
chainParams, err := parseChainParams(params.Net)
if err != nil {
return fmt.Errorf("error parsing chain params: %w", err)
}
recoveryCfg := new(RecoveryCfg)
err = config.Unmapify(params.Settings, recoveryCfg)
if err != nil {
return err
}
return createSPVWallet(params.Pass, params.Seed, params.DataDir, recoveryCfg.NumExternalAddresses,
recoveryCfg.NumInternalAddresses, chainParams)
}
func init() {
asset.Register(BipID, &Driver{})
}
// RecoveryCfg is the information that is transferred from the old wallet
// to the new one when the wallet is recovered.
type RecoveryCfg struct {
NumExternalAddresses uint32 `ini:"numexternaladdr"`
NumInternalAddresses uint32 `ini:"numinternaladdr"`
}
// swapOptions captures the available Swap options. Tagged to be used with
// config.Unmapify to decode e.g. asset.Order.Options.
type swapOptions struct {
Split *bool `ini:"swapsplit"`
FeeBump *float64 `ini:"swapfeebump"`
}
func (s *swapOptions) feeBump() (float64, error) {
bump := 1.0
if s.FeeBump != nil {
bump = *s.FeeBump
if bump > 2.0 {
return 0, fmt.Errorf("fee bump %f is higher than the 2.0 limit", bump)
}
if bump < 1.0 {
return 0, fmt.Errorf("fee bump %f is lower than 1", bump)
}
}
return bump, nil
}
// redeemOptions are order options that apply to redemptions.
type redeemOptions struct {
FeeBump *float64 `ini:"redeemfeebump"`
}
type feeStamped struct {
rate uint64
stamp time.Time
}
// exchangeWalletConfig is the validated, unit-converted, user-configurable
// wallet settings.
type exchangeWalletConfig struct {
primaryAcct string
unmixedAccount string // mixing-enabled wallets only
// tradingAccount (mixing-enabled wallets only) stores utxos reserved for
// executing order matches, the external branch stores split tx outputs,
// internal branch stores chained (non-final) swap change.
tradingAccount string
useSplitTx bool
fallbackFeeRate uint64
feeRateLimit uint64
redeemConfTarget uint64
apiFeeFallback bool
}
// 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 {
reservesMtx sync.RWMutex // frequent reads for balance, infrequent updates
// bondReservesEnforced is used to reserve unspent amounts for upcoming bond
// transactions, and does not include amounts that are currently locked in
// unspent bonds, which are in bondReservesUsed. When bonds are created,
// bondReservesEnforced is decremented and bondReservesUsed are incremented;
// when bonds are refunded, the reverse. bondReservesEnforced may become
// negative: during the unbonding process, if there is insufficient balance
// to cover tier changes due to penalties, or if the user has (pre)reserved
// more than is available.
bondReservesEnforced int64 // set by ReserveBondFunds, modified by bondSpent and bondLocked
bondReservesUsed uint64 // set by RegisterUnspent, modified by bondSpent and bondLocked
// When bondReservesEnforced is non-zero, bondReservesNominal is the
// cumulative of all ReserveBondFunds and RegisterUnspent input amounts,
// with no fee padding. It includes the future and live (currently unspent)
// bond amounts. This amount only changes via ReserveBondFunds, and it is
// used to recognize when all reserves have been released.
bondReservesNominal int64 // only set by ReserveBondFunds
cfgV atomic.Value // *exchangeWalletConfig
ctx context.Context // the asset subsystem starts with Connect(ctx)
wallet Wallet
chainParams *chaincfg.Params
log dex.Logger
network dex.Network
tipChange func(error)
lastPeerCount uint32
peersChange func(uint32, error)
oracleFeesMtx sync.Mutex
oracleFees map[uint64]feeStamped // conf target => fee rate
oracleFailing 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
externalTxMtx sync.RWMutex
externalTxCache map[chainhash.Hash]*externalTx
}
func (dcr *ExchangeWallet) config() *exchangeWalletConfig {
return dcr.cfgV.Load().(*exchangeWalletConfig)
}
// reserves returns the total non-negative amount reserved to inform balance
// reporting and transaction funding.
func (dcr *ExchangeWallet) reserves() uint64 {
dcr.reservesMtx.RLock()
defer dcr.reservesMtx.RUnlock()
if r := dcr.bondReservesEnforced; r > 0 {
return uint64(r)
}
if dcr.bondReservesNominal == 0 { // disabled
return 0
}
// When enforced is negative, we're unbonding. If nominal is still positive,
// we're partially unbonding and we need to report the remaining reserves
// after excess is unbonded, offsetting the negative enforced amount. This
// is the relatively small fee buffer.
if int64(dcr.bondReservesUsed) == dcr.bondReservesNominal {
return uint64(-dcr.bondReservesEnforced)
}
return 0
}
// bondLocked reduces reserves, increases bonded (used) amount.
func (dcr *ExchangeWallet) bondLocked(amt uint64) (reserved int64, unspent uint64) {
dcr.reservesMtx.Lock()
defer dcr.reservesMtx.Unlock()
e0 := dcr.bondReservesEnforced
dcr.bondReservesEnforced -= int64(amt)
dcr.bondReservesUsed += amt
dcr.log.Tracef("bondLocked (%v): enforced %v ==> %v (with bonded = %v / nominal = %v)",
toDCR(amt), toDCRSigned(e0), toDCRSigned(dcr.bondReservesEnforced),
toDCR(dcr.bondReservesUsed), toDCRSigned(dcr.bondReservesNominal))
return dcr.bondReservesEnforced, dcr.bondReservesUsed
}
// bondSpent increases enforce reserves, decreases bonded amount. When the
// tracked unspent amount is reduced to zero, this clears the enforced amount
// (just the remaining fee buffer).
func (dcr *ExchangeWallet) bondSpent(amt uint64) (reserved int64, unspent uint64) {
dcr.reservesMtx.Lock()
defer dcr.reservesMtx.Unlock()
if amt <= dcr.bondReservesUsed {
dcr.bondReservesUsed -= amt
} else {
dcr.log.Errorf("bondSpent: live bonds accounting error, spending bond worth %v with %v known live (zeroing!)",
amt, dcr.bondReservesUsed)
dcr.bondReservesUsed = 0
}
if dcr.bondReservesNominal == 0 { // disabled
return dcr.bondReservesEnforced, dcr.bondReservesUsed // return 0, ...
}
e0 := dcr.bondReservesEnforced
dcr.bondReservesEnforced += int64(amt)
dcr.log.Tracef("bondSpent (%v): enforced %v ==> %v (with bonded = %v / nominal = %v)",
toDCR(amt), toDCRSigned(e0), toDCRSigned(dcr.bondReservesEnforced),
toDCR(dcr.bondReservesUsed), toDCRSigned(dcr.bondReservesNominal))
return dcr.bondReservesEnforced, dcr.bondReservesUsed
}
// Check that ExchangeWallet satisfies the Wallet interface.
var _ asset.Wallet = (*ExchangeWallet)(nil)
var _ asset.FeeRater = (*ExchangeWallet)(nil)
var _ asset.Withdrawer = (*ExchangeWallet)(nil)
var _ asset.LiveReconfigurer = (*ExchangeWallet)(nil)
var _ asset.TxFeeEstimator = (*ExchangeWallet)(nil)
var _ asset.Bonder = (*ExchangeWallet)(nil)
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
}
// NewWallet is the exported constructor by which the DEX will import the
// exchange wallet.
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
// variable.
walletCfg := new(walletConfig)
chainParams, err := loadConfig(cfg.Settings, network, walletCfg)
if err != nil {
return nil, err
}
dcr, err := unconnectedWallet(cfg, walletCfg, chainParams, logger, network)
if err != nil {
return nil, err
}
switch cfg.Type {
case walletTypeDcrwRPC, walletTypeLegacy:
dcr.wallet, err = newRPCWallet(cfg.Settings, logger, network)
if err != nil {
return nil, err
}
case walletTypeSPV:
dcr.wallet, err = openSPVWallet(cfg.DataDir, chainParams, logger)
if err != nil {
return nil, err
}
default:
if makeCustomWallet, ok := customWalletConstructors[cfg.Type]; ok {
dcr.wallet, err = makeCustomWallet(cfg.Settings, chainParams, logger)
if err != nil {
return nil, fmt.Errorf("custom wallet setup error: %v", err)
}
} else {
return nil, fmt.Errorf("unknown wallet type %q", cfg.Type)
}
}
return dcr, nil
}
func getExchangeWalletCfg(dcrCfg *walletConfig, logger dex.Logger) (*exchangeWalletConfig, 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)
primaryAcct := dcrCfg.PrimaryAccount
if primaryAcct == "" {
primaryAcct = defaultAcctName
}
logger.Tracef("Primary account set to %s", primaryAcct)
// Both UnmixedAccount and TradingAccount must be provided if primary
// account is a mixed account. Providing one but not the other is bad
// configuration. If set, the account names will be validated on Connect.
if (dcrCfg.UnmixedAccount == "") != (dcrCfg.TradingAccount == "") {
return nil, fmt.Errorf("'Change Account Name' and 'Temporary Trading Account' MUST "+
"be set to treat %[1]q as a mixed account. If %[1]q is not a mixed account, values "+
"should NOT be set for 'Change Account Name' and 'Temporary Trading Account'",
dcrCfg.PrimaryAccount)
}
if dcrCfg.UnmixedAccount != "" {
switch {
case dcrCfg.PrimaryAccount == dcrCfg.UnmixedAccount:
return nil, fmt.Errorf("Primary Account should not be the same as Change Account")
case dcrCfg.PrimaryAccount == dcrCfg.TradingAccount:
return nil, fmt.Errorf("Primary Account should not be the same as Temporary Trading Account")
case dcrCfg.TradingAccount == dcrCfg.UnmixedAccount:
return nil, fmt.Errorf("Temporary Trading Account should not be the same as Change Account")
}
}
return &exchangeWalletConfig{
primaryAcct: primaryAcct,
unmixedAccount: dcrCfg.UnmixedAccount,
tradingAccount: dcrCfg.TradingAccount,
fallbackFeeRate: fallbackFeesPerByte,
feeRateLimit: feesLimitPerByte,
redeemConfTarget: redeemConfTarget,
useSplitTx: dcrCfg.UseSplitTx,
apiFeeFallback: dcrCfg.ApiFeeFallback,
}, nil
}
// unconnectedWallet returns an ExchangeWallet without a base wallet. The wallet
// should be set before use.
func unconnectedWallet(cfg *asset.WalletConfig, dcrCfg *walletConfig, chainParams *chaincfg.Params, logger dex.Logger, network dex.Network) (*ExchangeWallet, error) {
walletCfg, err := getExchangeWalletCfg(dcrCfg, logger)
if err != nil {
return nil, err
}
w := &ExchangeWallet{
log: logger,
chainParams: chainParams,
network: network,
tipChange: cfg.TipChange,
peersChange: cfg.PeersChange,
fundingCoins: make(map[outPoint]*fundingCoin),
findRedemptionQueue: make(map[outPoint]*findRedemptionReq),
externalTxCache: make(map[chainhash.Hash]*externalTx),
oracleFees: make(map[uint64]feeStamped),
}
w.cfgV.Store(walletCfg)
return w, nil
}
// openSPVWallet opens the previously created native SPV wallet.
func openSPVWallet(dataDir string, chainParams *chaincfg.Params, log dex.Logger) (*spvWallet, error) {
dir := filepath.Join(dataDir, chainParams.Name, "spv")
if exists, err := walletExists(dir); err != nil {
return nil, err
} else if !exists {
return nil, fmt.Errorf("wallet at %q doesn't exists", dir)
}
return &spvWallet{
acctNum: defaultAcct,
acctName: defaultAcctName,
dir: dir,
chainParams: chainParams,
log: log.SubLogger("SPV"),
blockCache: blockCache{
blocks: make(map[chainhash.Hash]*cachedBlock),
},
tipChan: make(chan *block, 1),
}, 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.
func (dcr *ExchangeWallet) Connect(ctx context.Context) (*sync.WaitGroup, error) {
// rpclog(dcr.log)
dcr.ctx = ctx
err := dcr.wallet.Connect(ctx)
if err != nil {
return nil, err
}
// The wallet is connected now, so if any of the following checks
// fails and we return with a non-nil error, we must disconnect the
// wallet.
// This is especially important as the wallet may be using an rpc
// connection which was established above and if we do not disconnect,
// subsequent reconnect attempts will be met with "websocket client
// has already connected".
var success bool
defer func() {
if !success {
dcr.wallet.Disconnect()
}
}()
// Validate accounts early on to prevent errors later.
for _, acct := range dcr.allAccounts() {
if acct == "" {
continue
}
_, err = dcr.wallet.AccountUnlocked(ctx, acct)
if err != nil {
return nil, fmt.Errorf("unexpected AccountUnlocked error for %q account: %w", acct, 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)
}
success = true // All good, don't disconnect the wallet when this method returns.
// NotifyOnTipChange will return false if the wallet does not support
// tip change notification. We'll use dcr.monitorBlocks below if so.
monitoringBlocks := dcr.wallet.NotifyOnTipChange(ctx, dcr.handleTipChange)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
if !monitoringBlocks {
dcr.monitorBlocks(ctx)
} else {
<-ctx.Done() // just wait for shutdown signal
}
dcr.shutdown()
}()
wg.Add(1)
go func() {
defer wg.Done()
dcr.monitorPeers(ctx)
}()
return &wg, nil
}
// Reconfigure attempts to reconfigure the wallet.
func (dcr *ExchangeWallet) Reconfigure(ctx context.Context, cfg *asset.WalletConfig, currentAddress string) (restart bool, err error) {
dcrCfg := new(walletConfig)
_, err = loadConfig(cfg.Settings, dcr.network, dcrCfg)
if err != nil {
return false, err
}
var depositAccount string
if dcrCfg.UnmixedAccount != "" {
depositAccount = dcrCfg.UnmixedAccount
} else {
depositAccount = dcrCfg.PrimaryAccount
}
restart, err = dcr.wallet.Reconfigure(ctx, cfg, dcr.network, currentAddress, depositAccount)
if err != nil || restart {
return restart, err
}
exchangeWalletCfg, err := getExchangeWalletCfg(dcrCfg, dcr.log)
if err != nil {
return false, err
}
dcr.cfgV.Store(exchangeWalletCfg)
return false, nil
}
// depositAccount returns the account that may be used to receive funds into
// the wallet, either by a direct deposit action or via redemption or refund.
func (dcr *ExchangeWallet) depositAccount() string {
cfg := dcr.config()
if cfg.unmixedAccount != "" {
return cfg.unmixedAccount
}
return cfg.primaryAcct
}
// fundingAccounts returns the primary account along with any configured trading
// account which may contain spendable outputs (split tx outputs or chained swap
// change).
func (dcr *ExchangeWallet) fundingAccounts() []string {
cfg := dcr.config()
if cfg.unmixedAccount == "" {
return []string{cfg.primaryAcct}
}
return []string{cfg.primaryAcct, cfg.tradingAccount}
}
func (dcr *ExchangeWallet) allAccounts() []string {
cfg := dcr.config()
if cfg.unmixedAccount == "" {
return []string{cfg.primaryAcct}
}
return []string{cfg.primaryAcct, cfg.tradingAccount, cfg.unmixedAccount}
}
// OwnsDepositAddress indicates if the provided address can be used to deposit
// funds into the wallet.
func (dcr *ExchangeWallet) OwnsDepositAddress(address string) (bool, error) {
addr, err := stdaddr.DecodeAddress(address, dcr.chainParams)
if err != nil {
return false, err
}
return dcr.wallet.AccountOwnsAddress(dcr.ctx, addr, dcr.depositAccount())
}
func (dcr *ExchangeWallet) balance() (*asset.Balance, error) {