-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathblockchain_test.go
More file actions
2358 lines (2146 loc) · 77 KB
/
blockchain_test.go
File metadata and controls
2358 lines (2146 loc) · 77 KB
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 2014 The go-ethereum Authors
// (original work)
// Copyright 2024 The Erigon Authors
// (modifications)
// This file is part of Erigon.
//
// Erigon is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Erigon 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Erigon. If not, see <http://www.gnu.org/licenses/>.
package executiontests
import (
"context"
"fmt"
"maps"
"math"
"math/big"
"testing"
"github.com/holiman/uint256"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/erigontech/erigon/common"
"github.com/erigontech/erigon/common/crypto"
"github.com/erigontech/erigon/common/hexutil"
"github.com/erigontech/erigon/common/log/v3"
"github.com/erigontech/erigon/common/u256"
"github.com/erigontech/erigon/db/kv"
"github.com/erigontech/erigon/db/kv/prune"
"github.com/erigontech/erigon/db/rawdb"
libchain "github.com/erigontech/erigon/execution/chain"
chainspec "github.com/erigontech/erigon/execution/chain/spec"
"github.com/erigontech/erigon/execution/execmodule/execmoduletester"
"github.com/erigontech/erigon/execution/protocol/params"
"github.com/erigontech/erigon/execution/protocol/rules/ethash"
"github.com/erigontech/erigon/execution/rlp"
"github.com/erigontech/erigon/execution/state"
"github.com/erigontech/erigon/execution/tests/blockgen"
"github.com/erigontech/erigon/execution/types"
"github.com/erigontech/erigon/execution/types/accounts"
"github.com/erigontech/erigon/execution/vm"
"github.com/erigontech/erigon/node/gointerfaces/sentryproto"
"github.com/erigontech/erigon/p2p/protocols/eth"
)
var (
canonicalSeed = 1
forkSeed = 2
triesInMemory = 128
)
// makeBlockChain creates a deterministic chain of blocks rooted at parent.
func makeBlockChain(parent *types.Block, n int, m *execmoduletester.ExecModuleTester, seed int) *blockgen.ChainPack {
chain, _ := blockgen.GenerateChain(m.ChainConfig, parent, m.Engine, m.DB, n, func(i int, b *blockgen.BlockGen) {
b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)})
})
return chain
}
// newCanonical creates a chain database, and injects a deterministic canonical
// chain. Depending on the full flag, if creates either a full block chain or a
// header only chain.
func newCanonical(t *testing.T, n int) *execmoduletester.ExecModuleTester {
m := execmoduletester.New(t)
// Create and inject the requested chain
if n == 0 {
return m
}
// Full block-chain requested
chain := makeBlockChain(m.Genesis, n, m, canonicalSeed)
if err := m.InsertChain(chain); err != nil {
t.Fatal(err)
}
return m
}
// Test fork of length N starting from block i
func testFork(t *testing.T, m *execmoduletester.ExecModuleTester, i, n int, comparator func(td1, td2 *big.Int)) {
// Copy old chain up to #i into a new db
canonicalMock := newCanonical(t, i)
var err error
ctx := context.Background()
// Assert the chains have the same header/block at #i
var hash1, hash2 common.Hash
err = m.DB.View(m.Ctx, func(tx kv.Tx) error {
if hash1, _, err = m.BlockReader.CanonicalHash(m.Ctx, tx, uint64(i)); err != nil {
t.Fatalf("Failed to read canonical hash: %v", err)
}
if block1, _, _ := m.BlockReader.BlockWithSenders(ctx, tx, hash1, uint64(i)); block1 == nil {
t.Fatalf("Did not find canonical block")
}
return nil
})
require.NoError(t, err)
canonicalMock.DB.View(ctx, func(tx kv.Tx) error {
if hash2, _, err = m.BlockReader.CanonicalHash(m.Ctx, tx, uint64(i)); err != nil {
t.Fatalf("Failed to read canonical hash: %v", err)
}
if block2, _, _ := m.BlockReader.BlockWithSenders(ctx, tx, hash2, uint64(i)); block2 == nil {
t.Fatalf("Did not find canonical block 2")
}
return nil
})
require.NoError(t, err)
if hash1 != hash2 {
t.Errorf("chain content mismatch at %d: have hash %v, want hash %v", i, hash2, hash1)
}
// Extend the newly created chain
var blockChainB *blockgen.ChainPack
var tdPre, tdPost *big.Int
var currentBlockB *types.Block
err = canonicalMock.DB.View(context.Background(), func(tx kv.Tx) error {
currentBlockB, err = m.BlockReader.CurrentBlock(tx)
return err
})
require.NoError(t, err)
blockChainB = makeBlockChain(currentBlockB, n, canonicalMock, forkSeed)
err = m.DB.View(context.Background(), func(tx kv.Tx) error {
currentBlock, err := m.BlockReader.CurrentBlock(tx)
if err != nil {
return err
}
tdPre, err = rawdb.ReadTd(tx, currentBlock.Hash(), currentBlock.NumberU64())
if err != nil {
t.Fatalf("Failed to read TD for current block: %v", err)
}
return nil
})
require.NoError(t, err)
if err = m.InsertChain(blockChainB); err != nil {
t.Fatalf("failed to insert forking chain: %v", err)
}
currentBlockHash := blockChainB.TopBlock.Hash()
err = m.DB.View(context.Background(), func(tx kv.Tx) error {
number, err := m.BlockReader.HeaderNumber(context.Background(), tx, currentBlockHash)
if err != nil {
return err
}
currentBlock, _, _ := m.BlockReader.BlockWithSenders(ctx, tx, currentBlockHash, *number)
tdPost, err = rawdb.ReadTd(tx, currentBlockHash, currentBlock.NumberU64())
if err != nil {
t.Fatalf("Failed to read TD for current header: %v", err)
}
return nil
})
require.NoError(t, err)
// Sanity check that the forked chain can be imported into the original
if err := canonicalMock.InsertChain(blockChainB); err != nil {
t.Fatalf("failed to import forked block chain: %v", err)
}
// Compare the total difficulties of the chains
comparator(tdPre, tdPost)
}
func TestLastBlock(t *testing.T) {
if testing.Short() {
t.Skip("slow test")
}
t.Parallel()
m := newCanonical(t, 0)
var err error
chain := makeBlockChain(m.Current(nil), 1, m, 0)
if err = m.InsertChain(chain); err != nil {
t.Fatalf("Failed to insert block: %v", err)
}
tx, err := m.DB.BeginRo(context.Background())
require.NoError(t, err)
defer tx.Rollback()
if chain.TopBlock.Hash() != rawdb.ReadHeadBlockHash(tx) {
t.Fatalf("Write/Get HeadBlockHash failed")
}
}
// Tests that given a starting canonical chain of a given size, it can be extended
// with various length chains.
func TestExtendCanonicalBlocks(t *testing.T) {
if testing.Short() {
t.Skip()
}
t.Parallel()
length := 5
// Make first chain starting from genesis
m := newCanonical(t, length)
// Define the difficulty comparator
better := func(td1, td2 *big.Int) {
if td2.Cmp(td1) <= 0 {
t.Errorf("total difficulty mismatch: have %v, expected more than %v", td2, td1)
}
}
// Start fork from current height
testFork(t, m, length, 1, better)
testFork(t, m, length, 2, better)
testFork(t, m, length, 5, better)
testFork(t, m, length, 10, better)
}
// Tests that given a starting canonical chain of a given size, creating shorter
// forks do not take canonical ownership.
func TestShorterForkBlocks(t *testing.T) {
t.Parallel()
t.Skip("Erigon does not insert shorter forks")
testShorterFork(t)
}
func testShorterFork(t *testing.T) {
t.Parallel()
length := 10
// Make first chain starting from genesis
m := newCanonical(t, length)
// Define the difficulty comparator
worse := func(td1, td2 *big.Int) {
if td2.Cmp(td1) >= 0 {
t.Errorf("total difficulty mismatch: have %v, expected less than %v", td2, td1)
}
}
// Sum of numbers must be less than `length` for this to be a shorter fork
testFork(t, m, 0, 3, worse)
testFork(t, m, 0, 7, worse)
testFork(t, m, 1, 1, worse)
testFork(t, m, 1, 7, worse)
testFork(t, m, 5, 3, worse)
testFork(t, m, 5, 4, worse)
}
// Tests that given a starting canonical chain of a given size, creating longer
// forks do take canonical ownership.
func TestLongerForkHeaders(t *testing.T) { testLongerFork(t, false) }
func TestLongerForkBlocks(t *testing.T) { testLongerFork(t, true) }
func testLongerFork(t *testing.T, full bool) {
if testing.Short() {
t.Skip()
}
length := 10
// Make first chain starting from genesis
m := newCanonical(t, length)
// Define the difficulty comparator
better := func(td1, td2 *big.Int) {
if td2.Cmp(td1) <= 0 {
t.Errorf("total difficulty mismatch: have %v, expected more than %v", td2, td1)
}
}
// Sum of numbers must be greater than `length` for this to be a longer fork
testFork(t, m, 5, 6, better)
testFork(t, m, 5, 8, better)
testFork(t, m, 1, 13, better)
testFork(t, m, 1, 14, better)
testFork(t, m, 0, 16, better)
testFork(t, m, 0, 17, better)
}
// Tests that chains missing links do not get accepted by the processor.
func TestBrokenBlockChain(t *testing.T) {
if testing.Short() {
t.Skip("slow test")
}
testBrokenChain(t)
}
func testBrokenChain(t *testing.T) {
t.Parallel()
// Make chain starting from genesis
m := newCanonical(t, 10)
// Create a forked chain, and try to insert with a missing link
chain := makeBlockChain(m.Current(nil), 5, m, forkSeed)
brokenChain := chain.Slice(1, chain.Length())
if err := m.InsertChain(brokenChain); err == nil {
t.Errorf("broken block chain not reported")
}
}
// Tests that reorganising a long chain after a short one overwrites the canonical numbers and links in the database.
func TestReorgLongBlocks(t *testing.T) {
if testing.Short() {
t.Skip("slow test")
}
testReorgLong(t)
}
func testReorgLong(t *testing.T) {
t.Parallel()
testReorg(t, []int64{0, 0, -9}, []int64{0, 0, 0, -9}, 524352)
}
// Tests that reorganising a short chain after a long one overwrites the canonical numbers and links in the database.
func TestReorgShortBlocks(t *testing.T) {
if testing.Short() {
t.Skip("slow test")
}
testReorgShort(t)
}
func testReorgShort(t *testing.T) {
t.Parallel()
long := make([]int64, 96)
for i := 0; i < len(long); i++ {
long[i] = 60
}
short := make([]int64, len(long)-1)
for i := 0; i < len(short); i++ {
short[i] = -9
}
testReorg(t, long, short, 12746192)
}
func testReorg(t *testing.T, first, second []int64, td int64) {
require := require.New(t)
// Create a pristine chain and database
m := newCanonical(t, 0)
// Insert one chain first, then the other
firstChain, err := blockgen.GenerateChain(m.ChainConfig, m.Current(nil), m.Engine, m.DB, len(first), func(i int, b *blockgen.BlockGen) {
b.OffsetTime(first[i])
})
if err != nil {
t.Fatalf("generate chain: %v", err)
}
secondChain, err := blockgen.GenerateChain(m.ChainConfig, m.Current(nil), m.Engine, m.DB, len(second), func(i int, b *blockgen.BlockGen) {
b.OffsetTime(second[i])
})
if err != nil {
t.Fatalf("generate chain: %v", err)
}
if err = m.InsertChain(firstChain); err != nil {
t.Fatalf("failed to insert first chain: %v", err)
}
if err = m.InsertChain(secondChain); err != nil {
t.Fatalf("failed to insert second chain: %v", err)
}
tx, err := m.DB.BeginRw(m.Ctx)
if err != nil {
fmt.Printf("beginro error: %v\n", err)
return
}
defer tx.Rollback()
// Check that the chain is valid number and link wise
prev, err := m.BlockReader.CurrentBlock(tx)
require.NoError(err)
block, err := m.BlockReader.BlockByNumber(m.Ctx, tx, rawdb.ReadCurrentHeader(tx).Number.Uint64()-1)
if err != nil {
t.Fatal(err)
}
hashPacket := make([]common.Hash, 0)
queryNum := 0
for block.NumberU64() != 0 {
hashPacket = append(hashPacket, block.Hash())
queryNum++
if prev.ParentHash() != block.Hash() {
t.Errorf("parent block hash mismatch: have %x, want %x", prev.ParentHash(), block.Hash())
}
prev = block
block, err = m.BlockReader.BlockByNumber(m.Ctx, tx, block.NumberU64()-1)
if err != nil {
t.Fatal(err)
}
}
b, err := rlp.EncodeToBytes(ð.GetReceiptsPacket66{
RequestId: 1,
GetReceiptsPacket: hashPacket,
})
if err != nil {
t.Fatal(err)
}
m.ReceiveWg.Add(1)
for _, err = range m.Send(&sentryproto.InboundMessage{Id: sentryproto.MessageId_GET_RECEIPTS_66, Data: b, PeerId: m.PeerId}) {
if err != nil {
t.Fatal(err)
}
}
m.ReceiveWg.Wait()
msg, err := m.SentMessage(0)
if err != nil {
t.Fatal(err)
}
require.Equal(sentryproto.MessageId_RECEIPTS_66, msg.Id)
encoded, err := rlp.EncodeToBytes(types.Receipts{})
require.NoError(err)
res := make([]rlp.RawValue, 0, queryNum)
for i := 0; i < queryNum; i++ {
res = append(res, encoded)
}
b, err = rlp.EncodeToBytes(ð.ReceiptsRLPPacket66{
RequestId: 1,
ReceiptsRLPPacket: res,
})
require.NoError(err)
require.Equal(b, msg.GetData())
// Make sure the chain total difficulty is the correct one
genDiff := m.Genesis.Difficulty()
want := new(uint256.Int).AddUint64(&genDiff, uint64(td))
have, err := rawdb.ReadTdByHash(tx, rawdb.ReadCurrentHeader(tx).Hash())
require.NoError(err)
if want.CmpBig(have) != 0 {
t.Errorf("total difficulty mismatch: have %v, want %v", have, want)
}
// Make sure the canonical chain is the correct one
require.Equal(secondChain.TopBlock.Hash(), rawdb.ReadHeadHeaderHash(tx))
for _, h := range secondChain.Headers {
canon, err := rawdb.ReadCanonicalHash(tx, h.Number.Uint64())
require.NoError(err)
require.Equal(h.Hash(), canon)
}
}
// Tests that chain reorganisations handle transaction removals and reinsertions.
func TestChainTxReorgs(t *testing.T) {
if testing.Short() {
t.Skip()
}
t.Parallel()
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)
gspec = &types.Genesis{
Config: libchain.TestChainBerlinConfig,
GasLimit: 3141592,
Alloc: types.GenesisAlloc{
addr1: {Balance: big.NewInt(1000000)},
addr2: {Balance: big.NewInt(1000000)},
addr3: {Balance: big.NewInt(1000000)},
},
}
signer = types.LatestSigner(gspec.Config)
)
m := execmoduletester.New(t, execmoduletester.WithGenesisSpec(gspec), execmoduletester.WithKey(key1))
m2 := execmoduletester.New(t, execmoduletester.WithGenesisSpec(gspec), execmoduletester.WithKey(key1))
defer m2.DB.Close()
// Create two transactions shared between the chains:
// - postponed: transaction included at a later block in the forked chain
// - swapped: transaction included at the same block number in the forked chain
postponed, _ := types.SignTx(types.NewTransaction(0, addr1, uint256.NewInt(1000), params.TxGas, nil, nil), *signer, key1)
swapped, _ := types.SignTx(types.NewTransaction(1, addr1, uint256.NewInt(1000), params.TxGas, nil, nil), *signer, key1)
// Create two transactions that will be dropped by the forked chain:
// - pastDrop: transaction dropped retroactively from a past block
// - freshDrop: transaction dropped exactly at the block where the reorg is detected
var pastDrop, freshDrop types.Transaction
// Create three transactions that will be added in the forked chain:
// - pastAdd: transaction added before the reorganization is detected
// - freshAdd: transaction added at the exact block the reorg is detected
// - futureAdd: transaction added after the reorg has already finished
var pastAdd, freshAdd, futureAdd types.Transaction
chain, err := blockgen.GenerateChain(m.ChainConfig, m.Genesis, m.Engine, m.DB, 3, func(i int, gen *blockgen.BlockGen) {
switch i {
case 0:
pastDrop, _ = types.SignTx(types.NewTransaction(gen.TxNonce(addr2), addr2, uint256.NewInt(1000), params.TxGas, nil, nil), *signer, key2)
gen.AddTx(pastDrop) // This transaction will be dropped in the fork from below the split point
gen.AddTx(postponed) // This transaction will be postponed till block #3 in the fork
case 2:
freshDrop, _ = types.SignTx(types.NewTransaction(gen.TxNonce(addr2), addr2, uint256.NewInt(1000), params.TxGas, nil, nil), *signer, key2)
gen.AddTx(freshDrop) // This transaction will be dropped in the fork from exactly at the split point
gen.AddTx(swapped) // This transaction will be swapped out at the exact height
gen.OffsetTime(9) // Lower the block difficulty to simulate a weaker chain
}
})
if err != nil {
t.Fatalf("generate chain: %v", err)
}
// Import the chain. This runs all block validation rules.
if err1 := m.InsertChain(chain); err1 != nil {
t.Fatalf("failed to insert original chain: %v", err1)
}
// overwrite the old chain
chain, err = blockgen.GenerateChain(m2.ChainConfig, m2.Genesis, m2.Engine, m2.DB, 5, func(i int, gen *blockgen.BlockGen) {
switch i {
case 0:
pastAdd, _ = types.SignTx(types.NewTransaction(gen.TxNonce(addr3), addr3, uint256.NewInt(1000), params.TxGas, nil, nil), *signer, key3)
gen.AddTx(pastAdd) // This transaction needs to be injected during reorg
case 2:
gen.AddTx(postponed) // This transaction was postponed from block #1 in the original chain
gen.AddTx(swapped) // This transaction was swapped from the exact current spot in the original chain
freshAdd, _ = types.SignTx(types.NewTransaction(gen.TxNonce(addr3), addr3, uint256.NewInt(1000), params.TxGas, nil, nil), *signer, key3)
gen.AddTx(freshAdd) // This transaction will be added exactly at reorg time
case 3:
futureAdd, _ = types.SignTx(types.NewTransaction(gen.TxNonce(addr3), addr3, uint256.NewInt(1000), params.TxGas, nil, nil), *signer, key3)
gen.AddTx(futureAdd) // This transaction will be added after a full reorg
}
})
if err != nil {
t.Fatalf("generate chain: %v", err)
}
if err := m.InsertChain(chain); err != nil {
t.Fatalf("failed to insert forked chain: %v", err)
}
tx, err := m.DB.BeginTemporalRo(context.Background())
require.NoError(t, err)
defer tx.Rollback()
// removed tx
txs := types.Transactions{pastDrop, freshDrop}
for i, txn := range txs {
if bn, _, _ := rawdb.ReadTxLookupEntry(tx, txn.Hash()); bn != nil {
t.Errorf("drop %d: tx %v found while shouldn't have been", i, txn)
}
if rcpt, _, _, _, _ := readReceipt(tx, txn.Hash(), m); rcpt != nil {
t.Errorf("drop %d: receipt %v found while shouldn't have been", i, rcpt)
}
}
// added tx
txs = types.Transactions{pastAdd, freshAdd, futureAdd}
for i, txn := range txs {
_, _, found, err := m.BlockReader.TxnLookup(m.Ctx, tx, txn.Hash())
require.NoError(t, err)
require.True(t, found)
if rcpt, _, _, _, err := readReceipt(tx, txn.Hash(), m); rcpt == nil {
t.Errorf("add %d: expected receipt to be found, err %v", i, err)
}
}
// shared tx
txs = types.Transactions{postponed, swapped}
for i, txn := range txs {
if bn, _, _ := rawdb.ReadTxLookupEntry(tx, txn.Hash()); bn == nil {
t.Errorf("drop %d: tx %v found while shouldn't have been", i, txn)
}
if rcpt, _, _, _, _ := readReceipt(tx, txn.Hash(), m); rcpt == nil {
t.Errorf("share %d: expected receipt to be found", i)
}
}
}
func readReceipt(db kv.TemporalTx, txHash common.Hash, m *execmoduletester.ExecModuleTester) (*types.Receipt, common.Hash, uint64, uint64, error) {
// Retrieve the context of the receipt based on the transaction hash
blockNumber, _, err := rawdb.ReadTxLookupEntry(db, txHash)
if err != nil {
return nil, common.Hash{}, 0, 0, err
}
if blockNumber == nil {
return nil, common.Hash{}, 0, 0, nil
}
blockHash, _, err := m.BlockReader.CanonicalHash(context.Background(), db, *blockNumber)
if err != nil {
return nil, common.Hash{}, 0, 0, err
}
if blockHash == (common.Hash{}) {
return nil, common.Hash{}, 0, 0, nil
}
b, _, err := m.BlockReader.BlockWithSenders(context.Background(), db, blockHash, *blockNumber)
if err != nil {
return nil, common.Hash{}, 0, 0, err
}
// Read all the receipts from the block and return the one with the matching hash
receipts, err := m.ReceiptsReader.GetReceipts(context.Background(), m.ChainConfig, db, b)
if err != nil {
return nil, common.Hash{}, 0, 0, err
}
for receiptIndex, receipt := range receipts {
if receipt.TxHash == txHash {
return receipt, blockHash, *blockNumber, uint64(receiptIndex), nil
}
}
log.Error("Receipt not found", "number", blockNumber, "hash", blockHash, "txhash", txHash)
return nil, common.Hash{}, 0, 0, nil
}
// Tests if the canonical block can be fetched from the database during chain insertion.
func TestCanonicalBlockRetrieval(t *testing.T) {
if testing.Short() {
t.Skip("slow test")
}
t.Parallel()
m := newCanonical(t, 0)
chain, err2 := blockgen.GenerateChain(m.ChainConfig, m.Genesis, m.Engine, m.DB, 10, func(i int, gen *blockgen.BlockGen) {})
if err2 != nil {
t.Fatalf("generate chain: %v", err2)
}
err := m.InsertChain(chain)
require.NoError(t, err)
tx, err := m.DB.BeginRo(m.Ctx)
require.NoError(t, err)
defer tx.Rollback()
for _, block := range chain.Blocks {
// try to retrieve a block by its canonical hash and see if the block data can be retrieved.
ch, _, err := m.BlockReader.CanonicalHash(m.Ctx, tx, block.NumberU64())
require.NoError(t, err)
if err != nil {
panic(err)
}
if ch == (common.Hash{}) {
continue // busy wait for canonical hash to be written
}
if ch != block.Hash() {
t.Errorf("unknown canonical hash, want %s, got %s", block.Hash().Hex(), ch.Hex())
return
}
fb, _ := m.BlockReader.Header(m.Ctx, tx, ch, block.NumberU64())
if fb == nil {
t.Errorf("unable to retrieve block %d for canonical hash: %s", block.NumberU64(), ch.Hex())
return
}
if fb.Hash() != block.Hash() {
t.Errorf("invalid block hash for block %d, want %s, got %s", block.NumberU64(), block.Hash().Hex(), fb.Hash().Hex())
return
}
}
}
func TestEIP155Transition(t *testing.T) {
if testing.Short() {
t.Skip("slow test")
}
t.Parallel()
// Configure and generate a sample block chai
var (
key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
address = crypto.PubkeyToAddress(key.PublicKey)
funds = big.NewInt(1000000000)
deleteAddr = common.Address{1}
gspec = &types.Genesis{
Config: &libchain.Config{ChainID: big.NewInt(1), TangerineWhistleBlock: common.NewUint64(0), SpuriousDragonBlock: common.NewUint64(2), HomesteadBlock: common.NewUint64(0)},
Alloc: types.GenesisAlloc{address: {Balance: funds}, deleteAddr: {Balance: new(big.Int)}},
}
)
m := execmoduletester.New(t, execmoduletester.WithGenesisSpec(gspec), execmoduletester.WithKey(key))
chain, chainErr := blockgen.GenerateChain(m.ChainConfig, m.Genesis, m.Engine, m.DB, 4, func(i int, block *blockgen.BlockGen) {
var (
tx types.Transaction
err error
basicTx = func(signer types.Signer) (types.Transaction, error) {
return types.SignTx(types.NewTransaction(block.TxNonce(address), common.Address{}, new(uint256.Int), 21000, new(uint256.Int), nil), signer, key)
}
)
switch i {
case 0:
tx, err = basicTx(*types.LatestSignerForChainID(nil))
if err != nil {
t.Fatal(err)
}
block.AddTx(tx)
case 2:
tx, err = basicTx(*types.LatestSignerForChainID(nil))
if err != nil {
t.Fatal(err)
}
block.AddTx(tx)
tx, err = basicTx(*types.LatestSigner(gspec.Config))
if err != nil {
t.Fatal(err)
}
block.AddTx(tx)
case 3:
tx, err = basicTx(*types.LatestSignerForChainID(nil))
if err != nil {
t.Fatal(err)
}
block.AddTx(tx)
tx, err = basicTx(*types.LatestSigner(gspec.Config))
if err != nil {
t.Fatal(err)
}
block.AddTx(tx)
}
})
if chainErr != nil {
t.Fatalf("generate chain: %v", chainErr)
}
if chainErr = m.InsertChain(chain); chainErr != nil {
t.Fatal(chainErr)
}
if err := m.DB.View(context.Background(), func(tx kv.Tx) error {
block, _ := m.BlockReader.BlockByNumber(m.Ctx, tx, 1)
if block.Transactions()[0].Protected() {
t.Error("Expected block[0].txs[0] to not be replay protected")
}
block, _ = m.BlockReader.BlockByNumber(m.Ctx, tx, 3)
if block.Transactions()[0].Protected() {
t.Error("Expected block[3].txs[0] to not be replay protected")
}
if !block.Transactions()[1].Protected() {
t.Error("Expected block[3].txs[1] to be replay protected")
}
return nil
}); err != nil {
t.Fatal(err)
}
// generate an invalid chain id transaction
config := &libchain.Config{ChainID: big.NewInt(2), TangerineWhistleBlock: common.NewUint64(0), SpuriousDragonBlock: common.NewUint64(2), HomesteadBlock: common.NewUint64(0)}
chain, chainErr = blockgen.GenerateChain(config, chain.TopBlock, m.Engine, m.DB, 4, func(i int, block *blockgen.BlockGen) {
var (
basicTx = func(signer types.Signer) (types.Transaction, error) {
return types.SignTx(types.NewTransaction(block.TxNonce(address), common.Address{}, new(uint256.Int), 21000, new(uint256.Int), nil), signer, key)
}
)
if i == 0 {
tx, txErr := basicTx(*types.LatestSigner(config))
if txErr != nil {
t.Fatal(txErr)
}
block.AddTx(tx)
}
})
if chainErr != nil {
t.Fatalf("generate blocks: %v", chainErr)
}
if err := m.InsertChain(chain); err == nil {
t.Errorf("expected error")
}
}
func TestModes(t *testing.T) {
if testing.Short() {
t.Skip()
}
t.Parallel()
// run test on all combination of flags
runWithModesPermuations(
t,
doModesTest,
)
}
func doModesTest(t *testing.T, pm prune.Mode) error {
fmt.Printf("h=%v\n", pm.History.Enabled())
require := require.New(t)
// Configure and generate a sample block chain
var (
key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
address = crypto.PubkeyToAddress(key.PublicKey)
funds = big.NewInt(1000000000)
deleteAddr = common.Address{1}
gspec = &types.Genesis{
Config: &libchain.Config{ChainID: big.NewInt(1), TangerineWhistleBlock: common.NewUint64(0), SpuriousDragonBlock: common.NewUint64(2), HomesteadBlock: common.NewUint64(0)},
Alloc: types.GenesisAlloc{address: {Balance: funds}, deleteAddr: {Balance: new(big.Int)}},
}
)
m := execmoduletester.New(t, execmoduletester.WithGenesisSpec(gspec), execmoduletester.WithKey(key), execmoduletester.WithBlockBufferSize(128), execmoduletester.WithPruneMode(pm))
head := uint64(4)
chain, err := blockgen.GenerateChain(m.ChainConfig, m.Genesis, m.Engine, m.DB, int(head), func(i int, block *blockgen.BlockGen) {
var (
tx types.Transaction
err error
basicTx = func(signer types.Signer) (types.Transaction, error) {
return types.SignTx(types.NewTransaction(block.TxNonce(address), common.Address{}, new(uint256.Int), 21000, new(uint256.Int), nil), signer, key)
}
)
switch i {
case 0:
tx, err = basicTx(*types.LatestSignerForChainID(nil))
if err != nil {
panic(err)
}
block.AddTx(tx)
case 2:
tx, err = basicTx(*types.LatestSignerForChainID(nil))
if err != nil {
panic(err)
}
block.AddTx(tx)
tx, err = basicTx(*types.LatestSignerForChainID(gspec.Config.ChainID))
if err != nil {
panic(err)
}
block.AddTx(tx)
case 3:
tx, err = basicTx(*types.LatestSignerForChainID(nil))
if err != nil {
panic(err)
}
block.AddTx(tx)
tx, err = basicTx(*types.LatestSignerForChainID(gspec.Config.ChainID))
if err != nil {
panic(err)
}
block.AddTx(tx)
}
})
if err != nil {
return fmt.Errorf("generate blocks: %w", err)
}
if err = m.InsertChain(chain); err != nil {
return err
}
tx, err := m.DB.BeginRo(context.Background())
require.NoError(err)
defer tx.Rollback()
//TODO: e3 not implemented Prune feature yet
/*
if pm.History.Enabled() {
it, err := tx.(kv.TemporalTx).HistoryRange(temporal.AccountsHistory, 0, int(pm.History.PruneTo(head)), order.Asc, -1)
require.NoError(err)
count, err := iter.CountKV(it)
require.NoError(err)
require.Zero(count)
it, err = tx.(kv.TemporalTx).HistoryRange(temporal.AccountsHistory, int(pm.History.PruneTo(head)), -1, order.Asc, -1)
require.NoError(err)
count, err = iter.CountKV(it)
require.NoError(err)
require.Equal(3, count)
} else {
it, err := tx.(kv.TemporalTx).HistoryRange(temporal.AccountsHistory, 0, -1, order.Asc, -1)
require.NoError(err)
count, err := iter.CountKV(it)
require.NoError(err)
require.Equal(3, count)
}
*/
if pm.History.Enabled() {
b, err := m.BlockReader.BlockByNumber(m.Ctx, tx, 1)
require.NoError(err)
for _, txn := range b.Transactions() {
found, _, err := rawdb.ReadTxLookupEntry(tx, txn.Hash())
require.NoError(err)
require.Nil(found)
}
} else {
b, err := m.BlockReader.BlockByNumber(m.Ctx, tx, 1)
require.NoError(err)
for _, txn := range b.Transactions() {
foundBlockNum, _, found, err := m.BlockReader.TxnLookup(context.Background(), tx, txn.Hash())
require.NoError(err)
require.True(found)
require.Equal(uint64(1), foundBlockNum)
}
}
/*
for bucketName, shouldBeEmpty := range map[string]bool{
//dbutils.AccountsHistory: pm.History.Enabled(),
dbutils.Receipts: pm.Receipts.Enabled(),
//dbutils.TxLookup: pm.TxIndex.Enabled(),
} {
numberOfEntries := 0
err := tx.ForEach(bucketName, nil, func(k, v []byte) error {
// we ignore empty account history
if bucketName == dbutils.AccountsHistory && len(v) == 0 {
return nil
}
numberOfEntries++
return nil
})
if err != nil {
return err
}
if bucketName == dbutils.Receipts {
// we will always have a receipt for genesis
numberOfEntries--
}
if (shouldBeEmpty && numberOfEntries > 0) || (!shouldBeEmpty && numberOfEntries == 0) {
return fmt.Errorf("bucket '%s' should be empty? %v (actually %d entries)", bucketName, shouldBeEmpty, numberOfEntries)
}
}
*/
return nil
}
func runWithModesPermuations(t *testing.T, testFunc func(*testing.T, prune.Mode) error) {
err := runPermutation(t, testFunc, 0, prune.MockMode)
if err != nil {
t.Errorf("error while testing stuff: %v", err)
}
}
func runPermutation(t *testing.T, testFunc func(*testing.T, prune.Mode) error, current int, pm prune.Mode) error {
if current == 1 {
return testFunc(t, pm)
}
if err := runPermutation(t, testFunc, current+1, pm); err != nil {
return err
}
invert := func(a prune.BlockAmount) prune.Distance {
if a.Enabled() {
return math.MaxUint64
}
return 2
}
switch current {
case 0:
pm.History = invert(pm.History)
default:
panic("unexpected current item")
}
return runPermutation(t, testFunc, current+1, pm)
}
func TestEIP161AccountRemoval(t *testing.T) {
if testing.Short() {
t.Skip("slow test")
}
t.Parallel()
// Configure and generate a sample block chain
var (
key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
address = crypto.PubkeyToAddress(key.PublicKey)
funds = big.NewInt(1000000000)
theAddr = accounts.InternAddress(common.Address{1})
gspec = &types.Genesis{
Config: &libchain.Config{
ChainID: big.NewInt(1),
HomesteadBlock: common.NewUint64(0),
TangerineWhistleBlock: common.NewUint64(0),
SpuriousDragonBlock: common.NewUint64(2),
},
Alloc: types.GenesisAlloc{address: {Balance: funds}},
}
)
m := execmoduletester.New(t, execmoduletester.WithGenesisSpec(gspec), execmoduletester.WithKey(key))
chain, err := blockgen.GenerateChain(m.ChainConfig, m.Genesis, m.Engine, m.DB, 3, func(i int, block *blockgen.BlockGen) {
var (
txn types.Transaction
err error
signer = types.MakeFrontierSigner()
)
switch i {
case 0:
txn, err = types.SignTx(types.NewTransaction(block.TxNonce(address), theAddr.Value(), new(uint256.Int), 21000, new(uint256.Int), nil), *signer, key)
case 1:
txn, err = types.SignTx(types.NewTransaction(block.TxNonce(address), theAddr.Value(), new(uint256.Int), 21000, new(uint256.Int), nil), *signer, key)
case 2:
txn, err = types.SignTx(types.NewTransaction(block.TxNonce(address), theAddr.Value(), new(uint256.Int), 21000, new(uint256.Int), nil), *signer, key)
}