forked from algorand/go-algorand
-
Notifications
You must be signed in to change notification settings - Fork 0
/
acctupdates.go
1826 lines (1591 loc) · 66.9 KB
/
acctupdates.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
// Copyright (C) 2019-2024 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand. If not, see <https://www.gnu.org/licenses/>.
package ledger
import (
"context"
"errors"
"fmt"
"io"
"sort"
"strings"
"sync"
"time"
"github.com/algorand/go-deadlock"
"github.com/algorand/go-algorand/config"
"github.com/algorand/go-algorand/data/basics"
"github.com/algorand/go-algorand/data/bookkeeping"
"github.com/algorand/go-algorand/ledger/ledgercore"
"github.com/algorand/go-algorand/ledger/store/trackerdb"
"github.com/algorand/go-algorand/logging"
"github.com/algorand/go-algorand/logging/telemetryspec"
"github.com/algorand/go-algorand/protocol"
"github.com/algorand/go-algorand/util/metrics"
)
const (
// balancesFlushInterval defines how frequently we want to flush our balances to disk.
balancesFlushInterval = 5 * time.Second
// pendingDeltasFlushThreshold is the deltas count threshold above we flush the pending balances regardless of the flush interval.
pendingDeltasFlushThreshold = 128
)
// baseAccountsPendingAccountsBufferSize defines the size of the base account pending accounts buffer size.
// At the beginning of a new round, the entries from this buffer are being flushed into the base accounts map.
const baseAccountsPendingAccountsBufferSize = 100000
// baseAccountsPendingAccountsWarnThreshold defines the threshold at which the lruAccounts would generate a warning
// after we've surpassed a given pending account size. The warning is being generated when the pending accounts data
// is being flushed into the main base account cache.
const baseAccountsPendingAccountsWarnThreshold = 85000
// baseResourcesPendingAccountsBufferSize defines the size of the base resources pending accounts buffer size.
// At the beginning of a new round, the entries from this buffer are being flushed into the base resources map.
const baseResourcesPendingAccountsBufferSize = 10000
// baseResourcesPendingAccountsWarnThreshold defines the threshold at which the lruResources would generate a warning
// after we've surpassed a given pending account resources size. The warning is being generated when the pending accounts data
// is being flushed into the main base resources cache.
const baseResourcesPendingAccountsWarnThreshold = 8500
// baseKVPendingBufferSize defines the size of the base KVs pending buffer size.
// At the beginning of a new round, the entries from this buffer are being flushed into the base KVs map.
const baseKVPendingBufferSize = 5000
// baseKVPendingWarnThreshold defines the threshold at which the lruKV would generate a warning
// after we've surpassed a given pending kv size. The warning is being generated when the pending kv data
// is being flushed into the main base kv cache.
const baseKVPendingWarnThreshold = 4250
// initializeCachesReadaheadBlocksStream defines how many block we're going to attempt to queue for the
// initializeCaches method before it can process and store the account changes to disk.
const initializeCachesReadaheadBlocksStream = 4
// initializeCachesRoundFlushInterval defines the number of rounds between every to consecutive
// attempts to flush the memory account data to disk. Setting this value too high would increase
// memory utilization. Setting this too low, would increase disk i/o.
const initializeCachesRoundFlushInterval = 1000
// initializingAccountCachesMessageTimeout controls the amount of time passes before we
// log "initializingAccount initializing.." message to the log file. This is primarily for
// nodes with slower disk access, where a feedback that the node is functioning correctly is needed.
const initializingAccountCachesMessageTimeout = 3 * time.Second
// accountsUpdatePerRoundHighWatermark is the warning watermark for updating accounts data that takes
// longer than expected. We set it up here for one second per round, so that if we're bulk updating
// four rounds, we would allow up to 4 seconds. This becomes important when supporting balances recovery
// where we end up batching up to 1000 rounds in a single update.
const accountsUpdatePerRoundHighWatermark = 1 * time.Second
// forceCatchpointFileGenerationTrackingMode defines the CatchpointTracking mode that would be used to
// force a node to generate catchpoint files.
const forceCatchpointFileGenerationTrackingMode = 99
// A modifiedAccount represents an account that has been modified since
// the persistent state stored in the account DB (i.e., in the range of
// rounds covered by the accountUpdates tracker).
type modifiedAccount struct {
// data stores the most recent ledgercore.AccountData for this modified
// account.
data ledgercore.AccountData
// ndelta keeps track of how many times this account appears in
// accountUpdates.deltas. This is used to evict modifiedAccount
// entries when all changes to an account have been reflected in
// the account DB, and no outstanding modifications remain.
ndeltas int
}
// accountCreatable is used as a map key.
type accountCreatable struct {
address basics.Address
index basics.CreatableIndex
}
//msgp:ignore modifiedResource
type modifiedResource struct {
// resource stores concrete information about this particular resource
resource ledgercore.AccountResource
// ndelta keeps track of how many times this resource appears in
// accountUpdates.deltas. This is used to evict modifiedResource
// entries when all changes to an account have been reflected in
// the account DB, and no outstanding modifications remain.
ndeltas int
}
// A modifiedKvValue represents a kv store change since the persistent state
// stored in the DB (i.e., in the range of rounds covered by the accountUpdates
// tracker).
type modifiedKvValue struct {
// data stores the most recent value (nil == deleted)
data []byte
// oldData stores the previous vlaue (nil == didn't exist)
oldData []byte
// ndelta keeps track of how many times the key for this value appears in
// accountUpdates.deltas. This is used to evict modifiedValue entries when
// all changes to a key have been reflected in the kv table, and no
// outstanding modifications remain.
ndeltas int
}
type accountUpdates struct {
// Connection to the database.
dbs trackerdb.Store
// Optimized reader for fast accounts DB lookups.
accountsq trackerdb.AccountsReader
// cachedDBRound is always exactly tracker DB round (and therefore, accountsRound()),
// cached to use in lookup functions
cachedDBRound basics.Round
// deltas stores updates for every round after dbRound.
deltas []ledgercore.StateDelta
// accounts stores the most recent account state for every
// address that appears in deltas.
accounts map[basics.Address]modifiedAccount
// resources stored the most recent resource state for every
// address&resource that appears in deltas.
resources resourcesUpdates
// kvStore has the most recent kv pairs for every write/del that appears in
// deltas.
kvStore map[string]modifiedKvValue
// creatables stores the most recent state for every creatable that
// appears in creatableDeltas
creatables map[basics.CreatableIndex]ledgercore.ModifiedCreatable
// versions stores consensus version dbRound and every
// round after it; i.e., versions is one longer than deltas.
versions []protocol.ConsensusVersion
// totals stores the totals for dbRound and every round after it;
// i.e., totals is one longer than deltas.
roundTotals []ledgercore.AccountTotals
// log copied from ledger
log logging.Logger
// ledger is the source ledger, which is used to synchronize
// the rounds at which we need to flush the balances to disk
// in favor of the catchpoint to be generated.
ledger ledgerForTracker
// deltasAccum stores the accumulated deltas for every round starting dbRound-1.
deltasAccum []int
// accountsMu is the synchronization mutex for accessing the various non-static variables.
accountsMu deadlock.RWMutex
// accountsReadCond used to synchronize read access to the internal data structures.
accountsReadCond *sync.Cond
// baseAccounts stores the most recently used accounts, at exactly dbRound
baseAccounts lruAccounts
// baseResources stores the most recently used resources, at exactly dbRound
baseResources lruResources
// baseKVs stores the most recently used KV, at exactly dbRound
baseKVs lruKV
// logAccountUpdatesMetrics is a flag for enable/disable metrics logging
logAccountUpdatesMetrics bool
// logAccountUpdatesInterval sets a time interval for metrics logging
logAccountUpdatesInterval time.Duration
// lastMetricsLogTime is the time when the previous metrics logging occurred
lastMetricsLogTime time.Time
// maxAcctLookback sets the minimim deltas size to keep in memory
acctLookback uint64
// disableCache (de)activates the LRU cache use in accountUpdates
disableCache bool
}
// RoundOffsetError is an error for when requested round is behind earliest stored db entry
type RoundOffsetError struct {
round basics.Round
dbRound basics.Round
}
func (e *RoundOffsetError) Error() string {
return fmt.Sprintf("round %d before dbRound %d", e.round, e.dbRound)
}
// StaleDatabaseRoundError is generated when we detect that the database round is behind the accountUpdates in-memory dbRound. This
// should never happen, since we update the database first, and only upon a successful update we update the in-memory dbRound.
type StaleDatabaseRoundError struct {
memoryRound basics.Round
databaseRound basics.Round
}
func (e *StaleDatabaseRoundError) Error() string {
return fmt.Sprintf("database round %d is behind in-memory round %d", e.databaseRound, e.memoryRound)
}
// MismatchingDatabaseRoundError is generated when we detect that the database round is different than the accountUpdates in-memory dbRound. This
// could happen normally when the database and the in-memory dbRound aren't synchronized. However, when we work in non-sync mode, we expect the database to be
// always synchronized with the in-memory data. When that condition is violated, this error is generated.
type MismatchingDatabaseRoundError struct {
memoryRound basics.Round
databaseRound basics.Round
}
func (e *MismatchingDatabaseRoundError) Error() string {
return fmt.Sprintf("database round %d mismatching in-memory round %d", e.databaseRound, e.memoryRound)
}
// ErrLookupLatestResources is returned if there is an error retrieving an account along with its resources.
var ErrLookupLatestResources = errors.New("couldn't find latest resources")
//msgp:ignore resourcesUpdates
type resourcesUpdates map[accountCreatable]modifiedResource
func (r resourcesUpdates) set(ac accountCreatable, m modifiedResource) { r[ac] = m }
func (r resourcesUpdates) get(ac accountCreatable) (m modifiedResource, ok bool) {
m, ok = r[ac]
return
}
func (r resourcesUpdates) getForAddress(addr basics.Address) map[basics.CreatableIndex]modifiedResource {
res := make(map[basics.CreatableIndex]modifiedResource)
for k, v := range r {
if k.address == addr {
res[k.index] = v
}
}
return res
}
// initialize initializes the accountUpdates structure
func (au *accountUpdates) initialize(cfg config.Local) {
au.accountsReadCond = sync.NewCond(au.accountsMu.RLocker())
au.acctLookback = cfg.MaxAcctLookback
// log metrics
au.logAccountUpdatesMetrics = cfg.EnableAccountUpdatesStats
au.logAccountUpdatesInterval = cfg.AccountUpdatesStatsInterval
au.disableCache = cfg.DisableLedgerLRUCache
}
// loadFromDisk is the 2nd level initialization, and is required before the accountUpdates becomes functional
// The close function is expected to be call in pair with loadFromDisk
func (au *accountUpdates) loadFromDisk(l ledgerForTracker, lastBalancesRound basics.Round) error {
au.accountsMu.Lock()
defer au.accountsMu.Unlock()
au.cachedDBRound = lastBalancesRound
err := au.initializeFromDisk(l, lastBalancesRound)
if err != nil {
return err
}
return nil
}
// close closes the accountUpdates, waiting for all the child go-routine to complete
func (au *accountUpdates) close() {
if au.accountsq != nil {
au.accountsq.Close()
au.accountsq = nil
}
au.baseAccounts.prune(0)
au.baseResources.prune(0)
au.baseKVs.prune(0)
}
// flushCaches flushes any pending data in caches so that it is fully available during future lookups.
func (au *accountUpdates) flushCaches() {
t0 := time.Now()
ledgerAccountsMuLockCount.Inc(nil)
au.accountsMu.Lock()
au.baseAccounts.flushPendingWrites()
au.baseResources.flushPendingWrites()
au.baseKVs.flushPendingWrites()
au.accountsMu.Unlock()
ledgerAccountsMuLockMicros.AddMicrosecondsSince(t0, nil)
}
func (au *accountUpdates) LookupResource(rnd basics.Round, addr basics.Address, aidx basics.CreatableIndex, ctype basics.CreatableType) (ledgercore.AccountResource, basics.Round, error) {
return au.lookupResource(rnd, addr, aidx, ctype, true /* take lock */)
}
func (au *accountUpdates) LookupKv(rnd basics.Round, key string) ([]byte, error) {
return au.lookupKv(rnd, key, true /* take lock */)
}
func (au *accountUpdates) lookupKv(rnd basics.Round, key string, synchronized bool) ([]byte, error) {
needUnlock := false
if synchronized {
au.accountsMu.RLock()
needUnlock = true
}
defer func() {
if needUnlock {
au.accountsMu.RUnlock()
}
}()
// TODO: This loop and round handling is copied from other routines like
// lookupResource. I believe that it is overly cautious, as it always reruns
// the lookup if the DB round does not match the expected round. However, as
// long as the db round has not advanced too far (greater than `rnd`), I
// believe it would be valid to use. In the interest of minimizing changes,
// I'm not doing that now.
for {
currentDbRound := au.cachedDBRound
currentDeltaLen := len(au.deltas)
offset, err := au.roundOffset(rnd)
if err != nil {
return nil, err
}
// check if we have this key in `kvStore`, as that means the change we
// care about is in kvDeltas (and maybe just kvStore itself)
mval, indeltas := au.kvStore[key]
if indeltas {
// Check if this is the most recent round, in which case, we can
// use a cache of the most recent kvStore state
if offset == uint64(len(au.deltas)) {
return mval.data, nil
}
// the key is in the deltas, but we don't know if it appears in the
// delta range of [0..offset-1], so we'll need to check. Walk deltas
// backwards so later updates take priority.
for offset > 0 {
offset--
mval, ok := au.deltas[offset].KvMods[key]
if ok {
return mval.Data, nil
}
}
} else {
// we know that the key is not in kvDeltas - so there is no point in scanning it.
// we've going to fall back to search in the database, but before doing so, we should
// update the rnd so that it would point to the end of the known delta range.
// ( that would give us the best validity range )
rnd = currentDbRound + basics.Round(currentDeltaLen)
}
// check the baseKV cache
if pbd, has := au.baseKVs.read(key); has {
// we don't technically need this, since it's already in the baseKV, however, writing this over
// would ensure that we promote this field.
au.baseKVs.writePending(pbd, key)
return pbd.Value, nil
}
if synchronized {
au.accountsMu.RUnlock()
needUnlock = false
}
// No updates of this account in kvDeltas; use on-disk DB. The check in
// roundOffset() made sure the round is exactly the one present in the
// on-disk DB.
persistedData, err := au.accountsq.LookupKeyValue(key)
if err != nil {
return nil, err
}
if persistedData.Round == currentDbRound {
// if we read actual data return it. This includes deleted values
// where persistedData.value == nil to avoid unnecessary db lookups
// for deleted KVs.
au.baseKVs.writePending(persistedData, key)
return persistedData.Value, nil
}
// The db round is unexpected...
if synchronized {
if persistedData.Round < currentDbRound {
// Somehow the db is LOWER than it should be.
au.log.Errorf("accountUpdates.lookupKvPair: database round %d is behind in-memory round %d", persistedData.Round, currentDbRound)
return nil, &StaleDatabaseRoundError{databaseRound: persistedData.Round, memoryRound: currentDbRound}
}
// The db is higher, so a write must have happened. Try again.
au.accountsMu.RLock()
needUnlock = true
// WHY BOTH - seems the goal is just to wait until the au is aware of progress. au.cachedDBRound should be enough?
for currentDbRound >= au.cachedDBRound && currentDeltaLen == len(au.deltas) {
au.accountsReadCond.Wait()
}
} else {
// in non-sync mode, we don't wait since we already assume that we're synchronized.
au.log.Errorf("accountUpdates.lookupKvPair: database round %d mismatching in-memory round %d", persistedData.Round, currentDbRound)
return nil, &MismatchingDatabaseRoundError{databaseRound: persistedData.Round, memoryRound: currentDbRound}
}
}
}
func (au *accountUpdates) LookupKeysByPrefix(round basics.Round, keyPrefix string, maxKeyNum uint64) ([]string, error) {
return au.lookupKeysByPrefix(round, keyPrefix, maxKeyNum, true /* take lock */)
}
func (au *accountUpdates) lookupKeysByPrefix(round basics.Round, keyPrefix string, maxKeyNum uint64, synchronized bool) (resultKeys []string, err error) {
var results map[string]bool
// keep track of the number of result key with value
var resultCount uint64
needUnlock := false
if synchronized {
au.accountsMu.RLock()
needUnlock = true
}
defer func() {
if needUnlock {
au.accountsMu.RUnlock()
}
// preparation of result happens in deferring function
// prepare result only when err != nil
if err == nil {
resultKeys = make([]string, 0, resultCount)
for resKey, present := range results {
if present {
resultKeys = append(resultKeys, resKey)
}
}
}
}()
// TODO: This loop and round handling is copied from other routines like
// lookupResource. I believe that it is overly cautious, as it always reruns
// the lookup if the DB round does not match the expected round. However, as
// long as the db round has not advanced too far (greater than `rnd`), I
// believe it would be valid to use. In the interest of minimizing changes,
// I'm not doing that now.
for {
currentDBRound := au.cachedDBRound
currentDeltaLen := len(au.deltas)
offset, rndErr := au.roundOffset(round)
if rndErr != nil {
return nil, rndErr
}
// reset `results` to be empty each iteration
// if db round does not match the round number returned from DB query, start over again
// NOTE: `results` is maintained as we walk backwards from the latest round, to DB
// IT IS NOT SIMPLY A SET STORING KEY NAMES!
// - if the boolean for the key is true: we consider the key is still valid in later round
// - otherwise, we consider that the key is deleted in later round, and we will not return it as part of result
// Thus: `resultCount` keeps track of how many VALID keys in the `results`
// DO NOT TRY `len(results)` TO SEE NUMBER OF VALID KEYS!
results = map[string]bool{}
resultCount = 0
for offset > 0 {
offset--
for keyInRound, mv := range au.deltas[offset].KvMods {
if !strings.HasPrefix(keyInRound, keyPrefix) {
continue
}
// whether it is set or deleted in later round, if such modification exists in later round
// we just ignore the earlier insert
if _, ok := results[keyInRound]; ok {
continue
}
if mv.Data == nil {
results[keyInRound] = false
} else {
// set such key to be valid with value
results[keyInRound] = true
resultCount++
// check if the size of `results` reaches `maxKeyNum`
// if so just return the list of keys
if resultCount == maxKeyNum {
return
}
}
}
}
round = currentDBRound + basics.Round(currentDeltaLen)
// after this line, we should dig into DB I guess
// OTHER LOOKUPS USE "base" caches here.
if synchronized {
au.accountsMu.RUnlock()
needUnlock = false
}
// NOTE: the kv cache isn't used here because the data structure doesn't support range
// queries. It may be preferable to increase the SQLite cache size if these reads become
// too slow.
// Finishing searching updates of this account in kvDeltas, keep going: use on-disk DB
// to find the rest matching keys in DB.
dbRound, dbErr := au.accountsq.LookupKeysByPrefix(keyPrefix, maxKeyNum, results, resultCount)
if dbErr != nil {
return nil, dbErr
}
if dbRound == currentDBRound {
return
}
// The DB round is unexpected... '_>'?
if synchronized {
if dbRound < currentDBRound {
// does not make sense if DB round is earlier than it should be
au.log.Errorf("accountUpdates.lookupKvPair: database round %d is behind in-memory round %d", dbRound, currentDBRound)
err = &StaleDatabaseRoundError{databaseRound: dbRound, memoryRound: currentDBRound}
return
}
// The DB round is higher than expected, so a write-into-DB must have happened. Start over again.
au.accountsMu.RLock()
needUnlock = true
// WHY BOTH - seems the goal is just to wait until the au is aware of progress. au.cachedDBRound should be enough?
for currentDBRound >= au.cachedDBRound && currentDeltaLen == len(au.deltas) {
au.accountsReadCond.Wait()
}
} else {
au.log.Errorf("accountUpdates.lookupKvPair: database round %d mismatching in-memory round %d", dbRound, currentDBRound)
err = &MismatchingDatabaseRoundError{databaseRound: dbRound, memoryRound: currentDBRound}
return
}
}
}
// LookupWithoutRewards returns the account data for a given address at a given round.
func (au *accountUpdates) LookupWithoutRewards(rnd basics.Round, addr basics.Address) (data ledgercore.AccountData, validThrough basics.Round, err error) {
data, validThrough, _, _, err = au.lookupWithoutRewards(rnd, addr, true /* take lock*/)
return
}
// GetCreatorForRound returns the creator for a given asset/app index at a given round
func (au *accountUpdates) GetCreatorForRound(rnd basics.Round, cidx basics.CreatableIndex, ctype basics.CreatableType) (creator basics.Address, ok bool, err error) {
return au.getCreatorForRound(rnd, cidx, ctype, true /* take the lock */)
}
// committedUpTo implements the ledgerTracker interface for accountUpdates.
// The method informs the tracker that committedRound and all it's previous rounds have
// been committed to the block database. The method returns what is the oldest round
// number that can be removed from the blocks database as well as the lookback that this
// tracker maintains.
func (au *accountUpdates) committedUpTo(committedRound basics.Round) (retRound, lookback basics.Round) {
au.accountsMu.RLock()
defer au.accountsMu.RUnlock()
retRound = basics.Round(0)
lookback = basics.Round(au.acctLookback)
if committedRound < lookback {
return
}
retRound = au.cachedDBRound
return
}
// produceCommittingTask enqueues committing the balances for round committedRound-lookback.
// The deferred committing is done so that we could calculate the historical balances lookback rounds back.
// Since we don't want to hold off the tracker's mutex for too long, we'll defer the database persistence of this
// operation to a syncer goroutine. The one caveat is that when storing a catchpoint round, we would want to
// wait until the catchpoint creation is done, so that the persistence of the catchpoint file would have an
// uninterrupted view of the balances at a given point of time.
func (au *accountUpdates) produceCommittingTask(committedRound basics.Round, dbRound basics.Round, dcr *deferredCommitRange) *deferredCommitRange {
var offset uint64
au.accountsMu.RLock()
defer au.accountsMu.RUnlock()
if committedRound < dcr.lookback {
return nil
}
newBase := committedRound - dcr.lookback
if newBase <= dbRound {
// Already forgotten
return nil
}
if newBase > dbRound+basics.Round(len(au.deltas)) {
au.log.Panicf("produceCommittingTask: block %d too far in the future, lookback %d, dbRound %d (cached %d), deltas %d", committedRound, dcr.lookback, dbRound, au.cachedDBRound, len(au.deltas))
}
offset = uint64(newBase - dbRound)
offset = au.consecutiveVersion(offset)
// calculate the number of pending deltas
dcr.pendingDeltas = au.deltasAccum[offset] - au.deltasAccum[0]
proto := config.Consensus[au.versions[offset]]
dcr.catchpointLookback = proto.CatchpointLookback
if dcr.catchpointLookback == 0 {
dcr.catchpointLookback = proto.MaxBalLookback
}
// submit committing task only if offset is non-zero in addition to
// 1) no pending catchpoint writes
// 2) batching requirements meet or catchpoint round
dcr.oldBase = dbRound
dcr.offset = offset
return dcr
}
func (au *accountUpdates) consecutiveVersion(offset uint64) uint64 {
// check if this update chunk spans across multiple consensus versions. If so, break it so that each update would tackle only a single
// consensus version.
if au.versions[1] != au.versions[offset] {
// find the tip point.
tipPoint := sort.Search(int(offset), func(i int) bool {
// we're going to search here for version inequality, with the assumption that consensus versions won't repeat.
// that allow us to support [ver1, ver1, ..., ver2, ver2, ..., ver3, ver3] but not [ver1, ver1, ..., ver2, ver2, ..., ver1, ver3].
return au.versions[1] != au.versions[1+i]
})
// no need to handle the case of "no found", or tipPoint==int(offset), since we already know that it's there.
offset = uint64(tipPoint)
}
return offset
}
// newBlock is the accountUpdates implementation of the ledgerTracker interface. This is the "external" facing function
// which invokes the internal implementation after taking the lock.
func (au *accountUpdates) newBlock(blk bookkeeping.Block, delta ledgercore.StateDelta) {
t0 := time.Now()
ledgerAccountsMuLockCount.Inc(nil)
au.accountsMu.Lock()
au.newBlockImpl(blk, delta)
au.accountsMu.Unlock()
ledgerAccountsMuLockMicros.AddMicrosecondsSince(t0, nil)
au.accountsReadCond.Broadcast()
}
// LatestTotals returns the totals of all accounts for the most recent round, as well as the round number
func (au *accountUpdates) LatestTotals() (basics.Round, ledgercore.AccountTotals, error) {
au.accountsMu.RLock()
defer au.accountsMu.RUnlock()
return au.latestTotalsImpl()
}
// Totals returns the totals of all accounts for the given round
func (au *accountUpdates) Totals(rnd basics.Round) (ledgercore.AccountTotals, error) {
au.accountsMu.RLock()
defer au.accountsMu.RUnlock()
return au.totalsImpl(rnd)
}
// ReadCloseSizer interface implements the standard io.Reader and io.Closer as well
// as supporting the Size() function that let the caller know what the size of the stream would be (in bytes).
type ReadCloseSizer interface {
io.ReadCloser
Size() (int64, error)
}
// readCloseSizer is an instance of the ReadCloseSizer interface
type readCloseSizer struct {
io.ReadCloser
size int64
}
// Size returns the length of the associated stream.
func (r *readCloseSizer) Size() (int64, error) {
if r.size < 0 {
return 0, fmt.Errorf("unknown stream size")
}
return r.size, nil
}
// functions below this line are all internal functions
// latestTotalsImpl returns the totals of all accounts for the most recent round, as well as the round number
func (au *accountUpdates) latestTotalsImpl() (basics.Round, ledgercore.AccountTotals, error) {
offset := len(au.deltas)
rnd := au.cachedDBRound + basics.Round(len(au.deltas))
return rnd, au.roundTotals[offset], nil
}
// totalsImpl returns the totals of all accounts for the given round
func (au *accountUpdates) totalsImpl(rnd basics.Round) (ledgercore.AccountTotals, error) {
offset, err := au.roundOffset(rnd)
if err != nil {
return ledgercore.AccountTotals{}, err
}
return au.roundTotals[offset], nil
}
// initializeFromDisk performs the atomic operation of loading the accounts data information from disk
// and preparing the accountUpdates for operation.
func (au *accountUpdates) initializeFromDisk(l ledgerForTracker, lastBalancesRound basics.Round) error {
au.dbs = l.trackerDB()
au.log = l.trackerLog()
au.ledger = l
start := time.Now()
ledgerAccountsinitCount.Inc(nil)
err := au.dbs.Snapshot(func(ctx context.Context, tx trackerdb.SnapshotScope) error {
ar, err0 := tx.MakeAccountsReader()
if err0 != nil {
return err0
}
totals, err0 := ar.AccountsTotals(ctx, false)
if err0 != nil {
return err0
}
au.roundTotals = []ledgercore.AccountTotals{totals}
return nil
})
ledgerAccountsinitMicros.AddMicrosecondsSince(start, nil)
if err != nil {
return err
}
au.accountsq, err = au.dbs.MakeAccountsOptimizedReader()
if err != nil {
return err
}
hdr, err := l.BlockHdr(lastBalancesRound)
if err != nil {
return err
}
au.versions = []protocol.ConsensusVersion{hdr.CurrentProtocol}
au.deltas = nil
au.accounts = make(map[basics.Address]modifiedAccount)
au.resources = make(resourcesUpdates)
au.kvStore = make(map[string]modifiedKvValue)
au.creatables = make(map[basics.CreatableIndex]ledgercore.ModifiedCreatable)
au.deltasAccum = []int{0}
if !au.disableCache {
au.baseAccounts.init(au.log, baseAccountsPendingAccountsBufferSize, baseAccountsPendingAccountsWarnThreshold)
au.baseResources.init(au.log, baseResourcesPendingAccountsBufferSize, baseResourcesPendingAccountsWarnThreshold)
au.baseKVs.init(au.log, baseKVPendingBufferSize, baseKVPendingWarnThreshold)
} else {
au.baseAccounts.init(au.log, 0, 1)
au.baseResources.init(au.log, 0, 1)
au.baseKVs.init(au.log, 0, 1)
}
return nil
}
// newBlockImpl is the accountUpdates implementation of the ledgerTracker interface. This is the "internal" facing function
// which assumes that no lock need to be taken.
func (au *accountUpdates) newBlockImpl(blk bookkeeping.Block, delta ledgercore.StateDelta) {
rnd := blk.Round()
if rnd <= au.latest() {
// Duplicate, ignore.
return
}
if rnd != au.latest()+1 {
au.log.Panicf("accountUpdates: newBlockImpl %d too far in the future, dbRound %d, deltas %d", rnd, au.cachedDBRound, len(au.deltas))
}
au.deltas = append(au.deltas, delta)
au.versions = append(au.versions, blk.CurrentProtocol)
au.deltasAccum = append(au.deltasAccum, delta.Accts.Len()+au.deltasAccum[len(au.deltasAccum)-1])
au.baseAccounts.flushPendingWrites()
au.baseResources.flushPendingWrites()
au.baseKVs.flushPendingWrites()
for i := 0; i < delta.Accts.Len(); i++ {
addr, data := delta.Accts.GetByIdx(i)
macct := au.accounts[addr]
macct.ndeltas++
macct.data = data
au.accounts[addr] = macct
}
for _, res := range delta.Accts.GetAllAssetResources() {
key := accountCreatable{
address: res.Addr,
index: basics.CreatableIndex(res.Aidx),
}
mres, _ := au.resources.get(key)
mres.resource.AssetHolding = res.Holding.Holding
mres.resource.AssetParams = res.Params.Params
mres.ndeltas++
au.resources.set(key, mres)
}
for _, res := range delta.Accts.GetAllAppResources() {
key := accountCreatable{
address: res.Addr,
index: basics.CreatableIndex(res.Aidx),
}
mres, _ := au.resources.get(key)
mres.resource.AppLocalState = res.State.LocalState
mres.resource.AppParams = res.Params.Params
mres.ndeltas++
au.resources.set(key, mres)
}
for k, v := range delta.KvMods {
mvalue := au.kvStore[k]
mvalue.ndeltas++
mvalue.data = v.Data
// leave mvalue.oldData alone
au.kvStore[k] = mvalue
}
for cidx, cdelta := range delta.Creatables {
mcreat := au.creatables[cidx]
mcreat.Creator = cdelta.Creator
mcreat.Created = cdelta.Created
mcreat.Ctype = cdelta.Ctype
mcreat.Ndeltas++
au.creatables[cidx] = mcreat
}
au.roundTotals = append(au.roundTotals, delta.Totals)
// calling prune would drop old entries from the base accounts.
newBaseAccountSize := (len(au.accounts) + 1) + baseAccountsPendingAccountsBufferSize
au.baseAccounts.prune(newBaseAccountSize)
newBaseResourcesSize := (len(au.resources) + 1) + baseResourcesPendingAccountsBufferSize
au.baseResources.prune(newBaseResourcesSize)
newBaseKVSize := (len(au.kvStore) + 1) + baseKVPendingBufferSize
au.baseKVs.prune(newBaseKVSize)
}
// lookupLatest returns the account data for a given address for the latest round.
// The rewards are added to the AccountData before returning.
// Note that the function doesn't update the account with the rewards,
// even while it does return the AccountData which represent the "rewarded" account data.
func (au *accountUpdates) lookupLatest(addr basics.Address) (data basics.AccountData, rnd basics.Round, withoutRewards basics.MicroAlgos, err error) {
au.accountsMu.RLock()
needUnlock := true
defer func() {
if needUnlock {
au.accountsMu.RUnlock()
}
}()
var offset uint64
var rewardsProto config.ConsensusParams
var rewardsLevel uint64
var persistedData trackerdb.PersistedAccountData
var persistedResources []trackerdb.PersistedResourcesData
var resourceDbRound basics.Round
withRewards := true
var foundAccount bool
var ad ledgercore.AccountData
var foundResources map[basics.CreatableIndex]basics.Round
var resourceCount uint64
addResource := func(cidx basics.CreatableIndex, round basics.Round, res ledgercore.AccountResource) error {
foundRound, ok := foundResources[cidx]
if !ok { // first time seeing this cidx
foundResources[cidx] = round
if ledgercore.AssignAccountResourceToAccountData(cidx, res, &data) {
resourceCount++
}
return nil
}
// is this newer than current "found" rnd for this resource?
if round > foundRound {
return fmt.Errorf("error in lookupAllResources, round %v > foundRound %v: %w", round, foundRound, ErrLookupLatestResources)
}
// otherwise older than current "found" rnd: ignore, since it's older than what we have
return nil
}
// possibly avoid a trip to the DB for more resources, if we can use totals info
checkDone := func() bool {
if foundAccount { // found AccountData
// no resources
if ad.TotalAssetParams == 0 && ad.TotalAppParams == 0 &&
ad.TotalAssets == 0 && ad.TotalAppLocalStates == 0 {
return true
}
// not possible to know how many resources rows to look for: totals conceal possibly overlapping assets/apps
// but asset params also assume asset holding
if (ad.TotalAssetParams != 0 && ad.TotalAssets != 0 && ad.TotalAssetParams != ad.TotalAssets) ||
(ad.TotalAppParams != 0 && ad.TotalAppLocalStates != 0) {
return false
}
// in cases where acct is only a holder of assets/apps, or is just a creator of assets/apps,
// we can know how many resources rows to look for
needToFind := uint64(0)
if ad.TotalAssetParams == 0 { // not a creator of assets
needToFind += uint64(ad.TotalAssets) // look for N asset holdings
} else if ad.TotalAssets == 0 { // not a holder of assets
needToFind += uint64(ad.TotalAssetParams) // look for N asset params
} else if ad.TotalAssetParams == ad.TotalAssets {
needToFind += uint64(ad.TotalAssetParams)
} else {
return false
}
if ad.TotalAppParams == 0 { // not a creator of apps
needToFind += uint64(ad.TotalAppLocalStates) // look for N AppLocalStates
} else if ad.TotalAppLocalStates == 0 { // not a user of apps
needToFind += uint64(ad.TotalAppParams) // look for N AppParams
} else {
return false
}
return needToFind == resourceCount
}
return false
}
for {
currentDbRound := au.cachedDBRound
currentDeltaLen := len(au.deltas)
rnd = au.latest()
offset, err = au.roundOffset(rnd)
if err != nil {
return
}
// offset should now be len(au.deltas)
if offset != uint64(len(au.deltas)) {
return basics.AccountData{}, basics.Round(0), basics.MicroAlgos{}, fmt.Errorf("offset != len(au.deltas): %w", ErrLookupLatestResources)
}
ad = ledgercore.AccountData{}
foundAccount = false
foundResources = make(map[basics.CreatableIndex]basics.Round)
resourceCount = 0
rewardsProto = config.Consensus[au.versions[offset]]
rewardsLevel = au.roundTotals[offset].RewardsLevel
// we're testing the withRewards here and setting the defer function only once, and only if withRewards is true.
// we want to make this defer only after setting the above rewardsProto/rewardsLevel.
if withRewards {
defer func() {
if err == nil {
ledgercore.AssignAccountData(&data, ad)
withoutRewards = data.MicroAlgos // record balance before updating rewards
data = data.WithUpdatedRewards(rewardsProto, rewardsLevel)
}
}()
withRewards = false
}
// check if we've had this address modified in the past rounds. ( i.e. if it's in the deltas )
if macct, has := au.accounts[addr]; has {
// This is the most recent round, so we can
// use a cache of the most recent account state.
ad = macct.data
foundAccount = true
} else if pad, inLRU := au.baseAccounts.read(addr); inLRU && pad.Round == currentDbRound {