Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions cmd/XDC/chaincmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,15 +189,16 @@ func initGenesis(ctx *cli.Context) error {
}

// Open and initialise both full and light databases
stack, _ := makeConfigNode(ctx)
stack, cfg := makeConfigNode(ctx)
defer stack.Close()

name := "chaindata"
chaindb, err := stack.OpenDatabase(name, 0, 0, "", false)
if err != nil {
utils.Fatalf("Failed to open database: %v", err)
}
_, hash, compatErr, err := core.SetupGenesisBlockWithOverride(chaindb, genesis, ctx.Bool(utils.AllowBuiltInConfigOverrideFlag.Name))
policy := utils.ResolveChainConfigMismatchPolicyOrFatal(ctx, cfg.Eth.ChainConfigMismatchPolicy)
_, hash, compatErr, err := core.SetupGenesisBlockWithPolicy(chaindb, genesis, ctx.Bool(utils.AllowBuiltInConfigOverrideFlag.Name), policy)
if err != nil {
utils.Fatalf("Failed to write genesis block: %s", utils.FormatChainConfigError(err))
}
Expand Down
165 changes: 165 additions & 0 deletions cmd/XDC/genesis_startup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,31 @@ func overwriteStoredBerlinBlock(t *testing.T, datadir string, block *big.Int) co
return genesisHash
}

// overwriteStoredPragueBlock updates the stored Prague activation block in the
// test chain config.
func overwriteStoredPragueBlock(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.PragueBlock = 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 {
Expand Down Expand Up @@ -1103,3 +1128,143 @@ func TestStartupRewindsStoredBuiltInConfigDriftToZero(t *testing.T) {
t.Fatalf("expected rewind-to-zero startup to reset head to genesis: have %s want %s", got.Hex(), genesisHash.Hex())
}
}

// TestStartupAdoptsStoredBuiltInFutureForkDrift tests that a testnet datadir
// whose stored config carries a stale bundled fork schedule starts again under
// update-config-only, and that the bundled config is persisted without moving
// the head.
func TestStartupAdoptsStoredBuiltInFutureForkDrift(t *testing.T) {
datadir := t.TempDir()

startTestnetConsole(t, datadir)

genesisHash := overwriteStoredPragueBlock(t, datadir, big.NewInt(99999999))
injectedHeadHash := injectCanonicalHeadBlock(t, datadir, genesisHash, 1)

startTestnetConsole(t, datadir, "--chain-config-mismatch-policy", "update-config-only")

_, config := readStoredChainConfig(t, datadir)
if config.PragueBlock == nil || config.PragueBlock.Cmp(params.TestnetChainConfig.PragueBlock) != 0 {
t.Fatalf("expected PragueBlock to be adopted as the bundled value %v, have %v", params.TestnetChainConfig.PragueBlock, config.PragueBlock)
}

path := filepath.Join(datadir, "XDC", "chaindata")
db := openTestChainDB(t, path)
defer db.Close()

if got := rawdb.ReadHeadBlockHash(db); got != injectedHeadHash {
t.Fatalf("expected the head to stay at %s, have %s", injectedHeadHash.Hex(), got.Hex())
}
}

// TestInitAdoptsStoredBuiltInFutureForkDrift tests that XDC init threads the
// startup policy too, so the repair remains available from that entry point.
func TestInitAdoptsStoredBuiltInFutureForkDrift(t *testing.T) {
datadir := t.TempDir()

startTestnetConsole(t, datadir)

genesisHash := overwriteStoredPragueBlock(t, datadir, big.NewInt(99999999))
injectedHeadHash := injectCanonicalHeadBlock(t, datadir, genesisHash, 1)

initCmd := runXDC(t,
"--chain-config-mismatch-policy", "update-config-only",
"init", "--datadir", datadir, "testnet",
)
assertCommandSucceeds(t, initCmd)

_, config := readStoredChainConfig(t, datadir)
if config.PragueBlock == nil || config.PragueBlock.Cmp(params.TestnetChainConfig.PragueBlock) != 0 {
t.Fatalf("expected init to adopt the bundled PragueBlock %v, have %v", params.TestnetChainConfig.PragueBlock, config.PragueBlock)
}

path := filepath.Join(datadir, "XDC", "chaindata")
db := openTestChainDB(t, path)
defer db.Close()

if got := rawdb.ReadHeadBlockHash(db); got != injectedHeadHash {
t.Fatalf("expected init to leave the head at %s, have %s", injectedHeadHash.Hex(), got.Hex())
}
}

// TestInitKeepsStoredBuiltInDriftUnderIgnoreMismatch tests that the genesis-only
// repair path honors the no-write contract of ignore-mismatch: init still runs,
// but the stored drift is left in place.
func TestInitKeepsStoredBuiltInDriftUnderIgnoreMismatch(t *testing.T) {
datadir := t.TempDir()

startTestnetConsole(t, datadir)

overwriteStoredPragueBlock(t, datadir, big.NewInt(99999999))

initCmd := runXDC(t,
"--chain-config-mismatch-policy", "ignore-mismatch",
"init", "--datadir", datadir, "testnet",
)
assertCommandSucceeds(t, initCmd)

_, config := readStoredChainConfig(t, datadir)
if config.PragueBlock == nil || config.PragueBlock.Cmp(big.NewInt(99999999)) != 0 {
t.Fatalf("expected init to keep the stored PragueBlock 99999999, have %v", config.PragueBlock)
}
}

// TestStartupKeepsStoredBuiltInFutureForkDriftConflictByDefault pins the
// default policy on the same fixture and checks the conflict names the policy.
func TestStartupKeepsStoredBuiltInFutureForkDriftConflictByDefault(t *testing.T) {
datadir := t.TempDir()

startTestnetConsole(t, datadir)

genesisHash := overwriteStoredPragueBlock(t, datadir, big.NewInt(99999999))
injectCanonicalHeadBlock(t, datadir, genesisHash, 1)

startupCmd := runXDC(t,
"--testnet", "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",
"--chain-config-mismatch-policy=update-config-only",
)
}

// TestOfflineExportAdoptsStoredBuiltInFutureForkDrift tests that the readonly
// export path adopts the bundled config under update-config-only without
// writing it back.
func TestOfflineExportAdoptsStoredBuiltInFutureForkDrift(t *testing.T) {
datadir := t.TempDir()
exportFile := filepath.Join(datadir, "chain.rlp")

startTestnetConsole(t, datadir)

genesisHash := overwriteStoredPragueBlock(t, datadir, big.NewInt(99999999))
injectedHeadHash := injectCanonicalHeadBlock(t, datadir, genesisHash, 1)

exportCmd := runXDC(t,
"--datadir", datadir, "--testnet",
"--chain-config-mismatch-policy", "update-config-only",
"export", exportFile,
)
assertCommandSucceeds(t, exportCmd)

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 stored chain config: %v", err)
}
if config == nil {
t.Fatal("expected stored chain config")
}
if config.PragueBlock == nil || config.PragueBlock.Cmp(big.NewInt(99999999)) != 0 {
t.Fatalf("expected readonly export to leave the drifted PragueBlock unchanged, have %v", config.PragueBlock)
}
if got := rawdb.ReadHeadBlockHash(db); got != injectedHeadHash {
t.Fatalf("expected readonly export to leave the head at %s, have %s", injectedHeadHash.Hex(), got.Hex())
}
}
12 changes: 9 additions & 3 deletions cmd/utils/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ var (
}
AllowBuiltInConfigOverrideFlag = &cli.BoolFlag{
Name: "allow-builtin-config-override",
Usage: "Allow same-hash custom overrides on built-in IDs to use custom chain config",
Usage: "Allow same-hash custom overrides on built-in IDs to use custom chain config (does not adopt an updated builtin config)",
Category: flags.EthCategory,
}
ChainConfigMismatchPolicyFlag = &cli.StringFlag{
Expand Down Expand Up @@ -1987,12 +1987,12 @@ func MakeChain(ctx *cli.Context, stack *node.Node, readonly bool, configuredComp
// Readonly startup still needs compatibility metadata so chain open can
// surface ErrReadOnlyConfigRewind instead of collapsing rewindable config
// drift into a generic config conflict.
config, ghash, compatErr, err = core.LoadChainConfigWithCompatWithOverride(chainDb, gspec, ctx.Bool(AllowBuiltInConfigOverrideFlag.Name))
config, ghash, compatErr, err = core.LoadChainConfigWithCompatWithPolicy(chainDb, gspec, ctx.Bool(AllowBuiltInConfigOverrideFlag.Name), compatPolicy)
if err != nil {
makeChainFatalf("%s", FormatChainConfigError(err))
}
} else {
config, ghash, compatErr, err = core.SetupGenesisBlockWithOverride(chainDb, gspec, ctx.Bool(AllowBuiltInConfigOverrideFlag.Name))
config, ghash, compatErr, err = core.SetupGenesisBlockWithPolicy(chainDb, gspec, ctx.Bool(AllowBuiltInConfigOverrideFlag.Name), compatPolicy)
if err != nil {
makeChainFatalf("%s", FormatChainConfigError(err))
}
Expand Down Expand Up @@ -2055,6 +2055,12 @@ func resolveChainConfigMismatchPolicyOrFatal(ctx *cli.Context, configured string
return policy
}

// ResolveChainConfigMismatchPolicyOrFatal exposes the validated startup policy
// to commands that resolve startup metadata outside MakeChain.
func ResolveChainConfigMismatchPolicyOrFatal(ctx *cli.Context, configured string) core.ChainConfigMismatchPolicy {
return core.ChainConfigMismatchPolicy(resolveChainConfigMismatchPolicyOrFatal(ctx, configured))
}

// MakeConsolePreloads retrieves the absolute paths for the console JavaScript
// scripts to preload before starting.
func MakeConsolePreloads(ctx *cli.Context) []string {
Expand Down
71 changes: 67 additions & 4 deletions core/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,13 +143,26 @@ func builtInNetworkName(hash common.Hash) string {
}
}

// builtInGenesisConfigConflictError wraps built-in conflicts with remediation guidance.
// builtInGenesisConfigConflictError wraps same-hash custom override conflicts
// with remediation guidance.
func builtInGenesisConfigConflictError(hash common.Hash) error {
cfg := builtInChainConfigByHash(hash)
if cfg == nil {
return errGenesisConfigConflict
}
return fmt.Errorf("%w: same-hash custom overrides on built-in networks require --allow-builtin-config-override; builtin=%s chainId=%d; repair by starting from a fresh datadir: delete chaindata and reinitialize with the intended genesis, or rerun with --allow-builtin-config-override using the matching explicit genesis", errGenesisConfigConflict, builtInNetworkName(hash), cfg.ChainID)
return fmt.Errorf("%w: same-hash custom overrides on built-in networks require --allow-builtin-config-override; builtin=%s chainId=%d; repair by starting from a fresh datadir: delete chaindata and reinitialize with the intended genesis, or rerun with --allow-builtin-config-override", errGenesisConfigConflict, builtInNetworkName(hash), cfg.ChainID)
}

// builtInStoredDriftConflictError wraps a stored built-in config that differs
// from the bundled one, naming only the remediations that can change the
// outcome. --allow-builtin-config-override is deliberately not one of them: it
// keeps a custom config, it does not adopt an updated bundled one.
func builtInStoredDriftConflictError(hash common.Hash) error {
cfg := builtInChainConfigByHash(hash)
if cfg == nil {
return errGenesisConfigConflict
}
return fmt.Errorf("%w: the stored chain config for builtin=%s chainId=%d differs from this binary's bundled config and was left untouched; adopt the bundled config with --chain-config-mismatch-policy=update-config-only (or rewind-and-update; no rewind is required while every changed fork is above the head), or delete the ethereum-config-%s blob and restart so it is rebuilt from the bundled genesis. --allow-builtin-config-override does not apply: it keeps a same-hash custom config, it does not adopt an updated bundled one", errGenesisConfigConflict, builtInNetworkName(hash), cfg.ChainID, hash.Hex())
}

// resolveProvidedChainConfig resolves a caller-supplied chain config for the
Expand Down Expand Up @@ -490,31 +503,81 @@ func annotateResolvedCustomBuiltInConfig(hash common.Hash, cfg *params.ChainConf
}
}

// builtInDriftPolicy is the operator-authorized disposition of a stored
// built-in config that differs from the bundled one.
type builtInDriftPolicy uint8

const (
// builtInDriftReject keeps the terminal conflict: unmarked drift may be an
// intentionally maintained same-hash custom config.
builtInDriftReject builtInDriftPolicy = iota
// builtInDriftAdopt replaces the stored config with the bundled one and
// persists it.
builtInDriftAdopt
// builtInDriftAdoptInMemory runs with the bundled config but leaves the
// stored blob untouched, mirroring ignore-mismatch.
builtInDriftAdoptInMemory
)

// builtInDriftPolicyFor maps the startup mismatch policy onto built-in drift.
// Only policies that already let the resolved runtime config win authorize the
// adoption; exit keeps the conflict, ignore-mismatch never writes.
func builtInDriftPolicyFor(policy ChainConfigMismatchPolicy) builtInDriftPolicy {
switch NormalizeChainConfigMismatchPolicy(policy) {
case MismatchUpdateConfigOnly, MismatchRewindAndUpdate:
return builtInDriftAdopt
case MismatchIgnoreMismatch:
return builtInDriftAdoptInMemory
default:
return builtInDriftReject
}
}

type builtInChainConfigFacts struct {
hasBuiltInConfig bool
trustedOverride bool
storedMatchesBuiltIn bool
candidateMatchesBuiltIn bool
allowStoredDriftRepair bool
driftPolicy builtInDriftPolicy
}

type builtInChainConfigAction struct {
canonicalizeToBuiltIn bool
persistCanonical bool
terminalError error
}

// decideBuiltInChainConfigAction resolves built-in canonicalization vs conflict outcomes.
// The drift policy only releases the stored-versus-bundled conflict: a
// candidate that itself differs from the bundled config stays terminal, so no
// policy can discard an explicit custom genesis.
func decideBuiltInChainConfigAction(facts builtInChainConfigFacts) builtInChainConfigAction {
if !facts.hasBuiltInConfig || facts.trustedOverride {
return builtInChainConfigAction{}
}
if !facts.candidateMatchesBuiltIn {
return builtInChainConfigAction{terminalError: startup.ErrGenesisConfigConflict}
}
if facts.storedMatchesBuiltIn || facts.allowStoredDriftRepair {
if facts.storedMatchesBuiltIn {
return builtInChainConfigAction{canonicalizeToBuiltIn: true, persistCanonical: true}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
// Genesis-only repair still persists for the default and adopting policies;
// ignore-mismatch must never write.
if facts.allowStoredDriftRepair {
return builtInChainConfigAction{
canonicalizeToBuiltIn: true,
persistCanonical: facts.driftPolicy != builtInDriftAdoptInMemory,
}
}
switch facts.driftPolicy {
case builtInDriftAdopt:
return builtInChainConfigAction{canonicalizeToBuiltIn: true, persistCanonical: true}
case builtInDriftAdoptInMemory:
return builtInChainConfigAction{canonicalizeToBuiltIn: true}
default:
return builtInChainConfigAction{terminalError: startup.ErrGenesisConfigConflict}
}
return builtInChainConfigAction{terminalError: startup.ErrGenesisConfigConflict}
}

// normalizeProvidedGenesisConfig clones and normalizes a caller-provided genesis config.
Expand Down
Loading