forked from decred/dcrdex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spv_test.go
849 lines (727 loc) · 24.3 KB
/
spv_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
//go:build !spvlive
// 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 (
"errors"
"fmt"
"sync/atomic"
"testing"
"time"
"decred.org/dcrdex/dex"
"decred.org/dcrdex/dex/encode"
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/peer"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"github.com/btcsuite/btcutil/gcs"
"github.com/btcsuite/btcutil/gcs/builder"
"github.com/btcsuite/btcutil/psbt"
"github.com/btcsuite/btcwallet/chain"
"github.com/btcsuite/btcwallet/waddrmgr"
"github.com/btcsuite/btcwallet/wallet"
"github.com/btcsuite/btcwallet/walletdb"
"github.com/btcsuite/btcwallet/wtxmgr"
"github.com/lightninglabs/neutrino"
"github.com/lightninglabs/neutrino/headerfs"
)
type tBtcWallet struct {
*testData
}
func (c *tBtcWallet) PublishTransaction(tx *wire.MsgTx, label string) error {
c.sentRawTx = tx
if c.sendErr != nil {
return c.sendErr
}
if c.sendToAddressErr != nil {
return c.sendToAddressErr
}
if c.badSendHash != nil {
// testData would return the badSendHash. We'll do something similar
// by adding a random output.
tx.AddTxOut(wire.NewTxOut(1, []byte{0x01}))
}
return c.sendErr
}
func (c *tBtcWallet) CalculateAccountBalances(account uint32, confirms int32) (wallet.Balances, error) {
if c.getBalancesErr != nil {
return wallet.Balances{}, c.getBalancesErr
}
bal := &c.getBalances.Mine
mustAmount := func(v float64) btcutil.Amount {
amt, _ := btcutil.NewAmount(v)
return amt
}
return wallet.Balances{
Total: mustAmount(bal.Trusted + bal.Untrusted),
Spendable: mustAmount(bal.Trusted + bal.Untrusted),
ImmatureReward: mustAmount(bal.Immature),
}, nil
}
func (c *tBtcWallet) ListUnspent(minconf, maxconf int32, acctName string) ([]*btcjson.ListUnspentResult, error) {
if c.listUnspentErr != nil {
return nil, c.listUnspentErr
}
unspents := make([]*btcjson.ListUnspentResult, 0, len(c.listUnspent))
for _, u := range c.listUnspent {
unspents = append(unspents, &btcjson.ListUnspentResult{
TxID: u.TxID,
Vout: u.Vout,
Address: u.Address,
// Account: ,
ScriptPubKey: u.ScriptPubKey.String(),
RedeemScript: u.RedeemScript.String(),
Amount: u.Amount,
Confirmations: int64(u.Confirmations),
Spendable: u.Spendable,
})
}
return unspents, nil
}
func (c *tBtcWallet) FetchInputInfo(prevOut *wire.OutPoint) (*wire.MsgTx, *wire.TxOut, *psbt.Bip32Derivation, int64, error) {
return c.fetchInputInfoTx, nil, nil, 0, nil
}
func (c *tBtcWallet) ResetLockedOutpoints() {}
func (c *tBtcWallet) LockOutpoint(op wire.OutPoint) {
c.lockedCoins = []*RPCOutpoint{{
TxID: op.Hash.String(),
Vout: op.Index,
}}
}
func (c *tBtcWallet) UnlockOutpoint(op wire.OutPoint) {}
func (c *tBtcWallet) LockedOutpoints() []btcjson.TransactionInput {
unspents := make([]btcjson.TransactionInput, 0)
for _, u := range c.listLockUnspent {
unspents = append(unspents, btcjson.TransactionInput{
Txid: u.TxID,
Vout: u.Vout,
})
}
return unspents
}
func (c *tBtcWallet) NewChangeAddress(account uint32, scope waddrmgr.KeyScope) (btcutil.Address, error) {
if c.changeAddrErr != nil {
return nil, c.changeAddrErr
}
return btcutil.DecodeAddress(c.changeAddr, &chaincfg.MainNetParams)
}
func (c *tBtcWallet) NewAddress(account uint32, scope waddrmgr.KeyScope) (btcutil.Address, error) {
if c.newAddressErr != nil {
return nil, c.newAddressErr
}
return btcutil.DecodeAddress(c.newAddress, &chaincfg.MainNetParams)
}
func (c *tBtcWallet) SignTransaction(tx *wire.MsgTx, hashType txscript.SigHashType, additionalPrevScriptsadditionalPrevScripts map[wire.OutPoint][]byte,
additionalKeysByAddress map[string]*btcutil.WIF, p2shRedeemScriptsByAddress map[string][]byte) ([]wallet.SignatureError, error) {
if c.signTxErr != nil {
return nil, c.signTxErr
}
c.signFunc(tx)
if c.sigIncomplete {
return []wallet.SignatureError{{Error: errors.New("tBtcWallet SignTransaction error")}}, nil
}
return nil, nil
}
func (c *tBtcWallet) PrivKeyForAddress(a btcutil.Address) (*btcec.PrivateKey, error) {
if c.privKeyForAddrErr != nil {
return nil, c.privKeyForAddrErr
}
return c.privKeyForAddr.PrivKey, nil
}
func (c *tBtcWallet) Database() walletdb.DB {
return nil
}
func (c *tBtcWallet) Unlock(passphrase []byte, lock <-chan time.Time) error {
return c.unlockErr
}
func (c *tBtcWallet) Lock() {}
func (c *tBtcWallet) Locked() bool {
return false
}
func (c *tBtcWallet) SendOutputs(outputs []*wire.TxOut, keyScope *waddrmgr.KeyScope, account uint32, minconf int32, satPerKb btcutil.Amount, label string) (*wire.MsgTx, error) {
if c.sendToAddressErr != nil {
return nil, c.sendToAddressErr
}
tx := wire.NewMsgTx(wire.TxVersion)
for _, txOut := range outputs {
tx.AddTxOut(txOut)
}
tx.AddTxIn(dummyInput())
return tx, nil
}
func (c *tBtcWallet) HaveAddress(a btcutil.Address) (bool, error) {
return false, nil
}
func (c *tBtcWallet) Stop() {}
func (c *tBtcWallet) WaitForShutdown() {}
func (c *tBtcWallet) ChainSynced() bool {
c.blockchainMtx.RLock()
defer c.blockchainMtx.RUnlock()
if c.getBlockchainInfo == nil {
return false
}
return c.getBlockchainInfo.Blocks >= c.getBlockchainInfo.Headers // -1 ok for chain sync ?
}
func (c *tBtcWallet) SynchronizeRPC(chainClient chain.Interface) {}
func (c *tBtcWallet) walletTransaction(txHash *chainhash.Hash) (*wtxmgr.TxDetails, error) {
if c.getTransactionErr != nil {
return nil, c.getTransactionErr
}
var txData *GetTransactionResult
if c.getTransactionMap != nil {
if txData = c.getTransactionMap["any"]; txData == nil {
txData = c.getTransactionMap[txHash.String()]
}
}
if txData == nil {
return nil, WalletTransactionNotFound
}
tx, _ := msgTxFromBytes(txData.Hex)
blockHash, _ := chainhash.NewHashFromStr(txData.BlockHash)
blk := c.getBlock(txData.BlockHash)
var blockHeight int32
if blk != nil {
blockHeight = int32(blk.height)
} else {
blockHeight = -1
}
credits := make([]wtxmgr.CreditRecord, 0, len(tx.TxIn))
debits := make([]wtxmgr.DebitRecord, 0, len(tx.TxIn))
for i, in := range tx.TxIn {
credits = append(credits, wtxmgr.CreditRecord{
// Amount:,
Index: uint32(i),
Spent: c.walletTxSpent,
// Change: ,
})
var debitAmount int64
// The sources of transaction inputs all need to be added to getTransactionMap
// in order to get accurate Fees and Amounts when calling GetWalletTransaction
// when using the SPV wallet.
if gtr := c.getTransactionMap[in.PreviousOutPoint.Hash.String()]; gtr != nil {
tx, _ := msgTxFromBytes(gtr.Hex)
debitAmount = tx.TxOut[in.PreviousOutPoint.Index].Value
}
debits = append(debits, wtxmgr.DebitRecord{
Amount: btcutil.Amount(debitAmount),
})
}
return &wtxmgr.TxDetails{
TxRecord: wtxmgr.TxRecord{
MsgTx: *tx,
Received: time.Unix(int64(txData.Time), 0),
},
Block: wtxmgr.BlockMeta{
Block: wtxmgr.Block{
Hash: *blockHash,
Height: blockHeight,
},
},
Credits: credits,
Debits: debits,
}, nil
}
func (c *tBtcWallet) getTransaction(txHash *chainhash.Hash) (*GetTransactionResult, error) {
if c.getTransactionErr != nil {
return nil, c.getTransactionErr
}
var txData *GetTransactionResult
if c.getTransactionMap != nil {
if txData = c.getTransactionMap["any"]; txData == nil {
txData = c.getTransactionMap[txHash.String()]
}
}
if txData == nil {
return nil, WalletTransactionNotFound
}
return txData, nil
}
func (c *tBtcWallet) syncedTo() waddrmgr.BlockStamp {
bestHash, bestHeight := c.bestBlock() // NOTE: in reality this may be lower than the chain service's best block
blk := c.getBlock(bestHash.String())
return waddrmgr.BlockStamp{
Height: int32(bestHeight),
Hash: *bestHash,
Timestamp: blk.msgBlock.Header.Timestamp,
}
}
func (c *tBtcWallet) signTransaction(tx *wire.MsgTx) error {
if c.signTxErr != nil {
return c.signTxErr
}
c.signFunc(tx)
if c.sigIncomplete {
return errors.New("tBtcWallet SignTransaction error")
}
return nil
}
func (c *tBtcWallet) txNotifications() wallet.TransactionNotificationsClient {
return wallet.TransactionNotificationsClient{}
}
type tNeutrinoClient struct {
*testData
}
func (c *tNeutrinoClient) Stop() error { return nil }
func (c *tNeutrinoClient) GetBlockHash(blockHeight int64) (*chainhash.Hash, error) {
c.blockchainMtx.RLock()
defer c.blockchainMtx.RUnlock()
for height, blockHash := range c.mainchain {
if height == blockHeight {
return blockHash, nil
}
}
return nil, fmt.Errorf("no (test) block at height %d", blockHeight)
}
func (c *tNeutrinoClient) BestBlock() (*headerfs.BlockStamp, error) {
c.blockchainMtx.RLock()
if c.getBestBlockHashErr != nil {
c.blockchainMtx.RUnlock()
return nil, c.getBestBlockHashErr
}
c.blockchainMtx.RUnlock()
bestHash, bestHeight := c.bestBlock()
blk := c.getBlock(bestHash.String())
return &headerfs.BlockStamp{
Height: int32(bestHeight),
Hash: *bestHash,
Timestamp: blk.msgBlock.Header.Timestamp, // neutrino sets this as of 88c025e
}, nil
}
func (c *tNeutrinoClient) Peers() []*neutrino.ServerPeer {
c.blockchainMtx.RLock()
defer c.blockchainMtx.RUnlock()
peer := &neutrino.ServerPeer{Peer: &peer.Peer{}}
if c.getBlockchainInfo != nil {
peer.UpdateLastBlockHeight(int32(c.getBlockchainInfo.Headers))
}
return []*neutrino.ServerPeer{peer}
}
func (c *tNeutrinoClient) GetBlockHeight(hash *chainhash.Hash) (int32, error) {
block := c.getBlock(hash.String())
if block == nil {
return 0, fmt.Errorf("(test) block not found for block hash %s", hash)
}
return int32(block.height), nil
}
func (c *tNeutrinoClient) GetBlockHeader(blkHash *chainhash.Hash) (*wire.BlockHeader, error) {
block := c.getBlock(blkHash.String())
if block == nil {
return nil, errors.New("no block verbose found")
}
return &block.msgBlock.Header, nil
}
func (c *tNeutrinoClient) GetCFilter(blockHash chainhash.Hash, filterType wire.FilterType, options ...neutrino.QueryOption) (*gcs.Filter, error) {
var key [gcs.KeySize]byte
copy(key[:], blockHash.CloneBytes()[:])
scripts := c.getCFilterScripts[blockHash]
scripts = append(scripts, encode.RandomBytes(10))
return gcs.BuildGCSFilter(builder.DefaultP, builder.DefaultM, key, scripts)
}
func (c *tNeutrinoClient) GetBlock(blockHash chainhash.Hash, options ...neutrino.QueryOption) (*btcutil.Block, error) {
blk := c.getBlock(blockHash.String())
if blk == nil {
return nil, fmt.Errorf("no (test) block %s", blockHash)
}
return btcutil.NewBlock(blk.msgBlock), nil
}
type tSPVPeer struct {
startHeight, lastHeight int32
}
func (p *tSPVPeer) StartingHeight() int32 {
return p.startHeight
}
func (p *tSPVPeer) LastBlock() int32 {
return p.lastHeight
}
func TestSwapConfirmations(t *testing.T) {
wallet, node, shutdown, _ := tNewWallet(true, walletTypeSPV)
defer shutdown()
spv := wallet.node.(*spvWallet)
node.txOutRes = nil
const tipHeight = 10
const swapHeight = 1
const spendHeight = 3
const swapConfs = tipHeight - swapHeight + 1
for i := int64(0); i <= tipHeight; i++ {
node.addRawTx(i, dummyTx())
}
_, _, pkScript, _, _, _, _ := makeSwapContract(true, time.Hour*12)
swapTx := makeRawTx([]dex.Bytes{pkScript}, []*wire.TxIn{dummyInput()})
swapTxHash := swapTx.TxHash()
const vout = 0
swapOutPt := newOutPoint(&swapTxHash, vout)
swapBlockHash, _ := node.addRawTx(swapHeight, swapTx)
spendTx := dummyTx()
spendTx.TxIn[0].PreviousOutPoint.Hash = swapTxHash
spendBlockHash, _ := node.addRawTx(spendHeight, spendTx)
spendTxHash := spendTx.TxHash()
matchTime := time.Unix(1, 0)
checkSuccess := func(tag string, expConfs uint32, expSpent bool) {
t.Helper()
confs, spent, err := spv.swapConfirmations(&swapTxHash, vout, pkScript, matchTime)
if err != nil {
t.Fatalf("%s error: %v", tag, err)
}
if confs != expConfs {
t.Fatalf("wrong number of %s confs. wanted %d, got %d", tag, expConfs, confs)
}
if spent != expSpent {
t.Fatalf("%s path not expected spent status. wanted %t, got %t", tag, expSpent, spent)
}
}
checkFailure := func(tag string) {
t.Helper()
_, _, err := spv.swapConfirmations(&swapTxHash, vout, pkScript, matchTime)
if err == nil {
t.Fatalf("no error for %q test", tag)
}
}
// confirmations() path
node.confsErr = tErr
checkFailure("confirmations")
node.confsErr = nil
node.confs = 10
node.confsSpent = true
txB, _ := serializeMsgTx(swapTx)
node.getTransactionMap = map[string]*GetTransactionResult{
"any": &GetTransactionResult{
BlockHash: swapBlockHash.String(),
BlockIndex: swapHeight,
Hex: txB,
}}
node.walletTxSpent = true
checkSuccess("confirmations", swapConfs, true)
node.getTransactionMap = nil
node.walletTxSpent = false
node.confsErr = WalletTransactionNotFound
// DB path.
node.dbBlockForTx[swapTxHash] = &hashEntry{hash: *swapBlockHash}
node.dbBlockForTx[spendTxHash] = &hashEntry{hash: *spendBlockHash}
node.checkpoints[swapOutPt] = &scanCheckpoint{res: &filterScanResult{
blockHash: swapBlockHash,
blockHeight: swapHeight,
spend: &spendingInput{},
checkpoint: *spendBlockHash,
}}
checkSuccess("GetSpend", swapConfs, true)
delete(node.checkpoints, swapOutPt)
delete(node.dbBlockForTx, swapTxHash)
// Neutrino scan
// Fail cuz no match time provided and block not known.
matchTime = time.Time{}
checkFailure("no match time")
matchTime = time.Unix(1, 0)
// spent
node.getCFilterScripts[*spendBlockHash] = [][]byte{pkScript}
delete(node.checkpoints, swapOutPt)
checkSuccess("spend", 0, true)
node.getCFilterScripts[*spendBlockHash] = nil
// Not found
delete(node.checkpoints, swapOutPt)
checkFailure("no utxo")
// Found.
node.getCFilterScripts[*swapBlockHash] = [][]byte{pkScript}
delete(node.checkpoints, swapOutPt)
checkSuccess("scan find", swapConfs, false)
}
func TestFindBlockForTime(t *testing.T) {
wallet, node, shutdown, _ := tNewWallet(true, walletTypeSPV)
defer shutdown()
spv := wallet.node.(*spvWallet)
const tipHeight = 40
for i := 0; i <= tipHeight; i++ {
node.addRawTx(int64(i), dummyTx())
}
const searchBlock = 35
matchTime := generateTestBlockTime(searchBlock)
const offsetBlock = searchBlock - testBlocksPerBlockTimeOffset
const startBlock = offsetBlock - medianTimeBlocks
_, height, err := spv.findBlockForTime(matchTime)
if err != nil {
t.Fatalf("findBlockForTime error: %v", err)
}
if height != startBlock {
t.Fatalf("wrong height. wanted %d, got %d", startBlock, height)
}
// But if we shift the startBlock time to > offsetBlock time, the window
// will continue down 11 more.
_, blk := node.getBlockAtHeight(startBlock)
blk.msgBlock.Header.Timestamp = generateTestBlockTime(offsetBlock)
_, height, err = spv.findBlockForTime(matchTime)
if err != nil {
t.Fatalf("findBlockForTime error for shifted start block: %v", err)
}
if height != startBlock-medianTimeBlocks {
t.Fatalf("wrong height. wanted %d, got %d", startBlock-11, height)
}
// And doing an early enough block just returns genesis
blockHash, height, err := spv.findBlockForTime(generateTestBlockTime(10))
if err != nil {
t.Fatalf("findBlockForTime error for genesis test: %v", err)
}
if *blockHash != *chaincfg.MainNetParams.GenesisHash {
t.Fatalf("not genesis: height = %d", height)
}
// A time way in the future still returns at least the last 11 blocks.
_, height, err = spv.findBlockForTime(generateTestBlockTime(100))
if err != nil {
t.Fatalf("findBlockForTime error for future test: %v", err)
}
// +1 because tip block is included here, as opposed to the shifted start
// block, where the shifted block wasn't included.
if height != tipHeight-medianTimeBlocks+1 {
t.Fatalf("didn't get tip - 11. wanted %d, got %d", tipHeight-medianTimeBlocks, height)
}
}
func TestGetTxOut(t *testing.T) {
wallet, node, shutdown, _ := tNewWallet(true, walletTypeSPV)
defer shutdown()
spv := wallet.node.(*spvWallet)
_, _, pkScript, _, _, _, _ := makeSwapContract(true, time.Hour*12)
const vout = 0
const blockHeight = 10
const tipHeight = 20
tx := makeRawTx([]dex.Bytes{pkScript}, []*wire.TxIn{dummyInput()})
txHash := tx.TxHash()
outPt := newOutPoint(&txHash, vout)
blockHash, _ := node.addRawTx(blockHeight, tx)
txB, _ := serializeMsgTx(tx)
node.addRawTx(tipHeight, dummyTx())
spendingTx := dummyTx()
spendingTx.TxIn[0].PreviousOutPoint.Hash = txHash
spendBlockHash, _ := node.addRawTx(tipHeight-1, spendingTx)
// Prime the db
for h := int64(1); h <= tipHeight; h++ {
node.addRawTx(h, dummyTx())
}
// Abnormal error
node.getTransactionErr = tErr
_, _, err := spv.getTxOut(&txHash, vout, pkScript, generateTestBlockTime(blockHeight))
if err == nil {
t.Fatalf("no error for getWalletTransaction error")
}
// Wallet transaction found
node.getTransactionErr = nil
node.getTransactionMap = map[string]*GetTransactionResult{"any": &GetTransactionResult{
BlockHash: blockHash.String(),
Hex: txB,
}}
_, confs, err := spv.getTxOut(&txHash, vout, pkScript, generateTestBlockTime(blockHeight))
if err != nil {
t.Fatalf("error for wallet transaction found: %v", err)
}
if confs != tipHeight-blockHeight+1 {
t.Fatalf("wrong confs for wallet transaction. wanted %d, got %d", tipHeight-blockHeight+1, confs)
}
// No wallet transaction, but we have a spend recorded.
node.getTransactionErr = WalletTransactionNotFound
node.getTransactionMap = nil
node.checkpoints[outPt] = &scanCheckpoint{res: &filterScanResult{
blockHash: blockHash,
spend: &spendingInput{},
checkpoint: *spendBlockHash,
}}
op, confs, err := spv.getTxOut(&txHash, vout, pkScript, generateTestBlockTime(blockHeight))
if op != nil || confs != 0 || err != nil {
t.Fatal("wrong result for spent txout", op != nil, confs, err)
}
delete(node.checkpoints, outPt)
// no spend record. gotta scan
// case 1: we have a block hash in the database
node.dbBlockForTx[txHash] = &hashEntry{hash: *blockHash}
node.getCFilterScripts[*blockHash] = [][]byte{pkScript}
_, _, err = spv.getTxOut(&txHash, vout, pkScript, generateTestBlockTime(blockHeight))
if err != nil {
t.Fatalf("error for GetUtxo with cached hash: %v", err)
}
// case 2: no block hash in db. Will do scan and store them.
delete(node.dbBlockForTx, txHash)
delete(node.checkpoints, outPt)
_, _, err = spv.getTxOut(&txHash, vout, pkScript, generateTestBlockTime(blockHeight))
if err != nil {
t.Fatalf("error for GetUtxo with no cached hash: %v", err)
}
if _, inserted := node.dbBlockForTx[txHash]; !inserted {
t.Fatalf("db not updated after GetUtxo scan success")
}
// case 3: spending tx found first
delete(node.checkpoints, outPt)
node.getCFilterScripts[*spendBlockHash] = [][]byte{pkScript}
txOut, _, err := spv.getTxOut(&txHash, vout, pkScript, generateTestBlockTime(blockHeight))
if err != nil {
t.Fatalf("error for spent tx: %v", err)
}
if txOut != nil {
t.Fatalf("spend output returned from getTxOut")
}
// Make sure we can find it with the checkpoint.
node.checkpoints[outPt].res.spend = nil
node.getCFilterScripts[*spendBlockHash] = nil
// We won't actually scan for the output itself, so nil'ing these should
// have no effect.
node.getCFilterScripts[*blockHash] = nil
_, _, err = spv.getTxOut(&txHash, vout, pkScript, generateTestBlockTime(blockHeight))
if err != nil {
t.Fatalf("error for checkpointed output: %v", err)
}
}
func TestSendWithSubtract(t *testing.T) {
wallet, node, shutdown, _ := tNewWallet(true, walletTypeSPV)
defer shutdown()
spv := wallet.node.(*spvWallet)
const availableFunds = 5e8
const feeRate = 100
const inputSize = dexbtc.RedeemP2WPKHInputTotalSize
const feesWithChange = (dexbtc.MinimumTxOverhead + 2*dexbtc.P2WPKHOutputSize + inputSize) * feeRate
const feesWithoutChange = (dexbtc.MinimumTxOverhead + dexbtc.P2WPKHOutputSize + inputSize) * feeRate
addr, _ := btcutil.DecodeAddress(tP2WPKHAddr, &chaincfg.MainNetParams)
pkScript, _ := txscript.PayToAddrScript(addr)
node.changeAddr = tP2WPKHAddr
node.signFunc = func(tx *wire.MsgTx) {
signFunc(tx, 0, true)
}
node.listUnspent = []*ListUnspentResult{{
TxID: tTxID,
Address: tP2WPKHAddr,
Confirmations: 5,
ScriptPubKey: pkScript,
Spendable: true,
Solvable: true,
SafePtr: boolPtr(true),
Amount: float64(availableFunds) / 1e8,
}}
test := func(req, expVal int64, expChange bool) {
t.Helper()
_, err := spv.sendWithSubtract(pkScript, uint64(req), feeRate)
if err != nil {
t.Fatalf("half withdraw error: %v", err)
}
opCount := len(node.sentRawTx.TxOut)
if (opCount == 1 && expChange) || (opCount == 2 && !expChange) {
t.Fatalf("%d outputs when expChange = %t", opCount, expChange)
}
received := node.sentRawTx.TxOut[opCount-1].Value
if received != expVal {
t.Fatalf("wrong value received. expected %d, got %d", expVal, received)
}
}
// No change
var req int64 = availableFunds / 2
test(req, req-feesWithChange, true)
// Drain it
test(availableFunds, availableFunds-feesWithoutChange, false)
// Requesting just a little less shouldn't result in a reduction of the
// amount received, since the change would be dust.
test(availableFunds-10, availableFunds-feesWithoutChange, false)
// Requesting too
// listUnspent error
node.listUnspentErr = tErr
_, err := spv.sendWithSubtract(pkScript, availableFunds/2, feeRate)
if err == nil {
t.Fatalf("test passed with listUnspent error")
}
node.listUnspentErr = nil
node.changeAddrErr = tErr
_, err = spv.sendWithSubtract(pkScript, availableFunds/2, feeRate)
if err == nil {
t.Fatalf("test passed with NewChangeAddress error")
}
node.changeAddrErr = nil
node.signTxErr = tErr
_, err = spv.sendWithSubtract(pkScript, availableFunds/2, feeRate)
if err == nil {
t.Fatalf("test passed with SignTransaction error")
}
node.signTxErr = nil
// outrageous fees
_, err = spv.sendWithSubtract(pkScript, availableFunds/2, 1e8)
if err == nil {
t.Fatalf("test passed with fees > available error")
}
}
func TestTryBlocksWithNotifier(t *testing.T) {
defaultWalletBlockAllowance := walletBlockAllowance
defaultBlockTicker := blockTicker
walletBlockAllowance = 30 * time.Millisecond
blockTicker = 5 * time.Millisecond
defer func() {
walletBlockAllowance = defaultWalletBlockAllowance
blockTicker = defaultBlockTicker
}()
wallet, node, shutdown, _ := tNewWallet(true, walletTypeSPV)
defer shutdown()
spv := wallet.node.(*spvWallet)
getNote := func(timeout time.Duration) bool {
select {
case <-node.tipChanged:
return true
case <-time.After(timeout):
return false
}
}
if getNote(walletBlockAllowance * 2) {
t.Fatalf("got a first block")
}
var tipHeight int64
addBlock := func() *block {
tipHeight++
h, _ := node.addRawTx(tipHeight, dummyTx())
return &block{tipHeight, *h}
}
// Start with no blocks so that we're not synced.
node.getBlockchainInfo = &getBlockchainInfoResult{
Headers: 2,
Blocks: 0,
}
addBlock()
// Prime the sync target to avoid the syncStatus tip send here.
atomic.StoreInt32(&spv.syncTarget, 1)
// It should not come through on the block tick, since it will be cached.
if getNote(blockTicker * 2) {
t.Fatalf("got block that should've been cached")
}
// And it won't come through after a sigle block allowance, because we're
// not synced.
if getNote(walletBlockAllowance * 2) {
t.Fatal("block didn't wait for the syncing mode allowance")
}
// But it will come through after the sync timeout = 10 * normal timeout.
if !getNote(walletBlockAllowance * 9) {
t.Fatal("block didn't time out in syncing mode")
}
// But if we're synced, it should come through after the normal block
// allowance.
addBlock()
node.blockchainMtx.Lock()
node.getBlockchainInfo = &getBlockchainInfoResult{
Headers: tipHeight,
Blocks: tipHeight,
}
node.blockchainMtx.Unlock()
if !getNote(walletBlockAllowance * 2) {
t.Fatal("block didn't time out in normal mode")
}
// On the other hand, a wallet block should come through immediately. Not
// even waiting on the block tick.
spv.tipChan <- addBlock()
if !getNote(blockTicker / 2) {
t.Fatal("wallet block wasn't sent through")
}
// If we do the same thing but make sure that a polled block is queued
// first, we should still see the block right away, and the queued block
// should be canceled.
blk := addBlock()
time.Sleep(blockTicker * 2)
spv.tipChan <- blk
if !getNote(blockTicker / 2) {
t.Fatal("wallet block wasn't sent through with polled block queued")
}
if getNote(walletBlockAllowance * 2) {
t.Fatal("queued polled block that should have been canceled came through")
}
}