forked from ava-labs/coreth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_blockchain.go
1504 lines (1357 loc) · 54 KB
/
test_blockchain.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
// (c) 2020-2021, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package core
import (
"fmt"
"math/big"
"strings"
"testing"
"github.com/ava-labs/coreth/consensus/dummy"
"github.com/ava-labs/coreth/core/rawdb"
"github.com/ava-labs/coreth/core/state"
"github.com/ava-labs/coreth/core/types"
"github.com/ava-labs/coreth/ethdb"
"github.com/ava-labs/coreth/params"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
)
type ChainTest struct {
Name string
testFunc func(
t *testing.T,
create func(db ethdb.Database, chainConfig *params.ChainConfig, lastAcceptedHash common.Hash) (*BlockChain, error),
)
}
var tests = []ChainTest{
{
"InsertChainAcceptSingleBlock",
TestInsertChainAcceptSingleBlock,
},
{
"InsertForkedChain",
TestInsertLongForkedChain,
},
{
"AcceptNonCanonicalBlock",
TestAcceptNonCanonicalBlock,
},
{
"SetPreferenceRewind",
TestSetPreferenceRewind,
},
{
"BuildOnVariousStages",
TestBuildOnVariousStages,
},
{
"EmptyBlocks",
TestEmptyBlocks,
},
{
"AcceptBlockIdenticalStateRoot",
TestAcceptBlockIdenticalStateRoot,
},
{
"ReprocessAcceptBlockIdenticalStateRoot",
TestReprocessAcceptBlockIdenticalStateRoot,
},
{
"GenerateChainInvalidBlockFee",
TestGenerateChainInvalidBlockFee,
},
{
"InsertChainInvalidBlockFee",
TestInsertChainInvalidBlockFee,
},
{
"InsertChainValidBlockFee",
TestInsertChainValidBlockFee,
},
}
func copyMemDB(db ethdb.Database) (ethdb.Database, error) {
newDB := rawdb.NewMemoryDatabase()
iter := db.NewIterator(nil, nil)
defer iter.Release()
for iter.Next() {
if err := newDB.Put(iter.Key(), iter.Value()); err != nil {
return nil, err
}
}
return newDB, nil
}
// checkBlockChainState creates a new BlockChain instance and checks that exporting each block from
// genesis to last acceptd from the original instance yields the same last accepted block and state
// root.
// Additionally, create another BlockChain instance from [originalDB] to ensure that BlockChain is
// persisted correctly through a restart.
func checkBlockChainState(
t *testing.T,
bc *BlockChain,
genesis *Genesis,
originalDB ethdb.Database,
create func(db ethdb.Database, chainConfig *params.ChainConfig, lastAcceptedHash common.Hash) (*BlockChain, error),
checkState func(sdb *state.StateDB) error,
) (*BlockChain, *BlockChain, *BlockChain) {
var (
chainConfig = bc.Config()
lastAcceptedBlock = bc.LastAcceptedBlock()
newDB = rawdb.NewMemoryDatabase()
)
acceptedState, err := bc.StateAt(lastAcceptedBlock.Root())
if err != nil {
t.Fatal(err)
}
if err := checkState(acceptedState); err != nil {
t.Fatalf("Check state failed for original blockchain due to: %s", err)
}
_ = genesis.MustCommit(newDB)
newBlockChain, err := create(newDB, chainConfig, common.Hash{})
if err != nil {
t.Fatalf("Failed to create new blockchain instance: %s", err)
}
for i := uint64(1); i <= lastAcceptedBlock.NumberU64(); i++ {
block := bc.GetBlockByNumber(i)
if block == nil {
t.Fatalf("Failed to retrieve block by number %d from original chain", i)
}
if err := newBlockChain.InsertBlock(block); err != nil {
t.Fatalf("Failed to insert block %s:%d due to %s", block.Hash().Hex(), block.NumberU64(), err)
}
if err := newBlockChain.Accept(block); err != nil {
t.Fatalf("Failed to accept block %s:%d due to %s", block.Hash().Hex(), block.NumberU64(), err)
}
}
newLastAcceptedBlock := newBlockChain.LastAcceptedBlock()
if newLastAcceptedBlock.Hash() != lastAcceptedBlock.Hash() {
t.Fatalf("Expected new blockchain to have last accepted block %s:%d, but found %s:%d", lastAcceptedBlock.Hash().Hex(), lastAcceptedBlock.NumberU64(), newLastAcceptedBlock.Hash().Hex(), newLastAcceptedBlock.NumberU64())
}
// Check that the state of [newBlockChain] passes the check
acceptedState, err = newBlockChain.StateAt(lastAcceptedBlock.Root())
if err != nil {
t.Fatal(err)
}
if err := checkState(acceptedState); err != nil {
t.Fatalf("Check state failed for newly generated blockchain due to: %s", err)
}
// Copy the database over to prevent any issues when re-using [originalDB] after this call.
originalDB, err = copyMemDB(originalDB)
if err != nil {
t.Fatal(err)
}
restartedChain, err := create(originalDB, chainConfig, lastAcceptedBlock.Hash())
if err != nil {
t.Fatal(err)
}
defer restartedChain.Stop()
if currentBlock := restartedChain.CurrentBlock(); currentBlock.Hash() != lastAcceptedBlock.Hash() {
t.Fatalf("Expected restarted chain to have current block %s:%d, but found %s:%d", lastAcceptedBlock.Hash().Hex(), lastAcceptedBlock.NumberU64(), currentBlock.Hash().Hex(), currentBlock.NumberU64())
}
if restartedLastAcceptedBlock := restartedChain.LastAcceptedBlock(); restartedLastAcceptedBlock.Hash() != lastAcceptedBlock.Hash() {
t.Fatalf("Expected restarted chain to have current block %s:%d, but found %s:%d", lastAcceptedBlock.Hash().Hex(), lastAcceptedBlock.NumberU64(), restartedLastAcceptedBlock.Hash().Hex(), restartedLastAcceptedBlock.NumberU64())
}
// Check that the state of [restartedChain] passes the check
acceptedState, err = restartedChain.StateAt(lastAcceptedBlock.Root())
if err != nil {
t.Fatal(err)
}
if err := checkState(acceptedState); err != nil {
t.Fatalf("Check state failed for restarted blockchain due to: %s", err)
}
return bc, newBlockChain, restartedChain
}
func TestInsertChainAcceptSingleBlock(t *testing.T, create func(db ethdb.Database, chainConfig *params.ChainConfig, lastAcceptedHash common.Hash) (*BlockChain, error)) {
var (
key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
key2, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
addr1 = crypto.PubkeyToAddress(key1.PublicKey)
addr2 = crypto.PubkeyToAddress(key2.PublicKey)
// We use two separate databases since GenerateChain commits the state roots to its underlying
// database.
genDB = rawdb.NewMemoryDatabase()
chainDB = rawdb.NewMemoryDatabase()
)
// Ensure that key1 has some funds in the genesis block.
genesisBalance := big.NewInt(1000000)
gspec := &Genesis{
Config: ¶ms.ChainConfig{HomesteadBlock: new(big.Int)},
Alloc: GenesisAlloc{addr1: {Balance: genesisBalance}},
}
genesis := gspec.MustCommit(genDB)
_ = gspec.MustCommit(chainDB)
blockchain, err := create(chainDB, gspec.Config, common.Hash{})
if err != nil {
t.Fatal(err)
}
defer blockchain.Stop()
// This call generates a chain of 3 blocks.
signer := types.HomesteadSigner{}
// Generate chain of blocks using [genDB] instead of [chainDB] to avoid writing
// to the BlockChain's database while generating blocks.
chain, _, err := GenerateChain(gspec.Config, genesis, blockchain.engine, genDB, 3, 10, func(i int, gen *BlockGen) {
tx, _ := types.SignTx(types.NewTransaction(gen.TxNonce(addr1), addr2, big.NewInt(10000), params.TxGas, nil, nil), signer, key1)
gen.AddTx(tx)
})
if err != nil {
t.Fatal(err)
}
// Insert three blocks into the chain and accept only the first block.
if _, err := blockchain.InsertChain(chain); err != nil {
t.Fatal(err)
}
if err := blockchain.Accept(chain[0]); err != nil {
t.Fatal(err)
}
// check the state of the last accepted block
checkState := func(sdb *state.StateDB) error {
nonce := sdb.GetNonce(addr1)
if nonce != 1 {
return fmt.Errorf("expected nonce addr1: 1, found nonce: %d", nonce)
}
transferredFunds := big.NewInt(10000)
balance1 := sdb.GetBalance(addr1)
expectedBalance1 := new(big.Int).Sub(genesisBalance, transferredFunds)
if balance1.Cmp(expectedBalance1) != 0 {
return fmt.Errorf("expected addr1 balance: %d, found balance: %d", expectedBalance1, balance1)
}
balance2 := sdb.GetBalance(addr2)
expectedBalance2 := transferredFunds
if balance2.Cmp(expectedBalance2) != 0 {
return fmt.Errorf("expected addr2 balance: %d, found balance: %d", expectedBalance2, balance2)
}
nonce = sdb.GetNonce(addr2)
if nonce != 0 {
return fmt.Errorf("expected addr2 nonce: 0, found nonce: %d", nonce)
}
return nil
}
checkBlockChainState(t, blockchain, gspec, chainDB, create, checkState)
}
func TestInsertLongForkedChain(t *testing.T, create func(db ethdb.Database, chainConfig *params.ChainConfig, lastAcceptedHash common.Hash) (*BlockChain, error)) {
var (
key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
key2, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
addr1 = crypto.PubkeyToAddress(key1.PublicKey)
addr2 = crypto.PubkeyToAddress(key2.PublicKey)
// We use two separate databases since GenerateChain commits the state roots to its underlying
// database.
genDB = rawdb.NewMemoryDatabase()
chainDB = rawdb.NewMemoryDatabase()
)
// Ensure that key1 has some funds in the genesis block.
genesisBalance := big.NewInt(1000000000)
gspec := &Genesis{
Config: ¶ms.ChainConfig{HomesteadBlock: new(big.Int)},
Alloc: GenesisAlloc{addr1: {Balance: genesisBalance}},
}
genesis := gspec.MustCommit(genDB)
_ = gspec.MustCommit(chainDB)
blockchain, err := create(chainDB, gspec.Config, common.Hash{})
if err != nil {
t.Fatal(err)
}
defer blockchain.Stop()
numBlocks := 129
signer := types.HomesteadSigner{}
// Generate chain of blocks using [genDB] instead of [chainDB] to avoid writing
// to the BlockChain's database while generating blocks.
chain1, _, err := GenerateChain(gspec.Config, genesis, blockchain.engine, genDB, numBlocks, 10, func(i int, gen *BlockGen) {
// Generate a transaction to create a unique block
tx, _ := types.SignTx(types.NewTransaction(gen.TxNonce(addr1), addr2, big.NewInt(10000), params.TxGas, nil, nil), signer, key1)
gen.AddTx(tx)
})
if err != nil {
t.Fatal(err)
}
// Generate the forked chain to be longer than the original chain to check for a regression where
// a longer chain can trigger a reorg.
chain2, _, err := GenerateChain(gspec.Config, genesis, blockchain.engine, genDB, numBlocks+1, 10, func(i int, gen *BlockGen) {
// Generate a transaction with a different amount to ensure [chain2] is different than [chain1].
tx, _ := types.SignTx(types.NewTransaction(gen.TxNonce(addr1), addr2, big.NewInt(5000), params.TxGas, nil, nil), signer, key1)
gen.AddTx(tx)
})
if err != nil {
t.Fatal(err)
}
if blockchain.snaps != nil {
if want, got := 1, blockchain.snaps.NumBlockLayers(); got != want {
t.Fatalf("incorrect snapshot layer count; got %d, want %d", got, want)
}
}
// Insert both chains.
if _, err := blockchain.InsertChain(chain1); err != nil {
t.Fatal(err)
}
if blockchain.snaps != nil {
if want, got := 1+len(chain1), blockchain.snaps.NumBlockLayers(); got != want {
t.Fatalf("incorrect snapshot layer count; got %d, want %d", got, want)
}
}
if _, err := blockchain.InsertChain(chain2); err != nil {
t.Fatal(err)
}
if blockchain.snaps != nil {
if want, got := 1+len(chain1)+len(chain2), blockchain.snaps.NumBlockLayers(); got != want {
t.Fatalf("incorrect snapshot layer count; got %d, want %d", got, want)
}
}
currentBlock := blockchain.CurrentBlock()
expectedCurrentBlock := chain1[len(chain1)-1]
if currentBlock.Hash() != expectedCurrentBlock.Hash() {
t.Fatalf("Expected current block to be %s:%d, but found %s%d", expectedCurrentBlock.Hash().Hex(), expectedCurrentBlock.NumberU64(), currentBlock.Hash().Hex(), currentBlock.NumberU64())
}
if err := blockchain.ValidateCanonicalChain(); err != nil {
t.Fatal(err)
}
// Accept the first block in [chain1], reject all blocks in [chain2] to
// mimic the order that the consensus engine will call Accept/Reject in
// and then Accept the rest of the blocks in [chain1].
if err := blockchain.Accept(chain1[0]); err != nil {
t.Fatal(err)
}
if blockchain.snaps != nil {
// Snap layer count should be 1 fewer
if want, got := len(chain1)+len(chain2), blockchain.snaps.NumBlockLayers(); got != want {
t.Fatalf("incorrect snapshot layer count; got %d, want %d", got, want)
}
}
for i := 0; i < len(chain2); i++ {
if err := blockchain.Reject(chain2[i]); err != nil {
t.Fatal(err)
}
if blockchain.snaps != nil {
// Snap layer count should decrease by 1 per Reject
if want, got := len(chain1)+len(chain2)-i-1, blockchain.snaps.NumBlockLayers(); got != want {
t.Fatalf("incorrect snapshot layer count; got %d, want %d", got, want)
}
}
}
if blockchain.snaps != nil {
if want, got := len(chain1), blockchain.snaps.NumBlockLayers(); got != want {
t.Fatalf("incorrect snapshot layer count; got %d, want %d", got, want)
}
}
for i := 1; i < len(chain1); i++ {
if err := blockchain.Accept(chain1[i]); err != nil {
t.Fatal(err)
}
if blockchain.snaps != nil {
// Snap layer count should decrease by 1 per Accept
if want, got := len(chain1)-i, blockchain.snaps.NumBlockLayers(); got != want {
t.Fatalf("incorrect snapshot layer count; got %d, want %d", got, want)
}
}
}
lastAcceptedBlock := blockchain.LastAcceptedBlock()
expectedLastAcceptedBlock := chain1[len(chain1)-1]
if lastAcceptedBlock.Hash() != expectedLastAcceptedBlock.Hash() {
t.Fatalf("Expected last accepted block to be %s:%d, but found %s%d", expectedLastAcceptedBlock.Hash().Hex(), expectedLastAcceptedBlock.NumberU64(), lastAcceptedBlock.Hash().Hex(), lastAcceptedBlock.NumberU64())
}
if err := blockchain.ValidateCanonicalChain(); err != nil {
t.Fatal(err)
}
// check the state of the last accepted block
checkState := func(sdb *state.StateDB) error {
nonce1 := sdb.GetNonce(addr1)
if nonce1 != 129 {
return fmt.Errorf("expected addr1 nonce: 129, found nonce %d", nonce1)
}
balance1 := sdb.GetBalance(addr1)
transferredFunds := new(big.Int).Mul(big.NewInt(129), big.NewInt(10000))
expectedBalance := new(big.Int).Sub(genesisBalance, transferredFunds)
if balance1.Cmp(expectedBalance) != 0 {
return fmt.Errorf("expected addr1 balance: %d, found balance: %d", expectedBalance, balance1)
}
nonce2 := sdb.GetNonce(addr2)
if nonce2 != 0 {
return fmt.Errorf("expected addr2 nonce: 0, found nonce: %d", nonce2)
}
balance2 := sdb.GetBalance(addr2)
if balance2.Cmp(transferredFunds) != 0 {
return fmt.Errorf("expected addr2 balance: %d, found balance: %d", transferredFunds, balance2)
}
return nil
}
checkBlockChainState(t, blockchain, gspec, chainDB, create, checkState)
}
func TestAcceptNonCanonicalBlock(t *testing.T, create func(db ethdb.Database, chainConfig *params.ChainConfig, lastAcceptedHash common.Hash) (*BlockChain, error)) {
var (
key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
key2, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
addr1 = crypto.PubkeyToAddress(key1.PublicKey)
addr2 = crypto.PubkeyToAddress(key2.PublicKey)
// We use two separate databases since GenerateChain commits the state roots to its underlying
// database.
genDB = rawdb.NewMemoryDatabase()
chainDB = rawdb.NewMemoryDatabase()
)
// Ensure that key1 has some funds in the genesis block.
genesisBalance := big.NewInt(1000000000)
gspec := &Genesis{
Config: ¶ms.ChainConfig{HomesteadBlock: new(big.Int)},
Alloc: GenesisAlloc{addr1: {Balance: genesisBalance}},
}
genesis := gspec.MustCommit(genDB)
_ = gspec.MustCommit(chainDB)
blockchain, err := create(chainDB, gspec.Config, common.Hash{})
if err != nil {
t.Fatal(err)
}
defer blockchain.Stop()
numBlocks := 3
signer := types.HomesteadSigner{}
// Generate chain of blocks using [genDB] instead of [chainDB] to avoid writing
// to the BlockChain's database while generating blocks.
chain1, _, err := GenerateChain(gspec.Config, genesis, blockchain.engine, genDB, numBlocks, 10, func(i int, gen *BlockGen) {
// Generate a transaction to create a unique block
tx, _ := types.SignTx(types.NewTransaction(gen.TxNonce(addr1), addr2, big.NewInt(10000), params.TxGas, nil, nil), signer, key1)
gen.AddTx(tx)
})
if err != nil {
t.Fatal(err)
}
chain2, _, err := GenerateChain(gspec.Config, genesis, blockchain.engine, genDB, numBlocks, 10, func(i int, gen *BlockGen) {
// Generate a transaction with a different amount to create a chain of blocks different from [chain1]
tx, _ := types.SignTx(types.NewTransaction(gen.TxNonce(addr1), addr2, big.NewInt(5000), params.TxGas, nil, nil), signer, key1)
gen.AddTx(tx)
})
if err != nil {
t.Fatal(err)
}
// Insert three blocks into the chain and accept only the first.
if _, err := blockchain.InsertChain(chain1); err != nil {
t.Fatal(err)
}
if _, err := blockchain.InsertChain(chain2); err != nil {
t.Fatal(err)
}
currentBlock := blockchain.CurrentBlock()
expectedCurrentBlock := chain1[len(chain1)-1]
if currentBlock.Hash() != expectedCurrentBlock.Hash() {
t.Fatalf("Expected current block to be %s:%d, but found %s%d", expectedCurrentBlock.Hash().Hex(), expectedCurrentBlock.NumberU64(), currentBlock.Hash().Hex(), currentBlock.NumberU64())
}
if err := blockchain.ValidateCanonicalChain(); err != nil {
t.Fatal(err)
}
// Accept the first block in [chain2], reject all blocks in [chain1] to
// mimic the order that the consensus engine will call Accept/Reject in.
if err := blockchain.Accept(chain2[0]); err != nil {
t.Fatal(err)
}
for i := 0; i < len(chain1); i++ {
if err := blockchain.Reject(chain1[i]); err != nil {
t.Fatal(err)
}
}
lastAcceptedBlock := blockchain.LastAcceptedBlock()
expectedLastAcceptedBlock := chain2[0]
if lastAcceptedBlock.Hash() != expectedLastAcceptedBlock.Hash() {
t.Fatalf("Expected last accepted block to be %s:%d, but found %s%d", expectedLastAcceptedBlock.Hash().Hex(), expectedLastAcceptedBlock.NumberU64(), lastAcceptedBlock.Hash().Hex(), lastAcceptedBlock.NumberU64())
}
if err := blockchain.ValidateCanonicalChain(); err != nil {
t.Fatal(err)
}
// check the state of the last accepted block
checkState := func(sdb *state.StateDB) error {
nonce1 := sdb.GetNonce(addr1)
if nonce1 != 1 {
return fmt.Errorf("expected addr1 nonce: 1, found nonce: %d", nonce1)
}
balance1 := sdb.GetBalance(addr1)
transferredFunds := big.NewInt(5000)
expectedBalance := new(big.Int).Sub(genesisBalance, transferredFunds)
if balance1.Cmp(expectedBalance) != 0 {
return fmt.Errorf("expected balance1: %d, found balance: %d", expectedBalance, balance1)
}
nonce2 := sdb.GetNonce(addr2)
if nonce2 != 0 {
return fmt.Errorf("expected addr2 nonce: 0, found nonce %d", nonce2)
}
balance2 := sdb.GetBalance(addr2)
if balance2.Cmp(transferredFunds) != 0 {
return fmt.Errorf("expected balance2: %d, found %d", transferredFunds, balance2)
}
return nil
}
checkBlockChainState(t, blockchain, gspec, chainDB, create, checkState)
}
func TestSetPreferenceRewind(t *testing.T, create func(db ethdb.Database, chainConfig *params.ChainConfig, lastAcceptedHash common.Hash) (*BlockChain, error)) {
var (
key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
key2, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
addr1 = crypto.PubkeyToAddress(key1.PublicKey)
addr2 = crypto.PubkeyToAddress(key2.PublicKey)
// We use two separate databases since GenerateChain commits the state roots to its underlying
// database.
genDB = rawdb.NewMemoryDatabase()
chainDB = rawdb.NewMemoryDatabase()
)
// Ensure that key1 has some funds in the genesis block.
genesisBalance := big.NewInt(1000000000)
gspec := &Genesis{
Config: ¶ms.ChainConfig{HomesteadBlock: new(big.Int)},
Alloc: GenesisAlloc{addr1: {Balance: genesisBalance}},
}
genesis := gspec.MustCommit(genDB)
_ = gspec.MustCommit(chainDB)
blockchain, err := create(chainDB, gspec.Config, common.Hash{})
if err != nil {
t.Fatal(err)
}
defer blockchain.Stop()
numBlocks := 3
signer := types.HomesteadSigner{}
// Generate chain of blocks using [genDB] instead of [chainDB] to avoid writing
// to the BlockChain's database while generating blocks.
chain, _, err := GenerateChain(gspec.Config, genesis, blockchain.engine, genDB, numBlocks, 10, func(i int, gen *BlockGen) {
// Generate a transaction to create a unique block
tx, _ := types.SignTx(types.NewTransaction(gen.TxNonce(addr1), addr2, big.NewInt(10000), params.TxGas, nil, nil), signer, key1)
gen.AddTx(tx)
})
if err != nil {
t.Fatal(err)
}
// Insert three blocks into the chain and accept only the first.
if _, err := blockchain.InsertChain(chain); err != nil {
t.Fatal(err)
}
currentBlock := blockchain.CurrentBlock()
expectedCurrentBlock := chain[len(chain)-1]
if currentBlock.Hash() != expectedCurrentBlock.Hash() {
t.Fatalf("Expected current block to be %s:%d, but found %s%d", expectedCurrentBlock.Hash().Hex(), expectedCurrentBlock.NumberU64(), currentBlock.Hash().Hex(), currentBlock.NumberU64())
}
if err := blockchain.ValidateCanonicalChain(); err != nil {
t.Fatal(err)
}
// SetPreference to an ancestor of the currently preferred block. Test that this unlikely, but possible behavior
// is handled correctly.
if err := blockchain.SetPreference(chain[0]); err != nil {
t.Fatal(err)
}
currentBlock = blockchain.CurrentBlock()
expectedCurrentBlock = chain[0]
if currentBlock.Hash() != expectedCurrentBlock.Hash() {
t.Fatalf("Expected current block to be %s:%d, but found %s%d", expectedCurrentBlock.Hash().Hex(), expectedCurrentBlock.NumberU64(), currentBlock.Hash().Hex(), currentBlock.NumberU64())
}
lastAcceptedBlock := blockchain.LastAcceptedBlock()
expectedLastAcceptedBlock := blockchain.Genesis()
if lastAcceptedBlock.Hash() != expectedLastAcceptedBlock.Hash() {
t.Fatalf("Expected last accepted block to be %s:%d, but found %s%d", expectedLastAcceptedBlock.Hash().Hex(), expectedLastAcceptedBlock.NumberU64(), lastAcceptedBlock.Hash().Hex(), lastAcceptedBlock.NumberU64())
}
if err := blockchain.ValidateCanonicalChain(); err != nil {
t.Fatal(err)
}
// check the state of the last accepted block
checkGenesisState := func(sdb *state.StateDB) error {
nonce1 := sdb.GetNonce(addr1)
if nonce1 != 0 {
return fmt.Errorf("expected addr1 nonce: 0, found nonce: %d", nonce1)
}
balance1 := sdb.GetBalance(addr1)
if balance1.Cmp(genesisBalance) != 0 {
return fmt.Errorf("expected addr1 balance: %d, found balance: %d", genesisBalance, balance1)
}
nonce2 := sdb.GetNonce(addr2)
if nonce2 != 0 {
return fmt.Errorf("expected addr2 nonce: 0, found nonce: %d", nonce2)
}
balance2 := sdb.GetBalance(addr2)
if balance2.Cmp(big.NewInt(0)) != 0 {
return fmt.Errorf("expected addr2 balance: 0, found balance %d", balance2)
}
return nil
}
checkBlockChainState(t, blockchain, gspec, chainDB, create, checkGenesisState)
if err := blockchain.Accept(chain[0]); err != nil {
t.Fatal(err)
}
lastAcceptedBlock = blockchain.LastAcceptedBlock()
expectedLastAcceptedBlock = chain[0]
if lastAcceptedBlock.Hash() != expectedLastAcceptedBlock.Hash() {
t.Fatalf("Expected last accepted block to be %s:%d, but found %s%d", expectedLastAcceptedBlock.Hash().Hex(), expectedLastAcceptedBlock.NumberU64(), lastAcceptedBlock.Hash().Hex(), lastAcceptedBlock.NumberU64())
}
if err := blockchain.ValidateCanonicalChain(); err != nil {
t.Fatal(err)
}
checkUpdatedState := func(sdb *state.StateDB) error {
nonce := sdb.GetNonce(addr1)
if nonce != 1 {
return fmt.Errorf("expected addr1 nonce: 1, found nonce: %d", nonce)
}
transferredFunds := big.NewInt(10000)
balance1 := sdb.GetBalance(addr1)
expectedBalance1 := new(big.Int).Sub(genesisBalance, transferredFunds)
if balance1.Cmp(expectedBalance1) != 0 {
return fmt.Errorf("expected addr1 balance: %d, found balance %d", expectedBalance1, balance1)
}
balance2 := sdb.GetBalance(addr2)
expectedBalance2 := transferredFunds
if balance2.Cmp(expectedBalance2) != 0 {
return fmt.Errorf("expected addr2 balance: %d, found balance: %d", expectedBalance2, balance2)
}
nonce = sdb.GetNonce(addr2)
if nonce != 0 {
return fmt.Errorf("expected addr2 nonce: 0, found nonce: %d", nonce)
}
return nil
}
checkBlockChainState(t, blockchain, gspec, chainDB, create, checkUpdatedState)
}
func TestBuildOnVariousStages(t *testing.T, create func(db ethdb.Database, chainConfig *params.ChainConfig, lastAcceptedHash common.Hash) (*BlockChain, error)) {
var (
key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
key2, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
key3, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
addr1 = crypto.PubkeyToAddress(key1.PublicKey)
addr2 = crypto.PubkeyToAddress(key2.PublicKey)
addr3 = crypto.PubkeyToAddress(key3.PublicKey)
// We use two separate databases since GenerateChain commits the state roots to its underlying
// database.
genDB = rawdb.NewMemoryDatabase()
chainDB = rawdb.NewMemoryDatabase()
)
// Ensure that key1 has some funds in the genesis block.
genesisBalance := big.NewInt(1000000)
gspec := &Genesis{
Config: ¶ms.ChainConfig{HomesteadBlock: new(big.Int)},
Alloc: GenesisAlloc{
addr1: {Balance: genesisBalance},
addr3: {Balance: genesisBalance},
},
}
genesis := gspec.MustCommit(genDB)
_ = gspec.MustCommit(chainDB)
blockchain, err := create(chainDB, gspec.Config, common.Hash{})
if err != nil {
t.Fatal(err)
}
defer blockchain.Stop()
// This call generates a chain of 3 blocks.
signer := types.HomesteadSigner{}
// Generate chain of blocks using [genDB] instead of [chainDB] to avoid writing
// to the BlockChain's database while generating blocks.
chain1, _, err := GenerateChain(gspec.Config, genesis, blockchain.engine, genDB, 20, 10, func(i int, gen *BlockGen) {
// Send all funds back and forth between the two accounts
if i%2 == 0 {
tx, _ := types.SignTx(types.NewTransaction(gen.TxNonce(addr1), addr2, genesisBalance, params.TxGas, nil, nil), signer, key1)
gen.AddTx(tx)
} else {
tx, _ := types.SignTx(types.NewTransaction(gen.TxNonce(addr2), addr1, genesisBalance, params.TxGas, nil, nil), signer, key2)
gen.AddTx(tx)
}
})
if err != nil {
t.Fatal(err)
}
// Build second chain forked off of the 10th block in [chain1]
chain2, _, err := GenerateChain(gspec.Config, chain1[9], blockchain.engine, genDB, 10, 10, func(i int, gen *BlockGen) {
// Send all funds back and forth between the two accounts
if i%2 == 0 {
tx, _ := types.SignTx(types.NewTransaction(gen.TxNonce(addr3), addr2, genesisBalance, params.TxGas, nil, nil), signer, key3)
gen.AddTx(tx)
} else {
tx, _ := types.SignTx(types.NewTransaction(gen.TxNonce(addr2), addr3, genesisBalance, params.TxGas, nil, nil), signer, key2)
gen.AddTx(tx)
}
})
if err != nil {
t.Fatal(err)
}
// Build third chain forked off of the 5th block in [chain1].
// The parent of this chain will be accepted before this fork
// is inserted.
chain3, _, err := GenerateChain(gspec.Config, chain1[4], blockchain.engine, genDB, 10, 10, func(i int, gen *BlockGen) {
// Send all funds back and forth between accounts 2 and 3.
if i%2 == 0 {
tx, _ := types.SignTx(types.NewTransaction(gen.TxNonce(addr2), addr3, genesisBalance, params.TxGas, nil, nil), signer, key2)
gen.AddTx(tx)
} else {
tx, _ := types.SignTx(types.NewTransaction(gen.TxNonce(addr3), addr2, genesisBalance, params.TxGas, nil, nil), signer, key3)
gen.AddTx(tx)
}
})
if err != nil {
t.Fatal(err)
}
// Insert first 10 blocks from [chain1]
if _, err := blockchain.InsertChain(chain1); err != nil {
t.Fatal(err)
}
// Accept the first 5 blocks
for _, block := range chain1[0:5] {
if err := blockchain.Accept(block); err != nil {
t.Fatal(err)
}
}
// Insert the forked chain [chain2] which starts at the 10th
// block in [chain1] ie. a block that is still in processing.
if _, err := blockchain.InsertChain(chain2); err != nil {
t.Fatal(err)
}
// Insert another forked chain starting at the last accepted
// block from [chain1].
if _, err := blockchain.InsertChain(chain3); err != nil {
t.Fatal(err)
}
// Accept the next block in [chain1] and then reject all
// of the blocks in [chain3], which would then be rejected.
if err := blockchain.Accept(chain1[5]); err != nil {
t.Fatal(err)
}
for _, block := range chain3 {
if err := blockchain.Reject(block); err != nil {
t.Fatal(err)
}
}
// Accept the rest of the blocks in [chain1]
for _, block := range chain1[6:10] {
if err := blockchain.Accept(block); err != nil {
t.Fatal(err)
}
}
// Accept the first block in [chain2] and reject the
// subsequent blocks in [chain1] which would then be rejected.
if err := blockchain.Accept(chain2[0]); err != nil {
t.Fatal(err)
}
for _, block := range chain1[10:] {
if err := blockchain.Reject(block); err != nil {
t.Fatal(err)
}
}
// check the state of the last accepted block
checkState := func(sdb *state.StateDB) error {
nonce := sdb.GetNonce(addr1)
if nonce != 5 {
return fmt.Errorf("expected nonce addr1: 5, found nonce: %d", nonce)
}
balance1 := sdb.GetBalance(addr1)
expectedBalance1 := genesisBalance
if balance1.Cmp(expectedBalance1) != 0 {
return fmt.Errorf("expected addr1 balance: %d, found balance: %d", expectedBalance1, balance1)
}
balance2 := sdb.GetBalance(addr2)
expectedBalance2 := genesisBalance
if balance2.Cmp(expectedBalance2) != 0 {
return fmt.Errorf("expected addr2 balance: %d, found balance: %d", expectedBalance2, balance2)
}
nonce = sdb.GetNonce(addr2)
if nonce != 5 {
return fmt.Errorf("expected addr2 nonce: 5, found nonce: %d", nonce)
}
balance3 := sdb.GetBalance(addr3)
expectedBalance3 := common.Big0
if balance3.Cmp(expectedBalance3) != 0 {
return fmt.Errorf("expected addr3 balance: %d, found balance: %d", expectedBalance3, balance3)
}
nonce = sdb.GetNonce(addr3)
if nonce != 1 {
return fmt.Errorf("expected addr3 nonce: 1, found nonce: %d", nonce)
}
return nil
}
checkBlockChainState(t, blockchain, gspec, chainDB, create, checkState)
}
func TestEmptyBlocks(t *testing.T, create func(db ethdb.Database, chainConfig *params.ChainConfig, lastAcceptedHash common.Hash) (*BlockChain, error)) {
var (
// We use two separate databases since GenerateChain commits the state roots to its underlying
// database.
genDB = rawdb.NewMemoryDatabase()
chainDB = rawdb.NewMemoryDatabase()
)
// Ensure that key1 has some funds in the genesis block.
gspec := &Genesis{
Config: ¶ms.ChainConfig{HomesteadBlock: new(big.Int)},
Alloc: GenesisAlloc{},
}
genesis := gspec.MustCommit(genDB)
_ = gspec.MustCommit(chainDB)
blockchain, err := create(chainDB, gspec.Config, common.Hash{})
if err != nil {
t.Fatal(err)
}
defer blockchain.Stop()
// Generate chain of blocks using [genDB] instead of [chainDB] to avoid writing
// to the BlockChain's database while generating blocks.
chain, _, err := GenerateChain(gspec.Config, genesis, blockchain.engine, genDB, 3, 10, func(i int, gen *BlockGen) {})
if err != nil {
t.Fatal(err)
}
// Insert three blocks into the chain and accept only the first block.
if _, err := blockchain.InsertChain(chain); err != nil {
t.Fatal(err)
}
for _, block := range chain {
if err := blockchain.Accept(block); err != nil {
t.Fatal(err)
}
}
// Nothing to assert about the state
checkState := func(sdb *state.StateDB) error {
return nil
}
checkBlockChainState(t, blockchain, gspec, chainDB, create, checkState)
}
func TestReorgReInsert(t *testing.T, create func(db ethdb.Database, chainConfig *params.ChainConfig, lastAcceptedHash common.Hash) (*BlockChain, error)) {
var (
key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
key2, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
addr1 = crypto.PubkeyToAddress(key1.PublicKey)
addr2 = crypto.PubkeyToAddress(key2.PublicKey)
// We use two separate databases since GenerateChain commits the state roots to its underlying
// database.
genDB = rawdb.NewMemoryDatabase()
chainDB = rawdb.NewMemoryDatabase()
)
// Ensure that key1 has some funds in the genesis block.
genesisBalance := big.NewInt(1000000000)
gspec := &Genesis{
Config: ¶ms.ChainConfig{HomesteadBlock: new(big.Int)},
Alloc: GenesisAlloc{addr1: {Balance: genesisBalance}},
}
genesis := gspec.MustCommit(genDB)
_ = gspec.MustCommit(chainDB)
blockchain, err := create(chainDB, gspec.Config, common.Hash{})
if err != nil {
t.Fatal(err)
}
defer blockchain.Stop()
signer := types.HomesteadSigner{}
numBlocks := 3
chain, _, err := GenerateChain(gspec.Config, genesis, blockchain.engine, genDB, numBlocks, 10, func(i int, gen *BlockGen) {
// Generate a transaction to create a unique block
tx, _ := types.SignTx(types.NewTransaction(gen.TxNonce(addr1), addr2, big.NewInt(10000), params.TxGas, nil, nil), signer, key1)
gen.AddTx(tx)
})
if err != nil {
t.Fatal(err)
}
// Insert and accept first block
if err := blockchain.InsertBlock(chain[0]); err != nil {
t.Fatal(err)
}
if err := blockchain.Accept(chain[0]); err != nil {
t.Fatal(err)
}
// Insert block and then set preference back (rewind) to last accepted blck
if err := blockchain.InsertBlock(chain[1]); err != nil {
t.Fatal(err)
}
if err := blockchain.SetPreference(chain[0]); err != nil {
t.Fatal(err)
}
// Re-insert and accept block
if err := blockchain.InsertBlock(chain[1]); err != nil {
t.Fatal(err)
}
if err := blockchain.Accept(chain[1]); err != nil {
t.Fatal(err)
}
// Build on top of the re-inserted block and accept
if err := blockchain.InsertBlock(chain[2]); err != nil {
t.Fatal(err)
}
if err := blockchain.Accept(chain[2]); err != nil {
t.Fatal(err)
}
// Nothing to assert about the state
checkState := func(sdb *state.StateDB) error {
nonce1 := sdb.GetNonce(addr1)
if nonce1 != 3 {
return fmt.Errorf("expected addr1 nonce: 3, found nonce: %d", nonce1)
}
balance1 := sdb.GetBalance(addr1)
transferredFunds := big.NewInt(30000)
expectedBalance := new(big.Int).Sub(genesisBalance, transferredFunds)
if balance1.Cmp(expectedBalance) != 0 {
return fmt.Errorf("expected balance1: %d, found balance: %d", expectedBalance, balance1)
}
nonce2 := sdb.GetNonce(addr2)
if nonce2 != 0 {
return fmt.Errorf("expected addr2 nonce: 0, found nonce %d", nonce2)
}
balance2 := sdb.GetBalance(addr2)
if balance2.Cmp(transferredFunds) != 0 {
return fmt.Errorf("expected balance2: %d, found %d", transferredFunds, balance2)
}
return nil
}
checkBlockChainState(t, blockchain, gspec, chainDB, create, checkState)
}
// Insert two different chains that result in the identical state root.
// Once we accept one of the chains, we insert and accept A3 on top of the shared
// state root
// G (genesis)
// / \
// A1 B1
// | |
// A2 B2 (A2 and B2 represent two different paths to the identical state trie)
// |
// A3
func TestAcceptBlockIdenticalStateRoot(t *testing.T, create func(db ethdb.Database, chainConfig *params.ChainConfig, lastAcceptedHash common.Hash) (*BlockChain, error)) {
var (
key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
key2, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
addr1 = crypto.PubkeyToAddress(key1.PublicKey)
addr2 = crypto.PubkeyToAddress(key2.PublicKey)
// We use two separate databases since GenerateChain commits the state roots to its underlying
// database.
genDB = rawdb.NewMemoryDatabase()
chainDB = rawdb.NewMemoryDatabase()
)
// Ensure that key1 has some funds in the genesis block.