-
Notifications
You must be signed in to change notification settings - Fork 84
/
btc_test.go
2970 lines (2650 loc) · 82.1 KB
/
btc_test.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
//go:build !spvlive
// +build !spvlive
package btc
import (
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"math/rand"
"os"
"sync"
"testing"
"time"
"decred.org/dcrdex/client/asset"
"decred.org/dcrdex/dex"
"decred.org/dcrdex/dex/calc"
dexbtc "decred.org/dcrdex/dex/networks/btc"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/btcjson"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
)
var (
tLogger dex.Logger
tCtx context.Context
tLotSize uint64 = 1e6 // 0.01 BTC
tRateStep uint64 = 10
tBTC = &dex.Asset{
ID: 0,
Symbol: "btc",
Version: version,
SwapSize: dexbtc.InitTxSize,
SwapSizeBase: dexbtc.InitTxSizeBase,
MaxFeeRate: 34,
SwapConf: 1,
}
optimalFeeRate uint64 = 24
tErr = fmt.Errorf("test error")
tTxID = "308e9a3675fc3ea3862b7863eeead08c621dcc37ff59de597dd3cdab41450ad9"
tTxHash *chainhash.Hash
tP2PKHAddr = "1Bggq7Vu5oaoLFV1NNp5KhAzcku83qQhgi"
tP2PKH []byte
tP2WPKH []byte
tP2WPKHAddr = "bc1qq49ypf420s0kh52l9pk7ha8n8nhsugdpculjas"
feeSuggestion uint64 = 10
)
func btcAddr(segwit bool) btcutil.Address {
var addr btcutil.Address
if segwit {
addr, _ = btcutil.DecodeAddress(tP2WPKHAddr, &chaincfg.MainNetParams)
} else {
addr, _ = btcutil.DecodeAddress(tP2PKHAddr, &chaincfg.MainNetParams)
}
return addr
}
func randBytes(l int) []byte {
b := make([]byte, l)
rand.Read(b)
return b
}
func signFuncRaw(t *testing.T, params []json.RawMessage, sizeTweak int, sigComplete, segwit bool) (json.RawMessage, error) {
signTxRes := SignTxResult{
Complete: sigComplete,
}
var msgHex string
err := json.Unmarshal(params[0], &msgHex)
if err != nil {
t.Fatalf("error unmarshaling transaction hex: %v", err)
}
msgBytes, _ := hex.DecodeString(msgHex)
txReader := bytes.NewReader(msgBytes)
msgTx := wire.NewMsgTx(wire.TxVersion)
err = msgTx.Deserialize(txReader)
if err != nil {
t.Fatalf("error deserializing contract: %v", err)
}
signFunc(msgTx, sizeTweak, segwit)
buf := new(bytes.Buffer)
err = msgTx.Serialize(buf)
if err != nil {
t.Fatalf("error serializing contract: %v", err)
}
signTxRes.Hex = buf.Bytes()
return mustMarshal(signTxRes), nil
}
func signFunc(tx *wire.MsgTx, sizeTweak int, segwit bool) {
// Set the sigScripts to random bytes of the correct length for spending a
// p2pkh output.
if segwit {
sigSize := 73 + sizeTweak
for i := range tx.TxIn {
tx.TxIn[i].Witness = wire.TxWitness{
randBytes(sigSize),
randBytes(33),
}
}
} else {
scriptSize := dexbtc.RedeemP2PKHSigScriptSize + sizeTweak
for i := range tx.TxIn {
tx.TxIn[i].SignatureScript = randBytes(scriptSize)
}
}
}
type msgBlockWithHeight struct {
msgBlock *wire.MsgBlock
height int64
}
type testData struct {
badSendHash *chainhash.Hash
sendErr error
sentRawTx *wire.MsgTx
txOutRes *btcjson.GetTxOutResult
txOutErr error
sigIncomplete bool
signFunc func(*wire.MsgTx)
signMsgFunc func([]json.RawMessage) (json.RawMessage, error)
blockchainMtx sync.RWMutex
verboseBlocks map[string]*msgBlockWithHeight
dbBlockForTx map[chainhash.Hash]*hashEntry
mainchain map[int64]*chainhash.Hash
getBestBlockHashErr error
mempoolTxs map[chainhash.Hash]*wire.MsgTx
rawVerboseErr error
lockedCoins []*RPCOutpoint
estFeeErr error
listLockUnspent []*RPCOutpoint
getBalances *GetBalancesResult
getBalancesErr error
lockUnspentErr error
changeAddr string
changeAddrErr error
newAddress string
newAddressErr error
privKeyForAddr *btcutil.WIF
privKeyForAddrErr error
getTransaction *GetTransactionResult
getTransactionErr error
getBlockchainInfo *getBlockchainInfoResult
getBlockchainInfoErr error
unlockErr error
lockErr error
sendToAddress string
sendToAddressErr error
setTxFee bool
signTxErr error
listUnspent []*ListUnspentResult
listUnspentErr error
// spv
fetchInputInfoTx *wire.MsgTx
getCFilterScripts map[chainhash.Hash][][]byte
checkpoints map[outPoint]*scanCheckpoint
confs uint32
confsSpent bool
confsErr error
walletTxSpent bool
}
func newTestData() *testData {
// setup genesis block, required by bestblock polling goroutine
genesisHash := chaincfg.MainNetParams.GenesisHash
return &testData{
txOutRes: newTxOutResult([]byte{}, 1, 0),
verboseBlocks: map[string]*msgBlockWithHeight{
genesisHash.String(): {msgBlock: &wire.MsgBlock{}},
},
dbBlockForTx: make(map[chainhash.Hash]*hashEntry),
mainchain: map[int64]*chainhash.Hash{
0: genesisHash,
},
mempoolTxs: make(map[chainhash.Hash]*wire.MsgTx),
fetchInputInfoTx: dummyTx(),
getCFilterScripts: make(map[chainhash.Hash][][]byte),
confsErr: WalletTransactionNotFound,
checkpoints: make(map[outPoint]*scanCheckpoint),
}
}
func (c *testData) getBlock(blockHash string) *msgBlockWithHeight {
c.blockchainMtx.Lock()
defer c.blockchainMtx.Unlock()
return c.verboseBlocks[blockHash]
}
func (c *testData) GetBestBlockHeight() int64 {
c.blockchainMtx.RLock()
defer c.blockchainMtx.RUnlock()
var bestBlkHeight int64
for height := range c.mainchain {
if height >= bestBlkHeight {
bestBlkHeight = height
}
}
return bestBlkHeight
}
func (c *testData) bestBlock() (*chainhash.Hash, int64) {
c.blockchainMtx.RLock()
defer c.blockchainMtx.RUnlock()
var bestHash *chainhash.Hash
var bestBlkHeight int64
for height, hash := range c.mainchain {
if height >= bestBlkHeight {
bestBlkHeight = height
bestHash = hash
}
}
return bestHash, bestBlkHeight
}
func encodeOrError(thing interface{}, err error) (json.RawMessage, error) {
if err != nil {
return nil, err
}
return json.Marshal(thing)
}
type tRawRequester struct {
*testData
}
func (c *tRawRequester) RawRequest(_ context.Context, method string, params []json.RawMessage) (json.RawMessage, error) {
switch method {
// TODO: handle methodGetBlockHash and add actual tests to cover it.
case methodEstimateSmartFee:
if c.testData.estFeeErr != nil {
return nil, c.testData.estFeeErr
}
optimalRate := float64(optimalFeeRate) * 1e-5 // ~0.00024
return json.Marshal(&btcjson.EstimateSmartFeeResult{
Blocks: 2,
FeeRate: &optimalRate,
})
case methodSendRawTransaction:
var txHex string
err := json.Unmarshal(params[0], &txHex)
if err != nil {
return nil, err
}
tx, err := msgTxFromHex(txHex)
if err != nil {
return nil, err
}
c.sentRawTx = tx
if c.sendErr == nil && c.badSendHash == nil {
h := tx.TxHash().String()
return json.Marshal(&h)
}
if c.sendErr != nil {
return nil, c.sendErr
}
return json.Marshal(c.badSendHash.String())
case methodGetTxOut:
return encodeOrError(c.txOutRes, c.txOutErr)
case methodGetBestBlockHash:
if c.getBestBlockHashErr != nil {
return nil, c.getBestBlockHashErr
}
bestHash, _ := c.bestBlock()
return json.Marshal(bestHash.String())
case methodGetBlockHash:
var blockHeight int64
if err := json.Unmarshal(params[0], &blockHeight); err != nil {
return nil, err
}
c.blockchainMtx.RLock()
defer c.blockchainMtx.RUnlock()
for height, blockHash := range c.mainchain {
if height == blockHeight {
return json.Marshal(blockHash.String())
}
}
return nil, fmt.Errorf("block not found")
case methodGetRawMempool:
hashes := make([]string, 0, len(c.mempoolTxs))
for txHash := range c.mempoolTxs {
hashes = append(hashes, txHash.String())
}
return json.Marshal(hashes)
case methodGetRawTransaction:
if c.testData.rawVerboseErr != nil {
return nil, c.testData.rawVerboseErr
}
var hashStr string
err := json.Unmarshal(params[0], &hashStr)
if err != nil {
return nil, err
}
txHash, err := chainhash.NewHashFromStr(hashStr)
if err != nil {
return nil, err
}
msgTx := c.mempoolTxs[*txHash]
if msgTx == nil {
return nil, fmt.Errorf("transaction not found")
}
txB, _ := serializeMsgTx(msgTx)
return json.Marshal(hex.EncodeToString(txB))
case methodSignTx:
if c.signTxErr != nil {
return nil, c.signTxErr
}
signTxRes := SignTxResult{
Complete: !c.sigIncomplete,
}
var msgHex string
err := json.Unmarshal(params[0], &msgHex)
if err != nil {
return nil, fmt.Errorf("json.Unmarshal error for tRawRequester -> RawRequest -> methodSignTx: %v", err)
}
msgBytes, _ := hex.DecodeString(msgHex)
txReader := bytes.NewReader(msgBytes)
msgTx := wire.NewMsgTx(wire.TxVersion)
err = msgTx.Deserialize(txReader)
if err != nil {
return nil, fmt.Errorf("MsgTx.Deserialize error for tRawRequester -> RawRequest -> methodSignTx: %v", err)
}
c.signFunc(msgTx)
buf := new(bytes.Buffer)
err = msgTx.Serialize(buf)
if err != nil {
return nil, fmt.Errorf("MsgTx.Serialize error for tRawRequester -> RawRequest -> methodSignTx: %v", err)
}
signTxRes.Hex = buf.Bytes()
return mustMarshal(signTxRes), nil
case methodGetBlock:
c.blockchainMtx.Lock()
defer c.blockchainMtx.Unlock()
var blockHashStr string
err := json.Unmarshal(params[0], &blockHashStr)
if err != nil {
return nil, err
}
blk, found := c.verboseBlocks[blockHashStr]
if !found {
return nil, fmt.Errorf("block not found")
}
var buf bytes.Buffer
err = blk.msgBlock.Serialize(&buf)
if err != nil {
return nil, err
}
return json.Marshal(hex.EncodeToString(buf.Bytes()))
case methodGetBlockHeader:
var blkHash string
_ = json.Unmarshal(params[0], &blkHash)
block := c.getBlock(blkHash)
if block == nil {
return nil, fmt.Errorf("no block verbose found")
}
// block may get modified concurrently, lock mtx before reading fields.
c.blockchainMtx.RLock()
defer c.blockchainMtx.RUnlock()
return json.Marshal(&blockHeader{
Hash: block.msgBlock.BlockHash().String(),
Height: block.height,
// Confirmations: block.Confirmations,
// Time: block.Time,
})
case methodLockUnspent:
if c.lockUnspentErr != nil {
return json.Marshal(false)
}
coins := make([]*RPCOutpoint, 0)
_ = json.Unmarshal(params[1], &coins)
if string(params[0]) == "false" {
c.lockedCoins = coins
}
return json.Marshal(true)
case methodListLockUnspent:
return mustMarshal(c.listLockUnspent), nil
case methodGetBalances:
return encodeOrError(c.getBalances, c.getBalancesErr)
case methodChangeAddress:
return encodeOrError(c.changeAddr, c.changeAddrErr)
case methodNewAddress:
return encodeOrError(c.newAddress, c.newAddressErr)
case methodPrivKeyForAddress:
if c.privKeyForAddrErr != nil {
return nil, c.privKeyForAddrErr
}
return json.Marshal(c.privKeyForAddr.String())
case methodGetTransaction:
return encodeOrError(c.getTransaction, c.getTransactionErr)
case methodGetBlockchainInfo:
return encodeOrError(c.getBlockchainInfo, c.getBlockchainInfoErr)
case methodLock:
return nil, c.lockErr
case methodUnlock:
return nil, c.unlockErr
case methodSendToAddress:
return encodeOrError(c.sendToAddress, c.sendToAddressErr)
case methodSetTxFee:
return json.Marshal(c.setTxFee)
case methodListUnspent:
return encodeOrError(c.listUnspent, c.listUnspentErr)
}
panic("method not registered: " + method)
}
const testBlocksPerBlockTimeOffset = 4
func generateTestBlockTime(blockHeight int64) time.Time {
return time.Unix(1e6, 0).Add(time.Duration(blockHeight) * maxFutureBlockTime / testBlocksPerBlockTimeOffset)
}
func (c *testData) addRawTx(blockHeight int64, tx *wire.MsgTx) (*chainhash.Hash, *wire.MsgBlock) {
c.blockchainMtx.Lock()
defer c.blockchainMtx.Unlock()
blockHash, found := c.mainchain[blockHeight]
if !found {
var newHash chainhash.Hash
copy(newHash[:], randBytes(32))
blockHash = &newHash
prevBlock := &chainhash.Hash{}
if blockHeight > 0 {
var exists bool
prevBlock, exists = c.mainchain[blockHeight-1]
if !exists {
prevBlock = &chainhash.Hash{}
}
}
header := wire.NewBlockHeader(0, prevBlock, &chainhash.Hash{}, 1, 2)
header.Timestamp = generateTestBlockTime(blockHeight)
msgBlock := wire.NewMsgBlock(header)
c.verboseBlocks[blockHash.String()] = &msgBlockWithHeight{
msgBlock: msgBlock,
height: blockHeight,
}
c.mainchain[blockHeight] = blockHash
}
block := c.verboseBlocks[blockHash.String()]
block.msgBlock.AddTransaction(tx)
return blockHash, block.msgBlock
}
func (c *testData) addDBBlockForTx(txHash, blockHash *chainhash.Hash) {
c.blockchainMtx.Lock()
defer c.blockchainMtx.Unlock()
c.dbBlockForTx[*txHash] = &hashEntry{hash: *blockHash}
}
func (c *testData) getBlockAtHeight(blockHeight int64) (*chainhash.Hash, *msgBlockWithHeight) {
c.blockchainMtx.RLock()
defer c.blockchainMtx.RUnlock()
blockHash, found := c.mainchain[blockHeight]
if !found {
return nil, nil
}
blk := c.verboseBlocks[blockHash.String()]
return blockHash, blk
}
func (c *testData) truncateChains() {
c.blockchainMtx.RLock()
defer c.blockchainMtx.RUnlock()
c.mainchain = make(map[int64]*chainhash.Hash)
c.verboseBlocks = make(map[string]*msgBlockWithHeight)
c.mempoolTxs = make(map[chainhash.Hash]*wire.MsgTx)
}
func makeRawTx(pkScripts []dex.Bytes, inputs []*wire.TxIn) *wire.MsgTx {
tx := &wire.MsgTx{
TxIn: inputs,
}
for _, pkScript := range pkScripts {
tx.TxOut = append(tx.TxOut, wire.NewTxOut(1, pkScript))
}
return tx
}
func makeTxHex(pkScripts []dex.Bytes, inputs []*wire.TxIn) ([]byte, error) {
msgTx := wire.NewMsgTx(wire.TxVersion)
for _, txIn := range inputs {
msgTx.AddTxIn(txIn)
}
for _, pkScript := range pkScripts {
txOut := wire.NewTxOut(100000000, pkScript)
msgTx.AddTxOut(txOut)
}
txBuf := bytes.NewBuffer(make([]byte, 0, dexbtc.MsgTxVBytes(msgTx)))
err := msgTx.Serialize(txBuf)
if err != nil {
return nil, err
}
return txBuf.Bytes(), nil
}
func makeRPCVin(txHash *chainhash.Hash, vout uint32, sigScript []byte, witness [][]byte) *wire.TxIn {
var rpcWitness []string
for _, b := range witness {
rpcWitness = append(rpcWitness, hex.EncodeToString(b))
}
return wire.NewTxIn(wire.NewOutPoint(txHash, vout), sigScript, witness)
}
func dummyInput() *wire.TxIn {
return wire.NewTxIn(wire.NewOutPoint(&chainhash.Hash{0x01}, 0), nil, nil)
}
func dummyTx() *wire.MsgTx {
return makeRawTx([]dex.Bytes{randBytes(32)}, []*wire.TxIn{dummyInput()})
}
func newTxOutResult(script []byte, value uint64, confs int64) *btcjson.GetTxOutResult {
return &btcjson.GetTxOutResult{
Confirmations: confs,
Value: float64(value) / 1e8,
ScriptPubKey: btcjson.ScriptPubKeyResult{
Hex: hex.EncodeToString(script),
},
}
}
func makeSwapContract(segwit bool, lockTimeOffset time.Duration) (secret []byte, secretHash [32]byte, pkScript, contract []byte, addr, contractAddr btcutil.Address, lockTime time.Time) {
secret = randBytes(32)
secretHash = sha256.Sum256(secret)
addr = btcAddr(segwit)
lockTime = time.Now().Add(lockTimeOffset)
contract, err := dexbtc.MakeContract(addr, addr, secretHash[:], lockTime.Unix(), segwit, &chaincfg.MainNetParams)
if err != nil {
panic("error making swap contract:" + err.Error())
}
contractAddr, _ = scriptHashAddress(segwit, contract, &chaincfg.MainNetParams)
pkScript, _ = txscript.PayToAddrScript(contractAddr)
return
}
func tNewWallet(segwit bool, walletType string) (*ExchangeWallet, *testData, func(), error) {
if segwit {
tBTC.SwapSize = dexbtc.InitTxSizeSegwit
tBTC.SwapSizeBase = dexbtc.InitTxSizeBaseSegwit
} else {
tBTC.SwapSize = dexbtc.InitTxSize
tBTC.SwapSizeBase = dexbtc.InitTxSizeBase
}
data := newTestData()
walletCfg := &asset.WalletConfig{
TipChange: func(error) {},
}
walletCtx, shutdown := context.WithCancel(tCtx)
cfg := &BTCCloneCFG{
WalletCFG: walletCfg,
Symbol: "btc",
Logger: tLogger,
ChainParams: &chaincfg.MainNetParams,
WalletInfo: WalletInfo,
DefaultFallbackFee: defaultFee,
DefaultFeeRateLimit: defaultFeeRateLimit,
Segwit: segwit,
}
// rpcClient := newRPCClient(requester, segwit, nil, false, minNetworkVersion, dex.StdOutLogger("RPCTEST", dex.LevelTrace), &chaincfg.MainNetParams)
var wallet *ExchangeWallet
var err error
switch walletType {
case walletTypeRPC:
wallet, err = newRPCWallet(&tRawRequester{data}, cfg, &WalletConfig{})
case walletTypeSPV:
wallet, err = newUnconnectedWallet(cfg, &WalletConfig{})
if err == nil {
neutrinoClient := &tNeutrinoClient{data}
wallet.node = &spvWallet{
chainParams: &chaincfg.MainNetParams,
wallet: &tBtcWallet{data},
cl: neutrinoClient,
chainClient: nil,
acctNum: 0,
txBlocks: data.dbBlockForTx,
checkpoints: data.checkpoints,
log: cfg.Logger.SubLogger("SPV"),
loader: nil,
}
}
}
if err != nil {
shutdown()
return nil, nil, nil, err
}
// Initialize the best block.
bestHash, err := wallet.node.getBestBlockHash()
if err != nil {
shutdown()
return nil, nil, nil, err
}
wallet.tipMtx.Lock()
wallet.currentTip = &block{
height: data.GetBestBlockHeight(),
hash: *bestHash,
}
wallet.tipMtx.Unlock()
go wallet.run(walletCtx)
return wallet, data, shutdown, nil
}
func mustMarshal(thing interface{}) []byte {
b, err := json.Marshal(thing)
if err != nil {
panic("mustMarshal error: " + err.Error())
}
return b
}
func TestMain(m *testing.M) {
tLogger = dex.StdOutLogger("TEST", dex.LevelTrace)
var shutdown func()
tCtx, shutdown = context.WithCancel(context.Background())
tTxHash, _ = chainhash.NewHashFromStr(tTxID)
tP2PKH, _ = hex.DecodeString("76a9148fc02268f208a61767504fe0b48d228641ba81e388ac")
tP2WPKH, _ = hex.DecodeString("0014148fc02268f208a61767504fe0b48d228641ba81")
// tP2SH, _ = hex.DecodeString("76a91412a9abf5c32392f38bd8a1f57d81b1aeecc5699588ac")
doIt := func() int {
// Not counted as coverage, must test Archiver constructor explicitly.
defer shutdown()
return m.Run()
}
os.Exit(doIt())
}
type testFunc func(t *testing.T, segwit bool, walletType string)
func runRubric(t *testing.T, f testFunc) {
t.Run("rpc|segwit", func(t *testing.T) {
f(t, true, walletTypeRPC)
})
t.Run("rpc|non-segwit", func(t *testing.T) {
f(t, false, walletTypeRPC)
})
t.Run("spv|segwit", func(t *testing.T) {
f(t, true, walletTypeSPV)
})
}
func TestAvailableFund(t *testing.T) {
runRubric(t, testAvailableFund)
}
func testAvailableFund(t *testing.T, segwit bool, walletType string) {
wallet, node, shutdown, err := tNewWallet(segwit, walletType)
defer shutdown()
if err != nil {
t.Fatal(err)
}
// With an empty list returned, there should be no error, but the value zero
// should be returned.
unspents := make([]*ListUnspentResult, 0)
node.listUnspent = unspents // only needed for Fund, not Balance
node.listLockUnspent = []*RPCOutpoint{}
var bals GetBalancesResult
node.getBalances = &bals
bal, err := wallet.Balance()
if err != nil {
t.Fatalf("error for zero utxos: %v", err)
}
if bal.Available != 0 {
t.Fatalf("expected available = 0, got %d", bal.Available)
}
if bal.Immature != 0 {
t.Fatalf("expected unconf = 0, got %d", bal.Immature)
}
node.getBalancesErr = tErr
_, err = wallet.Balance()
if err == nil {
t.Fatalf("no wallet error for rpc error")
}
node.getBalancesErr = nil
var littleLots uint64 = 12
littleOrder := tLotSize * littleLots
littleFunds := calc.RequiredOrderFunds(littleOrder, dexbtc.RedeemP2PKHInputSize, littleLots, tBTC)
littleUTXO := &ListUnspentResult{
TxID: tTxID,
Address: "1Bggq7Vu5oaoLFV1NNp5KhAzcku83qQhgi",
Amount: float64(littleFunds) / 1e8,
Confirmations: 0,
ScriptPubKey: tP2PKH,
Spendable: true,
Solvable: true,
Safe: true,
}
unspents = append(unspents, littleUTXO)
node.listUnspent = unspents
bals.Mine.Trusted = float64(littleFunds) / 1e8
node.getBalances = &bals
lockedVal := uint64(1e6)
node.listLockUnspent = []*RPCOutpoint{
{
TxID: tTxID,
Vout: 1,
},
}
msgTx := makeRawTx([]dex.Bytes{{0x01}, {0x02}}, []*wire.TxIn{dummyInput()})
msgTx.TxOut[1].Value = int64(lockedVal)
txBuf := bytes.NewBuffer(make([]byte, 0, dexbtc.MsgTxVBytes(msgTx)))
msgTx.Serialize(txBuf)
const blockHeight = 5
blockHash, _ := node.addRawTx(blockHeight, msgTx)
node.getTransaction = &GetTransactionResult{
BlockHash: blockHash.String(),
BlockIndex: blockHeight,
Details: []*WalletTxDetails{
{
Amount: float64(lockedVal) / 1e8,
Vout: 1,
},
},
Hex: txBuf.Bytes(),
}
bal, err = wallet.Balance()
if err != nil {
t.Fatalf("error for 1 utxo: %v", err)
}
if bal.Available != littleFunds-lockedVal {
t.Fatalf("expected available = %d for confirmed utxos, got %d", littleOrder-lockedVal, bal.Available)
}
if bal.Immature != 0 {
t.Fatalf("expected immature = 0, got %d", bal.Immature)
}
if bal.Locked != lockedVal {
t.Fatalf("expected locked = %d, got %d", lockedVal, bal.Locked)
}
var lottaLots uint64 = 100
lottaOrder := tLotSize * lottaLots
// Add funding for an extra input to accommodate the later combined tests.
lottaFunds := calc.RequiredOrderFunds(lottaOrder, 2*dexbtc.RedeemP2PKHInputSize, lottaLots, tBTC)
lottaUTXO := &ListUnspentResult{
TxID: tTxID,
Address: "1Bggq7Vu5oaoLFV1NNp5KhAzcku83qQhgi",
Amount: float64(lottaFunds) / 1e8,
Confirmations: 1,
Vout: 1,
ScriptPubKey: tP2PKH,
Spendable: true,
Solvable: true,
Safe: true,
}
unspents = append(unspents, lottaUTXO)
littleUTXO.Confirmations = 1
node.listUnspent = unspents
bals.Mine.Trusted += float64(lottaFunds) / 1e8
node.getBalances = &bals
bal, err = wallet.Balance()
if err != nil {
t.Fatalf("error for 2 utxos: %v", err)
}
if bal.Available != littleFunds+lottaFunds-lockedVal {
t.Fatalf("expected available = %d for 2 outputs, got %d", littleFunds+lottaFunds-lockedVal, bal.Available)
}
if bal.Immature != 0 {
t.Fatalf("expected immature = 0 for 2 outputs, got %d", bal.Immature)
}
ord := &asset.Order{
Value: 0,
MaxSwapCount: 1,
DEXConfig: tBTC,
FeeSuggestion: feeSuggestion,
}
setOrderValue := func(v uint64) {
ord.Value = v
ord.MaxSwapCount = v / tLotSize
}
// Zero value
_, _, err = wallet.FundOrder(ord)
if err == nil {
t.Fatalf("no funding error for zero value")
}
// Nothing to spend
node.listUnspent = []*ListUnspentResult{}
setOrderValue(littleOrder)
_, _, err = wallet.FundOrder(ord)
if err == nil {
t.Fatalf("no error for zero utxos")
}
node.listUnspent = unspents
// RPC error
node.listUnspentErr = tErr
_, _, err = wallet.FundOrder(ord)
if err == nil {
t.Fatalf("no funding error for rpc error")
}
node.listUnspentErr = nil
// Negative response when locking outputs.
// There is no way to error locking outpoints in spv
if walletType != walletTypeSPV {
node.lockUnspentErr = tErr
_, _, err = wallet.FundOrder(ord)
if err == nil {
t.Fatalf("no error for lockunspent result = false: %v", err)
}
node.lockUnspentErr = nil
}
// Fund a little bit, with unsafe littleUTXO.
littleUTXO.Safe = false
littleUTXO.Confirmations = 0
node.listUnspent = unspents
spendables, _, err := wallet.FundOrder(ord)
if err != nil {
t.Fatalf("error funding small amount: %v", err)
}
if len(spendables) != 1 {
t.Fatalf("expected 1 spendable, got %d", len(spendables))
}
v := spendables[0].Value()
if v != lottaFunds { // has to pick the larger output
t.Fatalf("expected spendable of value %d, got %d", lottaFunds, v)
}
// Now with safe confirmed littleUTXO.
littleUTXO.Safe = true
littleUTXO.Confirmations = 2
node.listUnspent = unspents
spendables, _, err = wallet.FundOrder(ord)
if err != nil {
t.Fatalf("error funding small amount: %v", err)
}
if len(spendables) != 1 {
t.Fatalf("expected 1 spendable, got %d", len(spendables))
}
v = spendables[0].Value()
if v != littleFunds {
t.Fatalf("expected spendable of value %d, got %d", littleFunds, v)
}
// Return/unlock the reserved coins to avoid warning in subsequent tests
// about fundingCoins map containing the coins already. i.e.
// "Known order-funding coin %v returned by listunspent"
_ = wallet.ReturnCoins(spendables)
// Make lottaOrder unconfirmed like littleOrder, favoring little now.
lottaUTXO.Confirmations = 0
node.listUnspent = unspents
spendables, _, err = wallet.FundOrder(ord)
if err != nil {
t.Fatalf("error funding small amount: %v", err)
}
if len(spendables) != 1 {
t.Fatalf("expected 1 spendable, got %d", len(spendables))
}
v = spendables[0].Value()
if v != littleFunds { // now picks the smaller output
t.Fatalf("expected spendable of value %d, got %d", littleFunds, v)
}
_ = wallet.ReturnCoins(spendables)
// Fund a lotta bit, covered by just the lottaBit UTXO.
setOrderValue(lottaOrder)
spendables, _, err = wallet.FundOrder(ord)
if err != nil {
t.Fatalf("error funding large amount: %v", err)
}
if len(spendables) != 1 {
t.Fatalf("expected 1 spendable, got %d", len(spendables))
}
v = spendables[0].Value()
if v != lottaFunds {
t.Fatalf("expected spendable of value %d, got %d", lottaFunds, v)
}
_ = wallet.ReturnCoins(spendables)
// require both spendables
extraLottaOrder := littleOrder + lottaOrder
extraLottaLots := littleLots + lottaLots
setOrderValue(extraLottaOrder)
spendables, _, err = wallet.FundOrder(ord)
if err != nil {
t.Fatalf("error funding large amount: %v", err)
}
if len(spendables) != 2 {
t.Fatalf("expected 2 spendable, got %d", len(spendables))
}
v = spendables[0].Value()
if v != lottaFunds {
t.Fatalf("expected spendable of value %d, got %d", lottaFunds, v)
}
_ = wallet.ReturnCoins(spendables)
// Not enough to cover transaction fees.
tweak := float64(littleFunds+lottaFunds-calc.RequiredOrderFunds(extraLottaOrder, 2*dexbtc.RedeemP2PKHInputSize, extraLottaLots, tBTC)+1) / 1e8
lottaUTXO.Amount -= tweak
node.listUnspent = unspents
_, _, err = wallet.FundOrder(ord)
if err == nil {
t.Fatalf("no error when not enough to cover tx fees")
}
lottaUTXO.Amount += tweak
node.listUnspent = unspents
// Prepare for a split transaction.
baggageFees := tBTC.MaxFeeRate * splitTxBaggage
node.changeAddr = tP2WPKHAddr
wallet.useSplitTx = true
// No error when no split performed cuz math.
coins, _, err := wallet.FundOrder(ord)
if err != nil {
t.Fatalf("error for no-split split: %v", err)
}
// Should be both coins.
if len(coins) != 2 {
t.Fatalf("no-split split didn't return both coins")
}
_ = wallet.ReturnCoins(coins)
// No split because not standing order.
ord.Immediate = true
coins, _, err = wallet.FundOrder(ord)
if err != nil {
t.Fatalf("error for no-split split: %v", err)
}
ord.Immediate = false
if len(coins) != 2 {
t.Fatalf("no-split split didn't return both coins")
}
_ = wallet.ReturnCoins(coins)
// With a little more locked, the split should be performed.
node.signFunc = func(tx *wire.MsgTx) {
signFunc(tx, 0, wallet.segwit)
}
lottaUTXO.Amount += float64(baggageFees) / 1e8
node.listUnspent = unspents
coins, _, err = wallet.FundOrder(ord)
if err != nil {
t.Fatalf("error for split tx: %v", err)
}
// Should be just one coin.
if len(coins) != 1 {
t.Fatalf("split failed - coin count != 1")
}
if node.sentRawTx == nil {
t.Fatalf("split failed - no tx sent")
}
_ = wallet.ReturnCoins(coins)
// // Hit some error paths.
// Split transaction requires valid fee suggestion.
// TODO:
// 1.0: Error when no suggestion.
// ord.FeeSuggestion = 0
// _, _, err = wallet.FundOrder(ord)
// if err == nil {
// t.Fatalf("no error for no fee suggestions on split tx")
// }
ord.FeeSuggestion = tBTC.MaxFeeRate + 1
_, _, err = wallet.FundOrder(ord)
if err == nil {
t.Fatalf("no error for no fee suggestions on split tx")
}
// Check success again.
ord.FeeSuggestion = tBTC.MaxFeeRate
coins, _, err = wallet.FundOrder(ord)
if err != nil {
t.Fatalf("error fixing split tx: %v", err)
}