forked from lightninglabs/neutrino
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync_test.go
1477 lines (1394 loc) · 42.1 KB
/
sync_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
package neutrino_test
import (
"bytes"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"os"
"reflect"
"runtime"
"strings"
"sync"
"testing"
"time"
"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/integration/rpctest"
"github.com/btcsuite/btcd/rpcclient"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btclog"
"github.com/btcsuite/btcutil"
"github.com/btcsuite/btcutil/gcs/builder"
"github.com/btcsuite/btcwallet/waddrmgr"
"github.com/btcsuite/btcwallet/wallet/txauthor"
"github.com/btcsuite/btcwallet/walletdb"
_ "github.com/btcsuite/btcwallet/walletdb/bdb"
"github.com/lightninglabs/neutrino"
)
var (
// Try btclog.LevelInfo for output like you'd see in normal operation,
// or btclog.LevelTrace to help debug code. Anything but
// btclog.LevelOff turns on log messages from the tests themselves as
// well. Keep in mind some log messages may not appear in order due to
// use of multiple query goroutines in the tests.
logLevel = btclog.LevelOff
syncTimeout = 30 * time.Second
syncUpdate = time.Second
// Don't set this too high for your platform, or the tests will miss
// messages.
// TODO: Make this a benchmark instead.
// TODO: Implement load limiting for both outgoing and incoming
// messages.
numQueryThreads = 20
queryOptions = []neutrino.QueryOption{}
// The logged sequence of events we want to see. The value of i
// represents the block for which a loop is generating a log entry,
// given for readability only.
// "bc": OnBlockConnected
// "fc" xx: OnFilteredBlockConnected with xx (uint8) relevant TXs
// "rv": OnRecvTx
// "rd": OnRedeemingTx
// "bd": OnBlockDisconnected
// "fd": OnFilteredBlockDisconnected
wantLog = func() (log []byte) {
for i := 1096; i <= 1100; i++ {
// FilteredBlockConnected
log = append(log, []byte("fc")...)
// 0 relevant TXs
log = append(log, 0x00)
// BlockConnected
log = append(log, []byte("bc")...)
}
// Block with one relevant (receive) transaction
log = append(log, []byte("rvfc")...)
log = append(log, 0x01)
log = append(log, []byte("bc")...)
// 124 blocks with nothing
for i := 1102; i <= 1225; i++ {
log = append(log, []byte("fc")...)
log = append(log, 0x00)
log = append(log, []byte("bc")...)
}
// Block with 1 redeeming transaction
log = append(log, []byte("rdfc")...)
log = append(log, 0x01)
log = append(log, []byte("bc")...)
// Block with nothing
log = append(log, []byte("fc")...)
log = append(log, 0x00)
log = append(log, []byte("bc")...)
// Update with rewind - rewind back to 1095, add another address,
// and see more interesting transactions.
for i := 1227; i >= 1096; i-- {
// BlockDisconnected and FilteredBlockDisconnected
log = append(log, []byte("bdfd")...)
}
// Forward to 1100
for i := 1096; i <= 1100; i++ {
// FilteredBlockConnected
log = append(log, []byte("fc")...)
// 0 relevant TXs
log = append(log, 0x00)
// BlockConnected
log = append(log, []byte("bc")...)
}
// Block with two relevant (receive) transactions
log = append(log, []byte("rvrvfc")...)
log = append(log, 0x02)
log = append(log, []byte("bc")...)
// 124 blocks with nothing
for i := 1102; i <= 1225; i++ {
log = append(log, []byte("fc")...)
log = append(log, 0x00)
log = append(log, []byte("bc")...)
}
// 2 blocks with 1 redeeming transaction each
for i := 1226; i <= 1227; i++ {
log = append(log, []byte("rdfc")...)
log = append(log, 0x01)
log = append(log, []byte("bc")...)
}
// Block with nothing
log = append(log, []byte("fc")...)
log = append(log, 0x00)
log = append(log, []byte("bc")...)
// 3 block rollback
for i := 1228; i >= 1226; i-- {
log = append(log, []byte("fdbd")...)
}
// 5 block empty reorg
for i := 1226; i <= 1230; i++ {
log = append(log, []byte("fc")...)
log = append(log, 0x00)
log = append(log, []byte("bc")...)
}
// 5 block rollback
for i := 1230; i >= 1226; i-- {
log = append(log, []byte("fdbd")...)
}
// 2 blocks with 1 redeeming transaction each
for i := 1226; i <= 1227; i++ {
log = append(log, []byte("rdfc")...)
log = append(log, 0x01)
log = append(log, []byte("bc")...)
}
// 8 block rest of reorg
for i := 1228; i <= 1235; i++ {
log = append(log, []byte("fc")...)
log = append(log, 0x00)
log = append(log, []byte("bc")...)
}
return log
}()
// rescanMtx locks all the variables to which the rescan goroutine's
// notifications write.
rescanMtx sync.RWMutex
// gotLog is where we accumulate the event log from the rescan. Then we
// compare it to wantLog to see if the series of events the rescan saw
// happened as expected.
gotLog []byte
// curBlockHeight lets the rescan goroutine track where it thinks the
// chain is based on OnBlockConnected and OnBlockDisconnected.
curBlockHeight int32
// curFilteredBlockHeight lets the rescan goroutine track where it
// thinks the chain is based on OnFilteredBlockConnected and
// OnFilteredBlockDisconnected.
curFilteredBlockHeight int32
// ourKnownTxsByBlock lets the rescan goroutine keep track of
// transactions we're interested in that are in the blockchain we're
// following as signalled by OnBlockConnected, OnBlockDisconnected,
// OnRecvTx, and OnRedeemingTx.
ourKnownTxsByBlock = make(map[chainhash.Hash][]*btcutil.Tx)
// ourKnownTxsByFilteredBlock lets the rescan goroutine keep track of
// transactions we're interested in that are in the blockchain we're
// following as signalled by OnFilteredBlockConnected and
// OnFilteredBlockDisconnected.
ourKnownTxsByFilteredBlock = make(map[chainhash.Hash][]*btcutil.Tx)
)
// secSource is an implementation of btcwallet/txauthor/SecretsSource that
// stores WitnessPubKeyHash addresses.
type secSource struct {
keys map[string]*btcec.PrivateKey
scripts map[string]*[]byte
params *chaincfg.Params
}
func (s *secSource) add(privKey *btcec.PrivateKey) (btcutil.Address, error) {
pubKeyHash := btcutil.Hash160(privKey.PubKey().SerializeCompressed())
addr, err := btcutil.NewAddressWitnessPubKeyHash(pubKeyHash, s.params)
if err != nil {
return nil, err
}
script, err := txscript.PayToAddrScript(addr)
if err != nil {
return nil, err
}
s.keys[addr.String()] = privKey
s.scripts[addr.String()] = &script
_, addrs, _, err := txscript.ExtractPkScriptAddrs(script, s.params)
if err != nil {
return nil, err
}
if addrs[0].String() != addr.String() {
return nil, fmt.Errorf("Encoded and decoded addresses don't "+
"match. Encoded: %s, decoded: %s", addr, addrs[0])
}
return addr, nil
}
// GetKey is required by the txscript.KeyDB interface
func (s *secSource) GetKey(addr btcutil.Address) (*btcec.PrivateKey, bool,
error) {
privKey, ok := s.keys[addr.String()]
if !ok {
return nil, true, fmt.Errorf("No key for address %s", addr)
}
return privKey, true, nil
}
// GetScript is required by the txscript.ScriptDB interface
func (s *secSource) GetScript(addr btcutil.Address) ([]byte, error) {
script, ok := s.scripts[addr.String()]
if !ok {
return nil, fmt.Errorf("No script for address %s", addr)
}
return *script, nil
}
// ChainParams is required by the SecretsSource interface
func (s *secSource) ChainParams() *chaincfg.Params {
return s.params
}
func newSecSource(params *chaincfg.Params) *secSource {
return &secSource{
keys: make(map[string]*btcec.PrivateKey),
scripts: make(map[string]*[]byte),
params: params,
}
}
type testLogger struct {
t *testing.T
}
type neutrinoHarness struct {
h1, h2, h3 *rpctest.Harness
svc *neutrino.ChainService
}
type syncTestCase struct {
name string
test func(harness *neutrinoHarness, t *testing.T)
}
var testCases = []*syncTestCase{
{
name: "initial sync",
test: testInitialSync,
},
{
name: "one-shot rescan",
test: testRescan,
},
{
name: "start long-running rescan",
test: testStartRescan,
},
{
name: "test blocks and filters in random order",
test: testRandomBlocks,
},
{
name: "check long-running rescan results",
test: testRescanResults,
},
}
// Make sure the client synchronizes with the correct node.
func testInitialSync(harness *neutrinoHarness, t *testing.T) {
err := waitForSync(t, harness.svc, harness.h1)
if err != nil {
t.Fatalf("Couldn't sync ChainService: %s", err)
}
}
// Variables used to track state between multiple rescan tests.
var (
quitRescan chan struct{}
errChan <-chan error
rescan *neutrino.Rescan
startBlock waddrmgr.BlockStamp
secSrc *secSource
addr1, addr2, addr3 btcutil.Address
script1, script2, script3 []byte
tx1, tx2, tx3 *wire.MsgTx
ourOutPoint wire.OutPoint
)
// testRescan tests several rescan modes. This should be broken up into
// smaller tests.
func testRescan(harness *neutrinoHarness, t *testing.T) {
// Generate an address and send it some coins on the h1 chain. We use
// this to test rescans and notifications.
modParams := harness.svc.ChainParams()
secSrc = newSecSource(&modParams)
privKey1, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
t.Fatalf("Couldn't generate private key: %s", err)
}
addr1, err = secSrc.add(privKey1)
if err != nil {
t.Fatalf("Couldn't create address from key: %s", err)
}
script1, err = secSrc.GetScript(addr1)
if err != nil {
t.Fatalf("Couldn't create script from address: %s", err)
}
out1 := wire.TxOut{
PkScript: script1,
Value: 1000000000,
}
// Fee rate is satoshis per byte
tx1, err = harness.h1.CreateTransaction(
[]*wire.TxOut{&out1}, 1000, true,
)
if err != nil {
t.Fatalf("Couldn't create transaction from script: %s", err)
}
_, err = harness.h1.Node.SendRawTransaction(tx1, true)
if err != nil {
t.Fatalf("Unable to send raw transaction to node: %s", err)
}
privKey2, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
t.Fatalf("Couldn't generate private key: %s", err)
}
addr2, err = secSrc.add(privKey2)
if err != nil {
t.Fatalf("Couldn't create address from key: %s", err)
}
script2, err = secSrc.GetScript(addr2)
if err != nil {
t.Fatalf("Couldn't create script from address: %s", err)
}
out2 := wire.TxOut{
PkScript: script2,
Value: 1000000000,
}
// Fee rate is satoshis per byte
tx2, err = harness.h1.CreateTransaction(
[]*wire.TxOut{&out2}, 1000, true,
)
if err != nil {
t.Fatalf("Couldn't create transaction from script: %s", err)
}
_, err = harness.h1.Node.SendRawTransaction(tx2, true)
if err != nil {
t.Fatalf("Unable to send raw transaction to node: %s", err)
}
_, err = harness.h1.Node.Generate(1)
if err != nil {
t.Fatalf("Couldn't generate/submit block: %s", err)
}
err = waitForSync(t, harness.svc, harness.h1)
if err != nil {
t.Fatalf("Couldn't sync ChainService: %s", err)
}
// Call GetUtxo for our output in tx1 to see if it's spent.
ourIndex := 1 << 30 // Should work on 32-bit systems
for i, txo := range tx1.TxOut {
if bytes.Equal(txo.PkScript, script1) {
ourIndex = i
}
}
if ourIndex != 1<<30 {
ourOutPoint = wire.OutPoint{
Hash: tx1.TxHash(),
Index: uint32(ourIndex),
}
} else {
t.Fatalf("Couldn't find the index of our output in transaction"+
" %s", tx1.TxHash())
}
spendReport, err := harness.svc.GetUtxo(
neutrino.WatchInputs(neutrino.InputWithScript{
PkScript: script1,
OutPoint: ourOutPoint,
}),
neutrino.StartBlock(&waddrmgr.BlockStamp{Height: 1101}),
)
if err != nil {
t.Fatalf("Couldn't get UTXO %s: %s", ourOutPoint, err)
}
if !bytes.Equal(spendReport.Output.PkScript, script1) {
t.Fatalf("UTXO's script doesn't match expected script for %s",
ourOutPoint)
}
}
func testStartRescan(harness *neutrinoHarness, t *testing.T) {
// Start a rescan with notifications in another goroutine. We'll kill
// it with a quit channel at the end and make sure we got the expected
// results.
quitRescan = make(chan struct{})
startBlock = waddrmgr.BlockStamp{Height: 1095}
rescan, errChan = startRescan(t, harness.svc, addr1, &startBlock,
quitRescan)
err := waitForSync(t, harness.svc, harness.h1)
if err != nil {
checkErrChan(t, errChan)
t.Fatalf("Couldn't sync ChainService: %s", err)
}
numTXs, _, err := checkRescanStatus()
if err != nil {
checkErrChan(t, errChan)
t.Fatalf("Checking rescan status failed: %s", err)
}
if numTXs != 1 {
t.Fatalf("Wrong number of relevant transactions. Want: 1, got:"+
" %d", numTXs)
}
// Generate 124 blocks on h1 to make sure it reorgs the other nodes.
// Ensure the ChainService instance stays caught up.
harness.h1.Node.Generate(124)
err = waitForSync(t, harness.svc, harness.h1)
if err != nil {
checkErrChan(t, errChan)
t.Fatalf("Couldn't sync ChainService: %s", err)
}
// Connect/sync/disconnect h2 to make it reorg to the h1 chain.
err = csd([]*rpctest.Harness{harness.h1, harness.h2})
if err != nil {
checkErrChan(t, errChan)
t.Fatalf("Couldn't sync h2 to h1: %s", err)
}
// Spend the outputs we sent ourselves over two blocks.
inSrc := func(tx wire.MsgTx) func(target btcutil.Amount) (
total btcutil.Amount, inputs []*wire.TxIn,
inputValues []btcutil.Amount, scripts [][]byte, err error) {
ourIndex := 1 << 30 // Should work on 32-bit systems
for i, txo := range tx.TxOut {
if bytes.Equal(txo.PkScript, script1) ||
bytes.Equal(txo.PkScript, script2) {
ourIndex = i
}
}
return func(target btcutil.Amount) (total btcutil.Amount,
inputs []*wire.TxIn, inputValues []btcutil.Amount,
scripts [][]byte, err error) {
if ourIndex == 1<<30 {
err = fmt.Errorf("Couldn't find our address " +
"in the passed transaction's outputs.")
return
}
total = target
inputs = []*wire.TxIn{
{
PreviousOutPoint: wire.OutPoint{
Hash: tx.TxHash(),
Index: uint32(ourIndex),
},
},
}
inputValues = []btcutil.Amount{
btcutil.Amount(tx.TxOut[ourIndex].Value)}
scripts = [][]byte{tx.TxOut[ourIndex].PkScript}
err = nil
return
}
}
// Create another address to send to so we don't trip the rescan with
// the old address and we can test monitoring both OutPoint usage and
// receipt by addresses.
privKey3, err := btcec.NewPrivateKey(btcec.S256())
if err != nil {
t.Fatalf("Couldn't generate private key: %s", err)
}
addr3, err = secSrc.add(privKey3)
if err != nil {
t.Fatalf("Couldn't create address from key: %s", err)
}
script3, err = secSrc.GetScript(addr3)
if err != nil {
t.Fatalf("Couldn't create script from address: %s", err)
}
out3 := wire.TxOut{
PkScript: script3,
Value: 500000000,
}
// Spend the first transaction and mine a block.
authTx1, err := txauthor.NewUnsignedTransaction(
[]*wire.TxOut{
&out3,
},
// Fee rate is satoshis per kilobyte
1024000,
inSrc(*tx1),
func() ([]byte, error) {
return script3, nil
},
)
if err != nil {
t.Fatalf("Couldn't create unsigned transaction: %s", err)
}
err = authTx1.AddAllInputScripts(secSrc)
if err != nil {
t.Fatalf("Couldn't sign transaction: %s", err)
}
banPeer(harness.svc, harness.h2)
err = harness.svc.SendTransaction(authTx1.Tx,
append(queryOptions,
neutrino.PeerConnectTimeout(3*time.Second))...)
if err != nil && !strings.Contains(err.Error(), "already have") {
t.Fatalf("Unable to send transaction to network: %s", err)
}
_, err = harness.h1.Node.Generate(1)
if err != nil {
t.Fatalf("Couldn't generate/submit block: %s", err)
}
err = waitForSync(t, harness.svc, harness.h1)
if err != nil {
checkErrChan(t, errChan)
t.Fatalf("Couldn't sync ChainService: %s", err)
}
numTXs, _, err = checkRescanStatus()
if numTXs != 2 {
t.Fatalf("Wrong number of relevant transactions. Want: 2, got:"+
" %d", numTXs)
}
// Spend the second transaction and mine a block.
authTx2, err := txauthor.NewUnsignedTransaction(
[]*wire.TxOut{
&out3,
},
// Fee rate is satoshis per kilobyte
1024000,
inSrc(*tx2),
func() ([]byte, error) {
return script3, nil
},
)
if err != nil {
t.Fatalf("Couldn't create unsigned transaction: %s", err)
}
err = authTx2.AddAllInputScripts(secSrc)
if err != nil {
t.Fatalf("Couldn't sign transaction: %s", err)
}
banPeer(harness.svc, harness.h2)
err = harness.svc.SendTransaction(authTx2.Tx,
append(queryOptions,
neutrino.PeerConnectTimeout(3*time.Second))...)
if err != nil && !strings.Contains(err.Error(), "already have") {
t.Fatalf("Unable to send transaction to network: %s", err)
}
_, err = harness.h1.Node.Generate(1)
if err != nil {
t.Fatalf("Couldn't generate/submit block: %s", err)
}
err = waitForSync(t, harness.svc, harness.h1)
if err != nil {
checkErrChan(t, errChan)
t.Fatalf("Couldn't sync ChainService: %s", err)
}
numTXs, _, err = checkRescanStatus()
if numTXs != 2 {
t.Fatalf("Wrong number of relevant transactions. Want: 2, got:"+
" %d", numTXs)
}
// Update the filter with the second address, and we should have 2 more
// relevant transactions.
err = rescan.Update(neutrino.AddAddrs(addr2), neutrino.Rewind(1095))
if err != nil {
t.Fatalf("Couldn't update the rescan filter: %s", err)
}
err = waitForSync(t, harness.svc, harness.h1)
if err != nil {
checkErrChan(t, errChan)
t.Fatalf("Couldn't sync ChainService: %s", err)
}
numTXs, _, err = checkRescanStatus()
if numTXs != 4 {
t.Fatalf("Wrong number of relevant transactions. Want: 4, got:"+
" %d", numTXs)
}
// Generate a block with a nonstandard coinbase to generate a basic
// filter with 0 entries.
_, err = harness.h1.GenerateAndSubmitBlockWithCustomCoinbaseOutputs(
[]*btcutil.Tx{}, rpctest.BlockVersion, time.Time{},
[]wire.TxOut{{
Value: 0,
PkScript: []byte{},
}})
if err != nil {
t.Fatalf("Couldn't generate/submit block: %s", err)
}
err = waitForSync(t, harness.svc, harness.h1)
if err != nil {
checkErrChan(t, errChan)
t.Fatalf("Couldn't sync ChainService: %s", err)
}
// Check and make sure the previous UTXO is now spent.
spendReport, err := harness.svc.GetUtxo(
neutrino.WatchInputs(neutrino.InputWithScript{
PkScript: script1,
OutPoint: ourOutPoint,
}),
neutrino.StartBlock(&waddrmgr.BlockStamp{Height: 801}),
)
if err != nil {
t.Fatalf("Couldn't get UTXO %s: %s", ourOutPoint, err)
}
if spendReport.SpendingTx == nil {
t.Fatalf("Unable to find initial transaction")
}
if spendReport.SpendingTx.TxHash() != authTx1.Tx.TxHash() {
t.Fatalf("Redeeming transaction doesn't match expected "+
"transaction: want %s, got %s", authTx1.Tx.TxHash(),
spendReport.SpendingTx.TxHash())
}
}
func fetchPrevInputScripts(block *wire.MsgBlock, client *rpctest.Harness) ([][]byte, error) {
var inputScripts [][]byte
for i, tx := range block.Transactions {
if i == 0 {
continue
}
for _, txIn := range tx.TxIn {
prevTxHash := txIn.PreviousOutPoint.Hash
prevTx, err := client.Node.GetRawTransaction(&prevTxHash)
if err != nil {
return nil, err
}
prevIndex := txIn.PreviousOutPoint.Index
prevOutput := prevTx.MsgTx().TxOut[prevIndex]
inputScripts = append(inputScripts, prevOutput.PkScript)
}
}
return inputScripts, nil
}
func testRescanResults(harness *neutrinoHarness, t *testing.T) {
// Generate 5 blocks on h2 and wait for ChainService to sync to the
// newly-best chain on h2. This includes the transactions sent via
// svc.SendTransaction earlier, so we'll have to check that the rescan
// status has updated for the correct number of transactions.
_, err := harness.h2.Node.Generate(5)
if err != nil {
t.Fatalf("Couldn't generate/submit blocks: %s", err)
}
err = waitForSync(t, harness.svc, harness.h2)
if err != nil {
checkErrChan(t, errChan)
t.Fatalf("Couldn't sync ChainService: %s", err)
}
numTXs, _, err := checkRescanStatus()
if numTXs != 2 {
t.Fatalf("Wrong number of relevant transactions. Want: 2, got:"+
" %d", numTXs)
}
// Generate 7 blocks on h1 and wait for ChainService to sync to the
// newly-best chain on h1.
_, err = harness.h1.Node.Generate(7)
if err != nil {
t.Fatalf("Couldn't generate/submit block: %s", err)
}
err = waitForSync(t, harness.svc, harness.h1)
if err != nil {
checkErrChan(t, errChan)
t.Fatalf("Couldn't sync ChainService: %s", err)
}
numTXs, _, err = checkRescanStatus()
if numTXs != 4 {
t.Fatalf("Wrong number of relevant transactions. Want: 4, got:"+
" %d", numTXs)
}
if !bytes.Equal(wantLog, gotLog) {
leastBytes := len(wantLog)
if len(gotLog) < leastBytes {
leastBytes = len(gotLog)
}
diffIndex := 0
for i := 0; i < leastBytes; i++ {
if wantLog[i] != gotLog[i] {
diffIndex = i
break
}
}
t.Fatalf("Rescan event logs differ starting at %d.\nWant: %v\n"+
"Got: %v\nDifference - want: %v\nDifference -- got: "+
"%v", diffIndex, wantLog, gotLog, wantLog[diffIndex:],
gotLog[diffIndex:])
}
// Connect h1 and h2, wait for them to synchronize and check for the
// ChainService synchronization status.
err = rpctest.ConnectNode(harness.h1, harness.h2)
if err != nil {
t.Fatalf("Couldn't connect h1 to h2: %s", err)
}
err = rpctest.JoinNodes([]*rpctest.Harness{harness.h1, harness.h2},
rpctest.Blocks)
if err != nil {
t.Fatalf("Couldn't sync h1 and h2: %s", err)
}
err = waitForSync(t, harness.svc, harness.h1)
if err != nil {
t.Fatalf("Couldn't sync ChainService: %s", err)
}
// Now generate a bunch of blocks on each while they're connected,
// triggering many tiny reorgs, and wait for sync again. The end result
// is somewhat random, depending on how quickly the nodes process each
// other's notifications vs finding new blocks, but the two nodes should
// remain fully synchronized with each other at the end.
go harness.h2.Node.Generate(75)
harness.h1.Node.Generate(50)
err = rpctest.JoinNodes([]*rpctest.Harness{harness.h1, harness.h2},
rpctest.Blocks)
if err != nil {
t.Fatalf("Couldn't sync h1 and h2: %s", err)
}
// We increase the timeout because running on Travis with race
// detection enabled can make this pretty slow.
syncTimeout *= 2
err = waitForSync(t, harness.svc, harness.h1)
if err != nil {
checkErrChan(t, errChan)
t.Fatalf("Couldn't sync ChainService: %s", err)
}
close(quitRescan)
err = <-errChan
quitRescan = nil
if err != neutrino.ErrRescanExit {
t.Fatalf("Rescan ended with error: %s", err)
}
// Immediately try to add a new update to to the rescan that was just
// shut down. This should fail as it is no longer running.
rescan.WaitForShutdown()
err = rescan.Update(neutrino.AddAddrs(addr2), neutrino.Rewind(1095))
if err == nil {
t.Fatalf("Expected update call to fail, it did not")
}
}
// testRandomBlocks goes through all blocks in random order and ensures we can
// correctly get cfilters from them. It uses numQueryThreads goroutines running
// at the same time to go through this. 50 is comfortable on my somewhat dated
// laptop with default query optimization settings.
// TODO: Make this a benchmark instead.
func testRandomBlocks(harness *neutrinoHarness, t *testing.T) {
var haveBest *waddrmgr.BlockStamp
haveBest, err := harness.svc.BestSnapshot()
if err != nil {
t.Fatalf("Couldn't get best snapshot from ChainService: %s", err)
}
// Keep track of an error channel with enough buffer space to track one
// error per block.
errChan := make(chan error, haveBest.Height)
// Test getting all of the blocks and filters.
var wg sync.WaitGroup
workerQueue := make(chan struct{}, numQueryThreads)
for i := int32(1); i <= haveBest.Height; i++ {
wg.Add(1)
height := uint32(i)
// Wait until there's room in the worker queue.
workerQueue <- struct{}{}
go func() {
// On exit, open a spot in workerQueue and tell the
// wait group we're done.
defer func() {
<-workerQueue
}()
defer wg.Done()
// Get block header from database.
blockHeader, err := harness.svc.BlockHeaders.
FetchHeaderByHeight(height)
if err != nil {
errChan <- fmt.Errorf("Couldn't get block "+
"header by height %d: %s", height, err)
return
}
blockHash := blockHeader.BlockHash()
// Get block via RPC.
wantBlock, err := harness.h1.Node.GetBlock(&blockHash)
if err != nil {
errChan <- fmt.Errorf("Couldn't get block %d "+
"(%s) by RPC", height, blockHash)
return
}
// Get block from network.
haveBlock, err := harness.svc.GetBlock(
blockHash, queryOptions...,
)
if err != nil {
errChan <- err
return
}
if haveBlock == nil {
errChan <- fmt.Errorf("Couldn't get block %d "+
"(%s) from network", height, blockHash)
return
}
// Check that network and RPC blocks match.
if !reflect.DeepEqual(*haveBlock.MsgBlock(),
*wantBlock) {
errChan <- fmt.Errorf("Block from network "+
"doesn't match block from RPC. Want: "+
"%s, RPC: %s, network: %s", blockHash,
wantBlock.BlockHash(),
haveBlock.MsgBlock().BlockHash())
return
}
// Check that block height matches what we have.
if height != uint32(haveBlock.Height()) {
errChan <- fmt.Errorf("Block height from "+
"network doesn't match expected "+
"height. Want: %v, network: %v",
height, haveBlock.Height())
return
}
// Get basic cfilter from network.
haveFilter, err := harness.svc.GetCFilter(blockHash,
wire.GCSFilterRegular, queryOptions...)
if err != nil {
errChan <- err
return
}
// Get basic cfilter from RPC.
wantFilter, err := harness.h1.Node.GetCFilter(
&blockHash, wire.GCSFilterRegular)
if err != nil {
errChan <- fmt.Errorf("Couldn't get basic "+
"filter for block %d (%s) via RPC: %s",
height, blockHash, err)
return
}
// Check that network and RPC cfilters match.
var haveBytes []byte
if haveFilter != nil {
haveBytes, err = haveFilter.NBytes()
if err != nil {
errChan <- fmt.Errorf("Couldn't get "+
"basic filter for block %d "+
"(%s) via P2P: %s", height,
blockHash, err)
return
}
}
if !bytes.Equal(haveBytes, wantFilter.Data) {
errChan <- fmt.Errorf("Basic filter from P2P "+
"network/DB doesn't match RPC value "+
"for block %d (%s):\nRPC: %s\nNet: %s",
height, blockHash,
hex.EncodeToString(wantFilter.Data),
hex.EncodeToString(haveBytes))
return
}
inputScripts, err := fetchPrevInputScripts(
haveBlock.MsgBlock(),
harness.h1,
)
if err != nil {
errChan <- fmt.Errorf("unable to create prev "+
"input scripts: %v", err)
return
}
// Calculate basic filter from block.
calcFilter, err := builder.BuildBasicFilter(
haveBlock.MsgBlock(), inputScripts,
)
if err != nil {
errChan <- fmt.Errorf("Couldn't build basic "+
"filter for block %d (%s): %s", height,
blockHash, err)
return
}
calcBytes, err := calcFilter.NBytes()
if err != nil {
errChan <- fmt.Errorf("Couldn't get bytes from"+
" calculated basic filter for block "+
"%d (%s): %s", height, blockHash, err)
}
// Check that the network value matches the calculated
// value from the block.
if !bytes.Equal(haveBytes, calcBytes) {
errChan <- fmt.Errorf("Basic filter from P2P "+
"network/DB doesn't match calculated "+
"value for block %d (%s)", height,
blockHash)
return
}
// Get previous basic filter header from the database.
prevHeader, err := harness.svc.RegFilterHeaders.
FetchHeader(&blockHeader.PrevBlock)
if err != nil {
errChan <- fmt.Errorf("Couldn't get basic "+
"filter header for block %d (%s) from "+
"DB: %s", height-1,
blockHeader.PrevBlock, err)
return
}
// Get current basic filter header from the database.
curHeader, err := harness.svc.RegFilterHeaders.
FetchHeader(&blockHash)
if err != nil {
errChan <- fmt.Errorf("Couldn't get basic "+
"filter header for block %d (%s) from "+
"DB: %s", height, blockHash, err)
return
}
// Check that the filter and header line up.
calcHeader, err := builder.MakeHeaderForFilter(
calcFilter, *prevHeader)
if err != nil {
errChan <- fmt.Errorf("Couldn't calculate "+
"header for basic filter for block "+
"%d (%s): %s", height, blockHash, err)
return
}
if !bytes.Equal(curHeader[:], calcHeader[:]) {
errChan <- fmt.Errorf("Filter header doesn't "+
"match. Want: %s, got: %s", curHeader,
calcHeader)
return
}
}()
}
// Wait for all queries to finish.
wg.Wait()
// Close the error channel to make the error monitoring goroutine
// finish.
close(errChan)
var lastErr error
for err := range errChan {
if err != nil {
t.Errorf("%s", err)
lastErr = fmt.Errorf("Couldn't validate all " +
"blocks, filters, and filter headers.")
}
}
if logLevel != btclog.LevelOff {
t.Logf("Finished checking %d blocks and their cfilters",
haveBest.Height)
}
if lastErr != nil {
t.Fatal(lastErr)
}
return
}
func TestNeutrinoSync(t *testing.T) {
// Set up logging.
logger := btclog.NewBackend(os.Stdout)
chainLogger := logger.Logger("CHAIN")
chainLogger.SetLevel(logLevel)
neutrino.UseLogger(chainLogger)
rpcLogger := logger.Logger("RPCC")
rpcLogger.SetLevel(logLevel)
rpcclient.UseLogger(rpcLogger)
// Create a btcd SimNet node and generate 800 blocks
h1, err := rpctest.New(
&chaincfg.SimNetParams, nil, []string{"--txindex"},
)
if err != nil {
t.Fatalf("Couldn't create harness: %s", err)
}
defer h1.TearDown()