forked from ethereum/go-ethereum
-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathgenesis_startup_test.go
More file actions
1038 lines (900 loc) · 36.9 KB
/
Copy pathgenesis_startup_test.go
File metadata and controls
1038 lines (900 loc) · 36.9 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
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
"os"
"path/filepath"
"strings"
"testing"
"time"
cmdutils "github.com/XinFinOrg/XDPoSChain/cmd/utils"
"github.com/XinFinOrg/XDPoSChain/common"
"github.com/XinFinOrg/XDPoSChain/core"
"github.com/XinFinOrg/XDPoSChain/core/rawdb"
"github.com/XinFinOrg/XDPoSChain/core/state"
"github.com/XinFinOrg/XDPoSChain/core/types"
"github.com/XinFinOrg/XDPoSChain/ethdb"
"github.com/XinFinOrg/XDPoSChain/params"
)
const startupTestXDPoSConfig = `
"XDPoS": {
"period": 2,
"epoch": 900,
"reward": 5000,
"rewardCheckpoint": 900,
"gap": 450,
"foundationWalletAddr": "0x0000000000000000000000000000000000000068",
"maxMasternodesV2": 108,
"v2": {
"switchEpoch": 1111111,
"switchBlock": 999999900,
"config": {
"maxMasternodes": 108,
"switchRound": 0,
"minePeriod": 2,
"timeoutSyncThreshold": 3,
"timeoutPeriod": 10,
"certificateThreshold": 0.667,
"expTimeoutConfig": {
"base": 1,
"maxExponent": 0
}
},
"allConfigs": {
"0": {
"maxMasternodes": 108,
"switchRound": 0,
"minePeriod": 2,
"timeoutSyncThreshold": 3,
"timeoutPeriod": 10,
"certificateThreshold": 0.667,
"expTimeoutConfig": {
"base": 1,
"maxExponent": 0
}
}
}
}
}`
// startupTestGenesis builds a minimal genesis JSON string with a caller-
// supplied config fragment.
func startupTestGenesis(configBody string) string {
return fmt.Sprintf(`{
"alloc" : {},
"coinbase" : "0x0000000000000000000000000000000000000000",
"difficulty" : "0x20000",
"extraData" : "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"gasLimit" : "0x2fefd8",
"nonce" : "0x0000000000000042",
"mixhash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
"parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
"timestamp" : "0x00",
"config" : {
"chainId" : 1337,
%s
%s
}
}`, configBody, startupTestXDPoSConfig)
}
// assertCommandFailsWithChainConfigError checks that a test command fails with
// the expected chain-config-related error text.
func assertCommandFailsWithChainConfigError(t *testing.T, cmd *testXDC, want string) {
t.Helper()
assertCommandFailsWithChainConfigErrors(t, cmd, want)
}
// assertCommandFailsWithChainConfigErrors checks that a test command fails with
// all expected chain-config-related error text fragments.
func assertCommandFailsWithChainConfigErrors(t *testing.T, cmd *testXDC, wants ...string) {
t.Helper()
cmd.WaitExit()
if status := cmd.ExitStatus(); status == 0 {
t.Fatalf("expected command to fail, got exit status 0, stderr=%q", cmd.StderrText())
}
stderr := cmd.StderrText()
for _, want := range wants {
if !strings.Contains(stderr, want) {
t.Fatalf("expected stderr to contain %q, got %q", want, stderr)
}
}
}
// assertCommandSucceeds checks that a test command exits successfully.
func assertCommandSucceeds(t *testing.T, cmd *testXDC) {
t.Helper()
cmd.WaitExit()
if status := cmd.ExitStatus(); status != 0 {
t.Fatalf("expected command to succeed, exit status=%d stderr=%q", status, cmd.StderrText())
}
}
func startTestnetConsole(t *testing.T, datadir string, extraArgs ...string) {
t.Helper()
args := []string{
"--testnet", "console", "--port", "0", "--maxpeers", "0", "--nodiscover", "--nat", "none", "--ipcdisable",
"--datadir", datadir,
}
args = append(args, extraArgs...)
args = append(args, "--exec", "2+2")
startupCmd := runXDC(t, args...)
assertCommandSucceeds(t, startupCmd)
}
// openTestChainDB retries shortly when a reexec'd child has just released the
// LevelDB lock but the parent races to reopen it.
func openTestChainDB(t *testing.T, path string) ethdb.Database {
t.Helper()
var lastErr error
for range 50 {
db, err := rawdb.NewLevelDBDatabase(path, 0, 0, "", false)
if err == nil {
return db
}
lastErr = err
if !strings.Contains(err.Error(), "resource temporarily unavailable") {
t.Fatalf("failed to open test database: %v", err)
}
time.Sleep(50 * time.Millisecond)
}
t.Fatalf("failed to open test database: %v", lastErr)
return nil
}
// assertNoCanonicalGenesis checks that a failed init left no canonical genesis
// hash in the test datadir.
func assertNoCanonicalGenesis(t *testing.T, datadir string) {
t.Helper()
path := filepath.Join(datadir, "XDC", "chaindata")
if _, err := os.Stat(path); err != nil {
if os.IsNotExist(err) {
return
}
t.Fatalf("failed to stat chaindata path: %v", err)
}
db := openTestChainDB(t, path)
defer db.Close()
if got := rawdb.ReadCanonicalHash(db, 0); got != (common.Hash{}) {
t.Fatalf("expected failed init to leave no canonical genesis, got %s", got.Hex())
}
}
// readStoredChainConfig loads the canonical genesis hash and persisted chain
// config from the test datadir.
func readStoredChainConfig(t *testing.T, datadir string) (common.Hash, *params.ChainConfig) {
t.Helper()
path := filepath.Join(datadir, "XDC", "chaindata")
db := openTestChainDB(t, path)
defer db.Close()
genesisHash := rawdb.ReadCanonicalHash(db, 0)
if genesisHash == (common.Hash{}) {
t.Fatal("expected canonical genesis hash")
}
config, err := rawdb.ReadChainConfig(db, genesisHash)
if err != nil {
t.Fatalf("failed to read chain config: %v", err)
}
if config == nil {
t.Fatal("expected stored chain config")
}
return genesisHash, config
}
// overwriteStoredIssuer replaces the stored TRC21 issuer address in the test
// chain config.
func overwriteStoredIssuer(t *testing.T, datadir string, issuer common.Address) {
t.Helper()
path := filepath.Join(datadir, "XDC", "chaindata")
db := openTestChainDB(t, path)
defer db.Close()
genesisHash := rawdb.ReadCanonicalHash(db, 0)
if genesisHash == (common.Hash{}) {
t.Fatal("expected canonical genesis hash")
}
config, err := rawdb.ReadChainConfig(db, genesisHash)
if err != nil {
t.Fatalf("failed to read chain config: %v", err)
}
if config == nil {
t.Fatal("expected stored chain config")
}
config.TRC21IssuerSMC = issuer
rawdb.WriteChainConfig(db, genesisHash, config)
}
// deleteStoredChainConfig removes the persisted chain-config blob from the test
// datadir and returns the canonical genesis hash.
func deleteStoredChainConfig(t *testing.T, datadir string) common.Hash {
t.Helper()
path := filepath.Join(datadir, "XDC", "chaindata")
db := openTestChainDB(t, path)
genesisHash := rawdb.ReadCanonicalHash(db, 0)
if genesisHash == (common.Hash{}) {
t.Fatal("expected canonical genesis hash")
}
if err := db.Delete(append([]byte("ethereum-config-"), genesisHash.Bytes()...)); err != nil {
t.Fatalf("failed to delete stored chain config: %v", err)
}
if err := db.Close(); err != nil {
t.Fatalf("failed to close test database after delete: %v", err)
}
db = openTestChainDB(t, path)
defer db.Close()
config, err := rawdb.ReadChainConfig(db, genesisHash)
if !errors.Is(err, rawdb.ErrChainConfigNotFound) {
t.Fatalf("expected missing chain config after delete, config=%v err=%v", config, err)
}
return genesisHash
}
// overwriteStoredBerlinBlock updates the stored Berlin activation block in the
// test chain config.
func overwriteStoredBerlinBlock(t *testing.T, datadir string, block *big.Int) common.Hash {
t.Helper()
path := filepath.Join(datadir, "XDC", "chaindata")
db := openTestChainDB(t, path)
defer db.Close()
genesisHash := rawdb.ReadCanonicalHash(db, 0)
if genesisHash == (common.Hash{}) {
t.Fatal("expected canonical genesis hash")
}
config, err := rawdb.ReadChainConfig(db, genesisHash)
if err != nil {
t.Fatalf("failed to read chain config: %v", err)
}
if config == nil {
t.Fatal("expected stored chain config")
}
config.BerlinBlock = common.CloneBigInt(block)
rawdb.WriteChainConfig(db, genesisHash, config)
return genesisHash
}
// overwriteStoredEIP150Block updates the stored EIP150 activation block in the
// test chain config.
func overwriteStoredEIP150Block(t *testing.T, datadir string, block *big.Int) common.Hash {
t.Helper()
path := filepath.Join(datadir, "XDC", "chaindata")
db := openTestChainDB(t, path)
defer db.Close()
genesisHash := rawdb.ReadCanonicalHash(db, 0)
if genesisHash == (common.Hash{}) {
t.Fatal("expected canonical genesis hash")
}
config, err := rawdb.ReadChainConfig(db, genesisHash)
if err != nil {
t.Fatalf("failed to read chain config: %v", err)
}
if config == nil {
t.Fatal("expected stored chain config")
}
config.EIP150Block = common.CloneBigInt(block)
rawdb.WriteChainConfig(db, genesisHash, config)
return genesisHash
}
// injectCanonicalHeadBlock inserts a synthetic canonical head block into the
// test datadir.
func injectCanonicalHeadBlock(t *testing.T, datadir string, genesisHash common.Hash, number uint64) common.Hash {
t.Helper()
path := filepath.Join(datadir, "XDC", "chaindata")
db := openTestChainDB(t, path)
genesis := rawdb.ReadBlock(db, genesisHash, 0)
if genesis == nil {
db.Close()
t.Fatal("expected stored genesis block")
}
root := genesis.Root()
if err := db.Close(); err != nil {
t.Fatalf("failed to close test database: %v", err)
}
return injectCanonicalHeadBlockWithRoot(t, datadir, genesisHash, number, root)
}
// injectCanonicalHeadBlockWithRoot inserts a synthetic canonical head block
// into the test datadir with the provided state root.
func injectCanonicalHeadBlockWithRoot(t *testing.T, datadir string, genesisHash common.Hash, number uint64, root common.Hash) common.Hash {
t.Helper()
path := filepath.Join(datadir, "XDC", "chaindata")
db := openTestChainDB(t, path)
defer db.Close()
genesis := rawdb.ReadBlock(db, genesisHash, 0)
if genesis == nil {
t.Fatal("expected stored genesis block")
}
head := types.NewBlockWithHeader(&types.Header{
Number: new(big.Int).SetUint64(number),
ParentHash: genesisHash,
Root: root,
Time: genesis.Time() + number,
GasLimit: genesis.GasLimit(),
Difficulty: genesis.Difficulty(),
})
rawdb.WriteTd(db, head.Hash(), number, new(big.Int).Add(genesis.Difficulty(), big.NewInt(int64(number))))
rawdb.WriteBlock(db, head)
rawdb.WriteCanonicalHash(db, head.Hash(), number)
rawdb.WriteHeadHeaderHash(db, head.Hash())
rawdb.WriteHeadBlockHash(db, head.Hash())
rawdb.WriteHeadFastBlockHash(db, head.Hash())
return head.Hash()
}
// deleteStoredGenesisState removes the persisted genesis trie node and returns
// the genesis hash and root.
func deleteStoredGenesisState(t *testing.T, datadir string) (common.Hash, common.Hash) {
t.Helper()
path := filepath.Join(datadir, "XDC", "chaindata")
db := openTestChainDB(t, path)
defer db.Close()
genesisHash := rawdb.ReadCanonicalHash(db, 0)
if genesisHash == (common.Hash{}) {
t.Fatal("expected canonical genesis hash")
}
genesis := rawdb.ReadBlock(db, genesisHash, 0)
if genesis == nil {
t.Fatal("expected stored genesis block")
}
rawdb.DeleteLegacyTrieNode(db, genesis.Root())
return genesisHash, genesis.Root()
}
// copyDir copies a test datadir while skipping lock files.
func copyDir(t *testing.T, src, dst string) {
t.Helper()
if err := filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
rel, err := filepath.Rel(src, path)
if err != nil {
return err
}
target := filepath.Join(dst, rel)
if info.IsDir() {
return os.MkdirAll(target, info.Mode())
}
if info.Name() == "LOCK" {
return nil
}
in, err := os.Open(path)
if err != nil {
return err
}
defer in.Close()
out, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, info.Mode())
if err != nil {
return err
}
defer out.Close()
if _, err := io.Copy(out, in); err != nil {
return err
}
return out.Close()
}); err != nil {
t.Fatalf("failed to copy %s to %s: %v", src, dst, err)
}
}
// TestInitRejectsBadGenesisConfigAtStartup tests init rejects bad genesis config at startup.
func TestInitRejectsBadGenesisConfigAtStartup(t *testing.T) {
datadir := t.TempDir()
json := filepath.Join(datadir, "genesis.json")
badConfig := strings.Replace(daoFutureForkConfig,
`"trc21IssuerSMC" : "0x8c0faeb5C6bEd2129b8674F262Fd45c4e9468bee",`,
`"trc21IssuerSMC" : "0x0000000000000000000000000000000000000000",`, 1)
if err := os.WriteFile(json, []byte(startupTestGenesis(badConfig)), 0600); err != nil {
t.Fatalf("failed to write genesis file: %v", err)
}
cmd := runXDC(t, "init", "--datadir", datadir, json)
assertCommandFailsWithChainConfigErrors(t, cmd,
"invalid chain config: missing fork switch: TRC21IssuerSMC",
"ensure the persisted chain config or external genesis JSON includes TIPTRC21FeeBlock, Gas50xBlock",
)
assertNoCanonicalGenesis(t, datadir)
}
// TestInitAcceptsSameHashCustomConfigOnEmptyDatadir tests init accepts same hash custom config on empty datadir.
func TestInitAcceptsSameHashCustomConfigOnEmptyDatadir(t *testing.T) {
datadir := t.TempDir()
jsonPath := filepath.Join(datadir, "genesis.json")
genesis := core.DefaultTestnetGenesisBlock()
genesis.Config = genesis.Config.Clone()
genesis.Config.ChainID = big.NewInt(99999)
rawGenesis, err := json.Marshal(genesis)
if err != nil {
t.Fatalf("failed to marshal genesis file: %v", err)
}
if err := os.WriteFile(jsonPath, rawGenesis, 0600); err != nil {
t.Fatalf("failed to write genesis file: %v", err)
}
cmd := runXDC(t, "--allow-builtin-config-override", "init", "--datadir", datadir, jsonPath)
assertCommandSucceeds(t, cmd)
genesisHash, config := readStoredChainConfig(t, datadir)
if genesisHash != params.TestnetGenesisHash {
t.Fatalf("unexpected hash: have %s want %s", genesisHash.Hex(), params.TestnetGenesisHash.Hex())
}
if config.ChainID == nil || config.ChainID.Cmp(big.NewInt(99999)) != 0 {
t.Fatalf("expected persisted custom chain id, have %v", config.ChainID)
}
path := filepath.Join(datadir, "XDC", "chaindata")
db, err := rawdb.NewLevelDBDatabase(path, 0, 0, "", false)
if err != nil {
t.Fatalf("failed to reopen test database: %v", err)
}
defer db.Close()
marker, err := rawdb.ReadChainConfigOverride(db, genesisHash)
if err != nil {
t.Fatalf("failed to read override marker: %v", err)
}
if !marker {
t.Fatal("expected same-hash custom config override marker")
}
}
// TestStartupUsesPersistedSameHashCustomConfig tests startup uses persisted same hash custom config.
func TestStartupUsesPersistedSameHashCustomConfig(t *testing.T) {
datadir := t.TempDir()
jsonPath := filepath.Join(datadir, "genesis.json")
genesis := core.DefaultTestnetGenesisBlock()
genesis.Config = genesis.Config.Clone()
genesis.Config.ChainID = big.NewInt(99999)
rawGenesis, err := json.Marshal(genesis)
if err != nil {
t.Fatalf("failed to marshal genesis file: %v", err)
}
if err := os.WriteFile(jsonPath, rawGenesis, 0600); err != nil {
t.Fatalf("failed to write genesis file: %v", err)
}
initCmd := runXDC(t, "--allow-builtin-config-override", "init", "--datadir", datadir, jsonPath)
assertCommandSucceeds(t, initCmd)
startupCmd := runXDC(t,
"--allow-builtin-config-override", "console", "--port", "0", "--maxpeers", "0", "--nodiscover", "--nat", "none", "--ipcdisable",
"--datadir", datadir, "--exec", "2+2",
)
assertCommandSucceeds(t, startupCmd)
genesisHash, config := readStoredChainConfig(t, datadir)
if genesisHash != params.TestnetGenesisHash {
t.Fatalf("unexpected hash: have %s want %s", genesisHash.Hex(), params.TestnetGenesisHash.Hex())
}
if config.ChainID == nil || config.ChainID.Cmp(big.NewInt(99999)) != 0 {
t.Fatalf("expected persisted custom chain id after restart, have %v", config.ChainID)
}
}
func TestInitRejectsSameHashCustomOverrideWithoutBuiltinConfigOverrideFlag(t *testing.T) {
datadir := t.TempDir()
jsonPath := filepath.Join(datadir, "genesis.json")
genesis := core.DefaultTestnetGenesisBlock()
genesis.Config = genesis.Config.Clone()
genesis.Config.ChainID = big.NewInt(99999)
rawGenesis, err := json.Marshal(genesis)
if err != nil {
t.Fatalf("failed to marshal genesis file: %v", err)
}
if err := os.WriteFile(jsonPath, rawGenesis, 0600); err != nil {
t.Fatalf("failed to write genesis file: %v", err)
}
cmd := runXDC(t, "init", "--datadir", datadir, jsonPath)
assertCommandFailsWithChainConfigErrors(t, cmd,
"provided genesis config conflicts with built-in chain config",
"same-hash custom overrides on built-in networks require --allow-builtin-config-override",
)
}
func TestStartupRejectsPersistedSameHashCustomConfigWithoutBuiltinConfigOverrideFlag(t *testing.T) {
datadir := t.TempDir()
jsonPath := filepath.Join(datadir, "genesis.json")
genesis := core.DefaultTestnetGenesisBlock()
genesis.Config = genesis.Config.Clone()
genesis.Config.ChainID = big.NewInt(99999)
rawGenesis, err := json.Marshal(genesis)
if err != nil {
t.Fatalf("failed to marshal genesis file: %v", err)
}
if err := os.WriteFile(jsonPath, rawGenesis, 0600); err != nil {
t.Fatalf("failed to write genesis file: %v", err)
}
initCmd := runXDC(t, "--allow-builtin-config-override", "init", "--datadir", datadir, jsonPath)
assertCommandSucceeds(t, initCmd)
startupCmd := runXDC(t,
"console", "--port", "0", "--maxpeers", "0", "--nodiscover", "--nat", "none", "--ipcdisable",
"--datadir", datadir, "--exec", "2+2",
)
assertCommandFailsWithChainConfigErrors(t, startupCmd,
"provided genesis config conflicts with built-in chain config",
"same-hash custom overrides on built-in networks require --allow-builtin-config-override",
)
}
// TestStartupPreservesSameHashCustomConfigWithTestnetFlag tests startup preserves same hash custom config with testnet flag.
func TestStartupPreservesSameHashCustomConfigWithTestnetFlag(t *testing.T) {
datadir := t.TempDir()
jsonPath := filepath.Join(datadir, "genesis.json")
genesis := core.DefaultTestnetGenesisBlock()
genesis.Config = genesis.Config.Clone()
genesis.Config.ChainID = big.NewInt(99999)
rawGenesis, err := json.Marshal(genesis)
if err != nil {
t.Fatalf("failed to marshal genesis file: %v", err)
}
if err := os.WriteFile(jsonPath, rawGenesis, 0600); err != nil {
t.Fatalf("failed to write genesis file: %v", err)
}
initCmd := runXDC(t, "--allow-builtin-config-override", "init", "--datadir", datadir, jsonPath)
assertCommandSucceeds(t, initCmd)
startupCmd := runXDC(t,
"--allow-builtin-config-override", "--testnet", "console", "--port", "0", "--maxpeers", "0", "--nodiscover", "--nat", "none", "--ipcdisable",
"--datadir", datadir, "--exec", "2+2",
)
assertCommandSucceeds(t, startupCmd)
genesisHash, config := readStoredChainConfig(t, datadir)
if genesisHash != params.TestnetGenesisHash {
t.Fatalf("unexpected hash: have %s want %s", genesisHash.Hex(), params.TestnetGenesisHash.Hex())
}
if config.ChainID == nil || config.ChainID.Cmp(big.NewInt(99999)) != 0 {
t.Fatalf("expected --testnet startup to preserve persisted custom chain id, have %v", config.ChainID)
}
}
// TestLegacySameHashCustomConfigRequiresExplicitInitMigration tests operator
// startup must fail on a legacy pre-marker same-hash custom database until a
// writable init path is run with the matching explicit genesis.
func TestLegacySameHashCustomConfigRequiresExplicitInitMigration(t *testing.T) {
datadir := t.TempDir()
jsonPath := filepath.Join(datadir, "genesis.json")
startupCmd := runXDC(t,
"--testnet", "console", "--port", "0", "--maxpeers", "0", "--nodiscover", "--nat", "none", "--ipcdisable",
"--datadir", datadir, "--exec", "2+2",
)
assertCommandSucceeds(t, startupCmd)
path := filepath.Join(datadir, "XDC", "chaindata")
db, err := rawdb.NewLevelDBDatabase(path, 0, 0, "", false)
if err != nil {
t.Fatalf("failed to open test database: %v", err)
}
legacyGenesis := core.DefaultTestnetGenesisBlock()
legacyGenesis.Config = legacyGenesis.Config.Clone()
legacyGenesis.Config.ChainID = big.NewInt(99999)
rawdb.WriteChainConfig(db, params.TestnetGenesisHash, legacyGenesis.Config)
if err := db.Close(); err != nil {
t.Fatalf("failed to close test database: %v", err)
}
db, err = rawdb.NewLevelDBDatabase(path, 0, 0, "", false)
if err != nil {
t.Fatalf("failed to reopen test database: %v", err)
}
marker, err := rawdb.ReadChainConfigOverride(db, params.TestnetGenesisHash)
if err != nil {
t.Fatalf("failed to read override marker: %v", err)
}
if marker {
t.Fatal("did not expect override marker before explicit migration")
}
if err := db.Close(); err != nil {
t.Fatalf("failed to close test database after marker check: %v", err)
}
failingStartupCmd := runXDC(t,
"console", "--port", "0", "--maxpeers", "0", "--nodiscover", "--nat", "none", "--ipcdisable",
"--datadir", datadir, "--exec", "2+2",
)
assertCommandFailsWithChainConfigError(t, failingStartupCmd, "provided genesis config conflicts with built-in chain config")
rawGenesis, err := json.Marshal(legacyGenesis)
if err != nil {
t.Fatalf("failed to marshal legacy genesis file: %v", err)
}
if err := os.WriteFile(jsonPath, rawGenesis, 0600); err != nil {
t.Fatalf("failed to write legacy genesis file: %v", err)
}
initCmd := runXDC(t, "--allow-builtin-config-override", "init", "--datadir", datadir, jsonPath)
assertCommandSucceeds(t, initCmd)
genesisHash, config := readStoredChainConfig(t, datadir)
if genesisHash != params.TestnetGenesisHash {
t.Fatalf("unexpected hash after migration: have %s want %s", genesisHash.Hex(), params.TestnetGenesisHash.Hex())
}
if config.ChainID == nil || config.ChainID.Cmp(legacyGenesis.Config.ChainID) != 0 {
t.Fatalf("expected migrated custom chain id, have %v want %v", config.ChainID, legacyGenesis.Config.ChainID)
}
db, err = rawdb.NewLevelDBDatabase(path, 0, 0, "", false)
if err != nil {
t.Fatalf("failed to reopen test database after migration: %v", err)
}
marker, err = rawdb.ReadChainConfigOverride(db, genesisHash)
if err != nil {
t.Fatalf("failed to read override marker after migration: %v", err)
}
if !marker {
t.Fatal("expected explicit init migration to persist override marker")
}
if err := db.Close(); err != nil {
t.Fatalf("failed to close test database after migration check: %v", err)
}
postMigrationStartupCmd := runXDC(t,
"--allow-builtin-config-override", "console", "--port", "0", "--maxpeers", "0", "--nodiscover", "--nat", "none", "--ipcdisable",
"--datadir", datadir, "--exec", "2+2",
)
assertCommandSucceeds(t, postMigrationStartupCmd)
}
// TestStartupRejectsStoredBadChainConfig tests startup rejects stored bad chain config.
func TestStartupRejectsStoredBadChainConfig(t *testing.T) {
datadir := t.TempDir()
json := filepath.Join(datadir, "genesis.json")
if err := os.WriteFile(json, []byte(startupTestGenesis(daoFutureForkConfig)), 0600); err != nil {
t.Fatalf("failed to write genesis file: %v", err)
}
initCmd := runXDC(t, "init", "--datadir", datadir, json)
initCmd.WaitExit()
if status := initCmd.ExitStatus(); status != 0 {
t.Fatalf("expected init to succeed, exit=%d stderr=%q", status, initCmd.StderrText())
}
overwriteStoredIssuer(t, datadir, common.Address{})
startupCmd := runXDC(t,
"console", "--port", "0", "--maxpeers", "0", "--nodiscover", "--nat", "none", "--ipcdisable",
"--datadir", datadir, "--exec", "2+2",
)
assertCommandFailsWithChainConfigErrors(t, startupCmd,
"invalid chain config: missing fork switch: TRC21IssuerSMC",
"ensure the persisted chain config or external genesis JSON includes TIPTRC21FeeBlock, Gas50xBlock",
)
}
// TestOfflineExportRejectsStoredBuiltInChainConfigDrift tests offline export rejects stored built in chain config drift.
func TestOfflineExportRejectsStoredBuiltInChainConfigDrift(t *testing.T) {
datadir := t.TempDir()
exportFile := filepath.Join(datadir, "chain.rlp")
startupCmd := runXDC(t,
"--testnet", "console", "--port", "0", "--maxpeers", "0", "--nodiscover", "--nat", "none", "--ipcdisable",
"--datadir", datadir, "--exec", "2+2",
)
startupCmd.WaitExit()
if status := startupCmd.ExitStatus(); status != 0 {
t.Fatalf("expected testnet startup to succeed, exit=%d stderr=%q", status, startupCmd.StderrText())
}
overwriteStoredIssuer(t, datadir, common.Address{})
exportCmd := runXDC(t, "--datadir", datadir, "--testnet", "export", exportFile)
assertCommandFailsWithChainConfigError(t, exportCmd, "provided genesis config conflicts with built-in chain config")
if _, err := os.Stat(exportFile); err == nil {
t.Fatalf("expected export to fail without creating %s", exportFile)
} else if !os.IsNotExist(err) {
t.Fatalf("failed to stat export file: %v", err)
}
}
// TestOfflineExportAllowsMissingStoredBuiltInChainConfig tests offline export allows missing stored built in chain config.
func TestOfflineExportAllowsMissingStoredBuiltInChainConfig(t *testing.T) {
sourceDatadir := t.TempDir()
startTestnetConsole(t, sourceDatadir)
deleteStoredChainConfig(t, sourceDatadir)
exportDatadir := t.TempDir()
copyDir(t, sourceDatadir, exportDatadir)
exportFile := filepath.Join(exportDatadir, "chain.rlp")
exportCmd := runXDC(t, "--datadir", exportDatadir, "--testnet", "export", exportFile)
assertCommandSucceeds(t, exportCmd)
if _, err := os.Stat(exportFile); err != nil {
t.Fatalf("expected export file to exist, stat failed: %v", err)
}
}
// TestOfflineExportRejectsMissingStoredChainConfigForSameHashCustomOverride tests offline export rejects missing stored chain config for same hash custom override.
func TestOfflineExportRejectsMissingStoredChainConfigForSameHashCustomOverride(t *testing.T) {
datadir := t.TempDir()
jsonPath := filepath.Join(datadir, "genesis.json")
exportFile := filepath.Join(datadir, "chain.rlp")
genesis := core.DefaultTestnetGenesisBlock()
genesis.Config = genesis.Config.Clone()
genesis.Config.ChainID = big.NewInt(99999)
rawGenesis, err := json.Marshal(genesis)
if err != nil {
t.Fatalf("failed to marshal genesis file: %v", err)
}
if err := os.WriteFile(jsonPath, rawGenesis, 0600); err != nil {
t.Fatalf("failed to write genesis file: %v", err)
}
initCmd := runXDC(t, "--allow-builtin-config-override", "init", "--datadir", datadir, jsonPath)
assertCommandSucceeds(t, initCmd)
deleteStoredChainConfig(t, datadir)
exportCmd := runXDC(t, "--allow-builtin-config-override", "--datadir", datadir, "export", exportFile)
assertCommandFailsWithChainConfigError(t, exportCmd, "genesis config conflict")
if _, err := os.Stat(exportFile); err == nil {
t.Fatalf("expected export to fail without creating %s", exportFile)
} else if !os.IsNotExist(err) {
t.Fatalf("failed to stat export file: %v", err)
}
}
// TestOfflineExportUsesStoredSameHashCustomOverrideWithoutBuiltinConfigOverrideFlag
// tests readonly export can reuse an authoritative stored same-hash custom
// override without re-requiring the writable recovery flag.
func TestOfflineExportUsesStoredSameHashCustomOverrideWithoutBuiltinConfigOverrideFlag(t *testing.T) {
datadir := t.TempDir()
jsonPath := filepath.Join(datadir, "genesis.json")
exportFile := filepath.Join(datadir, "chain.rlp")
genesis := core.DefaultTestnetGenesisBlock()
genesis.Config = genesis.Config.Clone()
genesis.Config.ChainID = big.NewInt(99999)
rawGenesis, err := json.Marshal(genesis)
if err != nil {
t.Fatalf("failed to marshal genesis file: %v", err)
}
if err := os.WriteFile(jsonPath, rawGenesis, 0600); err != nil {
t.Fatalf("failed to write genesis file: %v", err)
}
initCmd := runXDC(t, "--allow-builtin-config-override", "init", "--datadir", datadir, jsonPath)
assertCommandSucceeds(t, initCmd)
exportCmd := runXDC(t, "--datadir", datadir, "--testnet", "export", exportFile)
assertCommandSucceeds(t, exportCmd)
if _, err := os.Stat(exportFile); err != nil {
t.Fatalf("expected export file to exist, stat failed: %v", err)
}
if info, err := os.Stat(exportFile); err != nil {
t.Fatalf("failed to stat export file: %v", err)
} else if info.Size() == 0 {
t.Fatalf("expected exported chain data in %s", exportFile)
}
}
// TestOfflineExportFailsReadonlyGenesisStateRecoveryWithoutMutation tests offline export fails readonly genesis state recovery without mutation.
func TestOfflineExportFailsReadonlyGenesisStateRecoveryWithoutMutation(t *testing.T) {
sourceDatadir := t.TempDir()
startupCmd := runXDC(t,
"--testnet", "console", "--port", "0", "--maxpeers", "0", "--nodiscover", "--nat", "none", "--ipcdisable",
"--datadir", sourceDatadir, "--exec", "2+2",
)
assertCommandSucceeds(t, startupCmd)
exportDatadir := t.TempDir()
copyDir(t, sourceDatadir, exportDatadir)
exportFile := filepath.Join(exportDatadir, "chain.rlp")
genesisHash, genesisRoot := deleteStoredGenesisState(t, exportDatadir)
exportCmd := runXDC(t, "--datadir", exportDatadir, "--testnet", "export", exportFile)
assertCommandFailsWithChainConfigError(t, exportCmd, "Can't open blockchain in readonly mode: genesis state is missing and requires recovery. Reopen the database in writable mode to recover the missing genesis state, then retry.")
if _, err := os.Stat(exportFile); err == nil {
t.Fatalf("expected export to fail without creating %s", exportFile)
} else if !os.IsNotExist(err) {
t.Fatalf("failed to stat export file: %v", err)
}
path := filepath.Join(exportDatadir, "XDC", "chaindata")
db, err := rawdb.NewLevelDBDatabase(path, 0, 0, "", false)
if err != nil {
t.Fatalf("failed to open test database: %v", err)
}
defer db.Close()
if got := rawdb.ReadCanonicalHash(db, 0); got != genesisHash {
t.Fatalf("expected canonical genesis hash to remain unchanged: have %s want %s", got.Hex(), genesisHash.Hex())
}
if _, err := state.New(genesisRoot, state.NewDatabase(db)); err == nil {
t.Fatal("expected failed readonly export to leave genesis state missing")
}
}
// TestOfflineExportFailsReadonlyConfigRewindWithoutMutation tests offline export fails readonly config rewind without mutation.
func TestOfflineExportFailsReadonlyConfigRewindWithoutMutation(t *testing.T) {
datadir := t.TempDir()
exportFile := filepath.Join(datadir, "chain.rlp")
startTestnetConsole(t, datadir)
genesisHash := overwriteStoredBerlinBlock(t, datadir, big.NewInt(100))
injectedHeadHash := injectCanonicalHeadBlock(t, datadir, genesisHash, 101)
exportCmd := runXDC(t, "--datadir", datadir, "--testnet", "export", exportFile)
assertCommandFailsWithChainConfigErrors(
t,
exportCmd,
"Can't open blockchain: mismatching",
cmdutils.ChainConfigMismatchPolicyExitHint,
)
if _, err := os.Stat(exportFile); err == nil {
t.Fatalf("expected export to fail without creating %s", exportFile)
} else if !os.IsNotExist(err) {
t.Fatalf("failed to stat export file: %v", err)
}
path := filepath.Join(datadir, "XDC", "chaindata")
db := openTestChainDB(t, path)
defer db.Close()
if got := rawdb.ReadCanonicalHash(db, 0); got != genesisHash {
t.Fatalf("expected canonical genesis hash to remain unchanged: have %s want %s", got.Hex(), genesisHash.Hex())
}
if got := rawdb.ReadHeadBlockHash(db); got != injectedHeadHash {
t.Fatalf("expected failed readonly export to leave head hash unchanged: have %s want %s", got.Hex(), injectedHeadHash.Hex())
}
config, err := rawdb.ReadChainConfig(db, genesisHash)
if err != nil {
t.Fatalf("failed to read stored chain config: %v", err)
}
if config == nil {
t.Fatal("expected stored chain config")
}
if config.BerlinBlock == nil || config.BerlinBlock.Cmp(big.NewInt(100)) != 0 {
t.Fatalf("expected failed readonly export to leave drifted BerlinBlock unchanged: have %v want 100", config.BerlinBlock)
}
}
// TestOfflineExportFailsReadonlyHeadStateRepairWithoutMutation tests offline
// export fails readonly startup when the current head state is missing.
func TestOfflineExportFailsReadonlyHeadStateRepairWithoutMutation(t *testing.T) {
datadir := t.TempDir()
exportFile := filepath.Join(datadir, "chain.rlp")
startTestnetConsole(t, datadir)
genesisHash, _ := readStoredChainConfig(t, datadir)
missingRoot := common.HexToHash("0x1234")
injectedHeadHash := injectCanonicalHeadBlockWithRoot(t, datadir, genesisHash, 1, missingRoot)
exportCmd := runXDC(t, "--datadir", datadir, "--testnet", "export", exportFile)
assertCommandFailsWithChainConfigError(t, exportCmd, "Can't open blockchain in readonly mode: head state is missing and requires repair. Reopen the database in writable mode to repair the missing head state, then retry.")
if _, err := os.Stat(exportFile); err == nil {
t.Fatalf("expected export to fail without creating %s", exportFile)
} else if !os.IsNotExist(err) {
t.Fatalf("failed to stat export file: %v", err)
}
path := filepath.Join(datadir, "XDC", "chaindata")
db := openTestChainDB(t, path)
defer db.Close()
if got := rawdb.ReadHeadBlockHash(db); got != injectedHeadHash {
t.Fatalf("expected failed readonly export to leave head hash unchanged: have %s want %s", got.Hex(), injectedHeadHash.Hex())
}
if _, err := state.New(missingRoot, state.NewDatabase(db)); err == nil {
t.Fatal("expected failed readonly export to leave head state missing")
}
}
// TestOfflineExportFailsReadonlyConfigRewindToZeroWithoutMutation tests
// offline export still fails readonly startup when the required rewind target is
// zero.
func TestOfflineExportFailsReadonlyConfigRewindToZeroWithoutMutation(t *testing.T) {
datadir := t.TempDir()
exportFile := filepath.Join(datadir, "chain.rlp")
startTestnetConsole(t, datadir)
genesisHash := overwriteStoredEIP150Block(t, datadir, big.NewInt(1))
injectedHeadHash := injectCanonicalHeadBlock(t, datadir, genesisHash, 1)
exportCmd := runXDC(t, "--datadir", datadir, "--testnet", "export", exportFile)
assertCommandFailsWithChainConfigErrors(
t,
exportCmd,
"Can't open blockchain: mismatching",
cmdutils.ChainConfigMismatchPolicyExitHint,
)
if _, err := os.Stat(exportFile); err == nil {
t.Fatalf("expected export to fail without creating %s", exportFile)
} else if !os.IsNotExist(err) {
t.Fatalf("failed to stat export file: %v", err)
}
path := filepath.Join(datadir, "XDC", "chaindata")
db := openTestChainDB(t, path)
defer db.Close()
if got := rawdb.ReadCanonicalHash(db, 0); got != genesisHash {
t.Fatalf("expected canonical genesis hash to remain unchanged: have %s want %s", got.Hex(), genesisHash.Hex())
}
if got := rawdb.ReadHeadBlockHash(db); got != injectedHeadHash {
t.Fatalf("expected failed readonly export to leave head hash unchanged: have %s want %s", got.Hex(), injectedHeadHash.Hex())
}
config, err := rawdb.ReadChainConfig(db, genesisHash)
if err != nil {
t.Fatalf("failed to read stored chain config: %v", err)
}
if config == nil {
t.Fatal("expected stored chain config")
}
if config.EIP150Block == nil || config.EIP150Block.Cmp(big.NewInt(1)) != 0 {
t.Fatalf("expected failed readonly export to leave drifted EIP150Block unchanged: have %v want 1", config.EIP150Block)
}
}
// TestStartupRewindsStoredBuiltInHistoricalForkDrift tests startup rewinds stored built in historical fork drift.
func TestStartupRewindsStoredBuiltInHistoricalForkDrift(t *testing.T) {
datadir := t.TempDir()
startTestnetConsole(t, datadir)
genesisHash := overwriteStoredBerlinBlock(t, datadir, big.NewInt(100))
injectedHeadHash := injectCanonicalHeadBlock(t, datadir, genesisHash, 101)
startTestnetConsole(t, datadir, "--chain-config-mismatch-policy", "rewind-and-update")
path := filepath.Join(datadir, "XDC", "chaindata")
db := openTestChainDB(t, path)
defer db.Close()
config, err := rawdb.ReadChainConfig(db, genesisHash)
if err != nil {
t.Fatalf("failed to read chain config: %v", err)
}
if config == nil {
t.Fatal("expected stored chain config")
}
if config.BerlinBlock == nil || config.BerlinBlock.Cmp(params.TestnetChainConfig.BerlinBlock) != 0 {
t.Fatalf("expected BerlinBlock to be restored to bundled testnet value %v, have %v", params.TestnetChainConfig.BerlinBlock, config.BerlinBlock)
}