forked from decred/dcrdex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
btc.go
6262 lines (5588 loc) · 215 KB
/
btc.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 btc
import (
"bytes"
"context"
"crypto/sha256"
"encoding/binary"
"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"
dexbtc "decred.org/dcrdex/dex/networks/btc"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/ecdsa"
"github.com/btcsuite/btcd/btcjson"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcwallet/wallet"
"github.com/decred/dcrd/dcrec/secp256k1/v4"
"github.com/decred/dcrd/rpcclient/v7"
)
const (
version = 0
// BipID is the BIP-0044 asset ID.
BipID = 0
// The default fee is passed to the user as part of the asset.WalletInfo
// structure.
defaultFee = 100
// defaultFeeRateLimit is the default value for the feeratelimit.
defaultFeeRateLimit = 1400
// defaultRedeemConfTarget is the default redeem transaction confirmation
// target in blocks used by estimatesmartfee to get the optimal fee for a
// redeem transaction.
defaultRedeemConfTarget = 2
minNetworkVersion = 210000
minProtocolVersion = 70015
// version which descriptor wallets have been introduced.
minDescriptorVersion = 220000
// splitTxBaggage is the total number of additional bytes associated with
// using a split transaction to fund a swap.
splitTxBaggage = dexbtc.MinimumTxOverhead + dexbtc.RedeemP2PKHInputSize + 2*dexbtc.P2PKHOutputSize
// splitTxBaggageSegwit it the analogue of splitTxBaggage for segwit.
// We include the 2 bytes for marker and flag.
splitTxBaggageSegwit = dexbtc.MinimumTxOverhead + 2*dexbtc.P2WPKHOutputSize +
dexbtc.RedeemP2WPKHInputSize + ((dexbtc.RedeemP2WPKHInputWitnessWeight + dexbtc.SegwitMarkerAndFlagWeight + 3) / 4)
walletTypeLegacy = ""
walletTypeRPC = "bitcoindRPC"
walletTypeSPV = "SPV"
walletTypeElectrum = "electrumRPC"
swapFeeBumpKey = "swapfeebump"
splitKey = "swapsplit"
splitBufferKey = "splitbuffer"
overfundBufferKey = "overfundbuffer"
redeemFeeBumpFee = "redeemfeebump"
// externalApiUrl is the URL of the external API in case of fallback.
externalApiUrl = "https://mempool.space/api/"
// testnetExternalApiUrl is the URL of the testnet external API in case of
// fallback.
testnetExternalApiUrl = "https://mempool.space/testnet/api/"
// requiredRedeemConfirms is the amount of confirms a redeem transaction
// needs before the trade is considered confirmed. The redeem is
// monitored until this number of confirms is reached.
requiredRedeemConfirms = 1
)
const (
minTimeBeforeAcceleration uint64 = 3600 // 1 hour
)
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
walletBlockAllowance = time.Second * 10
conventionalConversionFactor = float64(dexbtc.UnitInfo.Conventional.ConversionFactor)
ElectrumConfigOpts = []*asset.ConfigOption{
{
Key: "rpcuser",
DisplayName: "JSON-RPC Username",
Description: "Electrum's 'rpcuser' setting",
},
{
Key: "rpcpassword",
DisplayName: "JSON-RPC Password",
Description: "Electrum's 'rpcpassword' setting",
NoEcho: true,
},
{
Key: "rpcport",
DisplayName: "JSON-RPC Port",
Description: "Electrum's 'rpcport' (if not set with rpcbind)",
},
{
Key: "rpcbind", // match RPCConfig struct field tags
DisplayName: "JSON-RPC Address",
Description: "Electrum's 'rpchost' <addr> or <addr>:<port>",
DefaultValue: "127.0.0.1",
},
{
Key: "walletname", // match RPCConfig struct field tags
DisplayName: "Wallet File",
Description: "Full path to the wallet file (empty is default_wallet)",
DefaultValue: "", // empty string, not a nil interface
},
}
// 02 Jun 21 21:12 CDT
defaultWalletBirthdayUnix = 1622668320
defaultWalletBirthday = time.Unix(int64(defaultWalletBirthdayUnix), 0)
rpcWalletDefinition = &asset.WalletDefinition{
Type: walletTypeRPC,
Tab: "External",
Description: "Connect to bitcoind",
DefaultConfigPath: dexbtc.SystemConfigPath("bitcoin"),
ConfigOpts: append(RPCConfigOpts("Bitcoin", "8332"), CommonConfigOpts("BTC", true)...),
}
spvWalletDefinition = &asset.WalletDefinition{
Type: walletTypeSPV,
Tab: "Native",
Description: "Use the built-in SPV wallet",
ConfigOpts: append(SPVConfigOpts("BTC"), CommonConfigOpts("BTC", true)...),
Seeded: true,
}
electrumWalletDefinition = &asset.WalletDefinition{
Type: walletTypeElectrum,
Tab: "Electrum (external)",
Description: "Use an external Electrum Wallet",
// json: DefaultConfigPath: filepath.Join(btcutil.AppDataDir("electrum", false), "config"), // e.g. ~/.electrum/config
ConfigOpts: append(append(ElectrumConfigOpts, CommonConfigOpts("BTC", false)...), apiFallbackOpt(false)),
}
// WalletInfo defines some general information about a Bitcoin wallet.
WalletInfo = &asset.WalletInfo{
Name: "Bitcoin",
Version: version,
SupportedVersions: []uint32{version},
UnitInfo: dexbtc.UnitInfo,
AvailableWallets: []*asset.WalletDefinition{
spvWalletDefinition,
rpcWalletDefinition,
electrumWalletDefinition,
},
LegacyWalletIndex: 1,
}
)
func apiFallbackOpt(defaultV bool) *asset.ConfigOption {
return &asset.ConfigOption{
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: defaultV,
}
}
// CommonConfigOpts are the common options that the Wallets recognize.
func CommonConfigOpts(symbol string /* upper-case */, withApiFallback bool) []*asset.ConfigOption {
opts := []*asset.ConfigOption{
{
Key: "fallbackfee",
DisplayName: "Fallback fee rate",
Description: fmt.Sprintf("The fee rate to use for sending or withdrawing funds and fee payment when"+
" estimatesmartfee is not available. Units: %s/kB", symbol),
DefaultValue: defaultFee * 1000 / 1e8,
},
{
Key: "feeratelimit",
DisplayName: "Highest acceptable fee rate",
Description: fmt.Sprintf("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: %s/kB", symbol),
DefaultValue: defaultFeeRateLimit * 1000 / 1e8,
},
{
Key: "redeemconftarget",
DisplayName: "Redeem confirmation target",
Description: "The target number of blocks for the redeem transaction " +
"to be mined. Used to set the transaction's fee rate. " +
"(default: 2 blocks)",
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.",
IsBoolean: true,
DefaultValue: false,
},
}
if withApiFallback {
opts = append(opts, apiFallbackOpt(true))
}
return opts
}
// SPVConfigOpts are the options common to built-in SPV wallets.
func SPVConfigOpts(symbol string) []*asset.ConfigOption {
return []*asset.ConfigOption{{
Key: "walletbirthday",
DisplayName: "Wallet Birthday",
Description: fmt.Sprintf("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 %s trades.", symbol),
DefaultValue: defaultWalletBirthdayUnix,
MaxValue: "now",
// This MinValue must be removed if we start supporting importing private keys
MinValue: defaultWalletBirthdayUnix,
IsDate: true,
DisableWhenActive: true,
IsBirthdayConfig: true,
}}
}
// RPCConfigOpts are the settings that are used to connect to and external RPC
// wallet.
func RPCConfigOpts(name, rpcPort string) []*asset.ConfigOption {
return []*asset.ConfigOption{
{
Key: "walletname",
DisplayName: "Wallet Name",
Description: "The wallet name",
},
{
Key: "rpcuser",
DisplayName: "JSON-RPC Username",
Description: fmt.Sprintf("%s's 'rpcuser' setting", name),
},
{
Key: "rpcpassword",
DisplayName: "JSON-RPC Password",
Description: fmt.Sprintf("%s's 'rpcpassword' setting", name),
NoEcho: true,
},
{
Key: "rpcbind",
DisplayName: "JSON-RPC Address",
Description: "<addr> or <addr>:<port> (default 'localhost')",
DefaultValue: "127.0.0.1",
},
{
Key: "rpcport",
DisplayName: "JSON-RPC Port",
Description: "Port for RPC connections (if not set in rpcbind)",
DefaultValue: rpcPort,
},
}
}
// TxInSigner is a transaction input signer. In addition to the standard Bitcoin
// arguments, TxInSigner receives all values and pubkey scripts for previous
// outpoints spent in this transaction.
type TxInSigner func(tx *wire.MsgTx, idx int, subScript []byte, hashType txscript.SigHashType,
key *btcec.PrivateKey, vals []int64, prevScripts [][]byte) ([]byte, error)
// BTCCloneCFG holds clone specific parameters.
type BTCCloneCFG struct {
WalletCFG *asset.WalletConfig
MinNetworkVersion uint64
WalletInfo *asset.WalletInfo
Symbol string
Logger dex.Logger
Network dex.Network
ChainParams *chaincfg.Params
// Ports is the default wallet RPC tcp ports used when undefined in
// WalletConfig.
Ports dexbtc.NetPorts
DefaultFallbackFee uint64 // sats/byte
DefaultFeeRateLimit uint64 // sats/byte
// LegacyBalance is for clones that don't yet support the 'getbalances' RPC
// call.
LegacyBalance bool
// ZECStyleBalance is for clones that don't support getbalances or
// walletinfo, and don't take an account name argument.
ZECStyleBalance bool
// If segwit is false, legacy addresses and contracts will be used. This
// setting must match the configuration of the server's asset backend.
Segwit bool
// LegacyRawFeeLimit can be true if the RPC only supports the boolean
// allowHighFees argument to the sendrawtransaction RPC.
LegacyRawFeeLimit bool
// InitTxSize is the size of a swap initiation transaction with a single
// input i.e. chained swaps.
InitTxSize uint32
// InitTxSizeBase is the size of a swap initiation transaction with no
// inputs. This is used to accurately determine the size of the first swap
// in a chain when considered with the actual inputs.
InitTxSizeBase uint32
// PrivKeyFunc is an optional function to get a private key for an address
// from the wallet. If not given the usual dumpprivkey RPC will be used.
PrivKeyFunc func(addr string) (*btcec.PrivateKey, error)
// AddrFunc is an optional function to produce new addresses. If AddrFunc
// is provided, the regular getnewaddress and getrawchangeaddress methods
// will not be used, and AddrFunc will be used instead.
AddrFunc func() (btcutil.Address, error)
// AddressDecoder is an optional argument that can decode an address string
// into btcutil.Address. If AddressDecoder is not supplied,
// btcutil.DecodeAddress will be used.
AddressDecoder dexbtc.AddressDecoder // string => btcutil.Address
// AddressStringer is an optional argument that can encode a btcutil.Address
// into an address string. If AddressStringer is not supplied, the
// (btcutil.Address).String method will be used.
AddressStringer dexbtc.AddressStringer // btcutil.Address => string, may be an override or just the String method
// BlockDeserializer can be used in place of (*wire.MsgBlock).Deserialize.
BlockDeserializer func([]byte) (*wire.MsgBlock, error)
// ArglessChangeAddrRPC can be true if the getrawchangeaddress takes no
// address-type argument.
ArglessChangeAddrRPC bool
// NonSegwitSigner can be true if the transaction signature hash data is not
// the standard for non-segwit Bitcoin. If nil, txscript.
NonSegwitSigner TxInSigner
// ConnectFunc, if provided, is called by the RPC client at the end of the
// (*rpcClient).connect method. Errors returned by ConnectFunc will preclude
// the starting of goroutines associated with block and peer monitoring.
ConnectFunc func() error
// FeeEstimator provides a way to get fees given an RawRequest-enabled
// client and a confirmation target.
FeeEstimator func(context.Context, RawRequester, uint64) (uint64, error)
// ExternalFeeEstimator should be supplied if the clone provides the
// apifeefallback ConfigOpt. TODO: confTarget uint64
ExternalFeeEstimator func(context.Context, dex.Network) (uint64, error)
// OmitAddressType causes the address type (bech32, legacy) to be omitted
// from calls to getnewaddress.
OmitAddressType bool
// LegacySignTxRPC causes the RPC client to use the signrawtransaction
// endpoint instead of the signrawtransactionwithwallet endpoint.
LegacySignTxRPC bool
// BooleanGetBlockRPC causes the RPC client to use a boolean second argument
// for the getblock endpoint, instead of Bitcoin's numeric.
BooleanGetBlockRPC bool
// NumericGetRawRPC uses a numeric boolean indicator for the
// getrawtransaction RPC.
NumericGetRawRPC bool
// LegacyValidateAddressRPC uses the validateaddress endpoint instead of
// getaddressinfo in order to discover ownership of an address.
LegacyValidateAddressRPC bool
// SingularWallet signals that the node software supports only one wallet,
// so the RPC endpoint does not have a /wallet/{walletname} path.
SingularWallet bool
// UnlockSpends manually unlocks outputs as they are spent. Most assets will
// unlock wallet outputs automatically as they are spent.
UnlockSpends bool
// ConstantDustLimit is used if an asset enforces a dust limit (minimum
// output value) that doesn't depend on the serialized size of the output.
// If ConstantDustLimit is zero, dexbtc.IsDust is used.
ConstantDustLimit uint64
// TxDeserializer is an optional function used to deserialize a transaction.
TxDeserializer func([]byte) (*wire.MsgTx, error)
// TxSerializer is an optional function used to serialize a transaction.
TxSerializer func(*wire.MsgTx) ([]byte, error)
// TxHasher is a function that generates a tx hash from a MsgTx.
TxHasher func(*wire.MsgTx) *chainhash.Hash
// TxSizeCalculator is an optional function that will be used to calculate
// the size of a transaction.
TxSizeCalculator func(*wire.MsgTx) uint64
// TxVersion is an optional function that returns a version to use for
// new transactions.
TxVersion func() int32
// ManualMedianTime causes the median time to be calculated manually.
ManualMedianTime bool
// OmitRPCOptionsArg is for clones that don't take an options argument.
OmitRPCOptionsArg bool
// AssetID is the asset ID of the clone.
AssetID uint32
}
// 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 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
value uint64
}
// newOutput is the constructor for an output.
func newOutput(txHash *chainhash.Hash, vout uint32, value uint64) *output {
return &output{
pt: newOutPoint(txHash, vout),
value: value,
}
}
// 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 BTC, 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 wire.OutPoint's Hash.
func (op *output) txHash() *chainhash.Hash {
return &op.pt.txHash
}
// vout returns the wire.OutPoint's Index.
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())
}
// auditInfo is information about a swap contract on that blockchain.
type auditInfo struct {
output *output
recipient btcutil.Address // caution: use stringAddr, not the Stringer
contract []byte
secretHash []byte
expiration time.Time
}
// Expiration returns 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
}
// Coin returns the output as an asset.Coin.
func (ci *auditInfo) Coin() asset.Coin {
return ci.output
}
// Contract is the contract script.
func (ci *auditInfo) Contract() dex.Bytes {
return ci.contract
}
// SecretHash is the contract's secret hash.
func (ci *auditInfo) SecretHash() dex.Bytes {
return ci.secretHash
}
// 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
}
// Contract 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
}
// RPCConfig adds a wallet name to the basic configuration.
type RPCConfig struct {
dexbtc.RPCConfig `ini:",extends"`
WalletName string `ini:"walletname"`
}
// RPCWalletConfig is a combination of RPCConfig and WalletConfig. Used for a
// wallet based on a bitcoind-like RPC API.
type RPCWalletConfig struct {
RPCConfig `ini:",extends"`
WalletConfig `ini:",extends"`
}
// WalletConfig are wallet-level configuration settings.
type WalletConfig struct {
UseSplitTx bool `ini:"txsplit"`
FallbackFeeRate float64 `ini:"fallbackfee"`
FeeRateLimit float64 `ini:"feeratelimit"`
RedeemConfTarget uint64 `ini:"redeemconftarget"`
ActivelyUsed bool `ini:"special_activelyUsed"` // injected by core
Birthday uint64 `ini:"walletbirthday"` // SPV
ApiFeeFallback bool `ini:"apifeefallback"`
}
// AdjustedBirthday converts WalletConfig.Birthday to a time.Time, and adjusts
// it so that defaultWalletBirthday <= WalletConfig.Birthday <= now.
func (cfg *WalletConfig) AdjustedBirthday() time.Time {
bday := time.Unix(int64(cfg.Birthday), 0)
now := time.Now()
if defaultWalletBirthday.After(bday) {
return defaultWalletBirthday
} else if bday.After(now) {
return now
} else {
return bday
}
}
func readBaseWalletConfig(walletCfg *WalletConfig) (*baseWalletConfig, error) {
cfg := &baseWalletConfig{}
// if values not specified, use defaults. As they are validated as BTC/KB,
// we need to convert first.
if walletCfg.FallbackFeeRate == 0 {
walletCfg.FallbackFeeRate = float64(defaultFee) * 1000 / 1e8
}
if walletCfg.FeeRateLimit == 0 {
walletCfg.FeeRateLimit = float64(defaultFeeRateLimit) * 1000 / 1e8
}
if walletCfg.RedeemConfTarget == 0 {
walletCfg.RedeemConfTarget = defaultRedeemConfTarget
}
// If set in the user config, the fallback fee will be in conventional units
// per kB, e.g. BTC/kB. Translate that to sats/byte.
cfg.fallbackFeeRate = toSatoshi(walletCfg.FallbackFeeRate / 1000)
if cfg.fallbackFeeRate == 0 {
return nil, fmt.Errorf("fallback fee rate limit is smaller than the minimum 1000 sats/byte: %v",
walletCfg.FallbackFeeRate)
}
// If set in the user config, the fee rate limit will be in units of BTC/KB.
// Convert to sats/byte & error if value is smaller than smallest unit.
cfg.feeRateLimit = toSatoshi(walletCfg.FeeRateLimit / 1000)
if cfg.feeRateLimit == 0 {
return nil, fmt.Errorf("fee rate limit is smaller than the minimum 1000 sats/byte: %v",
walletCfg.FeeRateLimit)
}
cfg.redeemConfTarget = walletCfg.RedeemConfTarget
cfg.useSplitTx = walletCfg.UseSplitTx
cfg.apiFeeFallback = walletCfg.ApiFeeFallback
return cfg, nil
}
// readRPCWalletConfig parses the settings map into a *RPCWalletConfig.
func readRPCWalletConfig(settings map[string]string, symbol string, net dex.Network, ports dexbtc.NetPorts) (cfg *RPCWalletConfig, err error) {
cfg = new(RPCWalletConfig)
err = config.Unmapify(settings, cfg)
if err != nil {
return nil, fmt.Errorf("error parsing rpc wallet config: %w", err)
}
err = dexbtc.CheckRPCConfig(&cfg.RPCConfig.RPCConfig, symbol, net, ports)
return
}
// parseRPCWalletConfig parses a *RPCWalletConfig from the settings map and
// creates the unconnected *rpcclient.Client.
func parseRPCWalletConfig(settings map[string]string, symbol string, net dex.Network,
ports dexbtc.NetPorts, singularWallet bool) (*RPCWalletConfig, *rpcclient.Client, error) {
cfg, err := readRPCWalletConfig(settings, symbol, net, ports)
if err != nil {
return nil, nil, err
}
cl, err := newRPCConnection(cfg, singularWallet)
if err != nil {
return nil, nil, err
}
return cfg, cl, nil
}
// newRPCConnection creates a new RPC client.
func newRPCConnection(cfg *RPCWalletConfig, singularWallet bool) (*rpcclient.Client, error) {
endpoint := cfg.RPCBind
if !singularWallet {
endpoint += "/wallet/" + cfg.WalletName
}
return rpcclient.New(&rpcclient.ConnConfig{
HTTPPostMode: true,
DisableTLS: true,
Host: endpoint,
User: cfg.RPCUser,
Pass: cfg.RPCPass,
}, nil)
}
// Driver implements asset.Driver.
type Driver struct{}
// Check that Driver implements Driver and Creator.
var _ asset.Driver = (*Driver)(nil)
var _ asset.Creator = (*Driver)(nil)
// Exists checks the existence of the wallet. Part of the Creator interface, so
// only used for wallets with WalletDefinition.Seeded = true.
func (d *Driver) Exists(walletType, dataDir string, settings map[string]string, net dex.Network) (bool, error) {
if walletType != walletTypeSPV {
return false, fmt.Errorf("no Bitcoin wallet of type %q available", walletType)
}
chainParams, err := parseChainParams(net)
if err != nil {
return false, err
}
dir := filepath.Join(dataDir, chainParams.Name)
// timeout and recoverWindow arguments borrowed from btcwallet directly.
loader := wallet.NewLoader(chainParams, dir, true, dbTimeout, 250)
return loader.WalletExists()
}
// createConfig combines the configuration settings used for wallet creation.
type createConfig struct {
WalletConfig `ini:",extends"`
RecoveryCfg `ini:",extends"`
}
// 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: %w", err)
}
cfg := new(createConfig)
err = config.Unmapify(params.Settings, cfg)
if err != nil {
return err
}
_, err = readBaseWalletConfig(&cfg.WalletConfig)
if err != nil {
return err
}
dir := filepath.Join(params.DataDir, chainParams.Name)
return createSPVWallet(params.Pass, params.Seed, cfg.AdjustedBirthday(), dir,
params.Logger, cfg.NumExternalAddresses, cfg.NumInternalAddresses, chainParams)
}
// Open opens or connects to the BTC 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
// Bitcoin.
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
}
// 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
}
// fundMultiOptions are the possible order options when calling FundMultiOrder.
type fundMultiOptions struct {
// Split, if true, and multi-order cannot be funded with the existing UTXOs
// in the wallet without going over the maxLock limit, a split transaction
// will be created with one output per order.
//
// Use the splitKey const defined above in the options map to set this option.
Split *bool
// SplitBuffer, if set, will instruct the wallet to add a buffer onto each
// output of the multi-order split transaction (if the split is needed).
// SplitBuffer is defined as a percentage of the output. If a .1 BTC output
// is required for an order and SplitBuffer is set to 5, a .105 BTC output
// will be created.
//
// The motivation for this is to assist market makers in having to do the
// least amount of splits as possible. It is useful when BTC is the quote
// asset on a market, and the price is increasing. During a market maker's
// operation, it will frequently have to cancel and replace orders as the
// rate moves. If BTC is the quote asset on a market, and the rate has
// lightly increased, the market maker will need to lock slightly more of
// the quote asset for the same amount of lots of the base asset. If there
// is no split buffer, this may necessitate a new split transaction.
//
// Use the splitBufferKey const defined above in the options map to set this.
SplitBuffer *uint64
// OverfundBuffer is the allowable amount of overfunding allowed in a
// single order. OverfundBuffer must be > SplitBuffer. If OverfundBuffer
// is not set or set to zero, the value will be set to SplitBuffer * 2.
OverfundBuffer *uint64
}
func decodeFundMultiOptions(options map[string]string) (*fundMultiOptions, error) {
opts := new(fundMultiOptions)
if options == nil {
return opts, nil
}
if split, ok := options[splitKey]; ok {
b, err := strconv.ParseBool(split)
if err != nil {
return nil, fmt.Errorf("error parsing split option: %w", err)
}
opts.Split = &b
}
if splitBuffer, ok := options[splitBufferKey]; ok {
b, err := strconv.ParseUint(splitBuffer, 10, 64)
if err != nil {
return nil, fmt.Errorf("error parsing split buffer option: %w", err)
}
opts.SplitBuffer = &b
}
if overfundBuffer, ok := options[overfundBufferKey]; ok {
b, err := strconv.ParseUint(overfundBuffer, 10, 64)
if err != nil {
return nil, fmt.Errorf("error parsing overfund buffer option: %w", err)
}
opts.OverfundBuffer = &b
}
return opts, nil
}
// redeemOptions are order options that apply to redemptions.
type redeemOptions struct {
FeeBump *float64 `ini:"redeemfeebump"`
}
func init() {
asset.Register(BipID, &Driver{})
}
// baseWalletConfig is the validated, unit-converted, user-configurable wallet
// settings.
type baseWalletConfig struct {
fallbackFeeRate uint64 // atoms/byte
feeRateLimit uint64 // atoms/byte
redeemConfTarget uint64
useSplitTx bool
apiFeeFallback bool
}
// baseWallet is a wallet backend for Bitcoin. The backend is how the DEX
// client app communicates with the BTC blockchain and wallet. baseWallet
// satisfies the dex.Wallet interface.
type baseWallet struct {
// 64-bit atomic variables first. See
// https://golang.org/pkg/sync/atomic/#pkg-note-BUG
tipAtConnect int64
cfgV atomic.Value // *baseWalletConfig
node Wallet
walletInfo *asset.WalletInfo
cloneParams *BTCCloneCFG
chainParams *chaincfg.Params
log dex.Logger
symbol string
tipChange func(error)
lastPeerCount uint32
peersChange func(uint32, error)
minNetworkVersion uint64
dustLimit uint64
initTxSize uint64
initTxSizeBase uint64
useLegacyBalance bool
zecStyleBalance bool
segwit bool
signNonSegwit TxInSigner
localFeeRate func(context.Context, RawRequester, uint64) (uint64, error)
externalFeeRate func(context.Context, dex.Network) (uint64, error)
decodeAddr dexbtc.AddressDecoder
deserializeTx func([]byte) (*wire.MsgTx, error)
serializeTx func(*wire.MsgTx) ([]byte, error)
calcTxSize func(*wire.MsgTx) uint64
hashTx func(*wire.MsgTx) *chainhash.Hash
stringAddr dexbtc.AddressStringer
txVersion func() int32
Network dex.Network
ctx context.Context // the asset subsystem starts with Connect(ctx)
// TODO: remove currentTip and the mutex, and make it local to the
// watchBlocks->reportNewTip call stack. The tests are reliant on current
// internals, so this will take a little work.
tipMtx sync.RWMutex
currentTip *block
// Coins returned by Fund are cached for quick reference.
fundingMtx sync.RWMutex
fundingCoins map[outPoint]*utxo
findRedemptionMtx sync.RWMutex
findRedemptionQueue map[outPoint]*findRedemptionReq
reservesMtx sync.RWMutex // frequent reads for balance, infrequent updates
// bondReservesEnforced is used to reserve unspent amounts for upcoming bond
// transactions, including projected transaction fees, 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.
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
}
func (w *baseWallet) fallbackFeeRate() uint64 {
return w.cfgV.Load().(*baseWalletConfig).fallbackFeeRate
}
func (w *baseWallet) feeRateLimit() uint64 {
return w.cfgV.Load().(*baseWalletConfig).feeRateLimit
}
func (w *baseWallet) redeemConfTarget() uint64 {
return w.cfgV.Load().(*baseWalletConfig).redeemConfTarget
}
func (w *baseWallet) useSplitTx() bool {
return w.cfgV.Load().(*baseWalletConfig).useSplitTx
}
func (w *baseWallet) apiFeeFallback() bool {
return w.cfgV.Load().(*baseWalletConfig).apiFeeFallback
}
type intermediaryWallet struct {
*baseWallet
txFeeEstimator txFeeEstimator
tipRedeemer tipRedemptionWallet
}
// ExchangeWalletSPV embeds a ExchangeWallet, but also provides the Rescan
// method to implement asset.Rescanner.
type ExchangeWalletSPV struct {
*intermediaryWallet
*authAddOn
spvNode *spvWallet
}
// ExchangeWalletFullNode implements Wallet and adds the FeeRate method.
type ExchangeWalletFullNode struct {
*intermediaryWallet
*authAddOn
}
type ExchangeWalletNoAuth struct {
*intermediaryWallet
}
// ExchangeWalletAccelerator implements the Accelerator interface on an
// ExchangeWalletFullNode.
type ExchangeWalletAccelerator struct {
*ExchangeWalletFullNode
}
// Check that wallets satisfy their supported interfaces.
var _ asset.Wallet = (*intermediaryWallet)(nil)
var _ asset.Accelerator = (*ExchangeWalletAccelerator)(nil)
var _ asset.Accelerator = (*ExchangeWalletSPV)(nil)
var _ asset.Withdrawer = (*baseWallet)(nil)
var _ asset.FeeRater = (*baseWallet)(nil)
var _ asset.Rescanner = (*ExchangeWalletSPV)(nil)
var _ asset.LogFiler = (*ExchangeWalletSPV)(nil)
var _ asset.Recoverer = (*ExchangeWalletSPV)(nil)
var _ asset.PeerManager = (*ExchangeWalletSPV)(nil)
var _ asset.TxFeeEstimator = (*intermediaryWallet)(nil)
var _ asset.Bonder = (*baseWallet)(nil)
var _ asset.Authenticator = (*ExchangeWalletSPV)(nil)
var _ asset.Authenticator = (*ExchangeWalletFullNode)(nil)
var _ asset.Authenticator = (*ExchangeWalletAccelerator)(nil)
var _ asset.MultiOrderFunder = (*baseWallet)(nil)
// 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"`
}
// GetRecoveryCfg returns information that will help the wallet get
// back to its previous state after it is recreated. Part of the
// Recoverer interface.
func (btc *ExchangeWalletSPV) GetRecoveryCfg() (map[string]string, error) {
internal, external, err := btc.spvNode.numDerivedAddresses()
if err != nil {
return nil, err
}