summaryrefslogtreecommitdiff
path: root/data/ledger_test.go
blob: dc50147db31914eec37cee4916341f16b14dcea9 (plain)
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
// Copyright (C) 2019-2022 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 data

import (
	"context"
	"fmt"
	"sync"
	"testing"

	"github.com/stretchr/testify/require"

	"github.com/algorand/go-algorand/agreement"
	"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/data/transactions"
	"github.com/algorand/go-algorand/ledger"
	"github.com/algorand/go-algorand/ledger/ledgercore"
	"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/execpool"
)

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}

func testGenerateInitState(tb testing.TB, proto protocol.ConsensusVersion) (genesisInitState ledgercore.InitState, initKeys map[basics.Address]*crypto.SignatureSecrets) {

	var poolSecret, sinkSecret *crypto.SignatureSecrets
	var seed crypto.Seed

	incentivePoolName := []byte("incentive pool")
	copy(seed[:], incentivePoolName)
	poolSecret = crypto.GenerateSignatureSecrets(seed)

	feeSinkName := []byte("fee sink")
	copy(seed[:], feeSinkName)
	sinkSecret = crypto.GenerateSignatureSecrets(seed)

	params := config.Consensus[proto]
	poolAddr := testPoolAddr
	sinkAddr := testSinkAddr

	var zeroSeed crypto.Seed
	var genaddrs [10]basics.Address
	var gensecrets [10]*crypto.SignatureSecrets
	for i := range genaddrs {
		seed := zeroSeed
		seed[0] = byte(i)
		x := crypto.GenerateSignatureSecrets(seed)
		genaddrs[i] = basics.Address(x.SignatureVerifier)
		gensecrets[i] = x
	}

	initKeys = make(map[basics.Address]*crypto.SignatureSecrets)
	initAccounts := make(map[basics.Address]basics.AccountData)
	for i := range genaddrs {
		initKeys[genaddrs[i]] = gensecrets[i]
		// Give each account quite a bit more balance than MinFee or MinBalance
		accountStatus := basics.Online
		if i%2 == 0 {
			accountStatus = basics.NotParticipating
		}
		initAccounts[genaddrs[i]] = basics.MakeAccountData(accountStatus, basics.MicroAlgos{Raw: uint64((i + 100) * 100000)})
	}
	initKeys[poolAddr] = poolSecret
	initAccounts[poolAddr] = basics.MakeAccountData(basics.NotParticipating, basics.MicroAlgos{Raw: 1234567})
	initKeys[sinkAddr] = sinkSecret
	initAccounts[sinkAddr] = basics.MakeAccountData(basics.NotParticipating, basics.MicroAlgos{Raw: 7654321})

	incentivePoolBalanceAtGenesis := initAccounts[poolAddr].MicroAlgos
	initialRewardsPerRound := incentivePoolBalanceAtGenesis.Raw / uint64(params.RewardsRateRefreshInterval)

	initBlock := bookkeeping.Block{
		BlockHeader: bookkeeping.BlockHeader{
			GenesisID: tb.Name(),
			Round:     0,
			RewardsState: bookkeeping.RewardsState{
				RewardsRate: initialRewardsPerRound,
				RewardsPool: poolAddr,
				FeeSink:     sinkAddr,
			},
			UpgradeState: bookkeeping.UpgradeState{
				CurrentProtocol: proto,
			},
		},
	}
	var err error
	initBlock.TxnRoot, err = initBlock.PaysetCommit()
	require.NoError(tb, err)
	if params.SupportGenesisHash {
		initBlock.BlockHeader.GenesisHash = crypto.Hash([]byte(tb.Name()))
	}

	genesisInitState.Block = initBlock
	genesisInitState.Accounts = initAccounts
	genesisInitState.GenesisHash = crypto.Hash([]byte(tb.Name()))

	return
}

func TestLedgerCirculation(t *testing.T) {
	partitiontest.PartitionTest(t)

	genesisInitState, keys := testGenerateInitState(t, protocol.ConsensusCurrentVersion)

	const inMem = true
	cfg := config.GetDefaultLocal()
	cfg.Archival = true
	log := logging.TestingLog(t)
	log.SetLevel(logging.Warn)
	realLedger, err := ledger.OpenLedger(log, t.Name(), inMem, genesisInitState, cfg)
	require.NoError(t, err, "could not open ledger")
	defer realLedger.Close()

	l := Ledger{Ledger: realLedger}
	require.NotNil(t, &l)

	var sourceAccount basics.Address
	var destAccount basics.Address
	for addr, acctData := range genesisInitState.Accounts {
		if addr == testPoolAddr || addr == testSinkAddr {
			continue
		}
		if acctData.Status == basics.Online {
			sourceAccount = addr
			break
		}
	}
	for addr, acctData := range genesisInitState.Accounts {
		if addr == testPoolAddr || addr == testSinkAddr {
			continue
		}
		if acctData.Status == basics.NotParticipating {
			destAccount = addr
			break
		}
	}
	require.False(t, sourceAccount.IsZero())
	require.False(t, destAccount.IsZero())

	data, err := realLedger.Lookup(basics.Round(0), destAccount)
	require.NoError(t, err)
	baseDestValue := data.MicroAlgos.Raw

	blk := genesisInitState.Block
	totalsRound, totals, err := realLedger.LatestTotals()
	require.NoError(t, err)
	require.Equal(t, basics.Round(0), totalsRound)
	baseCirculation := totals.Online.Money.Raw

	srcAccountKey := keys[sourceAccount]
	require.NotNil(t, srcAccountKey)

	for rnd := basics.Round(1); rnd < basics.Round(600); rnd++ {
		blk.BlockHeader.Round++
		blk.BlockHeader.TimeStamp += int64(crypto.RandUint64() % 100 * 1000)
		var tx transactions.Transaction
		tx.Sender = sourceAccount
		tx.Fee = basics.MicroAlgos{Raw: 10000}
		tx.FirstValid = rnd - 1
		tx.LastValid = tx.FirstValid + 999
		tx.Receiver = destAccount
		tx.Amount = basics.MicroAlgos{Raw: 1}
		tx.Type = protocol.PaymentTx
		signedTx := tx.Sign(srcAccountKey)
		blk.Payset = transactions.Payset{transactions.SignedTxnInBlock{
			SignedTxnWithAD: transactions.SignedTxnWithAD{
				SignedTxn: signedTx,
			},
		}}
		require.NoError(t, l.AddBlock(blk, agreement.Certificate{}))
		l.WaitForCommit(rnd)

		// test most recent round
		if rnd < basics.Round(500) {
			data, err = realLedger.Lookup(rnd, destAccount)
			require.NoError(t, err)
			require.Equal(t, baseDestValue+uint64(rnd), data.MicroAlgos.Raw)
			data, err = l.Lookup(rnd, destAccount)
			require.NoError(t, err)
			require.Equal(t, baseDestValue+uint64(rnd), data.MicroAlgos.Raw)

			roundCirculation, err := realLedger.OnlineTotals(rnd)
			require.NoError(t, err)
			require.Equal(t, baseCirculation-uint64(rnd)*(10001), roundCirculation.Raw)

			roundCirculation, err = l.OnlineTotals(rnd)
			require.NoError(t, err)
			require.Equal(t, baseCirculation-uint64(rnd)*(10001), roundCirculation.Raw)
		} else if rnd < basics.Round(510) {
			// test one round ago
			data, err = realLedger.Lookup(rnd-1, destAccount)
			require.NoError(t, err)
			require.Equal(t, baseDestValue+uint64(rnd)-1, data.MicroAlgos.Raw)
			data, err = l.Lookup(rnd-1, destAccount)
			require.NoError(t, err)
			require.Equal(t, baseDestValue+uint64(rnd)-1, data.MicroAlgos.Raw)

			roundCirculation, err := realLedger.OnlineTotals(rnd - 1)
			require.NoError(t, err)
			require.Equal(t, baseCirculation-uint64(rnd-1)*(10001), roundCirculation.Raw)

			roundCirculation, err = l.OnlineTotals(rnd - 1)
			require.NoError(t, err)
			require.Equal(t, baseCirculation-uint64(rnd-1)*(10001), roundCirculation.Raw)
		} else if rnd < basics.Round(520) {
			// test one round in the future ( expected error )
			data, err = realLedger.Lookup(rnd+1, destAccount)
			require.Error(t, err)
			require.Equal(t, uint64(0), data.MicroAlgos.Raw)
			data, err = l.Lookup(rnd+1, destAccount)
			require.Error(t, err)
			require.Equal(t, uint64(0), data.MicroAlgos.Raw)

			_, err = realLedger.OnlineTotals(rnd + 1)
			require.Error(t, err)

			_, err = l.OnlineTotals(rnd + 1)
			require.Error(t, err)
		} else if rnd < basics.Round(520) {
			// test expired round ( expected error )
			_, err = realLedger.OnlineTotals(rnd - 500)
			require.Error(t, err)

			_, err = l.OnlineTotals(rnd - 500)
			require.Error(t, err)
		}
	}
	return
}

func TestLedgerSeed(t *testing.T) {
	partitiontest.PartitionTest(t)

	genesisInitState, _ := testGenerateInitState(t, protocol.ConsensusCurrentVersion)

	const inMem = true
	cfg := config.GetDefaultLocal()
	cfg.Archival = true
	log := logging.TestingLog(t)
	log.SetLevel(logging.Warn)
	realLedger, err := ledger.OpenLedger(log, t.Name(), inMem, genesisInitState, cfg)
	require.NoError(t, err, "could not open ledger")
	defer realLedger.Close()

	l := Ledger{Ledger: realLedger}
	require.NotNil(t, &l)

	blk := genesisInitState.Block
	for rnd := basics.Round(1); rnd < basics.Round(32); rnd++ {
		blk.BlockHeader.Round++
		blk.BlockHeader.Seed[0] = byte(uint64(rnd))
		blk.BlockHeader.Seed[1] = byte(uint64(rnd) / 256)
		blk.BlockHeader.Seed[2] = byte(uint64(rnd) / 65536)
		blk.BlockHeader.TimeStamp += int64(crypto.RandUint64() % 100 * 1000)
		require.NoError(t, l.AddBlock(blk, agreement.Certificate{}))
		l.WaitForCommit(rnd)
		if rnd < basics.Round(16) {
			// test the current round
			expectedHdr, err := realLedger.BlockHdr(rnd)
			require.NoError(t, err)

			// ensure the item is not in the cache
			seed, cached := l.lastRoundSeed.Load().(roundSeed)
			if cached {
				require.NotEqual(t, seed.elements[1].seed, expectedHdr.Seed)
			}

			actualSeed, err := l.Seed(rnd)
			require.NoError(t, err)

			require.Equal(t, expectedHdr.Seed, actualSeed)

			seed, cached = l.lastRoundSeed.Load().(roundSeed)
			require.True(t, cached)
			require.Equal(t, seed.elements[1].seed, expectedHdr.Seed)
		} else if rnd < basics.Round(32) {
			// test against the previous round
			expectedHdr, err := realLedger.BlockHdr(rnd - 1)
			require.NoError(t, err)

			// ensure the cache is aligned with the previous round
			seed, cached := l.lastRoundSeed.Load().(roundSeed)
			require.True(t, cached)
			require.Equal(t, seed.elements[1].round, rnd-1)
			require.Equal(t, seed.elements[1].seed, expectedHdr.Seed)

			actualSeed, err := l.Seed(rnd)
			require.NoError(t, err)

			expectedHdr, err = realLedger.BlockHdr(rnd)
			require.NoError(t, err)

			require.Equal(t, expectedHdr.Seed, actualSeed)

			// ensure the cache is aligned with the updated round
			seed, cached = l.lastRoundSeed.Load().(roundSeed)
			require.True(t, cached)
			require.Equal(t, seed.elements[1].round, rnd)
			require.Equal(t, seed.elements[1].seed, expectedHdr.Seed)
		}
	}
	return
}

func TestConsensusVersion(t *testing.T) {
	partitiontest.PartitionTest(t)

	// find a consensus protocol that leads to ConsensusCurrentVersion
	var previousProtocol protocol.ConsensusVersion
	for ver, params := range config.Consensus {
		if _, has := params.ApprovedUpgrades[protocol.ConsensusCurrentVersion]; has {
			previousProtocol = ver
			break
		}
	}
	require.NotEqual(t, protocol.ConsensusVersion(""), previousProtocol)
	consensusParams := config.Consensus[previousProtocol]

	genesisInitState, _ := testGenerateInitState(t, previousProtocol)

	const inMem = true
	cfg := config.GetDefaultLocal()
	cfg.Archival = false
	log := logging.TestingLog(t)
	log.SetLevel(logging.Warn)
	realLedger, err := ledger.OpenLedger(log, t.Name(), inMem, genesisInitState, cfg)
	require.NoError(t, err, "could not open ledger")
	defer realLedger.Close()

	l := Ledger{Ledger: realLedger}
	require.NotNil(t, &l)

	blk := genesisInitState.Block

	// add 5 blocks.
	for rnd := basics.Round(1); rnd < basics.Round(consensusParams.MaxTxnLife+5); rnd++ {
		blk.BlockHeader.Round++
		blk.BlockHeader.Seed[0] = byte(uint64(rnd))
		blk.BlockHeader.Seed[1] = byte(uint64(rnd) / 256)
		blk.BlockHeader.Seed[2] = byte(uint64(rnd) / 65536)
		blk.BlockHeader.TimeStamp += int64(crypto.RandUint64() % 100 * 1000)
		blk.BlockHeader.CurrentProtocol = previousProtocol
		require.NoError(t, l.AddBlock(blk, agreement.Certificate{}))
		l.WaitForCommit(rnd)
	}
	// ensure that all the first 5 has the expected version.
	for rnd := basics.Round(consensusParams.MaxTxnLife); rnd < basics.Round(consensusParams.MaxTxnLife+5); rnd++ {
		ver, err := l.ConsensusVersion(rnd)
		require.NoError(t, err)
		require.Equal(t, previousProtocol, ver)
	}
	// the next UpgradeVoteRounds can also be known to have the previous version.
	for rnd := basics.Round(consensusParams.MaxTxnLife + 5); rnd < basics.Round(consensusParams.MaxTxnLife+5+consensusParams.UpgradeVoteRounds); rnd++ {
		ver, err := l.ConsensusVersion(rnd)
		require.NoError(t, err)
		require.Equal(t, previousProtocol, ver)
	}

	// but two rounds ahead is not known.
	ver, err := l.ConsensusVersion(basics.Round(consensusParams.MaxTxnLife + 6 + consensusParams.UpgradeVoteRounds))
	require.Equal(t, protocol.ConsensusVersion(""), ver)
	require.Equal(t, ledgercore.ErrNoEntry{Round: basics.Round(consensusParams.MaxTxnLife + 6 + consensusParams.UpgradeVoteRounds), Latest: basics.Round(consensusParams.MaxTxnLife + 4), Committed: basics.Round(consensusParams.MaxTxnLife + 4)}, err)

	// check round #1 which was already dropped.
	ver, err = l.ConsensusVersion(basics.Round(1))
	require.Equal(t, protocol.ConsensusVersion(""), ver)
	require.Equal(t, ledgercore.ErrNoEntry{Round: basics.Round(1), Latest: basics.Round(consensusParams.MaxTxnLife + 4), Committed: basics.Round(consensusParams.MaxTxnLife + 4)}, err)

	// add another round, with upgrade
	rnd := basics.Round(consensusParams.MaxTxnLife + 5)
	blk.BlockHeader.Round++
	blk.BlockHeader.Seed[0] = byte(uint64(rnd))
	blk.BlockHeader.Seed[1] = byte(uint64(rnd) / 256)
	blk.BlockHeader.Seed[2] = byte(uint64(rnd) / 65536)
	blk.BlockHeader.TimeStamp += int64(crypto.RandUint64() % 100 * 1000)
	blk.BlockHeader.CurrentProtocol = previousProtocol
	blk.BlockHeader.NextProtocol = protocol.ConsensusCurrentVersion
	blk.BlockHeader.NextProtocolVoteBefore = basics.Round(rnd) + basics.Round(consensusParams.UpgradeVoteRounds)
	blk.BlockHeader.NextProtocolSwitchOn = basics.Round(rnd) + basics.Round(consensusParams.UpgradeVoteRounds) + basics.Round(consensusParams.ApprovedUpgrades[protocol.ConsensusCurrentVersion])
	require.NoError(t, l.AddBlock(blk, agreement.Certificate{}))
	l.WaitForCommit(rnd)

	for ; rnd < blk.BlockHeader.NextProtocolSwitchOn; rnd++ {
		ver, err := l.ConsensusVersion(rnd)
		require.NoError(t, err)
		require.Equal(t, previousProtocol, ver)
	}

	for rnd = blk.BlockHeader.Round; rnd <= blk.BlockHeader.NextProtocolVoteBefore; rnd++ {
		blk.BlockHeader.Round++
		blk.BlockHeader.Seed[0] = byte(uint64(rnd))
		blk.BlockHeader.Seed[1] = byte(uint64(rnd) / 256)
		blk.BlockHeader.Seed[2] = byte(uint64(rnd) / 65536)
		blk.BlockHeader.NextProtocolApprovals++
		blk.BlockHeader.TimeStamp += int64(crypto.RandUint64() % 100 * 1000)
		require.NoError(t, l.AddBlock(blk, agreement.Certificate{}))
		l.WaitForCommit(rnd + 1)
	}

	ver, err = l.ConsensusVersion(blk.BlockHeader.NextProtocolSwitchOn)
	require.NoError(t, err)
	require.Equal(t, protocol.ConsensusCurrentVersion, ver)

	ver, err = l.ConsensusVersion(blk.BlockHeader.NextProtocolSwitchOn + 1)
	require.Equal(t, protocol.ConsensusVersion(""), ver)
	require.Equal(t, ledgercore.ErrNoEntry{Round: basics.Round(blk.BlockHeader.NextProtocolSwitchOn + 1), Latest: basics.Round(blk.BlockHeader.Round), Committed: basics.Round(blk.BlockHeader.Round)}, err)
}

type loggedMessages struct {
	logging.Logger
	expectedMessages   chan string
	unexpectedMessages chan string
}

func (lm loggedMessages) Debug(args ...interface{}) {
	m := fmt.Sprint(args...)
	lm.unexpectedMessages <- m
}
func (lm loggedMessages) Debugf(s string, args ...interface{}) {
	m := fmt.Sprintf(s, args...)
	lm.expectedMessages <- m
}
func (lm loggedMessages) Info(args ...interface{}) {
	m := fmt.Sprint(args...)
	lm.unexpectedMessages <- m
}
func (lm loggedMessages) Infof(s string, args ...interface{}) {
	m := fmt.Sprintf(s, args...)
	lm.unexpectedMessages <- m
}
func (lm loggedMessages) Warn(args ...interface{}) {
	m := fmt.Sprint(args...)
	lm.unexpectedMessages <- m
}
func (lm loggedMessages) Warnf(s string, args ...interface{}) {
	m := fmt.Sprintf(s, args...)
	lm.unexpectedMessages <- m
}
func (lm loggedMessages) Error(args ...interface{}) {
	m := fmt.Sprint(args...)
	lm.unexpectedMessages <- m
}
func (lm loggedMessages) Errorf(s string, args ...interface{}) {
	m := fmt.Sprintf(s, args...)
	lm.unexpectedMessages <- m
}

// TestLedgerErrorValidate creates 3 parallel routines adding blocks to the ledger through different interfaces.
// The purpose here is to simulate the scenario where the catchup and the agreement compete to add blocks to the ledger.
// The error messages reported can be excessive or unnecessary. This test evaluates what messages are generate and at what frequency.
func TestLedgerErrorValidate(t *testing.T) {
	partitiontest.PartitionTest(t)

	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}

	proto, _ := config.Consensus[protocol.ConsensusCurrentVersion]
	origProto := proto
	defer func() {
		config.Consensus[protocol.ConsensusCurrentVersion] = origProto
	}()
	proto.MinBalance = 0
	config.Consensus[protocol.ConsensusCurrentVersion] = proto

	blk := bookkeeping.Block{}
	blk.CurrentProtocol = protocol.ConsensusCurrentVersion
	blk.RewardsPool = testPoolAddr
	blk.FeeSink = testSinkAddr
	blk.BlockHeader.GenesisHash = crypto.Hash([]byte(t.Name()))

	accts := make(map[basics.Address]basics.AccountData)
	accts[testPoolAddr] = basics.MakeAccountData(basics.NotParticipating, basics.MicroAlgos{Raw: 0})
	accts[testSinkAddr] = basics.MakeAccountData(basics.NotParticipating, basics.MicroAlgos{Raw: 0})

	genesisInitState := ledgercore.InitState{
		Accounts:    accts,
		Block:       blk,
		GenesisHash: crypto.Hash([]byte(t.Name())),
	}

	expectedMessages := make(chan string, 100)
	unexpectedMessages := make(chan string, 100)

	const inMem = true
	cfg := config.GetDefaultLocal()
	cfg.Archival = true
	log := loggedMessages{Logger: logging.TestingLog(t), expectedMessages: expectedMessages, unexpectedMessages: unexpectedMessages}
	log.SetLevel(logging.Debug)
	realLedger, err := ledger.OpenLedger(log, t.Name(), inMem, genesisInitState, cfg)
	require.NoError(t, err, "could not open ledger")
	defer realLedger.Close()

	l := Ledger{Ledger: realLedger, log: log}
	l.log.SetLevel(logging.Debug)
	require.NotNil(t, &l)

	totalsRound, _, err := realLedger.LatestTotals()
	require.NoError(t, err)
	require.Equal(t, basics.Round(0), totalsRound)

	errChan := make(chan error, 1)
	defer close(errChan)

	wg := sync.WaitGroup{}
	defer wg.Wait()

	blkChan1 := make(chan bookkeeping.Block, 10)
	blkChan2 := make(chan bookkeeping.Block, 10)
	blkChan3 := make(chan bookkeeping.Block, 10)
	defer close(blkChan1)
	defer close(blkChan2)
	defer close(blkChan3)

	// Add blocks to the ledger via EnsureValidatedBlock. This calls AddValidatedBlock, which simply
	// passes the block to blockQueue. The returned error is handled by EnsureValidatedBlock, which reports
	// in the form of logged error message.
	go func() {
		wg.Add(1)
		i := 0
		for blk := range blkChan1 {
			i++
			vb, err := validatedBlock(l.Ledger, blk)
			if err != nil {
				// AddBlock already added the block
				// This is okay to ignore.
				// This error is generated from ledger.Ledger Validate function, used from:
				// - node blockValidatorImpl Validate
				// - catchup service s.ledger.Validate (Catchup service returns after the first error)
				continue
			}
			l.EnsureValidatedBlock(vb, agreement.Certificate{})
		}
		wg.Done()
	}()

	// Add blocks to the ledger via EnsureBlock. This basically calls AddBlock, but handles
	// the errors by logging them. Checking the logged messages to verify its behavior.
	go func() {
		wg.Add(1)
		i := 0
		for blk := range blkChan2 {
			i++
			l.EnsureBlock(&blk, agreement.Certificate{})
		}
		wg.Done()
	}()

	// Add blocks directly to the ledger
	go func() {
		wg.Add(1)
		i := 0
		for blk := range blkChan3 {
			i++
			err := l.AddBlock(blk, agreement.Certificate{})
			// AddBlock is used in 2 places:
			// - data.ledger.EnsureBlock which reports a log message as Error or Debug
			// - catchup.service.fetchAndWrite which leads to interrupting catchup or skiping the round
			if err != nil {
				switch err.(type) {
				// The following two cases are okay to ignore, since these are expected and handled
				case ledgercore.BlockInLedgerError:
				case ledgercore.ErrNonSequentialBlockEval:
					continue
				default:
					// Make sure unexpected error is not obtained here
					errChan <- err
				}
			}
			l.WaitForCommit(blk.BlockHeader.Round)
		}
		wg.Done()
	}()

	// flush the messages output during the setup
	more := true
	for more {
		select {
		case <-expectedMessages:
		case <-unexpectedMessages:
		default:
			more = false
		}
	}

	for rnd := basics.Round(1); rnd <= basics.Round(2000); rnd++ {
		blk, err := getEmptyBlock(rnd-1, l.Ledger, t.Name(), genesisInitState.Accounts)
		require.NoError(t, err)
		blkChan3 <- blk
		blkChan2 <- blk
		blkChan1 <- blk

		more = true
		for more {
			select {
			case err := <-errChan:
				require.NoError(t, err)
			case <-expectedMessages:
				// only debug messages should be reported
			case um := <-unexpectedMessages:
				require.Empty(t, um, um)
			default:
				more = false
			}
		}
	}
}

func validatedBlock(l *ledger.Ledger, blk bookkeeping.Block) (vb *ledgercore.ValidatedBlock, err error) {
	backlogPool := execpool.MakeBacklog(nil, 0, execpool.LowPriority, nil)
	defer backlogPool.Shutdown()
	vb, err = l.Validate(context.Background(), blk, backlogPool)
	return
}

func getEmptyBlock(afterRound basics.Round, l *ledger.Ledger, genesisID string, initAccounts map[basics.Address]basics.AccountData) (blk bookkeeping.Block, err error) {
	l.WaitForCommit(afterRound)

	lastBlock, err := l.Block(l.Latest())
	if err != nil {
		return
	}

	proto := config.Consensus[lastBlock.CurrentProtocol]
	blk.BlockHeader = bookkeeping.BlockHeader{
		GenesisID: genesisID,
		Round:     l.Latest() + 1,
		Branch:    lastBlock.Hash(),
		TimeStamp: 0,
	}

	if proto.SupportGenesisHash {
		blk.BlockHeader.GenesisHash = crypto.Hash([]byte(genesisID))
	}

	blk.RewardsPool = testPoolAddr
	blk.FeeSink = testSinkAddr
	blk.CurrentProtocol = lastBlock.CurrentProtocol

	blk.TxnRoot, err = blk.PaysetCommit()
	if err != nil {
		return
	}
	return
}