forked from algorand/go-algorand
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathacctupdates_test.go
2731 lines (2314 loc) · 103 KB
/
acctupdates_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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 (
"bytes"
"context"
"errors"
"fmt"
"os"
"runtime"
"strings"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/algorand/avm-abi/apps"
"github.com/algorand/go-algorand/config"
"github.com/algorand/go-algorand/crypto"
"github.com/algorand/go-algorand/data/basics"
"github.com/algorand/go-algorand/data/bookkeeping"
"github.com/algorand/go-algorand/ledger/eval"
"github.com/algorand/go-algorand/ledger/ledgercore"
"github.com/algorand/go-algorand/ledger/store/trackerdb"
"github.com/algorand/go-algorand/ledger/store/trackerdb/sqlitedriver"
ledgertesting "github.com/algorand/go-algorand/ledger/testing"
"github.com/algorand/go-algorand/logging"
"github.com/algorand/go-algorand/protocol"
"github.com/algorand/go-algorand/test/partitiontest"
"github.com/algorand/go-algorand/util/db"
"github.com/algorand/go-deadlock"
)
var testPoolAddr = basics.Address{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
var testSinkAddr = basics.Address{0x2c, 0x2a, 0x6c, 0xe9, 0xa9, 0xa7, 0xc2, 0x8c, 0x22, 0x95, 0xfd, 0x32, 0x4f, 0x77, 0xa5, 0x4, 0x8b, 0x42, 0xc2, 0xb7, 0xa8, 0x54, 0x84, 0xb6, 0x80, 0xb1, 0xe1, 0x3d, 0x59, 0x9b, 0xeb, 0x36}
type mockLedgerForTracker struct {
dbs trackerdb.Store
blocks []blockEntry
deltas []ledgercore.StateDelta
log logging.Logger
filename string
inMemory bool
consensusParams config.ConsensusParams
consensusVersion protocol.ConsensusVersion
accts map[basics.Address]basics.AccountData
mu deadlock.RWMutex
// trackerRegistry manages persistence into DB so we have to have it here even for a single tracker test
trackers trackerRegistry
}
// onlineTotals returns the online totals of all accounts at the end of round rnd.
// used in tests only
func (au *accountUpdates) onlineTotals(rnd basics.Round) (basics.MicroAlgos, error) {
au.accountsMu.RLock()
defer au.accountsMu.RUnlock()
offset, err := au.roundOffset(rnd)
if err != nil {
return basics.MicroAlgos{}, err
}
totals := au.roundTotals[offset]
return totals.Online.Money, nil
}
func accumulateTotals(t testing.TB, consensusVersion protocol.ConsensusVersion, accts []map[basics.Address]ledgercore.AccountData, rewardLevel uint64) (totals ledgercore.AccountTotals) {
var ot basics.OverflowTracker
proto := config.Consensus[consensusVersion]
totals.RewardsLevel = rewardLevel
for _, ar := range accts {
for _, data := range ar {
totals.AddAccount(proto, data, &ot)
}
}
require.False(t, ot.Overflowed)
return
}
func setupAccts(niter int) []map[basics.Address]basics.AccountData {
accts := []map[basics.Address]basics.AccountData{ledgertesting.RandomAccounts(niter, true)}
pooldata := basics.AccountData{}
pooldata.MicroAlgos.Raw = 100 * 1000 * 1000 * 1000 * 1000
pooldata.Status = basics.NotParticipating
accts[0][testPoolAddr] = pooldata
sinkdata := basics.AccountData{}
sinkdata.MicroAlgos.Raw = 1000 * 1000 * 1000 * 1000
sinkdata.Status = basics.NotParticipating
accts[0][testSinkAddr] = sinkdata
return accts
}
func makeMockLedgerForTrackerWithLogger(t testing.TB, inMemory bool, initialBlocksCount int, consensusVersion protocol.ConsensusVersion, accts []map[basics.Address]basics.AccountData, l logging.Logger) *mockLedgerForTracker {
dbs, fileName := sqlitedriver.OpenForTesting(t, inMemory)
blocks := randomInitChain(consensusVersion, initialBlocksCount)
deltas := make([]ledgercore.StateDelta, initialBlocksCount)
newAccts := make([]map[basics.Address]ledgercore.AccountData, len(accts))
for idx, update := range accts {
newAcct := make(map[basics.Address]ledgercore.AccountData, len(update))
for addr, bad := range update {
newAcct[addr] = ledgercore.ToAccountData(bad)
}
newAccts[idx] = newAcct
}
totals := accumulateTotals(t, consensusVersion, newAccts, 0)
for i := range deltas {
deltas[i] = ledgercore.StateDelta{
Hdr: &bookkeeping.BlockHeader{},
Totals: totals,
}
}
ml := &mockLedgerForTracker{
dbs: dbs,
log: l,
filename: fileName,
inMemory: inMemory,
blocks: blocks,
deltas: deltas, consensusParams: config.Consensus[consensusVersion],
consensusVersion: consensusVersion,
accts: accts[0],
trackers: trackerRegistry{log: l},
}
return ml
}
func makeMockLedgerForTracker(t testing.TB, inMemory bool, initialBlocksCount int, consensusVersion protocol.ConsensusVersion, accts []map[basics.Address]basics.AccountData) *mockLedgerForTracker {
dblogger := logging.TestingLog(t)
dblogger.SetLevel(logging.Info)
return makeMockLedgerForTrackerWithLogger(t, inMemory, initialBlocksCount, consensusVersion, accts, dblogger)
}
// fork creates another database which has the same content as the current one. Works only for non-memory databases.
func (ml *mockLedgerForTracker) fork(t testing.TB) *mockLedgerForTracker {
if ml.inMemory {
return nil
}
// create a new random file name.
fn := fmt.Sprintf("%s.%d", strings.ReplaceAll(t.Name(), "/", "."), crypto.RandUint64())
dblogger := logging.TestingLog(t)
dblogger.SetLevel(logging.Info)
newLedgerTracker := &mockLedgerForTracker{
inMemory: false,
log: dblogger,
blocks: make([]blockEntry, len(ml.blocks)),
deltas: make([]ledgercore.StateDelta, len(ml.deltas)),
accts: make(map[basics.Address]basics.AccountData),
filename: fn,
consensusParams: ml.consensusParams,
consensusVersion: ml.consensusVersion,
trackers: trackerRegistry{log: dblogger},
}
for k, v := range ml.accts {
newLedgerTracker.accts[k] = v
}
copy(newLedgerTracker.blocks, ml.blocks)
copy(newLedgerTracker.deltas, ml.deltas)
// calling Vacuum implies flushing the database content to disk..
ml.dbs.Vacuum(context.Background())
// copy the database files.
for _, ext := range []string{"", "-shm", "-wal"} {
bytes, err := os.ReadFile(ml.filename + ext)
require.NoError(t, err)
err = os.WriteFile(newLedgerTracker.filename+ext, bytes, 0600)
require.NoError(t, err)
}
dbs, err := db.OpenPair(newLedgerTracker.filename, false)
require.NoError(t, err)
dbs.Rdb.SetLogger(dblogger)
dbs.Wdb.SetLogger(dblogger)
newLedgerTracker.dbs = sqlitedriver.MakeStore(dbs)
return newLedgerTracker
}
func (ml *mockLedgerForTracker) Close() {
ml.trackers.close()
ml.dbs.Close()
// delete the database files of non-memory instances.
if !ml.inMemory {
os.Remove(ml.filename)
os.Remove(ml.filename + "-shm")
os.Remove(ml.filename + "-wal")
}
}
func (ml *mockLedgerForTracker) Latest() basics.Round {
ml.mu.RLock()
defer ml.mu.RUnlock()
return basics.Round(len(ml.blocks)) - 1
}
func (ml *mockLedgerForTracker) addBlock(be blockEntry, delta ledgercore.StateDelta) {
ml.addToBlockQueue(be, delta)
ml.trackers.newBlock(be.block, delta)
}
func (ml *mockLedgerForTracker) addToBlockQueue(be blockEntry, delta ledgercore.StateDelta) {
ml.mu.Lock()
defer ml.mu.Unlock()
ml.blocks = append(ml.blocks, be)
ml.deltas = append(ml.deltas, delta)
}
func (ml *mockLedgerForTracker) trackerEvalVerified(blk bookkeeping.Block, accUpdatesLedger eval.LedgerForEvaluator) (ledgercore.StateDelta, error) {
ml.mu.RLock()
defer ml.mu.RUnlock()
// support returning the deltas if the client explicitly provided them by calling addToBlockQueue, otherwise,
// just return an empty state delta ( since the client clearly didn't care about these )
if len(ml.deltas) > int(blk.Round()) {
return ml.deltas[uint64(blk.Round())], nil
}
return ledgercore.StateDelta{
Hdr: &bookkeeping.BlockHeader{},
}, nil
}
func (ml *mockLedgerForTracker) Block(rnd basics.Round) (bookkeeping.Block, error) {
if rnd > ml.Latest() {
return bookkeeping.Block{}, fmt.Errorf("rnd %d out of bounds", rnd)
}
ml.mu.Lock()
defer ml.mu.Unlock()
return ml.blocks[int(rnd)].block, nil
}
func (ml *mockLedgerForTracker) BlockHdr(rnd basics.Round) (bookkeeping.BlockHeader, error) {
if rnd > ml.Latest() {
return bookkeeping.BlockHeader{}, fmt.Errorf("rnd %d out of bounds", rnd)
}
ml.mu.RLock()
defer ml.mu.RUnlock()
return ml.blocks[int(rnd)].block.BlockHeader, nil
}
func (ml *mockLedgerForTracker) trackerDB() trackerdb.Store {
return ml.dbs
}
func (ml *mockLedgerForTracker) blockDB() db.Pair {
return db.Pair{}
}
func (ml *mockLedgerForTracker) trackerLog() logging.Logger {
return ml.log
}
func (ml *mockLedgerForTracker) GenesisHash() crypto.Digest {
if len(ml.blocks) > 0 {
return ml.blocks[0].block.GenesisHash()
}
return crypto.Digest{}
}
func (ml *mockLedgerForTracker) GenesisProto() config.ConsensusParams {
return ml.consensusParams
}
func (ml *mockLedgerForTracker) GenesisProtoVersion() protocol.ConsensusVersion {
return ml.consensusVersion
}
func (ml *mockLedgerForTracker) GenesisAccounts() map[basics.Address]basics.AccountData {
return ml.accts
}
// this function used to be in acctupdates.go, but we were never using it for production purposes. This
// function has a conceptual flaw in that it attempts to load the entire balances into memory. This might
// not work if we have large number of balances. On these unit testing, however, it's not the case, and it's
// safe to call it.
func (au *accountUpdates) allBalances(rnd basics.Round) (bals map[basics.Address]basics.AccountData, err error) {
au.accountsMu.RLock()
defer au.accountsMu.RUnlock()
offsetLimit, err := au.roundOffset(rnd)
if err != nil {
return
}
err = au.dbs.Snapshot(func(ctx context.Context, tx trackerdb.SnapshotScope) error {
var err0 error
ar, err := tx.MakeAccountsReader()
if err != nil {
return err
}
bals, err0 = ar.Testing().AccountsAllTest()
return err0
})
if err != nil {
return
}
for offset := uint64(0); offset < offsetLimit; offset++ {
deltas := au.deltas[offset]
bals = ledgercore.AccumulateDeltas(bals, deltas.Accts)
}
return
}
func newAcctUpdates(tb testing.TB, l *mockLedgerForTracker, conf config.Local) (*accountUpdates, *onlineAccounts) {
au := &accountUpdates{}
au.initialize(conf)
ao := &onlineAccounts{}
ao.initialize(conf)
_, err := trackerDBInitialize(l, false, ".")
require.NoError(tb, err)
err = l.trackers.initialize(l, []ledgerTracker{au, ao, &txTail{}}, conf)
require.NoError(tb, err)
err = l.trackers.loadFromDisk(l)
require.NoError(tb, err)
return au, ao
}
func checkAcctUpdates(t *testing.T, au *accountUpdates, ao *onlineAccounts, base basics.Round, latestRnd basics.Round, accts []map[basics.Address]basics.AccountData, rewards []uint64, proto config.ConsensusParams) {
latest := au.latest()
require.Equal(t, latestRnd, latest)
// the log has "onlineAccounts failed to fetch online totals for rnd" warning that is expected
_, err := ao.onlineCirculation(latest+1, latest+1+basics.Round(ao.maxBalLookback()))
require.Error(t, err)
var validThrough basics.Round
_, validThrough, err = au.LookupWithoutRewards(latest+1, ledgertesting.RandomAddress())
require.Error(t, err)
require.Equal(t, basics.Round(0), validThrough)
if base > 0 && base >= basics.Round(ao.maxBalLookback()) {
rnd := base - basics.Round(ao.maxBalLookback())
_, err := ao.onlineCirculation(rnd, base)
require.Error(t, err)
_, validThrough, err = au.LookupWithoutRewards(base-1, ledgertesting.RandomAddress())
require.Error(t, err)
require.Equal(t, basics.Round(0), validThrough)
}
roundsRanges := []struct {
start, end basics.Round
}{}
// running the checkAcctUpdates on the entire range of base..latestRnd is too slow, and unlikely to help us
// to trap a regression ( might be a good to find where the regression started ). so, for
// performance reasons, we're going to run it againt the first and last 5 rounds, plus few rounds
// in between.
if latestRnd-base <= 10 {
roundsRanges = append(roundsRanges, struct{ start, end basics.Round }{base, latestRnd})
} else {
roundsRanges = append(roundsRanges, struct{ start, end basics.Round }{base, base + 5})
roundsRanges = append(roundsRanges, struct{ start, end basics.Round }{latestRnd - 5, latestRnd})
for i := base + 5; i < latestRnd-5; i += 1 + (latestRnd-base-10)/10 {
roundsRanges = append(roundsRanges, struct{ start, end basics.Round }{i, i + 1})
}
}
for _, roundRange := range roundsRanges {
for rnd := roundRange.start; rnd <= roundRange.end; rnd++ {
var totalOnline, totalOffline, totalNotPart uint64
for addr, data := range accts[rnd] {
d, validThrough, err := au.LookupWithoutRewards(rnd, addr)
require.NoError(t, err)
require.Equal(t, d, ledgercore.ToAccountData(data))
require.GreaterOrEqualf(t, uint64(validThrough), uint64(rnd), fmt.Sprintf("validThrough :%v\nrnd :%v\n", validThrough, rnd))
// TODO: make lookupOnlineAccountData returning extended version of ledgercore.VotingData ?
od, err := ao.lookupOnlineAccountData(rnd, addr)
require.NoError(t, err)
// If lookupOnlineAccountData returned something, it should agree with `data`.
if !od.VoteID.IsEmpty() {
require.Equal(t, od.VoteID, data.VoteID)
require.Equal(t, od.SelectionID, data.SelectionID)
require.Equal(t, od.VoteFirstValid, data.VoteFirstValid)
require.Equal(t, od.VoteLastValid, data.VoteLastValid)
require.Equal(t, od.VoteKeyDilution, data.VoteKeyDilution)
}
rewardsDelta := rewards[rnd] - d.RewardsBase
switch d.Status {
case basics.Online:
totalOnline += d.MicroAlgos.Raw
totalOnline += (d.MicroAlgos.Raw / proto.RewardUnit) * rewardsDelta
case basics.Offline:
totalOffline += d.MicroAlgos.Raw
totalOffline += (d.MicroAlgos.Raw / proto.RewardUnit) * rewardsDelta
case basics.NotParticipating:
totalNotPart += d.MicroAlgos.Raw
default:
t.Errorf("unknown status %v", d.Status)
}
}
all, err := au.allBalances(rnd)
require.NoError(t, err)
bll := accts[rnd]
require.Equal(t, all, bll)
totals, err := ao.onlineCirculation(rnd, rnd+basics.Round(ao.maxBalLookback()))
require.NoError(t, err)
require.Equal(t, totals.Raw, totalOnline)
auTotals, err := au.onlineTotals(rnd)
require.NoError(t, err)
require.Equal(t, totals.Raw, auTotals.Raw)
d, validThrough, err := au.LookupWithoutRewards(rnd, ledgertesting.RandomAddress())
require.NoError(t, err)
require.GreaterOrEqualf(t, uint64(validThrough), uint64(rnd), fmt.Sprintf("validThrough :%v\nrnd :%v\n", validThrough, rnd))
require.Equal(t, d, ledgercore.AccountData{})
od, err := ao.lookupOnlineAccountData(rnd, ledgertesting.RandomAddress())
require.NoError(t, err)
require.Equal(t, od, basics.OnlineAccountData{})
}
}
checkAcctUpdatesConsistency(t, au, latestRnd)
checkOnlineAcctUpdatesConsistency(t, ao, latestRnd)
}
func checkAcctUpdatesConsistency(t *testing.T, au *accountUpdates, rnd basics.Round) {
accounts := make(map[basics.Address]modifiedAccount)
resources := make(resourcesUpdates)
for _, sdelta := range au.deltas {
rdelta := sdelta.Accts
for i := 0; i < rdelta.Len(); i++ {
addr, adelta := rdelta.GetByIdx(i)
macct := accounts[addr]
macct.data = adelta
macct.ndeltas++
accounts[addr] = macct
}
for _, rec := range rdelta.GetAllAppResources() {
key := accountCreatable{rec.Addr, basics.CreatableIndex(rec.Aidx)}
entry, _ := resources.get(key)
entry.resource.AppLocalState = rec.State.LocalState
entry.resource.AppParams = rec.Params.Params
entry.ndeltas++
resources[key] = entry
}
for _, rec := range rdelta.GetAllAssetResources() {
key := accountCreatable{rec.Addr, basics.CreatableIndex(rec.Aidx)}
entry, _ := resources.get(key)
entry.resource.AssetHolding = rec.Holding.Holding
entry.resource.AssetParams = rec.Params.Params
entry.ndeltas++
resources[key] = entry
}
}
require.Equal(t, au.accounts, accounts)
require.Equal(t, au.resources, resources)
latest := au.deltas[len(au.deltas)-1].Accts
for i := 0; i < latest.Len(); i++ {
addr, acct := latest.GetByIdx(i)
d, r, withoutRewards, err := au.lookupLatest(addr)
require.NoError(t, err)
require.Equal(t, rnd, r)
require.Equal(t, int(acct.TotalAppParams), len(d.AppParams))
require.Equal(t, int(acct.TotalAssetParams), len(d.AssetParams))
require.Equal(t, int(acct.TotalAppLocalStates), len(d.AppLocalStates))
require.Equal(t, int(acct.TotalAssets), len(d.Assets))
// check "withoutRewards" matches result of LookupWithoutRewards
d2, r2, err2 := au.LookupWithoutRewards(r, addr)
require.NoError(t, err2)
require.Equal(t, r2, r)
require.Equal(t, withoutRewards, d2.MicroAlgos)
}
}
func checkOnlineAcctUpdatesConsistency(t *testing.T, ao *onlineAccounts, rnd basics.Round) {
accounts := make(map[basics.Address]modifiedOnlineAccount)
for _, rdelta := range ao.deltas {
for i := 0; i < rdelta.Len(); i++ {
addr, adelta := rdelta.GetByIdx(i)
macct := accounts[addr]
macct.data = adelta
macct.ndeltas++
accounts[addr] = macct
}
}
require.Equal(t, ao.accounts, accounts)
latest := ao.deltas[len(ao.deltas)-1]
for i := 0; i < latest.Len(); i++ {
addr, acct := latest.GetByIdx(i)
od, err := ao.lookupOnlineAccountData(rnd, addr)
if od.VoteID.IsEmpty() {
// suspended accounts will be in `latest` (from ao.deltas), but
// `lookupOnlineAccountData` will return {}.
continue
}
require.NoError(t, err)
require.Equal(t, acct.VoteID, od.VoteID)
require.Equal(t, acct.SelectionID, od.SelectionID)
require.Equal(t, acct.VoteFirstValid, od.VoteFirstValid)
require.Equal(t, acct.VoteLastValid, od.VoteLastValid)
require.Equal(t, acct.VoteKeyDilution, od.VoteKeyDilution)
}
}
func testAcctUpdates(t *testing.T, conf config.Local) {
// The next operations are heavy on the memory.
// Garbage collection helps prevent trashing
runtime.GC()
proto := config.Consensus[protocol.ConsensusCurrentVersion]
for _, lookback := range []uint64{conf.MaxAcctLookback, proto.MaxBalLookback} {
t.Run(fmt.Sprintf("lookback=%d", lookback), func(t *testing.T) {
conf.MaxAcctLookback = lookback
accts := setupAccts(20)
rewardsLevels := []uint64{0}
initialBlocksCount := int(lookback)
ml := makeMockLedgerForTracker(t, true, initialBlocksCount, protocol.ConsensusCurrentVersion, accts)
defer ml.Close()
au, ao := newAcctUpdates(t, ml, conf)
// au and ao are closed via ml.Close() -> ml.trackers.close()
// cover 10 genesis blocks
rewardLevel := uint64(0)
for i := 1; i < initialBlocksCount; i++ {
accts = append(accts, accts[0])
rewardsLevels = append(rewardsLevels, rewardLevel)
}
checkAcctUpdates(t, au, ao, 0, basics.Round(initialBlocksCount-1), accts, rewardsLevels, proto)
// lastCreatableID stores asset or app max used index to get rid of conflicts
lastCreatableID := basics.CreatableIndex(crypto.RandUint64() % 512)
knownCreatables := make(map[basics.CreatableIndex]bool)
maxLookback := conf.MaxAcctLookback
start := basics.Round(initialBlocksCount)
end := basics.Round(maxLookback + 15)
for i := start; i < end; i++ {
rewardLevelDelta := crypto.RandUint64() % 5
rewardLevel += rewardLevelDelta
var updates ledgercore.AccountDeltas
var totals map[basics.Address]ledgercore.AccountData
base := accts[i-1]
updates, totals = ledgertesting.RandomDeltasBalancedFull(1, base, rewardLevel, &lastCreatableID)
prevRound, prevTotals, err := au.LatestTotals()
require.Equal(t, i-1, prevRound)
require.NoError(t, err)
newPool := totals[testPoolAddr]
newPool.MicroAlgos.Raw -= prevTotals.RewardUnits() * rewardLevelDelta
updates.Upsert(testPoolAddr, newPool)
totals[testPoolAddr] = newPool
newAccts := applyPartialDeltas(base, updates)
blk := bookkeeping.Block{
BlockHeader: bookkeeping.BlockHeader{
Round: basics.Round(i),
},
}
blk.RewardsLevel = rewardLevel
blk.CurrentProtocol = protocol.ConsensusCurrentVersion
delta := ledgercore.MakeStateDelta(&blk.BlockHeader, 0, updates.Len(), 0)
delta.Accts.MergeAccounts(updates)
delta.Creatables = creatablesFromUpdates(base, updates, knownCreatables)
delta.Totals = accumulateTotals(t, protocol.ConsensusCurrentVersion, []map[basics.Address]ledgercore.AccountData{totals}, rewardLevel)
ml.addBlock(blockEntry{block: blk}, delta)
accts = append(accts, newAccts)
rewardsLevels = append(rewardsLevels, rewardLevel)
// checkAcctUpdates is kind of slow because of amount of data it needs to compare
// instead, compare at start, end in between approx 10 rounds
if i == start || i == end-1 || crypto.RandUint64()%10 == 0 || lookback < 10 {
checkAcctUpdates(t, au, ao, 0, i, accts, rewardsLevels, proto)
}
}
for i := basics.Round(0); i < 15; i++ {
// Clear the timer to ensure a flush
ml.trackers.lastFlushTime = time.Time{}
ml.trackers.committedUpTo(basics.Round(maxLookback) + i)
ml.trackers.waitAccountsWriting()
checkAcctUpdates(t, au, ao, i, basics.Round(maxLookback+14), accts, rewardsLevels, proto)
}
// check the account totals.
var dbRound basics.Round
err := ml.dbs.Snapshot(func(ctx context.Context, tx trackerdb.SnapshotScope) (err error) {
ar, err := tx.MakeAccountsReader()
if err != nil {
return err
}
dbRound, err = ar.AccountsRound()
return
})
require.NoError(t, err)
var updates ledgercore.AccountDeltas
for addr, acctData := range accts[dbRound] {
updates.Upsert(addr, ledgercore.ToAccountData(acctData))
}
expectedTotals := ledgertesting.CalculateNewRoundAccountTotals(t, updates, rewardsLevels[dbRound], proto, nil, ledgercore.AccountTotals{})
var actualTotals ledgercore.AccountTotals
err = ml.dbs.Snapshot(func(ctx context.Context, tx trackerdb.SnapshotScope) (err error) {
ar, err := tx.MakeAccountsReader()
if err != nil {
return err
}
actualTotals, err = ar.AccountsTotals(ctx, false)
return
})
require.NoError(t, err)
require.Equal(t, expectedTotals, actualTotals)
})
}
}
func TestAcctUpdates(t *testing.T) {
partitiontest.PartitionTest(t)
conf := config.GetDefaultLocal()
ledgertesting.WithAndWithoutLRUCache(t, conf, testAcctUpdates)
}
func BenchmarkBalancesChanges(b *testing.B) {
if runtime.GOARCH == "arm" || runtime.GOARCH == "arm64" {
b.Skip("This test is too slow on ARM and causes travis builds to time out")
}
if b.N < 100 {
b.N = 50
}
protocolVersion := protocol.ConsensusCurrentVersion
initialRounds := uint64(1)
accountsCount := 5000
accts := setupAccts(accountsCount)
rewardsLevels := []uint64{0}
ml := makeMockLedgerForTracker(b, true, int(initialRounds), protocolVersion, accts)
defer ml.Close()
conf := config.GetDefaultLocal()
maxAcctLookback := conf.MaxAcctLookback
au, _ := newAcctUpdates(b, ml, conf)
// accountUpdates and onlineAccounts are closed via: ml.Close() -> ml.trackers.close()
// cover initialRounds genesis blocks
rewardLevel := uint64(0)
for i := 1; i < int(initialRounds); i++ {
accts = append(accts, accts[0])
rewardsLevels = append(rewardsLevels, rewardLevel)
}
for i := basics.Round(initialRounds); i < basics.Round(maxAcctLookback+uint64(b.N)); i++ {
rewardLevelDelta := crypto.RandUint64() % 5
rewardLevel += rewardLevelDelta
accountChanges := 0
if i <= basics.Round(initialRounds)+basics.Round(b.N) {
accountChanges = accountsCount - 2 - int(basics.Round(maxAcctLookback+uint64(b.N))+i)
}
updates, totals := ledgertesting.RandomDeltasBalanced(accountChanges, accts[i-1], rewardLevel)
prevRound, prevTotals, err := au.LatestTotals()
require.Equal(b, i-1, prevRound)
require.NoError(b, err)
newPool := totals[testPoolAddr]
newPool.MicroAlgos.Raw -= prevTotals.RewardUnits() * rewardLevelDelta
updates.Upsert(testPoolAddr, newPool)
totals[testPoolAddr] = newPool
newAccts := applyPartialDeltas(accts[i-1], updates)
blk := bookkeeping.Block{
BlockHeader: bookkeeping.BlockHeader{
Round: basics.Round(i),
},
}
blk.RewardsLevel = rewardLevel
blk.CurrentProtocol = protocolVersion
delta := ledgercore.MakeStateDelta(&blk.BlockHeader, 0, updates.Len(), 0)
delta.Accts.MergeAccounts(updates)
ml.addBlock(blockEntry{block: blk}, delta)
accts = append(accts, newAccts)
rewardsLevels = append(rewardsLevels, rewardLevel)
}
for i := maxAcctLookback; i < maxAcctLookback+initialRounds; i++ {
// Clear the timer to ensure a flush
ml.trackers.lastFlushTime = time.Time{}
ml.trackers.committedUpTo(basics.Round(i))
}
ml.trackers.waitAccountsWriting()
b.ResetTimer()
startTime := time.Now()
for i := maxAcctLookback + initialRounds; i < maxAcctLookback+uint64(b.N); i++ {
// Clear the timer to ensure a flush
ml.trackers.lastFlushTime = time.Time{}
ml.trackers.committedUpTo(basics.Round(i))
}
ml.trackers.waitAccountsWriting()
deltaTime := time.Since(startTime)
if deltaTime > time.Second {
return
}
// we want to fake the N to reflect the time it took us, if we were to wait an entire second.
singleIterationTime := deltaTime / time.Duration(uint64(b.N)-initialRounds)
b.N = int(time.Second / singleIterationTime)
// and now, wait for the reminder of the second.
time.Sleep(time.Second - deltaTime)
}
func BenchmarkCalibrateNodesPerPage(b *testing.B) {
b.Skip("This benchmark was used to tune up the NodesPerPage; it's not really useful otherwise")
defaultNodesPerPage := trackerdb.MerkleCommitterNodesPerPage
for nodesPerPage := 32; nodesPerPage < 300; nodesPerPage++ {
b.Run(fmt.Sprintf("Test_merkleCommitterNodesPerPage_%d", nodesPerPage), func(b *testing.B) {
trackerdb.MerkleCommitterNodesPerPage = int64(nodesPerPage)
BenchmarkBalancesChanges(b)
})
}
trackerdb.MerkleCommitterNodesPerPage = defaultNodesPerPage
}
func BenchmarkCalibrateCacheNodeSize(b *testing.B) {
//b.Skip("This benchmark was used to tune up the TrieCachedNodesCount; it's not really useful otherwise")
defaultTrieCachedNodesCount := trackerdb.TrieCachedNodesCount
for cacheSize := 3000; cacheSize < 50000; cacheSize += 1000 {
b.Run(fmt.Sprintf("Test_cacheSize_%d", cacheSize), func(b *testing.B) {
trackerdb.TrieCachedNodesCount = cacheSize
BenchmarkBalancesChanges(b)
})
}
trackerdb.TrieCachedNodesCount = defaultTrieCachedNodesCount
}
// The TestAcctUpdatesUpdatesCorrectness conduct a correctless test for the accounts update in the following way -
// Each account is initialized with 100 algos.
// On every round, each account move variable amount of funds to an accumulating account.
// The deltas for each account are picked by using the lookup method.
// At the end of the test, we verify that each account has the expected amount of algos.
// In addition, throughout the test, we check ( using lookup ) that the historical balances, *beyond* the
// lookback are generating either an error, or returning the correct amount.
func TestAcctUpdatesUpdatesCorrectness(t *testing.T) {
partitiontest.PartitionTest(t)
cfgLocal := config.GetDefaultLocal()
ledgertesting.WithAndWithoutLRUCache(t, cfgLocal, testAcctUpdatesUpdatesCorrectness)
}
func testAcctUpdatesUpdatesCorrectness(t *testing.T, cfg config.Local) {
// create new protocol version, which has lower look back.
testProtocolVersion := protocol.ConsensusCurrentVersion
maxAcctLookback := cfg.MaxAcctLookback
inMemory := true
testFunction := func(t *testing.T) {
accts := setupAccts(9)
ml := makeMockLedgerForTracker(t, inMemory, 10, testProtocolVersion, accts)
defer ml.Close()
var moneyAccounts []basics.Address
for addr := range accts[0] {
if bytes.Equal(addr[:], testPoolAddr[:]) || bytes.Equal(addr[:], testSinkAddr[:]) {
continue
}
moneyAccounts = append(moneyAccounts, addr)
}
moneyAccountsExpectedAmounts := make([][]uint64, 0)
// set all the accounts with 100 algos.
for _, addr := range moneyAccounts {
accountData := accts[0][addr]
accountData.MicroAlgos.Raw = 100 * 1000000
accts[0][addr] = accountData
}
au, _ := newAcctUpdates(t, ml, cfg)
// accountUpdates and onlineAccounts are closed via: ml.Close() -> ml.trackers.close()
// cover 10 genesis blocks
rewardLevel := uint64(0)
for i := 1; i < 10; i++ {
accts = append(accts, accts[0])
}
for i := 0; i < 10; i++ {
moneyAccountsExpectedAmounts = append(moneyAccountsExpectedAmounts, make([]uint64, len(moneyAccounts)))
for j := range moneyAccounts {
moneyAccountsExpectedAmounts[i][j] = 100 * 1000000
}
}
i := basics.Round(10)
roundCount := 50
for ; i < basics.Round(10+roundCount); i++ {
updates := make(map[basics.Address]ledgercore.AccountData)
moneyAccountsExpectedAmounts = append(moneyAccountsExpectedAmounts, make([]uint64, len(moneyAccounts)))
toAccount := moneyAccounts[0]
toAccountDataOld, validThrough, err := au.LookupWithoutRewards(i-1, toAccount)
require.NoError(t, err)
require.Equal(t, i-1, validThrough)
toAccountDataNew := toAccountDataOld
for j := 1; j < len(moneyAccounts); j++ {
fromAccount := moneyAccounts[j]
fromAccountDataOld, validThrough, err := au.LookupWithoutRewards(i-1, fromAccount)
require.NoError(t, err)
require.Equal(t, i-1, validThrough)
require.Equalf(t, moneyAccountsExpectedAmounts[i-1][j], fromAccountDataOld.MicroAlgos.Raw, "Account index : %d\nRound number : %d", j, i)
fromAccountDataNew := fromAccountDataOld
fromAccountDataNew.MicroAlgos.Raw -= uint64(i - 10)
toAccountDataNew.MicroAlgos.Raw += uint64(i - 10)
updates[fromAccount] = fromAccountDataNew
moneyAccountsExpectedAmounts[i][j] = fromAccountDataNew.MicroAlgos.Raw
}
moneyAccountsExpectedAmounts[i][0] = moneyAccountsExpectedAmounts[i-1][0] + uint64(len(moneyAccounts)-1)*uint64(i-10)
// force to perform a test that goes directly to disk, and see if it has the expected values.
if uint64(i) > maxAcctLookback+3 {
// check the status at a historical time:
checkRound := uint64(i) - maxAcctLookback - 2
testback := 1
for j := 1; j < len(moneyAccounts); j++ {
if checkRound < uint64(testback) {
continue
}
acct, validThrough, err := au.LookupWithoutRewards(basics.Round(checkRound-uint64(testback)), moneyAccounts[j])
// we might get an error like "round 2 before dbRound 5", which is the success case, so we'll ignore it.
roundOffsetError := &RoundOffsetError{}
if errors.As(err, &roundOffsetError) {
require.Equal(t, basics.Round(0), validThrough)
// verify it's the expected error and not anything else.
require.Less(t, int64(roundOffsetError.round), int64(roundOffsetError.dbRound))
if testback > 1 {
testback--
}
continue
}
require.NoError(t, err)
require.GreaterOrEqual(t, int64(validThrough), int64(basics.Round(checkRound-uint64(testback))))
// if we received no error, we want to make sure the reported amount is correct.
require.Equalf(t, moneyAccountsExpectedAmounts[checkRound-uint64(testback)][j], acct.MicroAlgos.Raw, "Account index : %d\nRound number : %d", j, checkRound)
testback++
j--
}
}
updates[toAccount] = toAccountDataNew
blk := bookkeeping.Block{
BlockHeader: bookkeeping.BlockHeader{
Round: basics.Round(i),
},
}
blk.RewardsLevel = rewardLevel
blk.CurrentProtocol = testProtocolVersion
delta := ledgercore.MakeStateDelta(&blk.BlockHeader, 0, len(updates), 0)
for addr, ad := range updates {
delta.Accts.Upsert(addr, ad)
}
ml.addBlock(blockEntry{block: blk}, delta)
ml.trackers.committedUpTo(i)
}
lastRound := i - 1
ml.trackers.waitAccountsWriting()
for idx, addr := range moneyAccounts {
balance, validThrough, err := au.LookupWithoutRewards(lastRound, addr)
require.NoErrorf(t, err, "unable to retrieve balance for account idx %d %v", idx, addr)
require.Equal(t, lastRound, validThrough)
if idx != 0 {
require.Equalf(t, 100*1000000-roundCount*(roundCount-1)/2, int(balance.MicroAlgos.Raw), "account idx %d %v has the wrong balance", idx, addr)
} else {
require.Equalf(t, 100*1000000+(len(moneyAccounts)-1)*roundCount*(roundCount-1)/2, int(balance.MicroAlgos.Raw), "account idx %d %v has the wrong balance", idx, addr)
}
}
}
t.Run("InMemoryDB", testFunction)
inMemory = false
t.Run("DiskDB", testFunction)
}
func TestBoxNamesByAppIDs(t *testing.T) {
partitiontest.PartitionTest(t)
t.Parallel()
initialBlocksCount := 1
accts := make(map[basics.Address]basics.AccountData)
protoParams := config.Consensus[protocol.ConsensusCurrentVersion]
ml := makeMockLedgerForTracker(t, true, initialBlocksCount, protocol.ConsensusCurrentVersion,
[]map[basics.Address]basics.AccountData{accts},
)
defer ml.Close()
conf := config.GetDefaultLocal()
au, _ := newAcctUpdates(t, ml, conf)
// accountUpdates and onlineAccounts are closed via: ml.Close() -> ml.trackers.close()
knownCreatables := make(map[basics.CreatableIndex]bool)
opts := auNewBlockOpts{ledgercore.AccountDeltas{}, protocol.ConsensusCurrentVersion, protoParams, knownCreatables}
testingBoxNames := []string{
` `,
` `,
` % `,
` ? = % ;`,
`; DROP *;`,
`OR 1 = 1;`,
`" ; SELECT * FROM kvstore; DROP acctrounds; `,
`; SELECT key from kvstore WHERE key LIKE %;`,
`?&%!=`,
"SELECT * FROM kvstore " + string([]byte{0, 0}) + " WHERE key LIKE %; ",
`b64:APj/AA==`,
`str:123.3/aa\\0`,
string([]byte{0, 255, 254, 254}),
string([]byte{0, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF}),
string([]byte{'%', 'a', 'b', 'c', 0, 0, '%', 'a', '!'}),
`
`,
`™£´´∂ƒ∂ƒßƒ©∑®ƒß∂†¬∆`,
`∑´´˙©˚¬∆ßåƒ√¬`,
`背负青天而莫之夭阏者,而后乃今将图南。`,
`於浩歌狂熱之際中寒﹔於天上看見深淵。`,
`於一切眼中看見無所有﹔於無所希望中得救。`,
`有一遊魂,化為長蛇,口有毒牙。`,
`不以嚙人,自嚙其身,終以殞顛。`,
`那些智力超常的人啊`,
`认为已经,熟悉了云和闪电的脾气`,
`就不再迷惑,就不必了解自己,世界和他人`,
`每天只管,被微风吹拂,与猛虎谈情`,
`他们从来,不需要楼梯,只有窗口`,
`把一切交付于梦境,和优美的浪潮`,
`在这颗行星所有的酒馆,青春自由似乎理所应得`,
`面向涣散的未来,只唱情歌,看不到坦克`,
`在科学和啤酒都不能安抚的夜晚`,
`他们丢失了四季,惶惑之行开始`,
`这颗行星所有的酒馆,无法听到远方的呼喊`,
`野心勃勃的灯火,瞬间吞没黑暗的脸庞`,
}
appIDset := make(map[basics.AppIndex]struct{}, len(testingBoxNames))
boxNameToAppID := make(map[string]basics.AppIndex, len(testingBoxNames))
var currentRound basics.Round
// keep adding one box key and one random appID (non-duplicated)
for i, boxName := range testingBoxNames {