diff --git a/cmd/devp2p/internal/ethtest/chain.go b/cmd/devp2p/internal/ethtest/chain.go index 83ceb2a4f2c5..f4db05db8e39 100644 --- a/cmd/devp2p/internal/ethtest/chain.go +++ b/cmd/devp2p/internal/ethtest/chain.go @@ -76,7 +76,7 @@ func (c *Chain) RootAt(height int) common.Hash { // ForkID gets the fork id of the chain. func (c *Chain) ForkID() forkid.ID { - return forkid.NewID(c.chainConfig, c.blocks[0].Hash(), uint64(c.Len())) + return forkid.NewID(c.chainConfig, c.blocks[0].Hash(), uint64(c.Len()), c.blocks[0].Time()) } // Shorten returns a copy chain of a desired height from the imported diff --git a/core/blockchain.go b/core/blockchain.go index f9b92192cc7d..8204812cb816 100644 --- a/core/blockchain.go +++ b/core/blockchain.go @@ -315,7 +315,7 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, genesis *Genesis if diskRoot != (common.Hash{}) { log.Warn("Head state missing, repairing", "number", head.Number(), "hash", head.Hash(), "snaproot", diskRoot) - snapDisk, err := bc.setHeadBeyondRoot(head.NumberU64(), diskRoot, true) + snapDisk, err := bc.setHeadBeyondRoot(head.NumberU64(), 0, diskRoot, true) if err != nil { return nil, err } @@ -325,7 +325,7 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, genesis *Genesis } } else { log.Warn("Head state missing, repairing", "number", head.Number(), "hash", head.Hash()) - if _, err := bc.setHeadBeyondRoot(head.NumberU64(), common.Hash{}, true); err != nil { + if _, err := bc.setHeadBeyondRoot(head.NumberU64(), 0, common.Hash{}, true); err != nil { return nil, err } } @@ -424,7 +424,11 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, genesis *Genesis // Rewind the chain in case of an incompatible config upgrade. if compat, ok := genesisErr.(*params.ConfigCompatError); ok { log.Warn("Rewinding chain to upgrade configuration", "err", compat) - bc.SetHead(compat.RewindTo) + if compat.RewindToTime > 0 { + bc.SetHeadWithTimestamp(compat.RewindToTime) + } else { + bc.SetHead(compat.RewindToBlock) + } rawdb.WriteChainConfig(db, genesisHash, chainConfig) } // Start tx indexer/unindexer if required. @@ -529,7 +533,16 @@ func (bc *BlockChain) loadLastState() error { // was fast synced or full synced and in which state, the method will try to // delete minimal data from disk whilst retaining chain consistency. func (bc *BlockChain) SetHead(head uint64) error { - _, err := bc.setHeadBeyondRoot(head, common.Hash{}, false) + _, err := bc.setHeadBeyondRoot(head, 0, common.Hash{}, false) + return err +} + +// SetHeadWithTimestamp rewinds the local chain to a new head that has at max +// the given timestamp. Depending on whether the node was fast synced or full +// synced and in which state, the method will try to delete minimal data from +// disk whilst retaining chain consistency. +func (bc *BlockChain) SetHeadWithTimestamp(timestamp uint64) error { + _, err := bc.setHeadBeyondRoot(0, timestamp, common.Hash{}, false) return err } @@ -562,8 +575,12 @@ func (bc *BlockChain) SetSafe(block *types.Block) { // in which state, the method will try to delete minimal data from disk whilst // retaining chain consistency. // +// The method also works in timestamp mode if `head == 0` but `time != 0`. In that +// case blocks are rolled back until the new head becomes older or equal to the +// requested time. If both `head` and `time` is 0, the chain is rewound to genesis. +// // The method returns the block number where the requested root cap was found. -func (bc *BlockChain) setHeadBeyondRoot(head uint64, root common.Hash, repair bool) (uint64, error) { +func (bc *BlockChain) setHeadBeyondRoot(head uint64, time uint64, root common.Hash, repair bool) (uint64, error) { if !bc.chainmu.TryLock() { return 0, errChainStopped } @@ -577,7 +594,7 @@ func (bc *BlockChain) setHeadBeyondRoot(head uint64, root common.Hash, repair bo pivot := rawdb.ReadLastPivotNumber(bc.db) frozen, _ := bc.db.Ancients() - updateFn := func(db ethdb.KeyValueWriter, header *types.Header) (uint64, bool) { + updateFn := func(db ethdb.KeyValueWriter, header *types.Header) (*types.Header, bool) { // Rewind the blockchain, ensuring we don't end up with a stateless head // block. Note, depth equality is permitted to allow using SetHead as a // chain reparation mechanism without deleting any data! @@ -658,16 +675,18 @@ func (bc *BlockChain) setHeadBeyondRoot(head uint64, root common.Hash, repair bo bc.currentFastBlock.Store(newHeadFastBlock) headFastBlockGauge.Update(int64(newHeadFastBlock.NumberU64())) } - head := bc.CurrentBlock().NumberU64() - + var ( + headHeader = bc.CurrentBlock().Header() + headNumber = headHeader.Number.Uint64() + ) // If setHead underflown the freezer threshold and the block processing // intent afterwards is full block importing, delete the chain segment // between the stateful-block and the sethead target. var wipe bool - if head+1 < frozen { - wipe = pivot == nil || head >= *pivot + if headNumber+1 < frozen { + wipe = pivot == nil || headNumber >= *pivot } - return head, wipe // Only force wipe if full synced + return headHeader, wipe // Only force wipe if full synced } // Rewind the header chain, deleting all block bodies until then delFn := func(db ethdb.KeyValueWriter, hash common.Hash, num uint64) { @@ -694,13 +713,18 @@ func (bc *BlockChain) setHeadBeyondRoot(head uint64, root common.Hash, repair bo // touching the header chain altogether, unless the freezer is broken if repair { if target, force := updateFn(bc.db, bc.CurrentBlock().Header()); force { - bc.hc.SetHead(target, updateFn, delFn) + bc.hc.SetHead(target.Number.Uint64(), updateFn, delFn) } } else { // Rewind the chain to the requested head and keep going backwards until a // block with a state is found or fast sync pivot is passed - log.Warn("Rewinding blockchain", "target", head) - bc.hc.SetHead(head, updateFn, delFn) + if head != 0 || time == 0 { + log.Warn("Rewinding blockchain to block", "target", head) + bc.hc.SetHead(head, updateFn, delFn) + } else { + log.Warn("Rewinding blockchain to timestamp", "target", time) + bc.hc.SetHeadWithTimestamp(time, updateFn, delFn) + } } // Clear out any stale content from the caches bc.bodyCache.Purge() diff --git a/core/blockchain_test.go b/core/blockchain_test.go index faa4b383feb4..a619ff63a483 100644 --- a/core/blockchain_test.go +++ b/core/blockchain_test.go @@ -4238,7 +4238,7 @@ func TestEIP3651(t *testing.T) { gspec.Config.BerlinBlock = common.Big0 gspec.Config.LondonBlock = common.Big0 - gspec.Config.ShanghaiBlock = common.Big0 + gspec.Config.ShanghaiTime = common.Big0 signer := types.LatestSigner(gspec.Config) _, blocks, _ := GenerateChainWithGenesis(gspec, engine, 1, func(i int, b *BlockGen) { diff --git a/core/forkid/forkid.go b/core/forkid/forkid.go index f56ce85feeed..b35fd92b2aa2 100644 --- a/core/forkid/forkid.go +++ b/core/forkid/forkid.go @@ -24,6 +24,7 @@ import ( "math" "math/big" "reflect" + "sort" "strings" "github.com/ethereum/go-ethereum/common" @@ -65,19 +66,28 @@ type ID struct { // Filter is a fork id filter to validate a remotely advertised ID. type Filter func(id ID) error -// NewID calculates the Ethereum fork ID from the chain config, genesis hash, and head. -func NewID(config *params.ChainConfig, genesis common.Hash, head uint64) ID { +// NewID calculates the Ethereum fork ID from the chain config, genesis hash, head and time. +func NewID(config *params.ChainConfig, genesis common.Hash, head, time uint64) ID { // Calculate the starting checksum from the genesis hash hash := crc32.ChecksumIEEE(genesis[:]) // Calculate the current fork checksum and the next fork block - var next uint64 - for _, fork := range gatherForks(config) { + forks, forksByTime := gatherForks(config) + for _, fork := range forks { if fork <= head { // Fork already passed, checksum the previous hash and the fork number hash = checksumUpdate(hash, fork) continue } + return ID{Hash: checksumToBytes(hash), Next: fork} + } + var next uint64 + for _, fork := range forksByTime { + if time >= fork { + // Fork passed, checksum previous hash and fork time + hash = checksumUpdate(hash, fork) + continue + } next = fork break } @@ -90,6 +100,7 @@ func NewIDWithChain(chain Blockchain) ID { chain.Config(), chain.Genesis().Hash(), chain.CurrentHeader().Number.Uint64(), + chain.CurrentHeader().Time, ) } @@ -99,36 +110,40 @@ func NewFilter(chain Blockchain) Filter { return newFilter( chain.Config(), chain.Genesis().Hash(), - func() uint64 { - return chain.CurrentHeader().Number.Uint64() + func() (uint64, uint64) { + return chain.CurrentHeader().Number.Uint64(), chain.CurrentHeader().Time }, ) } // NewStaticFilter creates a filter at block zero. func NewStaticFilter(config *params.ChainConfig, genesis common.Hash) Filter { - head := func() uint64 { return 0 } + head := func() (uint64, uint64) { return 0, 0 } return newFilter(config, genesis, head) } // newFilter is the internal version of NewFilter, taking closures as its arguments // instead of a chain. The reason is to allow testing it without having to simulate // an entire blockchain. -func newFilter(config *params.ChainConfig, genesis common.Hash, headfn func() uint64) Filter { +func newFilter(config *params.ChainConfig, genesis common.Hash, headfn func() (uint64, uint64)) Filter { // Calculate the all the valid fork hash and fork next combos var ( - forks = gatherForks(config) - sums = make([][4]byte, len(forks)+1) // 0th is the genesis + forks, forksByTime = gatherForks(config) + sums = make([][4]byte, len(forks)+len(forksByTime)+1) // 0th is the genesis ) + allForks := append(forks, forksByTime...) hash := crc32.ChecksumIEEE(genesis[:]) sums[0] = checksumToBytes(hash) - for i, fork := range forks { + for i, fork := range allForks { hash = checksumUpdate(hash, fork) sums[i+1] = checksumToBytes(hash) } // Add two sentries to simplify the fork checks and don't require special // casing the last one. - forks = append(forks, math.MaxUint64) // Last fork will never be passed + if len(forksByTime) == 0 { + forks = append(forks, math.MaxUint64) + } + forksByTime = append(forksByTime, math.MaxUint64) // Last fork will never be passed // Create a validator that will filter out incompatible chains return func(id ID) error { @@ -151,19 +166,14 @@ func newFilter(config *params.ChainConfig, genesis common.Hash, headfn func() ui // the remote, but at this current point in time we don't have enough // information. // 4. Reject in all other cases. - head := headfn() - for i, fork := range forks { - // If our head is beyond this fork, continue to the next (we have a dummy - // fork of maxuint64 as the last item to always fail this check eventually). - if head >= fork { - continue - } + + verify := func(index int, headOrTime uint64) error { // Found the first unpassed fork block, check if our current state matches // the remote checksum (rule #1). - if sums[i] == id.Hash { + if sums[index] == id.Hash { // Fork checksum matched, check if a remote future fork block already passed // locally without the local node being aware of it (rule #1a). - if id.Next > 0 && head >= id.Next { + if id.Next > 0 && headOrTime >= id.Next { return ErrLocalIncompatibleOrStale } // Haven't passed locally a remote-only fork, accept the connection (rule #1b). @@ -171,10 +181,10 @@ func newFilter(config *params.ChainConfig, genesis common.Hash, headfn func() ui } // The local and remote nodes are in different forks currently, check if the // remote checksum is a subset of our local forks (rule #2). - for j := 0; j < i; j++ { + for j := 0; j < index; j++ { if sums[j] == id.Hash { // Remote checksum is a subset, validate based on the announced next fork - if forks[j] != id.Next { + if allForks[j] != id.Next { return ErrRemoteStale } return nil @@ -182,7 +192,7 @@ func newFilter(config *params.ChainConfig, genesis common.Hash, headfn func() ui } // Remote chain is not a subset of our local one, check if it's a superset by // any chance, signalling that we're simply out of sync (rule #3). - for j := i + 1; j < len(sums); j++ { + for j := index + 1; j < len(sums); j++ { if sums[j] == id.Hash { // Yay, remote checksum is a superset, ignore upcoming forks return nil @@ -191,6 +201,27 @@ func newFilter(config *params.ChainConfig, genesis common.Hash, headfn func() ui // No exact, subset or superset match. We are on differing chains, reject. return ErrLocalIncompatibleOrStale } + + head, time := headfn() + // Verify forks by block + for i, fork := range forks { + // If our head is beyond this fork, continue to the next (we have a dummy + // fork of maxuint64 as the last item to always fail this check eventually). + if head >= fork { + continue + } + return verify(i, head) + } + // Verify forks by time + for i, fork := range forksByTime { + // If our head is beyond this fork, continue to the next (we have a dummy + // fork of maxuint64 as the last item to always fail this check eventually). + if time >= fork { + continue + } + return verify(len(forks)+i, time) + } + log.Error("Impossible fork ID validation", "id", id) return nil // Something's very wrong, accept rather than reject } @@ -212,17 +243,22 @@ func checksumToBytes(hash uint32) [4]byte { } // gatherForks gathers all the known forks and creates a sorted list out of them. -func gatherForks(config *params.ChainConfig) []uint64 { +func gatherForks(config *params.ChainConfig) ([]uint64, []uint64) { // Gather all the fork block numbers via reflection kind := reflect.TypeOf(params.ChainConfig{}) conf := reflect.ValueOf(config).Elem() var forks []uint64 + var forksByTime []uint64 for i := 0; i < kind.NumField(); i++ { // Fetch the next field and skip non-fork rules field := kind.Field(i) + time := false if !strings.HasSuffix(field.Name, "Block") { - continue + if !strings.HasSuffix(field.Name, "Time") { + continue + } + time = true } if field.Type != reflect.TypeOf(new(big.Int)) { continue @@ -230,17 +266,17 @@ func gatherForks(config *params.ChainConfig) []uint64 { // Extract the fork rule block number and aggregate it rule := conf.Field(i).Interface().(*big.Int) if rule != nil { - forks = append(forks, rule.Uint64()) - } - } - // Sort the fork block numbers to permit chronological XOR - for i := 0; i < len(forks); i++ { - for j := i + 1; j < len(forks); j++ { - if forks[i] > forks[j] { - forks[i], forks[j] = forks[j], forks[i] + if time { + forksByTime = append(forksByTime, rule.Uint64()) + } else { + forks = append(forks, rule.Uint64()) } } } + + sort.Slice(forks, func(i, j int) bool { return forks[i] < forks[j] }) + sort.Slice(forksByTime, func(i, j int) bool { return forksByTime[i] < forksByTime[j] }) + // Deduplicate block numbers applying multiple forks for i := 1; i < len(forks); i++ { if forks[i] == forks[i-1] { @@ -248,9 +284,18 @@ func gatherForks(config *params.ChainConfig) []uint64 { i-- } } + for i := 1; i < len(forksByTime); i++ { + if forksByTime[i] == forksByTime[i-1] { + forksByTime = append(forksByTime[:i], forksByTime[i+1:]...) + i-- + } + } // Skip any forks in block 0, that's the genesis ruleset if len(forks) > 0 && forks[0] == 0 { forks = forks[1:] } - return forks + if len(forksByTime) > 0 && forksByTime[0] == 0 { + forksByTime = forksByTime[1:] + } + return forks, forksByTime } diff --git a/core/forkid/forkid_test.go b/core/forkid/forkid_test.go index 2a0fb167d516..0158545f345e 100644 --- a/core/forkid/forkid_test.go +++ b/core/forkid/forkid_test.go @@ -185,7 +185,105 @@ func TestCreation(t *testing.T) { } for i, tt := range tests { for j, ttt := range tt.cases { - if have := NewID(tt.config, tt.genesis, ttt.head); have != ttt.want { + if have := NewID(tt.config, tt.genesis, ttt.head, 0); have != ttt.want { + t.Errorf("test %d, case %d: fork ID mismatch: have %x, want %x", i, j, have, ttt.want) + } + } + } +} + +// TestCreationWithTimestamps tests that different genesis and fork rule combinations result in +// the correct fork ID even for time based forks. +func TestCreationWithTimestamps(t *testing.T) { + mergeConfig := *params.MainnetChainConfig + mergeConfig.MergeNetsplitBlock = big.NewInt(18000000) + + withdrawalConfig := *params.MainnetChainConfig + withdrawalConfig.MergeNetsplitBlock = big.NewInt(18000000) + withdrawalConfig.ShanghaiTime = big.NewInt(1668000000) + type testcase struct { + head uint64 + time uint64 + want ID + } + tests := []struct { + config *params.ChainConfig + genesis common.Hash + cases []testcase + }{ + // Mainnet test cases + { + params.MainnetChainConfig, + params.MainnetGenesisHash, + []testcase{ + {0, 0, ID{Hash: checksumToBytes(0xfc64ec04), Next: 1150000}}, // Unsynced + {1149999, 0, ID{Hash: checksumToBytes(0xfc64ec04), Next: 1150000}}, // Last Frontier block + {1150000, 0, ID{Hash: checksumToBytes(0x97c2c34c), Next: 1920000}}, // First Homestead block + {1919999, 0, ID{Hash: checksumToBytes(0x97c2c34c), Next: 1920000}}, // Last Homestead block + {1920000, 0, ID{Hash: checksumToBytes(0x91d1f948), Next: 2463000}}, // First DAO block + {2462999, 0, ID{Hash: checksumToBytes(0x91d1f948), Next: 2463000}}, // Last DAO block + {2463000, 0, ID{Hash: checksumToBytes(0x7a64da13), Next: 2675000}}, // First Tangerine block + {2674999, 0, ID{Hash: checksumToBytes(0x7a64da13), Next: 2675000}}, // Last Tangerine block + {2675000, 0, ID{Hash: checksumToBytes(0x3edd5b10), Next: 4370000}}, // First Spurious block + {4369999, 0, ID{Hash: checksumToBytes(0x3edd5b10), Next: 4370000}}, // Last Spurious block + {4370000, 0, ID{Hash: checksumToBytes(0xa00bc324), Next: 7280000}}, // First Byzantium block + {7279999, 0, ID{Hash: checksumToBytes(0xa00bc324), Next: 7280000}}, // Last Byzantium block + {7280000, 0, ID{Hash: checksumToBytes(0x668db0af), Next: 9069000}}, // First and last Constantinople, first Petersburg block + {9068999, 0, ID{Hash: checksumToBytes(0x668db0af), Next: 9069000}}, // Last Petersburg block + {9069000, 0, ID{Hash: checksumToBytes(0x879d6e30), Next: 9200000}}, // First Istanbul and first Muir Glacier block + {9199999, 0, ID{Hash: checksumToBytes(0x879d6e30), Next: 9200000}}, // Last Istanbul and first Muir Glacier block + {9200000, 0, ID{Hash: checksumToBytes(0xe029e991), Next: 12244000}}, // First Muir Glacier block + {12243999, 0, ID{Hash: checksumToBytes(0xe029e991), Next: 12244000}}, // Last Muir Glacier block + {12244000, 0, ID{Hash: checksumToBytes(0x0eb440f6), Next: 12965000}}, // First Berlin block + {12964999, 0, ID{Hash: checksumToBytes(0x0eb440f6), Next: 12965000}}, // Last Berlin block + {12965000, 0, ID{Hash: checksumToBytes(0xb715077d), Next: 13773000}}, // First London block + {13772999, 0, ID{Hash: checksumToBytes(0xb715077d), Next: 13773000}}, // Last London block + {13773000, 0, ID{Hash: checksumToBytes(0x20c327fc), Next: 15050000}}, // First Arrow Glacier block + {15049999, 0, ID{Hash: checksumToBytes(0x20c327fc), Next: 15050000}}, // Last Arrow Glacier block + {15050000, 0, ID{Hash: checksumToBytes(0xf0afd0e3), Next: 0}}, // First Gray Glacier block + {20000000, 0, ID{Hash: checksumToBytes(0xf0afd0e3), Next: 0}}, // Future Gray Glacier block + }, + }, + // Withdrawal test cases + { + &withdrawalConfig, + params.MainnetGenesisHash, + []testcase{ + {0, 0, ID{Hash: checksumToBytes(0xfc64ec04), Next: 1150000}}, // Unsynced + {1149999, 0, ID{Hash: checksumToBytes(0xfc64ec04), Next: 1150000}}, // Last Frontier block + {1150000, 0, ID{Hash: checksumToBytes(0x97c2c34c), Next: 1920000}}, // First Homestead block + {1919999, 0, ID{Hash: checksumToBytes(0x97c2c34c), Next: 1920000}}, // Last Homestead block + {1920000, 0, ID{Hash: checksumToBytes(0x91d1f948), Next: 2463000}}, // First DAO block + {2462999, 0, ID{Hash: checksumToBytes(0x91d1f948), Next: 2463000}}, // Last DAO block + {2463000, 0, ID{Hash: checksumToBytes(0x7a64da13), Next: 2675000}}, // First Tangerine block + {2674999, 0, ID{Hash: checksumToBytes(0x7a64da13), Next: 2675000}}, // Last Tangerine block + {2675000, 0, ID{Hash: checksumToBytes(0x3edd5b10), Next: 4370000}}, // First Spurious block + {4369999, 0, ID{Hash: checksumToBytes(0x3edd5b10), Next: 4370000}}, // Last Spurious block + {4370000, 0, ID{Hash: checksumToBytes(0xa00bc324), Next: 7280000}}, // First Byzantium block + {7279999, 0, ID{Hash: checksumToBytes(0xa00bc324), Next: 7280000}}, // Last Byzantium block + {7280000, 0, ID{Hash: checksumToBytes(0x668db0af), Next: 9069000}}, // First and last Constantinople, first Petersburg block + {9068999, 0, ID{Hash: checksumToBytes(0x668db0af), Next: 9069000}}, // Last Petersburg block + {9069000, 0, ID{Hash: checksumToBytes(0x879d6e30), Next: 9200000}}, // First Istanbul and first Muir Glacier block + {9199999, 0, ID{Hash: checksumToBytes(0x879d6e30), Next: 9200000}}, // Last Istanbul and first Muir Glacier block + {9200000, 0, ID{Hash: checksumToBytes(0xe029e991), Next: 12244000}}, // First Muir Glacier block + {12243999, 0, ID{Hash: checksumToBytes(0xe029e991), Next: 12244000}}, // Last Muir Glacier block + {12244000, 0, ID{Hash: checksumToBytes(0x0eb440f6), Next: 12965000}}, // First Berlin block + {12964999, 0, ID{Hash: checksumToBytes(0x0eb440f6), Next: 12965000}}, // Last Berlin block + {12965000, 0, ID{Hash: checksumToBytes(0xb715077d), Next: 13773000}}, // First London block + {13772999, 0, ID{Hash: checksumToBytes(0xb715077d), Next: 13773000}}, // Last London block + {13773000, 0, ID{Hash: checksumToBytes(0x20c327fc), Next: 15050000}}, // First Arrow Glacier block + {15049999, 0, ID{Hash: checksumToBytes(0x20c327fc), Next: 15050000}}, // Last Arrow Glacier block + {15050000, 0, ID{Hash: checksumToBytes(0xf0afd0e3), Next: 18000000}}, // First Gray Glacier block + {18000000, 0, ID{Hash: checksumToBytes(0x4fb8a872), Next: 1668000000}}, // First Merge Start block + {20000000, 0, ID{Hash: checksumToBytes(0x4fb8a872), Next: 1668000000}}, // Last Merge Start block + {20000000, 1668000000, ID{Hash: checksumToBytes(0xc1fdf181), Next: 0}}, // First Merge Start block + {20000000, 2668000000, ID{Hash: checksumToBytes(0xc1fdf181), Next: 0}}, // Future Merge Start block + }, + }, + } + for i, tt := range tests { + for j, ttt := range tt.cases { + if have := NewID(tt.config, tt.genesis, ttt.head, ttt.time); have != ttt.want { t.Errorf("test %d, case %d: fork ID mismatch: have %x, want %x", i, j, have, ttt.want) } } @@ -267,7 +365,93 @@ func TestValidation(t *testing.T) { {7279999, ID{Hash: checksumToBytes(0xa00bc324), Next: 7279999}, ErrLocalIncompatibleOrStale}, } for i, tt := range tests { - filter := newFilter(params.MainnetChainConfig, params.MainnetGenesisHash, func() uint64 { return tt.head }) + filter := newFilter(params.MainnetChainConfig, params.MainnetGenesisHash, func() (uint64, uint64) { return tt.head, 0 }) + if err := filter(tt.id); err != tt.err { + t.Errorf("test %d: validation error mismatch: have %v, want %v", i, err, tt.err) + } + } +} + +// TestValidationByTimestamp tests that a local peer correctly validates and accepts a remote +// fork ID. +func TestValidationByTimestamp(t *testing.T) { + withdrawalConfig := *params.MainnetChainConfig + withdrawalConfig.MergeNetsplitBlock = big.NewInt(18000000) + withdrawalConfig.ShanghaiTime = big.NewInt(1668000000) + tests := []struct { + head uint64 + time uint64 + id ID + err error + }{ + // Local is mainnet Withdrawals, remote announces the same. No future fork is announced. + {20000000, 1668000001, ID{Hash: checksumToBytes(0xc1fdf181), Next: 0}, nil}, + + // Local is mainnet Withdrawals, remote announces the same also announces a next fork + // at block/time 0xffffffff, but that is uncertain. + {20000000, 1668000001, ID{Hash: checksumToBytes(0xc1fdf181), Next: math.MaxUint64}, nil}, + + // Local is mainnet currently in Byzantium only (so it's aware of Petersburg & Withdrawals), remote announces + // also Byzantium, but it's not yet aware of Petersburg (e.g. non updated node before the fork). + // In this case we don't know if Petersburg passed yet or not. + {7279999, 1667999999, ID{Hash: checksumToBytes(0xa00bc324), Next: 0}, nil}, + + // Local is mainnet currently in Byzantium only (so it's aware of Petersburg & Withdrawals), remote announces + // also Byzantium, and it's also aware of Petersburg (e.g. updated node before the fork). We + // don't know if Petersburg passed yet (will pass) or not. + {7279999, 1667999999, ID{Hash: checksumToBytes(0xa00bc324), Next: 7280000}, nil}, + + // Local is mainnet currently in Byzantium only (so it's aware of Petersburg & Withdrawals), remote announces + // also Byzantium, and it's also aware of some random fork (e.g. misconfigured Petersburg). As + // neither forks passed at neither nodes, they may mismatch, but we still connect for now. + {7279999, 1667999999, ID{Hash: checksumToBytes(0xa00bc324), Next: math.MaxUint64}, nil}, + + // Local is mainnet exactly on Withdrawals, remote announces Byzantium + knowledge about Petersburg. Remote + // is simply out of sync, accept. + {20000000, 1668000000, ID{Hash: checksumToBytes(0xa00bc324), Next: 7280000}, nil}, + + // Local is mainnet Withdrawals, remote announces Byzantium + knowledge about Petersburg. Remote + // is simply out of sync, accept. + {20000000, 1668000001, ID{Hash: checksumToBytes(0xa00bc324), Next: 7280000}, nil}, + + // Local is mainnet Withdrawals, remote announces Spurious + knowledge about Byzantium. Remote + // is definitely out of sync. It may or may not need the Petersburg update, we don't know yet. + {20000000, 1668000001, ID{Hash: checksumToBytes(0x3edd5b10), Next: 4370000}, nil}, + + // Local is mainnet Byzantium & pre-withdrawals, remote announces Petersburg. Local is out of sync, accept. + {7279999, 1667999999, ID{Hash: checksumToBytes(0x668db0af), Next: 0}, nil}, + + // Local is mainnet Spurious, remote announces Byzantium, but is not aware of Petersburg. Local + // out of sync. Local also knows about a future fork, but that is uncertain yet. + {4369999, 1667999999, ID{Hash: checksumToBytes(0xa00bc324), Next: 0}, nil}, + + // Local is mainnet Withdrawals. remote announces Byzantium but is not aware of further forks. + // Remote needs software update. + {20000000, 1668000001, ID{Hash: checksumToBytes(0xa00bc324), Next: 0}, ErrRemoteStale}, + + // Local is mainnet Withdrawals, and isn't aware of more forks. Remote announces Petersburg + + // 0xffffffff. Local needs software update, reject. + {20000000, 1668000001, ID{Hash: checksumToBytes(0x5cddc0e1), Next: 0}, ErrLocalIncompatibleOrStale}, + + // Local is mainnet Withdrawals, and is aware of Petersburg. Remote announces Petersburg + + // 0xffffffff. Local needs software update, reject. + {20000000, 1668000001, ID{Hash: checksumToBytes(0x5cddc0e1), Next: 0}, ErrLocalIncompatibleOrStale}, + + // Local is mainnet Withdrawals, remote is Rinkeby Petersburg. + {20000000, 1668000001, ID{Hash: checksumToBytes(0xafec6b27), Next: 0}, ErrLocalIncompatibleOrStale}, + + // Local is mainnet Withdrawals, far in the future. Remote announces Gopherium (non existing fork) + // at some future block 88888888, for itself, but past block for local. Local is incompatible. + // + // This case detects non-upgraded nodes with majority hash power (typical Ropsten mess). + {88888888, 1668000001, ID{Hash: checksumToBytes(0xf0afd0e3), Next: 88888888}, ErrRemoteStale}, + + // Local is mainnet Withdrawals. Remote is in Byzantium, but announces Gopherium (non existing + // fork) at block 7279999, before Petersburg. Local is incompatible. + {20000000, 1668000001, ID{Hash: checksumToBytes(0xa00bc324), Next: 7279999}, ErrRemoteStale}, + } + for i, tt := range tests { + filter := newFilter(&withdrawalConfig, params.MainnetGenesisHash, func() (uint64, uint64) { return tt.head, tt.time }) if err := filter(tt.id); err != tt.err { t.Errorf("test %d: validation error mismatch: have %v, want %v", i, err, tt.err) } diff --git a/core/genesis.go b/core/genesis.go index bbfa356af9f4..e1d7778bbb86 100644 --- a/core/genesis.go +++ b/core/genesis.go @@ -371,12 +371,12 @@ func SetupGenesisBlockWithOverride(db ethdb.Database, triedb *trie.Database, gen } // Check config compatibility and write the config. Compatibility errors // are returned to the caller unless we're already at block zero. - height := rawdb.ReadHeaderNumber(db, rawdb.ReadHeadHeaderHash(db)) - if height == nil { - return newcfg, stored, fmt.Errorf("missing block number for head header hash") + head := rawdb.ReadHeadHeader(db) + if head == nil { + return newcfg, stored, fmt.Errorf("missing head header") } - compatErr := storedcfg.CheckCompatible(newcfg, *height) - if compatErr != nil && *height != 0 && compatErr.RewindTo != 0 { + compatErr := storedcfg.CheckCompatible(newcfg, head.Number.Uint64(), head.Time) + if compatErr != nil && ((head.Number.Uint64() != 0 && compatErr.RewindToBlock != 0) || (head.Time != 0 && compatErr.RewindToTime != 0)) { return newcfg, stored, compatErr } // Don't overwrite if the old is identical to the new diff --git a/core/genesis_test.go b/core/genesis_test.go index 135ecb934c03..d7030a201ec4 100644 --- a/core/genesis_test.go +++ b/core/genesis_test.go @@ -132,10 +132,10 @@ func TestSetupGenesis(t *testing.T) { wantHash: customghash, wantConfig: customg.Config, wantErr: ¶ms.ConfigCompatError{ - What: "Homestead fork block", - StoredConfig: big.NewInt(2), - NewConfig: big.NewInt(3), - RewindTo: 1, + What: "Homestead fork block", + StoredBlock: big.NewInt(2), + NewBlock: big.NewInt(3), + RewindToBlock: 1, }, }, } diff --git a/core/headerchain.go b/core/headerchain.go index 482b5f6fbe91..ba8f550a8c86 100644 --- a/core/headerchain.go +++ b/core/headerchain.go @@ -556,7 +556,7 @@ type ( // before head header is updated. The method will return the actual block it // updated the head to (missing state) and a flag if setHead should continue // rewinding till that forcefully (exceeded ancient limits) - UpdateHeadBlocksCallback func(ethdb.KeyValueWriter, *types.Header) (uint64, bool) + UpdateHeadBlocksCallback func(ethdb.KeyValueWriter, *types.Header) (*types.Header, bool) // DeleteBlockContentCallback is a callback function that is called by SetHead // before each header is deleted. @@ -566,15 +566,33 @@ type ( // SetHead rewinds the local chain to a new head. Everything above the new head // will be deleted and the new one set. func (hc *HeaderChain) SetHead(head uint64, updateFn UpdateHeadBlocksCallback, delFn DeleteBlockContentCallback) { + hc.setHead(head, 0, updateFn, delFn) +} + +// SetHeadWithTimestamp rewinds the local chain to a new head timestamp. Everything +// above the new head will be deleted and the new one set. +func (hc *HeaderChain) SetHeadWithTimestamp(time uint64, updateFn UpdateHeadBlocksCallback, delFn DeleteBlockContentCallback) { + hc.setHead(0, time, updateFn, delFn) +} + +// setHead rewinds the local chain to a new head block or a head timestamp. +// Everything above the new head will be deleted and the new one set. +func (hc *HeaderChain) setHead(headBlock uint64, headTime uint64, updateFn UpdateHeadBlocksCallback, delFn DeleteBlockContentCallback) { var ( parentHash common.Hash batch = hc.chainDb.NewBatch() origin = true ) - for hdr := hc.CurrentHeader(); hdr != nil && hdr.Number.Uint64() > head; hdr = hc.CurrentHeader() { + done := func(header *types.Header) bool { + if headBlock != 0 || headTime == 0 { + return header.Number.Uint64() <= headBlock + } + return header.Time <= headTime + } + for hdr := hc.CurrentHeader(); hdr != nil && !done(hdr); hdr = hc.CurrentHeader() { num := hdr.Number.Uint64() - // Rewind block chain to new head. + // Rewind chain to new head parent := hc.GetHeader(hdr.ParentHash, num-1) if parent == nil { parent = hc.genesisHeader @@ -591,9 +609,9 @@ func (hc *HeaderChain) SetHead(head uint64, updateFn UpdateHeadBlocksCallback, d markerBatch := hc.chainDb.NewBatch() if updateFn != nil { newHead, force := updateFn(markerBatch, parent) - if force && newHead < head { - log.Warn("Force rewinding till ancient limit", "head", newHead) - head = newHead + if force && ((headTime > 0 && newHead.Time < headTime) || (headTime == 0 && newHead.Number.Uint64() < headBlock)) { + log.Warn("Force rewinding till ancient limit", "head", newHead.Number.Uint64()) + headBlock, headTime = newHead.Number.Uint64(), 0 } } // Update head header then. diff --git a/core/state_transition.go b/core/state_transition.go index a6cf3f7c32d6..797aab3ab3c9 100644 --- a/core/state_transition.go +++ b/core/state_transition.go @@ -300,7 +300,7 @@ func (st *StateTransition) TransitionDb() (*ExecutionResult, error) { var ( msg = st.msg sender = vm.AccountRef(msg.From()) - rules = st.evm.ChainConfig().Rules(st.evm.Context.BlockNumber, st.evm.Context.Random != nil) + rules = st.evm.ChainConfig().Rules(st.evm.Context.BlockNumber, st.evm.Context.Random != nil, st.evm.Context.Time) contractCreation = msg.To() == nil ) diff --git a/core/vm/evm.go b/core/vm/evm.go index b9a9d4636b7b..149e9f761be3 100644 --- a/core/vm/evm.go +++ b/core/vm/evm.go @@ -131,7 +131,7 @@ func NewEVM(blockCtx BlockContext, txCtx TxContext, statedb StateDB, chainConfig StateDB: statedb, Config: config, chainConfig: chainConfig, - chainRules: chainConfig.Rules(blockCtx.BlockNumber, blockCtx.Random != nil), + chainRules: chainConfig.Rules(blockCtx.BlockNumber, blockCtx.Random != nil, blockCtx.Time), } evm.interpreter = NewEVMInterpreter(evm, config) return evm diff --git a/core/vm/runtime/runtime.go b/core/vm/runtime/runtime.go index 6b355deeb6e2..a330825b10d8 100644 --- a/core/vm/runtime/runtime.go +++ b/core/vm/runtime/runtime.go @@ -117,7 +117,7 @@ func Execute(code, input []byte, cfg *Config) ([]byte, *state.StateDB, error) { address = common.BytesToAddress([]byte("contract")) vmenv = NewEnv(cfg) sender = vm.AccountRef(cfg.Origin) - rules = cfg.ChainConfig.Rules(vmenv.Context.BlockNumber, vmenv.Context.Random != nil) + rules = cfg.ChainConfig.Rules(vmenv.Context.BlockNumber, vmenv.Context.Random != nil, vmenv.Context.Time) ) // Execute the preparatory steps for state transition which includes: // - prepare accessList(post-berlin) @@ -151,7 +151,7 @@ func Create(input []byte, cfg *Config) ([]byte, common.Address, uint64, error) { var ( vmenv = NewEnv(cfg) sender = vm.AccountRef(cfg.Origin) - rules = cfg.ChainConfig.Rules(vmenv.Context.BlockNumber, vmenv.Context.Random != nil) + rules = cfg.ChainConfig.Rules(vmenv.Context.BlockNumber, vmenv.Context.Random != nil, vmenv.Context.Time) ) // Execute the preparatory steps for state transition which includes: // - prepare accessList(post-berlin) @@ -180,7 +180,7 @@ func Call(address common.Address, input []byte, cfg *Config) ([]byte, uint64, er vmenv = NewEnv(cfg) sender = cfg.State.GetOrNewStateObject(cfg.Origin) statedb = cfg.State - rules = cfg.ChainConfig.Rules(vmenv.Context.BlockNumber, vmenv.Context.Random != nil) + rules = cfg.ChainConfig.Rules(vmenv.Context.BlockNumber, vmenv.Context.Random != nil, vmenv.Context.Time) ) // Execute the preparatory steps for state transition which includes: // - prepare accessList(post-berlin) diff --git a/eth/handler.go b/eth/handler.go index 143147b0c815..c67a62b86700 100644 --- a/eth/handler.go +++ b/eth/handler.go @@ -331,7 +331,7 @@ func (h *handler) runEthPeer(peer *eth.Peer, handler eth.Handler) error { number = head.Number.Uint64() td = h.chain.GetTd(hash, number) ) - forkID := forkid.NewID(h.chain.Config(), h.chain.Genesis().Hash(), h.chain.CurrentHeader().Number.Uint64()) + forkID := forkid.NewID(h.chain.Config(), h.chain.Genesis().Hash(), h.chain.CurrentHeader().Number.Uint64(), h.chain.CurrentHeader().Time) if err := peer.Handshake(h.networkID, td, hash, genesis.Hash(), forkID, h.forkFilter); err != nil { peer.Log().Debug("Ethereum handshake failed", "err", err) return err diff --git a/eth/protocols/eth/discovery.go b/eth/protocols/eth/discovery.go index 03f2ea3cc297..345c6e5e2768 100644 --- a/eth/protocols/eth/discovery.go +++ b/eth/protocols/eth/discovery.go @@ -60,6 +60,6 @@ func StartENRUpdater(chain *core.BlockChain, ln *enode.LocalNode) { // currentENREntry constructs an `eth` ENR entry based on the current state of the chain. func currentENREntry(chain *core.BlockChain) *enrEntry { return &enrEntry{ - ForkID: forkid.NewID(chain.Config(), chain.Genesis().Hash(), chain.CurrentHeader().Number.Uint64()), + ForkID: forkid.NewID(chain.Config(), chain.Genesis().Hash(), chain.CurrentHeader().Number.Uint64(), chain.CurrentHeader().Time), } } diff --git a/eth/protocols/eth/handshake_test.go b/eth/protocols/eth/handshake_test.go index 8cf5216cf442..c768edaeac01 100644 --- a/eth/protocols/eth/handshake_test.go +++ b/eth/protocols/eth/handshake_test.go @@ -40,7 +40,7 @@ func testHandshake(t *testing.T, protocol uint) { genesis = backend.chain.Genesis() head = backend.chain.CurrentBlock() td = backend.chain.GetTd(head.Hash(), head.NumberU64()) - forkID = forkid.NewID(backend.chain.Config(), backend.chain.Genesis().Hash(), backend.chain.CurrentHeader().Number.Uint64()) + forkID = forkid.NewID(backend.chain.Config(), backend.chain.Genesis().Hash(), backend.chain.CurrentHeader().Number.Uint64(), backend.chain.CurrentHeader().Time) ) tests := []struct { code uint64 diff --git a/eth/tracers/js/goja.go b/eth/tracers/js/goja.go index 9adfca9fb62a..cf27acbb4ab2 100644 --- a/eth/tracers/js/goja.go +++ b/eth/tracers/js/goja.go @@ -242,7 +242,7 @@ func (t *jsTracer) CaptureStart(env *vm.EVM, from common.Address, to common.Addr t.ctx["value"] = valueBig t.ctx["block"] = t.vm.ToValue(env.Context.BlockNumber.Uint64()) // Update list of precompiles based on current block - rules := env.ChainConfig().Rules(env.Context.BlockNumber, env.Context.Random != nil) + rules := env.ChainConfig().Rules(env.Context.BlockNumber, env.Context.Random != nil, env.Context.Time) t.activePrecompiles = vm.ActivePrecompiles(rules) } diff --git a/eth/tracers/native/4byte.go b/eth/tracers/native/4byte.go index 00cd5fe77b8b..afe70ea089aa 100644 --- a/eth/tracers/native/4byte.go +++ b/eth/tracers/native/4byte.go @@ -81,7 +81,7 @@ func (t *fourByteTracer) store(id []byte, size int) { // CaptureStart implements the EVMLogger interface to initialize the tracing operation. func (t *fourByteTracer) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) { // Update list of precompiles based on current block - rules := env.ChainConfig().Rules(env.Context.BlockNumber, env.Context.Random != nil) + rules := env.ChainConfig().Rules(env.Context.BlockNumber, env.Context.Random != nil, env.Context.Time) t.activePrecompiles = vm.ActivePrecompiles(rules) // Save the outer calldata also diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index ea0cbfe867aa..50d690ba9b74 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -1438,7 +1438,7 @@ func AccessList(ctx context.Context, b Backend, blockNrOrHash rpc.BlockNumberOrH } isPostMerge := header.Difficulty.Cmp(common.Big0) == 0 // Retrieve the precompiles since they don't need to be added to the access list - precompiles := vm.ActivePrecompiles(b.ChainConfig().Rules(header.Number, isPostMerge)) + precompiles := vm.ActivePrecompiles(b.ChainConfig().Rules(header.Number, isPostMerge, new(big.Int).SetUint64(header.Time))) // Create an initial tracer prevTracer := logger.NewAccessListTracer(nil, args.from(), to, precompiles) diff --git a/les/client.go b/les/client.go index 7aa4f9b8cc81..3c222f819196 100644 --- a/les/client.go +++ b/les/client.go @@ -179,7 +179,11 @@ func New(stack *node.Node, config *ethconfig.Config) (*LightEthereum, error) { // Rewind the chain in case of an incompatible config upgrade. if compat, ok := genesisErr.(*params.ConfigCompatError); ok { log.Warn("Rewinding chain to upgrade configuration", "err", compat) - leth.blockchain.SetHead(compat.RewindTo) + if compat.RewindToTime > 0 { + leth.blockchain.SetHeadWithTimestamp(compat.RewindToTime) + } else { + leth.blockchain.SetHead(compat.RewindToBlock) + } rawdb.WriteChainConfig(chainDb, genesisHash, chainConfig) } diff --git a/les/client_handler.go b/les/client_handler.go index e416f92e29a9..cce99d41dc14 100644 --- a/les/client_handler.go +++ b/les/client_handler.go @@ -111,7 +111,7 @@ func (h *clientHandler) handle(p *serverPeer, noInitAnnounce bool) error { p.Log().Debug("Light Ethereum peer connected", "name", p.Name()) // Execute the LES handshake - forkid := forkid.NewID(h.backend.blockchain.Config(), h.backend.genesis, h.backend.blockchain.CurrentHeader().Number.Uint64()) + forkid := forkid.NewID(h.backend.blockchain.Config(), h.backend.genesis, h.backend.blockchain.CurrentHeader().Number.Uint64(), h.backend.blockchain.CurrentHeader().Time) if err := p.Handshake(h.backend.blockchain.Genesis().Hash(), forkid, h.forkFilter); err != nil { p.Log().Debug("Light Ethereum handshake failed", "err", err) return err diff --git a/les/peer_test.go b/les/peer_test.go index b8a1482a040a..021d5cb594c4 100644 --- a/les/peer_test.go +++ b/les/peer_test.go @@ -124,8 +124,8 @@ func TestHandshake(t *testing.T) { genesis = common.HexToHash("cafebabe") chain1, chain2 = &fakeChain{}, &fakeChain{} - forkID1 = forkid.NewID(chain1.Config(), chain1.Genesis().Hash(), chain1.CurrentHeader().Number.Uint64()) - forkID2 = forkid.NewID(chain2.Config(), chain2.Genesis().Hash(), chain2.CurrentHeader().Number.Uint64()) + forkID1 = forkid.NewID(chain1.Config(), chain1.Genesis().Hash(), chain1.CurrentHeader().Number.Uint64(), chain1.CurrentHeader().Time) + forkID2 = forkid.NewID(chain2.Config(), chain2.Genesis().Hash(), chain2.CurrentHeader().Number.Uint64(), chain2.CurrentHeader().Time) filter1, filter2 = forkid.NewFilter(chain1), forkid.NewFilter(chain2) ) diff --git a/les/server_handler.go b/les/server_handler.go index 28815c3d85ef..b9fb1d19bfc2 100644 --- a/les/server_handler.go +++ b/les/server_handler.go @@ -117,7 +117,7 @@ func (h *serverHandler) handle(p *clientPeer) error { hash = head.Hash() number = head.Number.Uint64() td = h.blockchain.GetTd(hash, number) - forkID = forkid.NewID(h.blockchain.Config(), h.blockchain.Genesis().Hash(), h.blockchain.CurrentBlock().NumberU64()) + forkID = forkid.NewID(h.blockchain.Config(), h.blockchain.Genesis().Hash(), h.blockchain.CurrentBlock().NumberU64(), h.blockchain.CurrentBlock().Time()) ) if err := p.Handshake(td, hash, number, h.blockchain.Genesis().Hash(), forkID, h.forkFilter, h.server); err != nil { p.Log().Debug("Light Ethereum handshake failed", "err", err) diff --git a/les/test_helper.go b/les/test_helper.go index 33a76252bf05..714bc7b3f625 100644 --- a/les/test_helper.go +++ b/les/test_helper.go @@ -489,7 +489,7 @@ func (client *testClient) newRawPeer(t *testing.T, name string, version int, rec head = client.handler.backend.blockchain.CurrentHeader() td = client.handler.backend.blockchain.GetTd(head.Hash(), head.Number.Uint64()) ) - forkID := forkid.NewID(client.handler.backend.blockchain.Config(), genesis.Hash(), head.Number.Uint64()) + forkID := forkid.NewID(client.handler.backend.blockchain.Config(), genesis.Hash(), head.Number.Uint64(), head.Time) tp.handshakeWithClient(t, td, head.Hash(), head.Number.Uint64(), genesis.Hash(), forkID, testCostList(0), recentTxLookup) // disable flow control by default // Ensure the connection is established or exits when any error occurs @@ -553,7 +553,7 @@ func (server *testServer) newRawPeer(t *testing.T, name string, version int) (*t head = server.handler.blockchain.CurrentHeader() td = server.handler.blockchain.GetTd(head.Hash(), head.Number.Uint64()) ) - forkID := forkid.NewID(server.handler.blockchain.Config(), genesis.Hash(), head.Number.Uint64()) + forkID := forkid.NewID(server.handler.blockchain.Config(), genesis.Hash(), head.Number.Uint64(), head.Time) tp.handshakeWithServer(t, td, head.Hash(), head.Number.Uint64(), genesis.Hash(), forkID) // Ensure the connection is established or exits when any error occurs diff --git a/light/lightchain.go b/light/lightchain.go index 155f7b0c0548..f42c904f57eb 100644 --- a/light/lightchain.go +++ b/light/lightchain.go @@ -178,6 +178,17 @@ func (lc *LightChain) SetHead(head uint64) error { return lc.loadLastState() } +// SetHeadWithTimestamp rewinds the local chain to a new head that has at max +// the given timestamp. Everything above the new head will be deleted and the +// new one set. +func (lc *LightChain) SetHeadWithTimestamp(timestamp uint64) error { + lc.chainmu.Lock() + defer lc.chainmu.Unlock() + + lc.hc.SetHeadWithTimestamp(timestamp, nil, nil) + return lc.loadLastState() +} + // GasLimit returns the gas limit of the current HEAD block. func (lc *LightChain) GasLimit() uint64 { return lc.hc.CurrentHeader().GasLimit diff --git a/params/config.go b/params/config.go index e3e48f9c2597..215c6848a68b 100644 --- a/params/config.go +++ b/params/config.go @@ -281,7 +281,7 @@ var ( TestChainConfig = &ChainConfig{big.NewInt(1), big.NewInt(0), nil, false, big.NewInt(0), common.Hash{}, big.NewInt(0), big.NewInt(0), big.NewInt(0), big.NewInt(0), big.NewInt(0), big.NewInt(0), big.NewInt(0), big.NewInt(0), big.NewInt(0), big.NewInt(0), big.NewInt(0), nil, nil, nil, nil, false, new(EthashConfig), nil} NonActivatedConfig = &ChainConfig{big.NewInt(1), nil, nil, false, nil, common.Hash{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, false, new(EthashConfig), nil} - TestRules = TestChainConfig.Rules(new(big.Int), false) + TestRules = TestChainConfig.Rules(new(big.Int), false, new(big.Int)) ) // NetworkNames are user friendly names to use in the chain spec banner. @@ -371,9 +371,12 @@ type ChainConfig struct { ArrowGlacierBlock *big.Int `json:"arrowGlacierBlock,omitempty"` // Eip-4345 (bomb delay) switch block (nil = no fork, 0 = already activated) GrayGlacierBlock *big.Int `json:"grayGlacierBlock,omitempty"` // Eip-5133 (bomb delay) switch block (nil = no fork, 0 = already activated) MergeNetsplitBlock *big.Int `json:"mergeNetsplitBlock,omitempty"` // Virtual fork after The Merge to use as a network splitter - ShanghaiBlock *big.Int `json:"shanghaiBlock,omitempty"` // Shanghai switch block (nil = no fork, 0 = already on shanghai) CancunBlock *big.Int `json:"cancunBlock,omitempty"` // Cancun switch block (nil = no fork, 0 = already on cancun) + // Fork scheduling was switched from blocks to timestamps here + + ShanghaiTime *big.Int `json:"shanghaiTime,omitempty"` // Shanghai switch time (nil = no fork, 0 = already on shanghai) + // TerminalTotalDifficulty is the amount of total difficulty reached by // the network that triggers the consensus upgrade. TerminalTotalDifficulty *big.Int `json:"terminalTotalDifficulty,omitempty"` @@ -465,9 +468,7 @@ func (c *ChainConfig) Description() string { if c.GrayGlacierBlock != nil { banner += fmt.Sprintf(" - Gray Glacier: %-8v (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/gray-glacier.md)\n", c.GrayGlacierBlock) } - if c.ShanghaiBlock != nil { - banner += fmt.Sprintf(" - Shanghai: %-8v (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/shanghai.md)\n", c.ShanghaiBlock) - } + banner += fmt.Sprintf(" - Shanghai: %-8v (https://github.com/ethereum/execution-specs/blob/master/network-upgrades/mainnet-upgrades/shanghai.md)\n", c.ShanghaiTime) if c.CancunBlock != nil { banner += fmt.Sprintf(" - Cancun: %-8v\n", c.CancunBlock) } @@ -489,74 +490,74 @@ func (c *ChainConfig) Description() string { // IsHomestead returns whether num is either equal to the homestead block or greater. func (c *ChainConfig) IsHomestead(num *big.Int) bool { - return isForked(c.HomesteadBlock, num) + return isBlockForked(c.HomesteadBlock, num) } // IsDAOFork returns whether num is either equal to the DAO fork block or greater. func (c *ChainConfig) IsDAOFork(num *big.Int) bool { - return isForked(c.DAOForkBlock, num) + return isBlockForked(c.DAOForkBlock, num) } // IsEIP150 returns whether num is either equal to the EIP150 fork block or greater. func (c *ChainConfig) IsEIP150(num *big.Int) bool { - return isForked(c.EIP150Block, num) + return isBlockForked(c.EIP150Block, num) } // IsEIP155 returns whether num is either equal to the EIP155 fork block or greater. func (c *ChainConfig) IsEIP155(num *big.Int) bool { - return isForked(c.EIP155Block, num) + return isBlockForked(c.EIP155Block, num) } // IsEIP158 returns whether num is either equal to the EIP158 fork block or greater. func (c *ChainConfig) IsEIP158(num *big.Int) bool { - return isForked(c.EIP158Block, num) + return isBlockForked(c.EIP158Block, num) } // IsByzantium returns whether num is either equal to the Byzantium fork block or greater. func (c *ChainConfig) IsByzantium(num *big.Int) bool { - return isForked(c.ByzantiumBlock, num) + return isBlockForked(c.ByzantiumBlock, num) } // IsConstantinople returns whether num is either equal to the Constantinople fork block or greater. func (c *ChainConfig) IsConstantinople(num *big.Int) bool { - return isForked(c.ConstantinopleBlock, num) + return isBlockForked(c.ConstantinopleBlock, num) } // IsMuirGlacier returns whether num is either equal to the Muir Glacier (EIP-2384) fork block or greater. func (c *ChainConfig) IsMuirGlacier(num *big.Int) bool { - return isForked(c.MuirGlacierBlock, num) + return isBlockForked(c.MuirGlacierBlock, num) } // IsPetersburg returns whether num is either // - equal to or greater than the PetersburgBlock fork block, // - OR is nil, and Constantinople is active func (c *ChainConfig) IsPetersburg(num *big.Int) bool { - return isForked(c.PetersburgBlock, num) || c.PetersburgBlock == nil && isForked(c.ConstantinopleBlock, num) + return isBlockForked(c.PetersburgBlock, num) || c.PetersburgBlock == nil && isBlockForked(c.ConstantinopleBlock, num) } // IsIstanbul returns whether num is either equal to the Istanbul fork block or greater. func (c *ChainConfig) IsIstanbul(num *big.Int) bool { - return isForked(c.IstanbulBlock, num) + return isBlockForked(c.IstanbulBlock, num) } // IsBerlin returns whether num is either equal to the Berlin fork block or greater. func (c *ChainConfig) IsBerlin(num *big.Int) bool { - return isForked(c.BerlinBlock, num) + return isBlockForked(c.BerlinBlock, num) } // IsLondon returns whether num is either equal to the London fork block or greater. func (c *ChainConfig) IsLondon(num *big.Int) bool { - return isForked(c.LondonBlock, num) + return isBlockForked(c.LondonBlock, num) } // IsArrowGlacier returns whether num is either equal to the Arrow Glacier (EIP-4345) fork block or greater. func (c *ChainConfig) IsArrowGlacier(num *big.Int) bool { - return isForked(c.ArrowGlacierBlock, num) + return isBlockForked(c.ArrowGlacierBlock, num) } // IsGrayGlacier returns whether num is either equal to the Gray Glacier (EIP-5133) fork block or greater. func (c *ChainConfig) IsGrayGlacier(num *big.Int) bool { - return isForked(c.GrayGlacierBlock, num) + return isBlockForked(c.GrayGlacierBlock, num) } // IsTerminalPoWBlock returns whether the given block is the last block of PoW stage. @@ -567,30 +568,37 @@ func (c *ChainConfig) IsTerminalPoWBlock(parentTotalDiff *big.Int, totalDiff *bi return parentTotalDiff.Cmp(c.TerminalTotalDifficulty) < 0 && totalDiff.Cmp(c.TerminalTotalDifficulty) >= 0 } -// IsShanghai returns whether num is either equal to the Shanghai fork block or greater. -func (c *ChainConfig) IsShanghai(num *big.Int) bool { - return isForked(c.ShanghaiBlock, num) -} - // IsCancun returns whether num is either equal to the Cancun fork block or greater. func (c *ChainConfig) IsCancun(num *big.Int) bool { - return isForked(c.CancunBlock, num) + return isBlockForked(c.CancunBlock, num) +} + +// IsShanghai returns whether time is either equal to the Shanghai fork time or greater. +func (c *ChainConfig) IsShanghai(time *big.Int) bool { + return isTimestampForked(c.ShanghaiTime, time) } // CheckCompatible checks whether scheduled fork transitions have been imported // with a mismatching chain configuration. -func (c *ChainConfig) CheckCompatible(newcfg *ChainConfig, height uint64) *ConfigCompatError { - bhead := new(big.Int).SetUint64(height) - +func (c *ChainConfig) CheckCompatible(newcfg *ChainConfig, height uint64, time uint64) *ConfigCompatError { + var ( + bhead = new(big.Int).SetUint64(height) + btime = new(big.Int).SetUint64(time) + ) // Iterate checkCompatible to find the lowest conflict. var lasterr *ConfigCompatError for { - err := c.checkCompatible(newcfg, bhead) - if err == nil || (lasterr != nil && err.RewindTo == lasterr.RewindTo) { + err := c.checkCompatible(newcfg, bhead, btime) + if err == nil || (lasterr != nil && err.RewindToBlock == lasterr.RewindToBlock && err.RewindToTime == lasterr.RewindToTime) { break } lasterr = err - bhead.SetUint64(err.RewindTo) + + if err.RewindToTime > 0 { + btime.SetUint64(err.RewindToTime) + } else { + bhead.SetUint64(err.RewindToBlock) + } } return lasterr } @@ -599,9 +607,10 @@ func (c *ChainConfig) CheckCompatible(newcfg *ChainConfig, height uint64) *Confi // to guarantee that forks can be implemented in a different order than on official networks func (c *ChainConfig) CheckConfigForkOrder() error { type fork struct { - name string - block *big.Int - optional bool // if true, the fork may be nil and next fork is still allowed + name string + block *big.Int // forks up to - and including the merge - were defined with block numbers + timestamp *big.Int // forks after the merge are scheduled using timestamps + optional bool // if true, the fork may be nil and next fork is still allowed } var lastFork fork for _, cur := range []fork{ @@ -620,91 +629,107 @@ func (c *ChainConfig) CheckConfigForkOrder() error { {name: "arrowGlacierBlock", block: c.ArrowGlacierBlock, optional: true}, {name: "grayGlacierBlock", block: c.GrayGlacierBlock, optional: true}, {name: "mergeNetsplitBlock", block: c.MergeNetsplitBlock, optional: true}, - {name: "shanghaiBlock", block: c.ShanghaiBlock, optional: true}, {name: "cancunBlock", block: c.CancunBlock, optional: true}, + {name: "shanghaiTime", timestamp: c.ShanghaiTime}, } { if lastFork.name != "" { - // Next one must be higher number - if lastFork.block == nil && cur.block != nil { - return fmt.Errorf("unsupported fork ordering: %v not enabled, but %v enabled at %v", - lastFork.name, cur.name, cur.block) - } - if lastFork.block != nil && cur.block != nil { - if lastFork.block.Cmp(cur.block) > 0 { - return fmt.Errorf("unsupported fork ordering: %v enabled at %v, but %v enabled at %v", + switch { + // Non-optional forks must all be present in the chain config up to the last defined fork + case lastFork.block == nil && lastFork.timestamp == nil && (cur.block != nil || cur.timestamp != nil): + if cur.block != nil { + return fmt.Errorf("unsupported fork ordering: %v not enabled, but %v enabled at block %v", + lastFork.name, cur.name, cur.block) + } else { + return fmt.Errorf("unsupported fork ordering: %v not enabled, but %v enabled at timestamp %v", + lastFork.name, cur.name, cur.timestamp) + } + + // Fork (whether defined by block or timestamp) must follow the fork definition sequence + case (lastFork.block != nil && cur.block != nil) || (lastFork.timestamp != nil && cur.timestamp != nil): + if lastFork.block != nil && lastFork.block.Cmp(cur.block) > 0 { + return fmt.Errorf("unsupported fork ordering: %v enabled at block %v, but %v enabled at block %v", lastFork.name, lastFork.block, cur.name, cur.block) + } else if lastFork.timestamp != nil && lastFork.timestamp.Cmp(cur.timestamp) > 0 { + return fmt.Errorf("unsupported fork ordering: %v enabled at timestamp %v, but %v enabled at timestamp %v", + lastFork.name, lastFork.timestamp, cur.name, cur.timestamp) + } + + // Timestamp based forks can follow block based ones, but not the other way around + if lastFork.timestamp != nil && cur.block != nil { + return fmt.Errorf("unsupported fork ordering: %v used timestamp ordering, but %v reverted to block ordering", + lastFork.name, cur.name) } } } // If it was optional and not set, then ignore it - if !cur.optional || cur.block != nil { + if !cur.optional || (cur.block != nil || cur.timestamp != nil) { lastFork = cur } } return nil } -func (c *ChainConfig) checkCompatible(newcfg *ChainConfig, head *big.Int) *ConfigCompatError { - if isForkIncompatible(c.HomesteadBlock, newcfg.HomesteadBlock, head) { - return newCompatError("Homestead fork block", c.HomesteadBlock, newcfg.HomesteadBlock) +func (c *ChainConfig) checkCompatible(newcfg *ChainConfig, headNumber *big.Int, headTimestamp *big.Int) *ConfigCompatError { + if isForkBlockIncompatible(c.HomesteadBlock, newcfg.HomesteadBlock, headNumber) { + return newBlockCompatError("Homestead fork block", c.HomesteadBlock, newcfg.HomesteadBlock) } - if isForkIncompatible(c.DAOForkBlock, newcfg.DAOForkBlock, head) { - return newCompatError("DAO fork block", c.DAOForkBlock, newcfg.DAOForkBlock) + if isForkBlockIncompatible(c.DAOForkBlock, newcfg.DAOForkBlock, headNumber) { + return newBlockCompatError("DAO fork block", c.DAOForkBlock, newcfg.DAOForkBlock) } - if c.IsDAOFork(head) && c.DAOForkSupport != newcfg.DAOForkSupport { - return newCompatError("DAO fork support flag", c.DAOForkBlock, newcfg.DAOForkBlock) + if c.IsDAOFork(headNumber) && c.DAOForkSupport != newcfg.DAOForkSupport { + return newBlockCompatError("DAO fork support flag", c.DAOForkBlock, newcfg.DAOForkBlock) } - if isForkIncompatible(c.EIP150Block, newcfg.EIP150Block, head) { - return newCompatError("EIP150 fork block", c.EIP150Block, newcfg.EIP150Block) + if isForkBlockIncompatible(c.EIP150Block, newcfg.EIP150Block, headNumber) { + return newBlockCompatError("EIP150 fork block", c.EIP150Block, newcfg.EIP150Block) } - if isForkIncompatible(c.EIP155Block, newcfg.EIP155Block, head) { - return newCompatError("EIP155 fork block", c.EIP155Block, newcfg.EIP155Block) + if isForkBlockIncompatible(c.EIP155Block, newcfg.EIP155Block, headNumber) { + return newBlockCompatError("EIP155 fork block", c.EIP155Block, newcfg.EIP155Block) } - if isForkIncompatible(c.EIP158Block, newcfg.EIP158Block, head) { - return newCompatError("EIP158 fork block", c.EIP158Block, newcfg.EIP158Block) + if isForkBlockIncompatible(c.EIP158Block, newcfg.EIP158Block, headNumber) { + return newBlockCompatError("EIP158 fork block", c.EIP158Block, newcfg.EIP158Block) } - if c.IsEIP158(head) && !configNumEqual(c.ChainID, newcfg.ChainID) { - return newCompatError("EIP158 chain ID", c.EIP158Block, newcfg.EIP158Block) + if c.IsEIP158(headNumber) && !configBlockEqual(c.ChainID, newcfg.ChainID) { + return newBlockCompatError("EIP158 chain ID", c.EIP158Block, newcfg.EIP158Block) } - if isForkIncompatible(c.ByzantiumBlock, newcfg.ByzantiumBlock, head) { - return newCompatError("Byzantium fork block", c.ByzantiumBlock, newcfg.ByzantiumBlock) + if isForkBlockIncompatible(c.ByzantiumBlock, newcfg.ByzantiumBlock, headNumber) { + return newBlockCompatError("Byzantium fork block", c.ByzantiumBlock, newcfg.ByzantiumBlock) } - if isForkIncompatible(c.ConstantinopleBlock, newcfg.ConstantinopleBlock, head) { - return newCompatError("Constantinople fork block", c.ConstantinopleBlock, newcfg.ConstantinopleBlock) + if isForkBlockIncompatible(c.ConstantinopleBlock, newcfg.ConstantinopleBlock, headNumber) { + return newBlockCompatError("Constantinople fork block", c.ConstantinopleBlock, newcfg.ConstantinopleBlock) } - if isForkIncompatible(c.PetersburgBlock, newcfg.PetersburgBlock, head) { + if isForkBlockIncompatible(c.PetersburgBlock, newcfg.PetersburgBlock, headNumber) { // the only case where we allow Petersburg to be set in the past is if it is equal to Constantinople // mainly to satisfy fork ordering requirements which state that Petersburg fork be set if Constantinople fork is set - if isForkIncompatible(c.ConstantinopleBlock, newcfg.PetersburgBlock, head) { - return newCompatError("Petersburg fork block", c.PetersburgBlock, newcfg.PetersburgBlock) + if isForkBlockIncompatible(c.ConstantinopleBlock, newcfg.PetersburgBlock, headNumber) { + return newBlockCompatError("Petersburg fork block", c.PetersburgBlock, newcfg.PetersburgBlock) } } - if isForkIncompatible(c.IstanbulBlock, newcfg.IstanbulBlock, head) { - return newCompatError("Istanbul fork block", c.IstanbulBlock, newcfg.IstanbulBlock) + if isForkBlockIncompatible(c.IstanbulBlock, newcfg.IstanbulBlock, headNumber) { + return newBlockCompatError("Istanbul fork block", c.IstanbulBlock, newcfg.IstanbulBlock) } - if isForkIncompatible(c.MuirGlacierBlock, newcfg.MuirGlacierBlock, head) { - return newCompatError("Muir Glacier fork block", c.MuirGlacierBlock, newcfg.MuirGlacierBlock) + if isForkBlockIncompatible(c.MuirGlacierBlock, newcfg.MuirGlacierBlock, headNumber) { + return newBlockCompatError("Muir Glacier fork block", c.MuirGlacierBlock, newcfg.MuirGlacierBlock) } - if isForkIncompatible(c.BerlinBlock, newcfg.BerlinBlock, head) { - return newCompatError("Berlin fork block", c.BerlinBlock, newcfg.BerlinBlock) + if isForkBlockIncompatible(c.BerlinBlock, newcfg.BerlinBlock, headNumber) { + return newBlockCompatError("Berlin fork block", c.BerlinBlock, newcfg.BerlinBlock) } - if isForkIncompatible(c.LondonBlock, newcfg.LondonBlock, head) { - return newCompatError("London fork block", c.LondonBlock, newcfg.LondonBlock) + if isForkBlockIncompatible(c.LondonBlock, newcfg.LondonBlock, headNumber) { + return newBlockCompatError("London fork block", c.LondonBlock, newcfg.LondonBlock) } - if isForkIncompatible(c.ArrowGlacierBlock, newcfg.ArrowGlacierBlock, head) { - return newCompatError("Arrow Glacier fork block", c.ArrowGlacierBlock, newcfg.ArrowGlacierBlock) + if isForkBlockIncompatible(c.ArrowGlacierBlock, newcfg.ArrowGlacierBlock, headNumber) { + return newBlockCompatError("Arrow Glacier fork block", c.ArrowGlacierBlock, newcfg.ArrowGlacierBlock) } - if isForkIncompatible(c.GrayGlacierBlock, newcfg.GrayGlacierBlock, head) { - return newCompatError("Gray Glacier fork block", c.GrayGlacierBlock, newcfg.GrayGlacierBlock) + if isForkBlockIncompatible(c.GrayGlacierBlock, newcfg.GrayGlacierBlock, headNumber) { + return newBlockCompatError("Gray Glacier fork block", c.GrayGlacierBlock, newcfg.GrayGlacierBlock) } - if isForkIncompatible(c.MergeNetsplitBlock, newcfg.MergeNetsplitBlock, head) { - return newCompatError("Merge netsplit fork block", c.MergeNetsplitBlock, newcfg.MergeNetsplitBlock) + if isForkBlockIncompatible(c.MergeNetsplitBlock, newcfg.MergeNetsplitBlock, headNumber) { + return newBlockCompatError("Merge netsplit fork block", c.MergeNetsplitBlock, newcfg.MergeNetsplitBlock) } - if isForkIncompatible(c.ShanghaiBlock, newcfg.ShanghaiBlock, head) { - return newCompatError("Shanghai fork block", c.ShanghaiBlock, newcfg.ShanghaiBlock) + if isForkBlockIncompatible(c.CancunBlock, newcfg.CancunBlock, headNumber) { + return newBlockCompatError("Cancun fork block", c.CancunBlock, newcfg.CancunBlock) } - if isForkIncompatible(c.CancunBlock, newcfg.CancunBlock, head) { - return newCompatError("Cancun fork block", c.CancunBlock, newcfg.CancunBlock) + if isForkTimestampIncompatible(c.ShanghaiTime, newcfg.ShanghaiTime, headTimestamp) { + return newTimestampCompatError("Shanghai fork timestamp", c.ShanghaiTime, newcfg.ShanghaiTime) } return nil } @@ -719,21 +744,49 @@ func (c *ChainConfig) ElasticityMultiplier() uint64 { return DefaultElasticityMultiplier } -// isForkIncompatible returns true if a fork scheduled at s1 cannot be rescheduled to -// block s2 because head is already past the fork. -func isForkIncompatible(s1, s2, head *big.Int) bool { - return (isForked(s1, head) || isForked(s2, head)) && !configNumEqual(s1, s2) +// isForkBlockIncompatible returns true if a fork scheduled at block s1 cannot be +// rescheduled to block s2 because head is already past the fork. +func isForkBlockIncompatible(s1, s2, head *big.Int) bool { + return (isBlockForked(s1, head) || isBlockForked(s2, head)) && !configBlockEqual(s1, s2) } -// isForked returns whether a fork scheduled at block s is active at the given head block. -func isForked(s, head *big.Int) bool { +// isBlockForked returns whether a fork scheduled at block s is active at the +// given head block. Whilst this method is the same as isTimestampForked, they +// are explicitly separate for clearer reading. +func isBlockForked(s, head *big.Int) bool { if s == nil || head == nil { return false } return s.Cmp(head) <= 0 } -func configNumEqual(x, y *big.Int) bool { +func configBlockEqual(x, y *big.Int) bool { + if x == nil { + return y == nil + } + if y == nil { + return x == nil + } + return x.Cmp(y) == 0 +} + +// isForkTimestampIncompatible returns true if a fork scheduled at timestamp s1 +// cannot be rescheduled to timestamp s2 because head is already past the fork. +func isForkTimestampIncompatible(s1, s2, head *big.Int) bool { + return (isTimestampForked(s1, head) || isTimestampForked(s2, head)) && !configTimestampEqual(s1, s2) +} + +// isTimestampForked returns whether a fork scheduled at timestamp s is active +// at the given head timestamp. Whilst this method is the same as isBlockForked, +// they are explicitly separate for clearer reading. +func isTimestampForked(s, head *big.Int) bool { + if s == nil || head == nil { + return false + } + return s.Cmp(head) <= 0 +} + +func configTimestampEqual(x, y *big.Int) bool { if x == nil { return y == nil } @@ -747,13 +800,21 @@ func configNumEqual(x, y *big.Int) bool { // ChainConfig that would alter the past. type ConfigCompatError struct { What string - // block numbers of the stored and new configurations - StoredConfig, NewConfig *big.Int + + // block numbers of the stored and new configurations if block based forking + StoredBlock, NewBlock *big.Int + + // timestamps of the stored and new configurations if time based forking + StoredTime, NewTime *big.Int + // the block number to which the local chain must be rewound to correct the error - RewindTo uint64 + RewindToBlock uint64 + + // the timestamp to which the local chain must be rewound to correct the error + RewindToTime uint64 } -func newCompatError(what string, storedblock, newblock *big.Int) *ConfigCompatError { +func newBlockCompatError(what string, storedblock, newblock *big.Int) *ConfigCompatError { var rew *big.Int switch { case storedblock == nil: @@ -763,15 +824,45 @@ func newCompatError(what string, storedblock, newblock *big.Int) *ConfigCompatEr default: rew = newblock } - err := &ConfigCompatError{what, storedblock, newblock, 0} + err := &ConfigCompatError{ + What: what, + StoredBlock: storedblock, + NewBlock: newblock, + RewindToBlock: 0, + } + if rew != nil && rew.Sign() > 0 { + err.RewindToBlock = rew.Uint64() - 1 + } + return err +} + +func newTimestampCompatError(what string, storedtime, newtime *big.Int) *ConfigCompatError { + var rew *big.Int + switch { + case storedtime == nil: + rew = newtime + case newtime == nil || storedtime.Cmp(newtime) < 0: + rew = storedtime + default: + rew = newtime + } + err := &ConfigCompatError{ + What: what, + StoredTime: storedtime, + NewTime: newtime, + RewindToTime: 0, + } if rew != nil && rew.Sign() > 0 { - err.RewindTo = rew.Uint64() - 1 + err.RewindToTime = rew.Uint64() - 1 } return err } func (err *ConfigCompatError) Error() string { - return fmt.Sprintf("mismatching %s in database (have %d, want %d, rewindto %d)", err.What, err.StoredConfig, err.NewConfig, err.RewindTo) + if err.StoredBlock != nil { + return fmt.Sprintf("mismatching %s in database (have block %d, want block %d, rewindto block %d)", err.What, err.StoredBlock, err.NewBlock, err.RewindToBlock) + } + return fmt.Sprintf("mismatching %s in database (have timestamp %d, want timestamp %d, rewindto timestamp %d)", err.What, err.StoredTime, err.NewTime, err.RewindToTime) } // Rules wraps ChainConfig and is merely syntactic sugar or can be used for functions @@ -788,7 +879,7 @@ type Rules struct { } // Rules ensures c's ChainID is not nil. -func (c *ChainConfig) Rules(num *big.Int, isMerge bool) Rules { +func (c *ChainConfig) Rules(num *big.Int, isMerge bool, timestamp *big.Int) Rules { chainID := c.ChainID if chainID == nil { chainID = new(big.Int) @@ -806,7 +897,7 @@ func (c *ChainConfig) Rules(num *big.Int, isMerge bool) Rules { IsBerlin: c.IsBerlin(num), IsLondon: c.IsLondon(num), IsMerge: isMerge, - IsShanghai: c.IsShanghai(num), + IsShanghai: c.IsShanghai(timestamp), isCancun: c.IsCancun(num), } } diff --git a/params/config_test.go b/params/config_test.go index 3c8ebaf4a511..523ba26fdc7d 100644 --- a/params/config_test.go +++ b/params/config_test.go @@ -20,79 +20,99 @@ import ( "math/big" "reflect" "testing" + "time" ) func TestCheckCompatible(t *testing.T) { type test struct { - stored, new *ChainConfig - head uint64 - wantErr *ConfigCompatError + stored, new *ChainConfig + headBlock uint64 + headTimestamp uint64 + wantErr *ConfigCompatError } tests := []test{ - {stored: AllEthashProtocolChanges, new: AllEthashProtocolChanges, head: 0, wantErr: nil}, - {stored: AllEthashProtocolChanges, new: AllEthashProtocolChanges, head: 100, wantErr: nil}, + {stored: AllEthashProtocolChanges, new: AllEthashProtocolChanges, headBlock: 0, headTimestamp: 0, wantErr: nil}, + {stored: AllEthashProtocolChanges, new: AllEthashProtocolChanges, headBlock: 0, headTimestamp: uint64(time.Now().Unix()), wantErr: nil}, + {stored: AllEthashProtocolChanges, new: AllEthashProtocolChanges, headBlock: 100, wantErr: nil}, { - stored: &ChainConfig{EIP150Block: big.NewInt(10)}, - new: &ChainConfig{EIP150Block: big.NewInt(20)}, - head: 9, - wantErr: nil, + stored: &ChainConfig{EIP150Block: big.NewInt(10)}, + new: &ChainConfig{EIP150Block: big.NewInt(20)}, + headBlock: 9, + wantErr: nil, }, { - stored: AllEthashProtocolChanges, - new: &ChainConfig{HomesteadBlock: nil}, - head: 3, + stored: AllEthashProtocolChanges, + new: &ChainConfig{HomesteadBlock: nil}, + headBlock: 3, wantErr: &ConfigCompatError{ - What: "Homestead fork block", - StoredConfig: big.NewInt(0), - NewConfig: nil, - RewindTo: 0, + What: "Homestead fork block", + StoredBlock: big.NewInt(0), + NewBlock: nil, + RewindToBlock: 0, }, }, { - stored: AllEthashProtocolChanges, - new: &ChainConfig{HomesteadBlock: big.NewInt(1)}, - head: 3, + stored: AllEthashProtocolChanges, + new: &ChainConfig{HomesteadBlock: big.NewInt(1)}, + headBlock: 3, wantErr: &ConfigCompatError{ - What: "Homestead fork block", - StoredConfig: big.NewInt(0), - NewConfig: big.NewInt(1), - RewindTo: 0, + What: "Homestead fork block", + StoredBlock: big.NewInt(0), + NewBlock: big.NewInt(1), + RewindToBlock: 0, }, }, { - stored: &ChainConfig{HomesteadBlock: big.NewInt(30), EIP150Block: big.NewInt(10)}, - new: &ChainConfig{HomesteadBlock: big.NewInt(25), EIP150Block: big.NewInt(20)}, - head: 25, + stored: &ChainConfig{HomesteadBlock: big.NewInt(30), EIP150Block: big.NewInt(10)}, + new: &ChainConfig{HomesteadBlock: big.NewInt(25), EIP150Block: big.NewInt(20)}, + headBlock: 25, wantErr: &ConfigCompatError{ - What: "EIP150 fork block", - StoredConfig: big.NewInt(10), - NewConfig: big.NewInt(20), - RewindTo: 9, + What: "EIP150 fork block", + StoredBlock: big.NewInt(10), + NewBlock: big.NewInt(20), + RewindToBlock: 9, }, }, { - stored: &ChainConfig{ConstantinopleBlock: big.NewInt(30)}, - new: &ChainConfig{ConstantinopleBlock: big.NewInt(30), PetersburgBlock: big.NewInt(30)}, - head: 40, - wantErr: nil, + stored: &ChainConfig{ConstantinopleBlock: big.NewInt(30)}, + new: &ChainConfig{ConstantinopleBlock: big.NewInt(30), PetersburgBlock: big.NewInt(30)}, + headBlock: 40, + wantErr: nil, }, { - stored: &ChainConfig{ConstantinopleBlock: big.NewInt(30)}, - new: &ChainConfig{ConstantinopleBlock: big.NewInt(30), PetersburgBlock: big.NewInt(31)}, - head: 40, + stored: &ChainConfig{ConstantinopleBlock: big.NewInt(30)}, + new: &ChainConfig{ConstantinopleBlock: big.NewInt(30), PetersburgBlock: big.NewInt(31)}, + headBlock: 40, wantErr: &ConfigCompatError{ - What: "Petersburg fork block", - StoredConfig: nil, - NewConfig: big.NewInt(31), - RewindTo: 30, + What: "Petersburg fork block", + StoredBlock: nil, + NewBlock: big.NewInt(31), + RewindToBlock: 30, + }, + }, + { + stored: &ChainConfig{ShanghaiTime: big.NewInt(10)}, + new: &ChainConfig{ShanghaiTime: big.NewInt(20)}, + headTimestamp: 9, + wantErr: nil, + }, + { + stored: &ChainConfig{ShanghaiTime: big.NewInt(10)}, + new: &ChainConfig{ShanghaiTime: big.NewInt(20)}, + headTimestamp: 25, + wantErr: &ConfigCompatError{ + What: "Shanghai fork timestamp", + StoredTime: big.NewInt(10), + NewTime: big.NewInt(20), + RewindToTime: 9, }, }, } for _, test := range tests { - err := test.stored.CheckCompatible(test.new, test.head) + err := test.stored.CheckCompatible(test.new, test.headBlock, test.headTimestamp) if !reflect.DeepEqual(err, test.wantErr) { - t.Errorf("error mismatch:\nstored: %v\nnew: %v\nhead: %v\nerr: %v\nwant: %v", test.stored, test.new, test.head, err, test.wantErr) + t.Errorf("error mismatch:\nstored: %v\nnew: %v\nheadBlock: %v\nheadTimestamp: %v\nerr: %v\nwant: %v", test.stored, test.new, test.headBlock, test.headTimestamp, err, test.wantErr) } } } diff --git a/tests/state_test.go b/tests/state_test.go index cb7f76521780..accf6eaf69b4 100644 --- a/tests/state_test.go +++ b/tests/state_test.go @@ -185,7 +185,7 @@ func runBenchmark(b *testing.B, t *StateTest) { b.Error(err) return } - var rules = config.Rules(new(big.Int), false) + var rules = config.Rules(new(big.Int), false, new(big.Int)) vmconfig.ExtraEips = eips block := t.genesis(config).ToBlock()