forked from ltcsuite/neutrino
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rescan.go
1508 lines (1295 loc) · 43.6 KB
/
rescan.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
// NOTE: THIS API IS UNSTABLE RIGHT NOW.
package neutrino
import (
"bytes"
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/dcrlabs/neutrino-ltc/blockntfns"
"github.com/dcrlabs/neutrino-ltc/headerfs"
"github.com/ltcsuite/ltcd/btcjson"
"github.com/ltcsuite/ltcd/chaincfg"
"github.com/ltcsuite/ltcd/chaincfg/chainhash"
"github.com/ltcsuite/ltcd/ltcutil"
"github.com/ltcsuite/ltcd/ltcutil/gcs"
"github.com/ltcsuite/ltcd/ltcutil/gcs/builder"
"github.com/ltcsuite/ltcd/rpcclient"
"github.com/ltcsuite/ltcd/txscript"
"github.com/ltcsuite/ltcd/wire"
)
var (
// zeroOutPoint indicates that we should match on an output's script
// when dispatching a spend notification.
zeroOutPoint wire.OutPoint
// ErrRescanExit is an error returned to the caller in case the ongoing
// rescan exits.
ErrRescanExit = errors.New("rescan exited")
// errRetryBlock is an internal error used to signal to the rescan
// should it should attempt to retry processing a block.
errRetryBlock = errors.New("block must be retried")
)
// ChainSource is an interface that's in charge of retrieving information about
// the existing chain.
type ChainSource interface {
// ChainParams returns the parameters of the current chain.
ChainParams() chaincfg.Params
// BestBlock retrieves the most recent block's height and hash where we
// have both the header and filter header ready.
BestBlock() (*headerfs.BlockStamp, error)
// GetBlockHeaderByHeight returns the header of the block with the given
// height.
GetBlockHeaderByHeight(uint32) (*wire.BlockHeader, error)
// GetBlockHeader returns the header of the block with the given hash.
GetBlockHeader(*chainhash.Hash) (*wire.BlockHeader, uint32, error)
// GetBlock returns the block with the given hash.
GetBlock(chainhash.Hash, ...QueryOption) (*ltcutil.Block, error)
// GetFilterHeaderByHeight returns the filter header of the block with
// the given height.
GetFilterHeaderByHeight(uint32) (*chainhash.Hash, error)
// GetCFilter returns the filter of the given type for the block with
// the given hash.
GetCFilter(chainhash.Hash, wire.FilterType,
...QueryOption) (*gcs.Filter, error)
// Subscribe returns a block subscription that delivers block
// notifications in order. The bestHeight parameter can be used to
// signal that a backlog of notifications should be delivered from this
// height. When providing a bestHeight of 0, a backlog will not be
// delivered.
//
// TODO(wilmer): extend with best hash as well.
Subscribe(bestHeight uint32) (*blockntfns.Subscription, error)
}
// ScanProgressHandler is used in rescanOptions to update the caller with the
// rescan progress.
type ScanProgressHandler func(lastProcessedBlock uint32)
// rescanOptions holds the set of functional parameters for Rescan.
type rescanOptions struct {
queryOptions []QueryOption
ntfn rpcclient.NotificationHandlers
progressHandler ScanProgressHandler
startTime time.Time
startBlock *headerfs.BlockStamp
endBlock *headerfs.BlockStamp
watchAddrs []ltcutil.Address
watchInputs []InputWithScript
watchList [][]byte
txIdx uint32
update <-chan *updateOptions
quit <-chan struct{}
}
// RescanOption is a functional option argument to any of the rescan and
// notification subscription methods. These are always processed in order, with
// later options overriding earlier ones.
type RescanOption func(ro *rescanOptions)
func defaultRescanOptions() *rescanOptions {
return &rescanOptions{}
}
// QueryOptions pass onto the underlying queries.
func QueryOptions(options ...QueryOption) RescanOption {
return func(ro *rescanOptions) {
ro.queryOptions = options
}
}
// NotificationHandlers specifies notification handlers for the rescan. These
// will always run in the same goroutine as the caller.
func NotificationHandlers(ntfn rpcclient.NotificationHandlers) RescanOption {
return func(ro *rescanOptions) {
ro.ntfn = ntfn
}
}
// ProgressHandler specifies a handler to be used when the utxo
// scanner reports its progress.
// The passed handler should be non-blocking for the rescan to continue
// normally.
func ProgressHandler(
handler ScanProgressHandler) RescanOption {
return func(ro *rescanOptions) {
ro.progressHandler = handler
}
}
// StartBlock specifies the start block. The hash is checked first; if there's
// no such hash (zero hash avoids lookup), the height is checked next. If the
// height is 0 or the start block isn't specified, starts from the genesis
// block. This block is assumed to already be known, and no notifications will
// be sent for this block. The rescan uses the latter of StartBlock and
// StartTime.
func StartBlock(startBlock *headerfs.BlockStamp) RescanOption {
return func(ro *rescanOptions) {
ro.startBlock = startBlock
}
}
// StartTime specifies the start time. The time is compared to the timestamp of
// each block, and the rescan only begins once the first block crosses that
// timestamp. When using this, it is advisable to use a margin of error and
// start rescans slightly earlier than required. The rescan uses the latter of
// StartBlock and StartTime.
func StartTime(startTime time.Time) RescanOption {
return func(ro *rescanOptions) {
ro.startTime = startTime
}
}
// EndBlock specifies the end block. The hash is checked first; if there's no
// such hash (zero hash avoids lookup), the height is checked next. If the
// height is 0 or in the future or the end block isn't specified, the quit
// channel MUST be specified as Rescan will sync to the tip of the blockchain
// and continue to stay in sync and pass notifications. This is enforced at
// runtime.
func EndBlock(endBlock *headerfs.BlockStamp) RescanOption {
return func(ro *rescanOptions) {
ro.endBlock = endBlock
}
}
// WatchAddrs specifies the addresses to watch/filter for. Each call to this
// function adds to the list of addresses being watched rather than replacing
// the list. Each time a transaction spends to the specified address, the
// outpoint is added to the WatchOutPoints list.
func WatchAddrs(watchAddrs ...ltcutil.Address) RescanOption {
return func(ro *rescanOptions) {
ro.watchAddrs = append(ro.watchAddrs, watchAddrs...)
}
}
// InputWithScript couples an previous outpoint along with its input script.
// We'll use the prev script to match the filter itself, but then scan for the
// particular outpoint when we need to make a notification decision.
type InputWithScript struct {
// OutPoint identifies the previous output to watch.
OutPoint wire.OutPoint
// PkScript is the script of the previous output.
PkScript []byte
}
// WatchInputs specifies the outpoints to watch for on-chain spends. We also
// require the script as we'll match on the script, but then notify based on
// the outpoint. Each call to this function adds to the list of outpoints being
// watched rather than replacing the list.
func WatchInputs(watchInputs ...InputWithScript) RescanOption {
return func(ro *rescanOptions) {
ro.watchInputs = append(ro.watchInputs, watchInputs...)
}
}
// TxIdx specifies a hint transaction index into the block in which the UTXO is
// created (eg, coinbase is 0, next transaction is 1, etc.)
func TxIdx(txIdx uint32) RescanOption {
return func(ro *rescanOptions) {
ro.txIdx = txIdx
}
}
// QuitChan specifies the quit channel. This can be used by the caller to let
// an indefinite rescan (one with no EndBlock set) know it should gracefully
// shut down. If this isn't specified, an end block MUST be specified as Rescan
// must know when to stop. This is enforced at runtime.
func QuitChan(quit <-chan struct{}) RescanOption {
return func(ro *rescanOptions) {
ro.quit = quit
}
}
// blockRetryQueue is a helper struct that maintains a queue of blocks for which
// we need to fetch filters.
type blockRetryQueue struct {
blocks []*blockntfns.Connected
}
// newBlockRetryQueue constructs a new, empty retry block queue.
func newBlockRetryQueue() *blockRetryQueue {
return &blockRetryQueue{}
}
// push enqueues a block at the end of the queue.
func (q *blockRetryQueue) push(block *blockntfns.Connected) {
q.blocks = append(q.blocks, block)
}
// peek returns the next block to be retried but doesn't consume it.
func (q *blockRetryQueue) peek() *blockntfns.Connected {
if len(q.blocks) == 0 {
return nil
}
return q.blocks[0]
}
// pop returns and consumes the next block to be retried.
func (q *blockRetryQueue) pop() *blockntfns.Connected {
if len(q.blocks) == 0 {
return nil
}
block := q.blocks[0]
q.blocks[0] = nil
q.blocks = q.blocks[1:]
return block
}
// remove removes the block from the queue and any others that follow it. If the
// block doesn't exit within the queue, then this acts as a NOP.
func (q *blockRetryQueue) remove(header wire.BlockHeader) {
headerIdx := -1
targetHash := header.BlockHash()
for i, block := range q.blocks {
blockHeader := block.Header()
if blockHeader.BlockHash() == targetHash {
headerIdx = i
break
}
}
if headerIdx != -1 {
for i := headerIdx; i < len(q.blocks); i++ {
q.blocks[i] = nil
}
q.blocks = q.blocks[:headerIdx]
}
}
// clear clears the queue.
func (q *blockRetryQueue) clear() {
q.blocks = nil
}
// updateChan specifies an update channel. This is for internal use by the
// Rescan.Update functionality.
func updateChan(update <-chan *updateOptions) RescanOption {
return func(ro *rescanOptions) {
ro.update = update
}
}
// rescan is a single-threaded function that uses headers from the database and
// functional options as arguments.
func rescan(chain ChainSource, options ...RescanOption) error {
// First, we'll apply the set of default options, then serially apply
// all the options that've been passed in.
ro := defaultRescanOptions()
ro.endBlock = &headerfs.BlockStamp{
Hash: chainhash.Hash{},
Height: 0,
}
for _, option := range options {
option(ro)
}
// If we have something to watch, create a watch list. The watch list
// can be composed of a set of scripts, outpoints, and txids.
for _, addr := range ro.watchAddrs {
script, err := txscript.PayToAddrScript(addr)
if err != nil {
return err
}
ro.watchList = append(ro.watchList, script)
}
for _, input := range ro.watchInputs {
ro.watchList = append(ro.watchList, input.PkScript)
}
// Check that we have either an end block or a quit channel.
if ro.endBlock != nil {
// If the end block hash is non-nil, then we'll query the
// database to find out the stop height.
if (ro.endBlock.Hash != chainhash.Hash{}) {
_, height, err := chain.GetBlockHeader(
&ro.endBlock.Hash,
)
if err != nil {
ro.endBlock.Hash = chainhash.Hash{}
} else {
ro.endBlock.Height = int32(height)
}
}
// If the ending hash it nil, then check to see if the target
// height is non-nil. If not, then we'll use this to find the
// stopping hash.
if (ro.endBlock.Hash == chainhash.Hash{}) {
if ro.endBlock.Height != 0 {
header, err := chain.GetBlockHeaderByHeight(
uint32(ro.endBlock.Height),
)
if err == nil {
ro.endBlock.Hash = header.BlockHash()
} else {
ro.endBlock = &headerfs.BlockStamp{}
}
}
}
} else {
ro.endBlock = &headerfs.BlockStamp{}
}
// If we don't have a quit channel, and the end height is still
// unspecified, then we'll exit out here.
if ro.quit == nil && ro.endBlock.Height == 0 {
return fmt.Errorf("rescan request must specify a quit channel" +
" or valid end block")
}
// Track our position in the chain.
var (
curHeader wire.BlockHeader
curStamp headerfs.BlockStamp
)
// If no start block is specified, start the scan from our current best
// block.
if ro.startBlock == nil {
bs, err := chain.BestBlock()
if err != nil {
return err
}
ro.startBlock = bs
}
curStamp = *ro.startBlock
// To find our starting block, either the start hash should be set, or
// the start height should be set. If neither is, then we'll be
// starting from the genesis block.
if (curStamp.Hash != chainhash.Hash{}) {
header, height, err := chain.GetBlockHeader(&curStamp.Hash)
if err == nil {
curHeader = *header
curStamp.Height = int32(height)
} else {
curStamp.Hash = chainhash.Hash{}
}
}
if (curStamp.Hash == chainhash.Hash{}) {
if curStamp.Height == 0 {
curStamp.Hash = *chain.ChainParams().GenesisHash
} else {
header, err := chain.GetBlockHeaderByHeight(
uint32(curStamp.Height),
)
if err == nil {
curHeader = *header
curStamp.Hash = curHeader.BlockHash()
} else {
curHeader = chain.ChainParams().GenesisBlock.Header
curStamp.Hash = *chain.ChainParams().GenesisHash
curStamp.Height = 0
}
}
}
// Now that we've determined the starting point of our rescan, we can
// begin processing updates from the client.
var updates []*updateOptions
// We'll need to ensure that the backing chain has actually caught up to
// the rescan's starting height.
bestBlock, err := chain.BestBlock()
if err != nil {
return err
}
// If it hasn't, we'll subscribe for block notifications at tip and wait
// until we receive a notification for a block with the rescan's
// starting height.
if bestBlock.Height < curStamp.Height {
log.Debugf("Waiting to catch up to the rescan start height=%d "+
"from height=%d", curStamp.Height, bestBlock.Height)
blockSubscription, err := chain.Subscribe(
uint32(bestBlock.Height),
)
if err != nil {
return err
}
waitUntilSynced:
for {
select {
// We'll make sure to process any updates while we're
// syncing to prevent blocking the client.
case update := <-ro.update:
updates = append(updates, update)
// A new block notification for the tip of the chain has
// arrived. We'll determine we've caught up to the
// rescan's starting height by receiving a block
// connected notification for the same height.
case ntfn, ok := <-blockSubscription.Notifications:
if !ok {
return errors.New("rescan block " +
"subscription was canceled " +
"while waiting to catch up")
}
if _, ok := ntfn.(*blockntfns.Connected); !ok {
continue
}
if ntfn.Height() < uint32(curStamp.Height) {
continue
}
break waitUntilSynced
case <-ro.quit:
blockSubscription.Cancel()
return ErrRescanExit
}
}
blockSubscription.Cancel()
// If any updates were queued while waiting to catch up to the
// start height of the rescan, apply them now.
for _, upd := range updates {
_, err := ro.updateFilter(
chain, upd, &curStamp, &curHeader,
)
if err != nil {
return err
}
}
}
log.Debugf("Starting rescan from known block %d (%s)", curStamp.Height,
curStamp.Hash)
// Compare the start time to the start block. If the start time is
// later, cycle through blocks until we find a block timestamp later
// than the start time, and begin filter download at that block. Since
// time is non-monotonic between blocks, we look for the first block to
// trip the switch, and download filters from there, rather than
// checking timestamps at each block.
scanning := ro.startTime.Before(curHeader.Timestamp)
// Even though we'll have multiple subscriptions, they'll always be
// referred to by the same variable, so we only need to defer its
// cancellation once at the end. Any intermediate subscriptions should
// be properly canceled before registering a new one.
var blockSubscription *blockntfns.Subscription
defer func() {
if blockSubscription != nil {
blockSubscription.Cancel()
blockSubscription = nil
}
}()
var (
blockRetrySignal <-chan time.Time
// blockRetryInterval is the interval in which we'll continually
// retry to fetch the latest filter from our peers.
//
// TODO(roasbeef): add exponential back-off
blockRetryInterval = time.Millisecond * 100
blockRetryQueue = newBlockRetryQueue()
)
// handleBlockConnected is a closure that handles a new block connected
// notification.
//
// TODO(wilmer): refactor this and handleBlockDisconnected into their
// own methods.
handleBlockConnected := func(ntfn *blockntfns.Connected) error {
// If we've somehow missed a header in the range, then we'll
// mark ourselves as not current so we can walk down the chain
// and notify the callers of blocks we may have missed.
header := ntfn.Header()
if header.PrevBlock != curStamp.Hash {
return fmt.Errorf("out of order block %v: expected "+
"PrevBlock %v, got %v", header.BlockHash(),
curStamp.Hash, header.PrevBlock)
}
// Ensure the filter header still exists before attempting to
// fetch the filter. This should usually succeed since
// notifications are delivered once filter headers are synced.
nextBlockHeight := uint32(curStamp.Height + 1)
_, err := chain.GetFilterHeaderByHeight(nextBlockHeight)
if err != nil {
return fmt.Errorf("unable to get filter header for "+
"new block with height %v: %v", nextBlockHeight,
err)
}
newStamp := headerfs.BlockStamp{
Hash: header.BlockHash(),
Height: int32(nextBlockHeight),
Timestamp: header.Timestamp,
}
log.Tracef("Rescan got block %d (%s)", newStamp.Height,
newStamp.Hash)
// We're only scanning if the header is beyond the horizon of
// our start time.
if !scanning {
scanning = ro.startTime.Before(header.Timestamp)
}
// If we're not scanning or our watch list is empty, then we can
// just notify the block without fetching any filters/blocks.
if !scanning || len(ro.watchList) == 0 {
if ro.ntfn.OnFilteredBlockConnected != nil {
ro.ntfn.OnFilteredBlockConnected(
newStamp.Height, &header, nil,
)
}
if ro.ntfn.OnBlockConnected != nil { // nolint:staticcheck
ro.ntfn.OnBlockConnected( // nolint:staticcheck
&newStamp.Hash, newStamp.Height,
header.Timestamp,
)
}
curHeader = header
curStamp = newStamp
return nil
}
// Otherwise, we'll attempt to fetch the filter to retrieve the
// relevant transactions and notify them.
queryOptions := NumRetries(0)
blockFilter, err := chain.GetCFilter(
newStamp.Hash, wire.GCSFilterRegular, queryOptions,
)
if err != nil {
// If the query failed, then this either means that we
// don't have any peers to fetch this filter from, or
// the peer(s) that we're trying to fetch from are in
// the progress of a re-org.
log.Errorf("unable to get filter for hash=%v, "+
"retrying: %v", curStamp.Hash, err)
return errRetryBlock
}
err = notifyBlockWithFilter(
chain, ro, &header, &newStamp, blockFilter,
)
if err != nil {
return err
}
// With the block successfully notified, we'll advance our state
// to it.
curHeader = header
curStamp = newStamp
return nil
}
// handleBlockDisconnected is a helper closure that handles a new block
// disconnected notification.
handleBlockDisconnected := func(ntfn *blockntfns.Disconnected) error { // nolint:unparam
blockDisconnected := ntfn.Header()
log.Debugf("Rescan got disconnected block %d (%s)",
ntfn.Height(), blockDisconnected.BlockHash())
// Only deal with it if it's the current block we know about.
// Otherwise, it's in the future.
if blockDisconnected.BlockHash() != curStamp.Hash {
return nil
}
// Run through notifications. This is all single-threaded. We
// include deprecated calls as they're still used, for now.
if ro.ntfn.OnFilteredBlockDisconnected != nil {
ro.ntfn.OnFilteredBlockDisconnected(
curStamp.Height, &curHeader,
)
}
if ro.ntfn.OnBlockDisconnected != nil { // nolint:staticcheck
ro.ntfn.OnBlockDisconnected( // nolint:staticcheck
&curStamp.Hash, curStamp.Height,
curHeader.Timestamp,
)
}
curHeader = ntfn.ChainTip()
curStamp.Hash = curHeader.BlockHash()
curStamp.Height--
return nil
}
// We'll need to keep track of whether we are current with the chain in
// order to properly recover from a re-org. We'll start by assuming that
// we are not current in order to catch up from the starting point to
// the tip of the chain.
current := false
// Loop through blocks, one at a time. This relies on the underlying
// chain source to deliver notifications in the correct order.
rescanLoop:
for {
// If we've reached the ending height or hash for this rescan,
// then we'll exit.
if curStamp.Hash == ro.endBlock.Hash ||
(ro.endBlock.Height > 0 &&
curStamp.Height == ro.endBlock.Height) {
return nil
}
// If we're current, we wait for notifications that will be
// delivered each time a block is connecting, disconnecting, or
// we can an update to the filter we should be looking for.
switch current {
case true:
// Wait for a signal that we have a newly connected
// header and cfheader, or a newly disconnected header;
// alternatively, forward ourselves to the next block
// if possible.
select {
case <-ro.quit:
return ErrRescanExit
// An update mesage has just come across, if it points
// to a prior point in the chain, then we may need to
// rewind a bit in order to provide the client all its
// requested client.
case update := <-ro.update:
rewound, err := ro.updateFilter(
chain, update, &curStamp, &curHeader,
)
if err != nil {
return err
}
// If we have to rewind our state, then we'll
// mark ourselves as not current so we can walk
// forward in the chain again until we we are
// current. This is our way of doing a manual
// rescan.
if rewound {
log.Tracef("Rewound to block %d (%s), "+
"no longer current",
curStamp.Height, curStamp.Hash)
current = false
blockSubscription.Cancel()
blockSubscription = nil
}
case ntfn, ok := <-blockSubscription.Notifications:
if !ok {
return errors.New("rescan block " +
"subscription was canceled")
}
switch ntfn := ntfn.(type) {
case *blockntfns.Connected:
// If we have any blocks to retry, we'll
// defer processing this notification
// until later.
if blockRetryQueue.peek() != nil {
log.Debugf("Stashing %v", ntfn)
blockRetryQueue.push(ntfn)
continue rescanLoop
}
err := handleBlockConnected(ntfn)
switch err {
case nil:
// We'll need to retry the block again
// as we couldn't fetch its filter.
case errRetryBlock:
log.Debugf("Retrying %v after %v",
ntfn, blockRetryInterval)
blockRetryQueue.push(ntfn)
blockRetrySignal = time.After(
blockRetryInterval,
)
// Since we weren't able to successfully
// process the block, we'll set
// ourselves to not be current in order
// to attempt catching up with the chain
// ourselves.
//
// TODO(wilmer): determine if the error
// is fatal and return it?
default:
log.Errorf("Unable to process "+
"%v: %v", ntfn, err)
current = false
}
case *blockntfns.Disconnected:
// Check whether the block being
// disconnected is one for which we've
// queued up to retry. If it is, we'll
// remove it and any others that follow
// as they are now considered stale.
blockRetryQueue.remove(ntfn.Header())
err := handleBlockDisconnected(ntfn)
if err != nil {
log.Errorf("Unable to process "+
"%v: %v", ntfn, err)
}
default:
log.Warnf("Received unhandled block "+
"notification: %T", ntfn)
}
// Our retry signal has fired, so we'll attempt to
// refetch and notify the filter for our queued blocks.
case <-blockRetrySignal:
blockRetrySignal = nil
// We'll go through all of our retry blocks in
// order unless we need to retry any of them.
retryLoop:
for {
retryBlock := blockRetryQueue.peek()
if retryBlock == nil {
continue rescanLoop
}
err := handleBlockConnected(retryBlock)
switch err {
// We successfully notified the block
// this time, so we can remove it from
// our queue and move on to the next.
case nil:
_ = blockRetryQueue.pop()
continue retryLoop
// We'll need to retry the block again
// as we couldn't fetch its filter.
case errRetryBlock:
log.Debugf("Retrying %v after "+
"%v", retryBlock,
blockRetryInterval)
blockRetrySignal = time.After(
blockRetryInterval,
)
continue rescanLoop
// Since we weren't able to successfully
// process the block, we'll set
// ourselves to not be current in order
// to attempt catching up with the chain
// ourselves.
//
// TODO(wilmer): determine if the error
// is fatal and return it?
default:
log.Errorf("Unable to process "+
"retry of %v: %v",
retryBlock, err)
current = false
continue rescanLoop
}
}
}
// If we're not yet current, then we'll walk down the chain
// until we reach the tip of the chain as we know it. At this
// point, we'll be "current" again.
case false:
// Apply all queued filter updates.
updateFilterLoop:
for {
select {
case update := <-ro.update:
_, err := ro.updateFilter(
chain, update, &curStamp,
&curHeader,
)
if err != nil {
return err
}
default:
break updateFilterLoop
}
}
bestBlock, err := chain.BestBlock()
if err != nil {
return err
}
// Since we're not current, we try to manually advance
// the block. If the next height is above the best
// height known to the chain service, then we mark
// ourselves as current and follow notifications.
nextHeight := curStamp.Height + 1
if nextHeight > bestBlock.Height {
// Ensure we cancel the old subscription if
// we're going back to scan for missed blocks.
if blockSubscription != nil {
blockSubscription.Cancel()
}
// Subscribe to block notifications.
blockSubscription, err = chain.Subscribe(
uint32(curStamp.Height),
)
if err != nil {
return fmt.Errorf("unable to register "+
"block subscription: %v", err)
}
log.Debugf("Rescan became current at %d (%s), "+
"subscribing to block notifications",
curStamp.Height, curStamp.Hash)
current = true
blockRetryQueue.clear()
continue rescanLoop
}
// If the next height is known to the chain service,
// then we'll fetch the next block and send a
// notification, maybe also scanning the filters for
// the block.
header, err := chain.GetBlockHeaderByHeight(
uint32(nextHeight),
)
if err != nil {
return err
}
curHeader = *header
curStamp.Height++
curStamp.Hash = header.BlockHash()
if !scanning {
scanning = ro.startTime.Before(curHeader.Timestamp)
}
err = notifyBlock(chain, ro, curHeader, curStamp, scanning)
if err != nil {
return err
}
}
}
}
// notifyBlock calls appropriate listeners based on the block filter.
func notifyBlock(chain ChainSource, ro *rescanOptions,
curHeader wire.BlockHeader, curStamp headerfs.BlockStamp,
scanning bool) error {
// Find relevant transactions based on watch list. If scanning is
// false, we can safely assume this block has no relevant transactions.
var relevantTxs []*ltcutil.Tx
if len(ro.watchList) != 0 && scanning {
// If we have a non-empty watch list, then we need to see if it
// matches the rescan's filters, so we get the basic filter
// from the DB or network.
matched, filter, err := blockFilterMatches(
chain, ro, &curStamp.Hash,
)
if err != nil {
return err
}
if matched {
relevantTxs, err = extractBlockMatches(
chain, ro, &curStamp, filter,
)
if err != nil {
return err
}
}
}
if ro.ntfn.OnFilteredBlockConnected != nil {
ro.ntfn.OnFilteredBlockConnected(curStamp.Height, &curHeader,
relevantTxs)
}
if ro.ntfn.OnBlockConnected != nil { // nolint:staticcheck
ro.ntfn.OnBlockConnected(&curStamp.Hash, // nolint:staticcheck
curStamp.Height, curHeader.Timestamp)
}
return nil
}
// extractBlockMatches fetches the target block from the network, and filters
// out any relevant transactions found within the block.
func extractBlockMatches(chain ChainSource, ro *rescanOptions,
curStamp *headerfs.BlockStamp, filter *gcs.Filter) ([]*ltcutil.Tx,
error) {
// We've matched. Now we actually get the block and cycle through the
// transactions to see which ones are relevant.
block, err := chain.GetBlock(curStamp.Hash, ro.queryOptions...)
if err != nil {
return nil, err
}
if block == nil {
return nil, fmt.Errorf("couldn't get block %d (%s) from "+
"network", curStamp.Height, curStamp.Hash)
}
// Before we go through the transactions, let's make sure the filter we
// got from our peer is valid and includes all spent previous output
// scripts. If there's a problem, the error returned here will be
// interpreted by the block manager to disconnect/ban said peer.
if _, err := VerifyBasicBlockFilter(filter, block); err != nil {
return nil, fmt.Errorf("error verifying filter against "+
"downloaded block %d (%s), possibly got invalid "+
"filter from peer: %v", curStamp.Height, curStamp.Hash,
err)
}
blockHeader := block.MsgBlock().Header
blockDetails := btcjson.BlockDetails{
Height: block.Height(),
Hash: block.Hash().String(),
Time: blockHeader.Timestamp.Unix(),
}
relevantTxs := make([]*ltcutil.Tx, 0, len(block.Transactions()))
for txIdx, tx := range block.Transactions() {
txDetails := blockDetails
txDetails.Index = txIdx
var relevant bool
if ro.spendsWatchedInput(tx) {
relevant = true
if ro.ntfn.OnRedeemingTx != nil { // nolint:staticcheck
ro.ntfn.OnRedeemingTx(tx, &txDetails) // nolint:staticcheck
}
}
// Even though the transaction may already be known as relevant
// and there might not be a notification callback, we need to
// call paysWatchedAddr anyway as it updates the rescan
// options.
pays, err := ro.paysWatchedAddr(tx)
if err != nil {
return nil, err