forked from planetdecred/dcrlibwallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
syncnotification.go
686 lines (555 loc) · 26.5 KB
/
syncnotification.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
package dcrlibwallet
import (
"math"
"time"
"github.com/planetdecred/dcrlibwallet/spv"
"golang.org/x/sync/errgroup"
)
func (mw *MultiWallet) spvSyncNotificationCallbacks() *spv.Notifications {
return &spv.Notifications{
PeerConnected: func(peerCount int32, addr string) {
mw.handlePeerCountUpdate(peerCount)
},
PeerDisconnected: func(peerCount int32, addr string) {
mw.handlePeerCountUpdate(peerCount)
},
Synced: mw.synced,
FetchHeadersStarted: mw.fetchHeadersStarted,
FetchHeadersProgress: mw.fetchHeadersProgress,
FetchHeadersFinished: mw.fetchHeadersFinished,
FetchMissingCFiltersStarted: mw.fetchCFiltersStarted,
FetchMissingCFiltersProgress: mw.fetchCFiltersProgress,
FetchMissingCFiltersFinished: mw.fetchCFiltersEnded,
DiscoverAddressesStarted: mw.discoverAddressesStarted,
DiscoverAddressesFinished: mw.discoverAddressesFinished,
RescanStarted: mw.rescanStarted,
RescanProgress: mw.rescanProgress,
RescanFinished: mw.rescanFinished,
}
}
func (mw *MultiWallet) handlePeerCountUpdate(peerCount int32) {
mw.syncData.mu.Lock()
mw.syncData.connectedPeers = peerCount
shouldLog := mw.syncData.showLogs && mw.syncData.syncing
mw.syncData.mu.Unlock()
for _, syncProgressListener := range mw.syncProgressListeners() {
syncProgressListener.OnPeerConnectedOrDisconnected(peerCount)
}
if shouldLog {
if peerCount == 1 {
log.Infof("Connected to %d peer on %s.", peerCount, mw.chainParams.Name)
} else {
log.Infof("Connected to %d peers on %s.", peerCount, mw.chainParams.Name)
}
}
}
// Fetch CFilters Callbacks
func (mw *MultiWallet) fetchCFiltersStarted(walletID int) {
mw.syncData.mu.Lock()
mw.syncData.activeSyncData.syncStage = CFiltersFetchSyncStage
mw.syncData.activeSyncData.cfiltersFetchProgress.beginFetchCFiltersTimeStamp = time.Now().Unix()
mw.syncData.activeSyncData.cfiltersFetchProgress.totalFetchedCFiltersCount = 0
showLogs := mw.syncData.showLogs
mw.syncData.mu.Unlock()
if showLogs {
log.Infof("Step 1 of 3 - fetching %d block headers.")
}
}
func (mw *MultiWallet) fetchCFiltersProgress(walletID int, startCFiltersHeight, endCFiltersHeight int32) {
// lock the mutex before reading and writing to mw.syncData.*
mw.syncData.mu.Lock()
if mw.syncData.activeSyncData.cfiltersFetchProgress.startCFiltersHeight == -1 {
mw.syncData.activeSyncData.cfiltersFetchProgress.startCFiltersHeight = startCFiltersHeight
}
wallet := mw.WalletWithID(walletID)
mw.syncData.activeSyncData.cfiltersFetchProgress.totalFetchedCFiltersCount += endCFiltersHeight - startCFiltersHeight
totalCFiltersToFetch := wallet.GetBestBlock() - mw.syncData.activeSyncData.cfiltersFetchProgress.startCFiltersHeight
// cfiltersLeftToFetch := totalCFiltersToFetch - mw.syncData.activeSyncData.cfiltersFetchProgress.totalFetchedCFiltersCount
cfiltersFetchProgress := float64(mw.syncData.activeSyncData.cfiltersFetchProgress.totalFetchedCFiltersCount) / float64(totalCFiltersToFetch)
// If there was some period of inactivity,
// assume that this process started at some point in the future,
// thereby accounting for the total reported time of inactivity.
mw.syncData.activeSyncData.cfiltersFetchProgress.beginFetchCFiltersTimeStamp += mw.syncData.activeSyncData.totalInactiveSeconds
mw.syncData.activeSyncData.totalInactiveSeconds = 0
timeTakenSoFar := time.Now().Unix() - mw.syncData.activeSyncData.cfiltersFetchProgress.beginFetchCFiltersTimeStamp
if timeTakenSoFar < 1 {
timeTakenSoFar = 1
}
estimatedTotalCFiltersFetchTime := float64(timeTakenSoFar) / cfiltersFetchProgress
// Use CFilters fetch rate to estimate headers fetch time.
cfiltersFetchRate := float64(mw.syncData.activeSyncData.cfiltersFetchProgress.totalFetchedCFiltersCount) / float64(timeTakenSoFar)
estimatedHeadersLeftToFetch := mw.estimateBlockHeadersCountAfter(wallet.GetBestBlockTimeStamp())
estimatedTotalHeadersFetchTime := float64(estimatedHeadersLeftToFetch) / cfiltersFetchRate
// increase estimated value by FetchPercentage
estimatedTotalHeadersFetchTime /= FetchPercentage
estimatedDiscoveryTime := estimatedTotalHeadersFetchTime * DiscoveryPercentage
estimatedRescanTime := estimatedTotalHeadersFetchTime * RescanPercentage
estimatedTotalSyncTime := estimatedTotalCFiltersFetchTime + estimatedTotalHeadersFetchTime + estimatedDiscoveryTime + estimatedRescanTime
totalSyncProgress := float64(timeTakenSoFar) / estimatedTotalSyncTime
totalTimeRemainingSeconds := int64(math.Round(estimatedTotalSyncTime)) - timeTakenSoFar
// update headers fetching progress report including total progress percentage and total time remaining
mw.syncData.activeSyncData.cfiltersFetchProgress.TotalCFiltersToFetch = totalCFiltersToFetch
mw.syncData.activeSyncData.cfiltersFetchProgress.CurrentCFilterHeight = startCFiltersHeight
mw.syncData.activeSyncData.cfiltersFetchProgress.CFiltersFetchProgress = roundUp(cfiltersFetchProgress * 100.0)
mw.syncData.activeSyncData.cfiltersFetchProgress.TotalSyncProgress = roundUp(totalSyncProgress * 100.0)
mw.syncData.activeSyncData.cfiltersFetchProgress.TotalTimeRemainingSeconds = totalTimeRemainingSeconds
mw.syncData.mu.Unlock()
// notify progress listener of estimated progress report
mw.publishFetchCFiltersProgress()
cfiltersFetchTimeRemaining := estimatedTotalCFiltersFetchTime - float64(timeTakenSoFar)
debugInfo := &DebugInfo{
timeTakenSoFar,
totalTimeRemainingSeconds,
timeTakenSoFar,
int64(math.Round(cfiltersFetchTimeRemaining)),
}
mw.publishDebugInfo(debugInfo)
}
func (mw *MultiWallet) publishFetchCFiltersProgress() {
for _, syncProgressListener := range mw.syncProgressListeners() {
syncProgressListener.OnCFiltersFetchProgress(&mw.syncData.cfiltersFetchProgress)
}
}
func (mw *MultiWallet) fetchCFiltersEnded(walletID int) {
mw.syncData.mu.Lock()
defer mw.syncData.mu.Unlock()
mw.syncData.activeSyncData.cfiltersFetchProgress.cfiltersFetchTimeSpent = time.Now().Unix() - mw.syncData.cfiltersFetchProgress.beginFetchCFiltersTimeStamp
// If there is some period of inactivity reported at this stage,
// subtract it from the total stage time.
mw.syncData.activeSyncData.cfiltersFetchProgress.cfiltersFetchTimeSpent -= mw.syncData.totalInactiveSeconds
mw.syncData.activeSyncData.totalInactiveSeconds = 0
}
// Fetch Headers Callbacks
func (mw *MultiWallet) fetchHeadersStarted(peerInitialHeight int32) {
if !mw.IsSyncing() {
return
}
mw.syncData.mu.RLock()
headersFetchingStarted := mw.syncData.headersFetchProgress.beginFetchTimeStamp != -1
showLogs := mw.syncData.showLogs
mw.syncData.mu.RUnlock()
if headersFetchingStarted {
// This function gets called for each newly connected peer so
// ignore if headers fetching was already started.
return
}
for _, wallet := range mw.wallets {
wallet.waitingForHeaders = true
}
lowestBlockHeight := mw.GetLowestBlock().Height
mw.syncData.mu.Lock()
mw.syncData.activeSyncData.syncStage = HeadersFetchSyncStage
mw.syncData.activeSyncData.headersFetchProgress.beginFetchTimeStamp = time.Now().Unix()
mw.syncData.activeSyncData.headersFetchProgress.startHeaderHeight = lowestBlockHeight
mw.syncData.headersFetchProgress.totalFetchedHeadersCount = 0
mw.syncData.activeSyncData.totalInactiveSeconds = 0
mw.syncData.mu.Unlock()
if showLogs {
log.Infof("Step 1 of 3 - fetching %d block headers.", peerInitialHeight-lowestBlockHeight)
}
}
func (mw *MultiWallet) fetchHeadersProgress(lastFetchedHeaderHeight int32, lastFetchedHeaderTime int64) {
if !mw.IsSyncing() {
return
}
mw.syncData.mu.RLock()
headersFetchingCompleted := mw.syncData.activeSyncData.headersFetchProgress.headersFetchTimeSpent != -1
mw.syncData.mu.RUnlock()
if headersFetchingCompleted {
// This function gets called for each newly connected peer so ignore
// this call if the headers fetching phase was previously completed.
return
}
for _, wallet := range mw.wallets {
if wallet.waitingForHeaders {
wallet.waitingForHeaders = wallet.GetBestBlock() > lastFetchedHeaderHeight
}
}
// lock the mutex before reading and writing to mw.syncData.*
mw.syncData.mu.Lock()
if lastFetchedHeaderHeight > mw.syncData.activeSyncData.headersFetchProgress.startHeaderHeight {
mw.syncData.activeSyncData.headersFetchProgress.totalFetchedHeadersCount = lastFetchedHeaderHeight - mw.syncData.activeSyncData.headersFetchProgress.startHeaderHeight
}
headersLeftToFetch := mw.estimateBlockHeadersCountAfter(lastFetchedHeaderTime)
totalHeadersToFetch := lastFetchedHeaderHeight + headersLeftToFetch
headersFetchProgress := float64(mw.syncData.activeSyncData.headersFetchProgress.totalFetchedHeadersCount) / float64(totalHeadersToFetch)
// If there was some period of inactivity,
// assume that this process started at some point in the future,
// thereby accounting for the total reported time of inactivity.
mw.syncData.activeSyncData.headersFetchProgress.beginFetchTimeStamp += mw.syncData.activeSyncData.totalInactiveSeconds
mw.syncData.activeSyncData.totalInactiveSeconds = 0
fetchTimeTakenSoFar := time.Now().Unix() - mw.syncData.activeSyncData.headersFetchProgress.beginFetchTimeStamp
if fetchTimeTakenSoFar < 1 {
fetchTimeTakenSoFar = 1
}
estimatedTotalHeadersFetchTime := float64(fetchTimeTakenSoFar) / headersFetchProgress
// For some reason, the actual total headers fetch time is more than the predicted/estimated time.
// Account for this difference by multiplying the estimatedTotalHeadersFetchTime by an incrementing factor.
// The incrementing factor is inversely proportional to the headers fetch progress,
// ranging from 0.5 to 0 as headers fetching progress increases from 0 to 1.
// todo, the above noted (mal)calculation may explain this difference.
// TODO: is this adjustment still needed since the calculation has been corrected.
adjustmentFactor := 0.5 * (1 - headersFetchProgress)
estimatedTotalHeadersFetchTime += estimatedTotalHeadersFetchTime * adjustmentFactor
estimatedDiscoveryTime := estimatedTotalHeadersFetchTime * DiscoveryPercentage
estimatedRescanTime := estimatedTotalHeadersFetchTime * RescanPercentage
estimatedTotalSyncTime := float64(mw.syncData.activeSyncData.cfiltersFetchProgress.cfiltersFetchTimeSpent) +
estimatedTotalHeadersFetchTime + estimatedDiscoveryTime + estimatedRescanTime
totalSyncProgress := float64(fetchTimeTakenSoFar) / estimatedTotalSyncTime
totalTimeRemainingSeconds := int64(math.Round(estimatedTotalSyncTime)) - fetchTimeTakenSoFar
// update headers fetching progress report including total progress percentage and total time remaining
mw.syncData.activeSyncData.headersFetchProgress.TotalHeadersToFetch = totalHeadersToFetch
mw.syncData.activeSyncData.headersFetchProgress.CurrentHeaderHeight = lastFetchedHeaderHeight
mw.syncData.activeSyncData.headersFetchProgress.CurrentHeaderTimestamp = lastFetchedHeaderTime
mw.syncData.activeSyncData.headersFetchProgress.HeadersFetchProgress = roundUp(headersFetchProgress * 100.0)
mw.syncData.activeSyncData.headersFetchProgress.TotalSyncProgress = roundUp(totalSyncProgress * 100.0)
mw.syncData.activeSyncData.headersFetchProgress.TotalTimeRemainingSeconds = totalTimeRemainingSeconds
// unlock the mutex before issuing notification callbacks to prevent potential deadlock
// if any invoked callback takes a considerable amount of time to execute.
mw.syncData.mu.Unlock()
// notify progress listener of estimated progress report
mw.publishFetchHeadersProgress()
// todo: also log report if showLog == true
timeTakenSoFar := mw.syncData.activeSyncData.cfiltersFetchProgress.cfiltersFetchTimeSpent + fetchTimeTakenSoFar
headersFetchTimeRemaining := estimatedTotalHeadersFetchTime - float64(fetchTimeTakenSoFar)
debugInfo := &DebugInfo{
timeTakenSoFar,
totalTimeRemainingSeconds,
fetchTimeTakenSoFar,
int64(math.Round(headersFetchTimeRemaining)),
}
mw.publishDebugInfo(debugInfo)
}
func (mw *MultiWallet) publishFetchHeadersProgress() {
for _, syncProgressListener := range mw.syncProgressListeners() {
syncProgressListener.OnHeadersFetchProgress(&mw.syncData.headersFetchProgress)
}
}
func (mw *MultiWallet) fetchHeadersFinished() {
mw.syncData.mu.Lock()
defer mw.syncData.mu.Unlock()
if !mw.syncData.syncing {
// ignore if sync is not in progress
return
}
mw.syncData.activeSyncData.headersFetchProgress.startHeaderHeight = -1
mw.syncData.headersFetchProgress.totalFetchedHeadersCount = 0
mw.syncData.activeSyncData.headersFetchProgress.headersFetchTimeSpent = time.Now().Unix() - mw.syncData.headersFetchProgress.beginFetchTimeStamp
// If there is some period of inactivity reported at this stage,
// subtract it from the total stage time.
mw.syncData.activeSyncData.headersFetchProgress.headersFetchTimeSpent -= mw.syncData.totalInactiveSeconds
mw.syncData.activeSyncData.totalInactiveSeconds = 0
if mw.syncData.activeSyncData.headersFetchProgress.headersFetchTimeSpent < 150 {
// This ensures that minimum ETA used for stage 2 (address discovery) is 120 seconds (80% of 150 seconds).
mw.syncData.activeSyncData.headersFetchProgress.headersFetchTimeSpent = 150
}
if mw.syncData.showLogs && mw.syncData.syncing {
log.Info("Fetch headers completed.")
}
}
// Address/Account Discovery Callbacks
func (mw *MultiWallet) discoverAddressesStarted(walletID int) {
if !mw.IsSyncing() {
return
}
mw.syncData.mu.RLock()
addressDiscoveryAlreadyStarted := mw.syncData.activeSyncData.addressDiscoveryProgress.addressDiscoveryStartTime != -1
totalHeadersFetchTime := float64(mw.syncData.activeSyncData.headersFetchProgress.headersFetchTimeSpent)
mw.syncData.mu.RUnlock()
if addressDiscoveryAlreadyStarted {
return
}
mw.syncData.mu.Lock()
mw.syncData.activeSyncData.syncStage = AddressDiscoverySyncStage
mw.syncData.activeSyncData.addressDiscoveryProgress.addressDiscoveryStartTime = time.Now().Unix()
mw.syncData.activeSyncData.addressDiscoveryProgress.WalletID = walletID
mw.syncData.addressDiscoveryCompletedOrCanceled = make(chan bool)
mw.syncData.mu.Unlock()
go mw.updateAddressDiscoveryProgress(totalHeadersFetchTime)
if mw.syncData.showLogs {
log.Info("Step 2 of 3 - discovering used addresses.")
}
}
func (mw *MultiWallet) updateAddressDiscoveryProgress(totalHeadersFetchTime float64) {
// use ticker to calculate and broadcast address discovery progress every second
everySecondTicker := time.NewTicker(1 * time.Second)
// these values will be used every second to calculate the total sync progress
estimatedDiscoveryTime := totalHeadersFetchTime * DiscoveryPercentage
estimatedRescanTime := totalHeadersFetchTime * RescanPercentage
// track last logged time remaining and total percent to avoid re-logging same message
var lastTimeRemaining int64
var lastTotalPercent int32 = -1
for {
if !mw.IsSyncing() {
return
}
// If there was some period of inactivity,
// assume that this process started at some point in the future,
// thereby accounting for the total reported time of inactivity.
mw.syncData.mu.Lock()
mw.syncData.addressDiscoveryProgress.addressDiscoveryStartTime += mw.syncData.totalInactiveSeconds
mw.syncData.totalInactiveSeconds = 0
addressDiscoveryStartTime := mw.syncData.addressDiscoveryProgress.addressDiscoveryStartTime
totalCfiltersFetchTime := float64(mw.syncData.cfiltersFetchProgress.cfiltersFetchTimeSpent)
showLogs := mw.syncData.showLogs
mw.syncData.mu.Unlock()
select {
case <-mw.syncData.addressDiscoveryCompletedOrCanceled:
// stop calculating and broadcasting address discovery progress
everySecondTicker.Stop()
if showLogs {
log.Info("Address discovery complete.")
}
return
case <-everySecondTicker.C:
// calculate address discovery progress
elapsedDiscoveryTime := float64(time.Now().Unix() - addressDiscoveryStartTime)
discoveryProgress := (elapsedDiscoveryTime / estimatedDiscoveryTime) * 100
var totalSyncTime float64
if elapsedDiscoveryTime > estimatedDiscoveryTime {
totalSyncTime = totalCfiltersFetchTime + totalHeadersFetchTime + elapsedDiscoveryTime + estimatedRescanTime
} else {
totalSyncTime = totalCfiltersFetchTime + totalHeadersFetchTime + estimatedDiscoveryTime + estimatedRescanTime
}
totalElapsedTime := totalCfiltersFetchTime + totalHeadersFetchTime + elapsedDiscoveryTime
totalProgress := (totalElapsedTime / totalSyncTime) * 100
remainingAccountDiscoveryTime := math.Round(estimatedDiscoveryTime - elapsedDiscoveryTime)
if remainingAccountDiscoveryTime < 0 {
remainingAccountDiscoveryTime = 0
}
totalProgressPercent := int32(math.Round(totalProgress))
totalTimeRemainingSeconds := int64(math.Round(remainingAccountDiscoveryTime + estimatedRescanTime))
// update address discovery progress, total progress and total time remaining
mw.syncData.mu.Lock()
mw.syncData.addressDiscoveryProgress.AddressDiscoveryProgress = int32(math.Round(discoveryProgress))
mw.syncData.addressDiscoveryProgress.TotalSyncProgress = totalProgressPercent
mw.syncData.addressDiscoveryProgress.TotalTimeRemainingSeconds = totalTimeRemainingSeconds
mw.syncData.mu.Unlock()
mw.publishAddressDiscoveryProgress()
debugInfo := &DebugInfo{
int64(math.Round(totalElapsedTime)),
totalTimeRemainingSeconds,
int64(math.Round(elapsedDiscoveryTime)),
int64(math.Round(remainingAccountDiscoveryTime)),
}
mw.publishDebugInfo(debugInfo)
if showLogs {
// avoid logging same message multiple times
if totalProgressPercent != lastTotalPercent || totalTimeRemainingSeconds != lastTimeRemaining {
log.Infof("Syncing %d%%, %s remaining, discovering used addresses.",
totalProgressPercent, CalculateTotalTimeRemaining(totalTimeRemainingSeconds))
lastTotalPercent = totalProgressPercent
lastTimeRemaining = totalTimeRemainingSeconds
}
}
}
}
}
func (mw *MultiWallet) publishAddressDiscoveryProgress() {
for _, syncProgressListener := range mw.syncProgressListeners() {
syncProgressListener.OnAddressDiscoveryProgress(&mw.syncData.activeSyncData.addressDiscoveryProgress)
}
}
func (mw *MultiWallet) discoverAddressesFinished(walletID int) {
if !mw.IsSyncing() {
return
}
mw.stopUpdatingAddressDiscoveryProgress()
}
func (mw *MultiWallet) stopUpdatingAddressDiscoveryProgress() {
mw.syncData.mu.Lock()
if mw.syncData.activeSyncData != nil && mw.syncData.activeSyncData.addressDiscoveryCompletedOrCanceled != nil {
close(mw.syncData.activeSyncData.addressDiscoveryCompletedOrCanceled)
mw.syncData.activeSyncData.addressDiscoveryCompletedOrCanceled = nil
mw.syncData.activeSyncData.addressDiscoveryProgress.totalDiscoveryTimeSpent = time.Now().Unix() - mw.syncData.addressDiscoveryProgress.addressDiscoveryStartTime
}
mw.syncData.mu.Unlock()
}
// Blocks Scan Callbacks
func (mw *MultiWallet) rescanStarted(walletID int) {
mw.stopUpdatingAddressDiscoveryProgress()
mw.syncData.mu.Lock()
defer mw.syncData.mu.Unlock()
if !mw.syncData.syncing {
// ignore if sync is not in progress
return
}
mw.syncData.activeSyncData.syncStage = HeadersRescanSyncStage
mw.syncData.activeSyncData.rescanStartTime = time.Now().Unix()
// retain last total progress report from address discovery phase
mw.syncData.activeSyncData.headersRescanProgress.TotalTimeRemainingSeconds = mw.syncData.activeSyncData.addressDiscoveryProgress.TotalTimeRemainingSeconds
mw.syncData.activeSyncData.headersRescanProgress.TotalSyncProgress = mw.syncData.activeSyncData.addressDiscoveryProgress.TotalSyncProgress
mw.syncData.activeSyncData.headersRescanProgress.WalletID = walletID
if mw.syncData.showLogs && mw.syncData.syncing {
log.Info("Step 3 of 3 - Scanning block headers.")
}
}
func (mw *MultiWallet) rescanProgress(walletID int, rescannedThrough int32) {
if !mw.IsSyncing() {
// ignore if sync is not in progress
return
}
wallet := mw.wallets[walletID]
totalHeadersToScan := wallet.GetBestBlock()
rescanRate := float64(rescannedThrough) / float64(totalHeadersToScan)
mw.syncData.mu.Lock()
// If there was some period of inactivity,
// assume that this process started at some point in the future,
// thereby accounting for the total reported time of inactivity.
mw.syncData.activeSyncData.rescanStartTime += mw.syncData.activeSyncData.totalInactiveSeconds
mw.syncData.activeSyncData.totalInactiveSeconds = 0
elapsedRescanTime := time.Now().Unix() - mw.syncData.activeSyncData.rescanStartTime
estimatedTotalRescanTime := int64(math.Round(float64(elapsedRescanTime) / rescanRate))
totalTimeRemainingSeconds := estimatedTotalRescanTime - elapsedRescanTime
totalElapsedTime := mw.syncData.activeSyncData.cfiltersFetchProgress.cfiltersFetchTimeSpent + mw.syncData.activeSyncData.headersFetchProgress.headersFetchTimeSpent +
mw.syncData.activeSyncData.addressDiscoveryProgress.totalDiscoveryTimeSpent + elapsedRescanTime
mw.syncData.activeSyncData.headersRescanProgress.WalletID = walletID
mw.syncData.activeSyncData.headersRescanProgress.TotalHeadersToScan = totalHeadersToScan
mw.syncData.activeSyncData.headersRescanProgress.RescanProgress = int32(math.Round(rescanRate * 100))
mw.syncData.activeSyncData.headersRescanProgress.CurrentRescanHeight = rescannedThrough
mw.syncData.activeSyncData.headersRescanProgress.RescanTimeRemaining = totalTimeRemainingSeconds
// do not update total time taken and total progress percent if elapsedRescanTime is 0
// because the estimatedTotalRescanTime will be inaccurate (also 0)
// which will make the estimatedTotalSyncTime equal to totalElapsedTime
// giving the wrong impression that the process is complete
if elapsedRescanTime > 0 {
estimatedTotalSyncTime := mw.syncData.activeSyncData.cfiltersFetchProgress.cfiltersFetchTimeSpent + mw.syncData.activeSyncData.headersFetchProgress.headersFetchTimeSpent +
mw.syncData.activeSyncData.addressDiscoveryProgress.totalDiscoveryTimeSpent + estimatedTotalRescanTime
totalProgress := (float64(totalElapsedTime) / float64(estimatedTotalSyncTime)) * 100
mw.syncData.activeSyncData.headersRescanProgress.TotalTimeRemainingSeconds = totalTimeRemainingSeconds
mw.syncData.activeSyncData.headersRescanProgress.TotalSyncProgress = int32(math.Round(totalProgress))
}
mw.syncData.mu.Unlock()
mw.publishHeadersRescanProgress()
debugInfo := &DebugInfo{
totalElapsedTime,
totalTimeRemainingSeconds,
elapsedRescanTime,
totalTimeRemainingSeconds,
}
mw.publishDebugInfo(debugInfo)
mw.syncData.mu.RLock()
if mw.syncData.showLogs {
log.Infof("Syncing %d%%, %s remaining, scanning %d of %d block headers.",
mw.syncData.activeSyncData.headersRescanProgress.TotalSyncProgress,
CalculateTotalTimeRemaining(mw.syncData.activeSyncData.headersRescanProgress.TotalTimeRemainingSeconds),
mw.syncData.activeSyncData.headersRescanProgress.CurrentRescanHeight,
mw.syncData.activeSyncData.headersRescanProgress.TotalHeadersToScan,
)
}
mw.syncData.mu.RUnlock()
}
func (mw *MultiWallet) publishHeadersRescanProgress() {
for _, syncProgressListener := range mw.syncProgressListeners() {
syncProgressListener.OnHeadersRescanProgress(&mw.syncData.activeSyncData.headersRescanProgress)
}
}
func (mw *MultiWallet) rescanFinished(walletID int) {
if !mw.IsSyncing() {
// ignore if sync is not in progress
return
}
mw.syncData.mu.Lock()
mw.syncData.activeSyncData.headersRescanProgress.WalletID = walletID
mw.syncData.activeSyncData.headersRescanProgress.TotalTimeRemainingSeconds = 0
mw.syncData.activeSyncData.headersRescanProgress.TotalSyncProgress = 100
// Reset these value so that address discovery would
// not be skipped for the next wallet.
mw.syncData.activeSyncData.addressDiscoveryProgress.addressDiscoveryStartTime = -1
mw.syncData.activeSyncData.addressDiscoveryProgress.totalDiscoveryTimeSpent = -1
mw.syncData.mu.Unlock()
mw.publishHeadersRescanProgress()
}
func (mw *MultiWallet) publishDebugInfo(debugInfo *DebugInfo) {
for _, syncProgressListener := range mw.syncProgressListeners() {
syncProgressListener.Debug(debugInfo)
}
}
/** Helper functions start here */
func (mw *MultiWallet) estimateBlockHeadersCountAfter(lastHeaderTime int64) int32 {
// Use the difference between current time (now) and last reported block time,
// to estimate total headers to fetch.
timeDifferenceInSeconds := float64(time.Now().Unix() - lastHeaderTime)
targetTimePerBlockInSeconds := mw.chainParams.TargetTimePerBlock.Seconds()
estimatedHeadersDifference := timeDifferenceInSeconds / targetTimePerBlockInSeconds
// return next integer value (upper limit) if estimatedHeadersDifference is a fraction
return int32(math.Ceil(estimatedHeadersDifference))
}
func (mw *MultiWallet) notifySyncError(err error) {
for _, syncProgressListener := range mw.syncProgressListeners() {
syncProgressListener.OnSyncEndedWithError(err)
}
}
func (mw *MultiWallet) notifySyncCanceled() {
mw.syncData.mu.RLock()
restartSyncRequested := mw.syncData.restartSyncRequested
mw.syncData.mu.RUnlock()
for _, syncProgressListener := range mw.syncProgressListeners() {
syncProgressListener.OnSyncCanceled(restartSyncRequested)
}
}
func (mw *MultiWallet) resetSyncData() {
// It's possible that sync ends or errors while address discovery is ongoing.
// If this happens, it's important to stop the address discovery process before
// resetting sync data.
mw.stopUpdatingAddressDiscoveryProgress()
mw.syncData.mu.Lock()
mw.syncData.syncing = false
mw.syncData.synced = false
mw.syncData.cancelSync = nil
mw.syncData.syncCanceled = nil
mw.syncData.activeSyncData = nil
mw.syncData.mu.Unlock()
for _, wallet := range mw.wallets {
wallet.waitingForHeaders = true
wallet.LockWallet() // lock wallet if previously unlocked to perform account discovery.
}
}
func (mw *MultiWallet) synced(walletID int, synced bool) {
indexTransactions := func() {
// begin indexing transactions after sync is completed,
// syncProgressListeners.OnSynced() will be invoked after transactions are indexed
var txIndexing errgroup.Group
for _, wallet := range mw.wallets {
txIndexing.Go(wallet.IndexTransactions)
}
go func() {
err := txIndexing.Wait()
if err != nil {
log.Errorf("Tx Index Error: %v", err)
}
for _, syncProgressListener := range mw.syncProgressListeners() {
if synced {
syncProgressListener.OnSyncCompleted()
} else {
syncProgressListener.OnSyncCanceled(false)
}
}
}()
}
mw.syncData.mu.RLock()
allWalletsSynced := mw.syncData.synced
mw.syncData.mu.RUnlock()
if allWalletsSynced && synced {
indexTransactions()
return
}
wallet := mw.wallets[walletID]
wallet.synced = synced
wallet.syncing = false
mw.listenForTransactions(wallet.ID)
if !wallet.Internal().Locked() {
wallet.LockWallet() // lock wallet if previously unlocked to perform account discovery.
err := mw.markWalletAsDiscoveredAccounts(walletID)
if err != nil {
log.Error(err)
}
}
if mw.OpenedWalletsCount() == mw.SyncedWalletsCount() {
mw.syncData.mu.Lock()
mw.syncData.syncing = false
mw.syncData.synced = true
mw.syncData.mu.Unlock()
indexTransactions()
}
}