Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

aristo: fork support via layers/txframes #2960

Open
wants to merge 46 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 37 commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
0971b72
aristo: fork support via layers/txframes
arnetheduck Dec 19, 2024
fe6bee5
fix layer vtop after rollback
arnetheduck Dec 20, 2024
f0678f1
engine fix
arnetheduck Dec 20, 2024
64597c2
Merge remote-tracking branch 'origin/master' into forked-layers
arnetheduck Dec 27, 2024
4e5b7eb
Merge remote-tracking branch 'origin/master' into forked-layers
arnetheduck Dec 27, 2024
d26b6ff
Merge branch 'master' into fc-forked-layers
jangko Jan 7, 2025
e07d5ad
Merge branch 'master' into fc-forked-layers
jangko Jan 13, 2025
296b348
Fix test_txpool
jangko Jan 13, 2025
fc059c7
Fix test_rpc
jangko Jan 13, 2025
785a518
Fix copyright year
jangko Jan 13, 2025
315d93e
fix simulator
jangko Jan 13, 2025
9ea4bb8
Fix copyright year
jangko Jan 13, 2025
76646f0
Fix copyright year
jangko Jan 13, 2025
416dc69
Fix tracer
jangko Jan 13, 2025
078e02d
Merge branch 'master' into forked-layers
jangko Jan 13, 2025
11cd560
Fix infinite recursion bug
jangko Jan 14, 2025
16e243a
Remove aristo and kvt empty files
jangko Jan 14, 2025
16ebff9
Merge branch 'master' into forked-layers
jangko Jan 16, 2025
44e08e2
Fic copyright year
jangko Jan 16, 2025
6b8219f
Merge branch 'master' into forked-layers
jangko Jan 16, 2025
026f4c9
Fix fc chain_kvt
jangko Jan 16, 2025
58c997d
ForkedChain refactoring
jangko Jan 17, 2025
e9c79ad
Merge branch 'master' into forked-layers
jangko Jan 20, 2025
1e1df66
Fix merge master conflict
jangko Jan 20, 2025
527182a
Merge branch 'master' into forked-layers
jangko Jan 22, 2025
3239041
Fix copyright year
jangko Jan 22, 2025
54f0390
Merge branch 'master' into forked-layers
jangko Jan 25, 2025
1c42092
Merge branch 'master' into forked-layers
jangko Jan 28, 2025
94fdc1f
Reparent txFrame
jangko Jan 28, 2025
fc94d68
Fix test
jangko Jan 28, 2025
d93db90
Fix txFrame reparent again
jangko Jan 29, 2025
009d905
Cleanup and fix test
jangko Jan 29, 2025
7ce26af
UpdateBase bugfix and fix test
jangko Jan 29, 2025
bfedb06
Fixe newPayload bug discovered by hive
jangko Jan 29, 2025
ff865a4
Merge branch 'master' into forked-layers
jangko Jan 29, 2025
9eb7f24
Fix engine api fcu
jangko Jan 29, 2025
82dd3b7
Merge branch 'master' into forked-layers
jangko Jan 29, 2025
861f89b
Clean up call template, chain_kvt, andn txguid
jangko Jan 29, 2025
f2292d0
Fix copyright year
jangko Jan 29, 2025
3cda3f5
Merge remote-tracking branch 'origin/master' into forked-layers
arnetheduck Jan 31, 2025
9d1dd61
work around base block loading issue
arnetheduck Jan 31, 2025
2b5e3fe
Add test
jangko Feb 1, 2025
1c43270
Fix updateHead bug
jangko Feb 3, 2025
776517f
Merge branch 'master' into forked-layers
jangko Feb 3, 2025
9397960
Fix updateBase bug
jangko Feb 3, 2025
4c67170
Change func commitBase to proc commitBase
jangko Feb 3, 2025
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
2 changes: 1 addition & 1 deletion hive_integration/nodocker/consensus/consensus_sim.nim
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ proc processChainData(cd: ChainData, taskPool: Taskpool): TestStatus =
cd.params
)

let c = newForkedChain(com, com.genesisHeader)
let c = ForkedChainRef.init(com)

for bytes in cd.blocksRlp:
# ignore return value here
Expand Down
44 changes: 18 additions & 26 deletions hive_integration/nodocker/engine/node.nim
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Nimbus
# Copyright (c) 2024 Status Research & Development GmbH
# Copyright (c) 2024-2025 Status Research & Development GmbH
# Licensed under either of
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
# http://www.apache.org/licenses/LICENSE-2.0)
Expand Down Expand Up @@ -42,8 +42,6 @@ proc processBlock(
## implementations (but can be savely removed, as well.)
## variant of `processBlock()` where the `header` argument is explicitely set.
template header: Header = blk.header
var dbTx = vmState.com.db.ctx.txFrameBegin()
defer: dbTx.dispose()

let com = vmState.com
if com.daoForkSupport and
Expand All @@ -61,61 +59,55 @@ proc processBlock(
vmState.ledger.addBalance(withdrawal.address, withdrawal.weiAmount)

if header.ommersHash != EMPTY_UNCLE_HASH:
discard com.db.persistUncles(blk.uncles)
discard vmState.ledger.txFrame.persistUncles(blk.uncles)

# EIP-3675: no reward for miner in POA/POS
if com.proofOfStake(header):
if com.proofOfStake(header, vmState.ledger.txFrame):
vmState.calculateReward(header, blk.uncles)

vmState.mutateLedger:
let clearEmptyAccount = com.isSpuriousOrLater(header.number)
db.persist(clearEmptyAccount)

dbTx.commit()
vmState.ledger.txFrame.commit()

ok()

proc getVmState(c: ChainRef, header: Header):
Result[BaseVMState, void] =
let vmState = BaseVMState()
if not vmState.init(header, c.com, storeSlotHash = false):
debug "Cannot initialise VmState",
number = header.number
return err()

proc getVmState(c: ChainRef, header: Header, txFrame: CoreDbTxRef):
Result[BaseVMState, string] =
let
parent = ?txFrame.getBlockHeader(header.parentHash)
vmState = BaseVMState()
vmState.init(parent, header, c.com, txFrame, storeSlotHash = false)
return ok(vmState)

# A stripped down version of persistBlocks without validation
# intended to accepts invalid block
proc setBlock*(c: ChainRef; blk: Block): Result[void, string] =
template header: Header = blk.header
let dbTx = c.db.ctx.txFrameBegin()
defer: dbTx.dispose()
let txFrame = c.db.ctx.txFrameBegin(nil)
defer: txFrame.dispose()

# Needed for figuring out whether KVT cleanup is due (see at the end)
let
vmState = c.getVmState(header).valueOr:
return err("no vmstate")
vmState = ? c.getVmState(header, txFrame)
? vmState.processBlock(blk)

? c.db.persistHeaderAndSetHead(header, c.com.startOfHistory)
? txFrame.persistHeaderAndSetHead(header, c.com.startOfHistory)

c.db.persistTransactions(header.number, header.txRoot, blk.transactions)
c.db.persistReceipts(header.receiptsRoot, vmState.receipts)
txFrame.persistTransactions(header.number, header.txRoot, blk.transactions)
txFrame.persistReceipts(header.receiptsRoot, vmState.receipts)

if blk.withdrawals.isSome:
c.db.persistWithdrawals(header.withdrawalsRoot.get, blk.withdrawals.get)
txFrame.persistWithdrawals(header.withdrawalsRoot.get, blk.withdrawals.get)

# update currentBlock *after* we persist it
# so the rpc return consistent result
# between eth_blockNumber and eth_syncing
c.com.syncCurrent = header.number

dbTx.commit()
txFrame.commit()

# The `c.db.persistent()` call is ignored by the legacy DB which
# automatically saves persistently when reaching the zero level transaction.
#
# For the `Aristo` database, this code position is only reached if the
# the parent state of the first block (as registered in `headers[0]`) was
# the canonical state before updating. So this state will be saved with
Expand Down
6 changes: 3 additions & 3 deletions hive_integration/nodocker/pyspec/test_env.nim
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Nimbus
# Copyright (c) 2023-2024 Status Research & Development GmbH
# Copyright (c) 2023-2025 Status Research & Development GmbH
# Licensed under either of
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
# http://www.apache.org/licenses/LICENSE-2.0)
Expand Down Expand Up @@ -37,9 +37,9 @@ proc genesisHeader(node: JsonNode): Header =
proc initializeDb(memDB: CoreDbRef, node: JsonNode): Hash32 =
let
genesisHeader = node.genesisHeader
ledger = LedgerRef.init(memDB)
ledger = LedgerRef.init(memDB.baseTxFrame())

memDB.persistHeaderAndSetHead(genesisHeader).expect("persistHeader no error")
ledger.txFrame.persistHeaderAndSetHead(genesisHeader).expect("persistHeader no error")
setupLedger(node["pre"], ledger)
ledger.persist()
doAssert ledger.getStateRoot == genesisHeader.stateRoot
Expand Down
6 changes: 3 additions & 3 deletions nimbus/beacon/api_handler/api_exchangeconf.nim
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Nimbus
# Copyright (c) 2023-2024 Status Research & Development GmbH
# Copyright (c) 2023-2025 Status Research & Development GmbH
# Licensed under either of
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
# * MIT license ([LICENSE-MIT](LICENSE-MIT))
Expand Down Expand Up @@ -43,15 +43,15 @@ proc exchangeConf*(ben: BeaconEngineRef,
terminalBlockHash = conf.terminalBlockHash

if terminalBlockHash != default(Hash32):
let headerHash = db.getBlockHash(terminalBlockNumber).valueOr:
let headerHash = db.baseTxFrame().getBlockHash(terminalBlockNumber).valueOr:
raise newException(ValueError, "cannot get terminal block hash, number $1, msg: $2" %
[$terminalBlockNumber, error])

if terminalBlockHash != headerHash:
raise newException(ValueError, "invalid terminal block hash, got $1 want $2" %
[$terminalBlockHash, $headerHash])

let header = db.getBlockHeader(headerHash).valueOr:
let header = db.baseTxFrame().getBlockHeader(headerHash).valueOr:
raise newException(ValueError, "cannot get terminal block header, hash $1, msg: $2" %
[$terminalBlockHash, error])

Expand Down
11 changes: 6 additions & 5 deletions nimbus/beacon/api_handler/api_forkchoice.nim
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ proc forkchoiceUpdated*(ben: BeaconEngineRef,
ForkchoiceUpdatedResponse =
let
com = ben.com
db = com.db
txFrame = ben.chain.latestTxFrame()
chain = ben.chain
blockHash = update.headBlockHash

Expand Down Expand Up @@ -125,8 +125,8 @@ proc forkchoiceUpdated*(ben: BeaconEngineRef,
let blockNumber = header.number
if header.difficulty > 0.u256 or blockNumber == 0'u64:
let
td = db.getScore(blockHash)
ptd = db.getScore(header.parentHash)
td = txFrame.getScore(blockHash)
ptd = txFrame.getScore(header.parentHash)
ttd = com.ttd.get(high(UInt256))

if td.isNone or (blockNumber > 0'u64 and ptd.isNone):
Expand Down Expand Up @@ -160,21 +160,22 @@ proc forkchoiceUpdated*(ben: BeaconEngineRef,

# If the beacon client also advertised a finalized block, mark the local
# chain final and completely in PoS mode.
let baseTxFrame = ben.chain.baseTxFrame
let finalizedBlockHash = update.finalizedBlockHash
if finalizedBlockHash != default(Hash32):
if not ben.chain.isCanonical(finalizedBlockHash):
warn "Final block not in canonical chain",
hash=finalizedBlockHash.short
raise invalidForkChoiceState("finalized block not canonical")
db.finalizedHeaderHash(finalizedBlockHash)
baseTxFrame.finalizedHeaderHash(finalizedBlockHash)

let safeBlockHash = update.safeBlockHash
if safeBlockHash != default(Hash32):
if not ben.chain.isCanonical(safeBlockHash):
warn "Safe block not in canonical chain",
hash=safeBlockHash.short
raise invalidForkChoiceState("safe head not canonical")
db.safeHeaderHash(safeBlockHash)
baseTxFrame.safeHeaderHash(safeBlockHash)

chain.forkChoice(blockHash, finalizedBlockHash).isOkOr:
return invalidFCU(error, chain, header)
Expand Down
10 changes: 5 additions & 5 deletions nimbus/beacon/api_handler/api_newpayload.nim
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ proc newPayload*(ben: BeaconEngineRef,

let
com = ben.com
db = com.db
txFrame = ben.chain.latestTxFrame()
timestamp = ethTime payload.timestamp
version = payload.version
requestsHash = calcRequestsHash(executionRequests)
Expand Down Expand Up @@ -185,9 +185,9 @@ proc newPayload*(ben: BeaconEngineRef,
let ttd = com.ttd.get(high(UInt256))

if version == Version.V1:
let ptd = db.getScore(header.parentHash).valueOr:
let ptd = txFrame.getScore(header.parentHash).valueOr:
0.u256
let gptd = db.getScore(parent.parentHash)
let gptd = txFrame.getScore(parent.parentHash)
if ptd < ttd:
warn "Ignoring pre-merge payload",
number = header.number, hash = blockHash.short, ptd, ttd
Expand Down Expand Up @@ -216,7 +216,7 @@ proc newPayload*(ben: BeaconEngineRef,
warn "State not available, ignoring new payload",
hash = blockHash,
number = header.number
let blockHash = latestValidHash(db, parent, ttd)
let blockHash = latestValidHash(txFrame, parent, ttd)
return acceptedStatus(blockHash)

trace "Inserting block without sethead",
Expand All @@ -229,7 +229,7 @@ proc newPayload*(ben: BeaconEngineRef,
parent = header.parentHash.short,
error = vres.error()
ben.setInvalidAncestor(header, blockHash)
let blockHash = latestValidHash(db, parent, ttd)
let blockHash = latestValidHash(txFrame, parent, ttd)
return invalidStatus(blockHash, vres.error())

ben.txPool.removeNewBlockTxs(blk, Opt.some(blockHash))
Expand Down
9 changes: 5 additions & 4 deletions nimbus/beacon/api_handler/api_utils.nim
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Nimbus
# Copyright (c) 2022-2024 Status Research & Development GmbH
# Copyright (c) 2022-2025 Status Research & Development GmbH
# Licensed under either of
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
# * MIT license ([LICENSE-MIT](LICENSE-MIT))
Expand Down Expand Up @@ -172,12 +172,13 @@ proc tooLargeRequest*(msg: string): ref InvalidRequest =
msg: msg
)

proc latestValidHash*(db: CoreDbRef,
proc latestValidHash*(txFrame: CoreDbTxRef,
parent: Header,
ttd: DifficultyInt): Hash32 =
if parent.isGenesis:
return default(Hash32)
let ptd = db.getScore(parent.parentHash).valueOr(0.u256)
# TODO shouldn't this be in forkedchainref?
let ptd = txFrame.getScore(parent.parentHash).valueOr(0.u256)
if ptd >= ttd:
parent.blockHash
else:
Expand All @@ -192,6 +193,6 @@ proc invalidFCU*(validationError: string,
return invalidFCU(validationError)

let blockHash =
latestValidHash(chain.db, parent, chain.com.ttd.get(high(UInt256)))
latestValidHash(chain.latestTxFrame, parent, chain.com.ttd.get(high(UInt256)))

invalidFCU(validationError, blockHash)
5 changes: 0 additions & 5 deletions nimbus/common/chain_config_hash.nim
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,6 @@ func update[T: ref](ctx: var sha256, val: T) =
for f in fields(val[]):
ctx.update(f)

func update(ctx: var sha256, list: openArray[Opt[BlobSchedule]]) =
mixin update
for val in list:
ctx.update(val)

# ------------------------------------------------------------------------------
# Public functions
# ------------------------------------------------------------------------------
Expand Down
34 changes: 18 additions & 16 deletions nimbus/common/common.nim
Original file line number Diff line number Diff line change
Expand Up @@ -121,10 +121,10 @@ func daoCheck(conf: ChainConfig) =
conf.daoForkBlock = conf.homesteadBlock

proc initializeDb(com: CommonRef) =
let kvt = com.db.ctx.getKvt()
proc contains(kvt: CoreDbKvtRef; key: openArray[byte]): bool =
kvt.hasKeyRc(key).expect "valid bool"
if canonicalHeadHashKey().toOpenArray notin kvt:
let txFrame = com.db.baseTxFrame()
proc contains(txFrame: CoreDbTxRef; key: openArray[byte]): bool =
txFrame.hasKeyRc(key).expect "valid bool"
if canonicalHeadHashKey().toOpenArray notin txFrame:
info "Writing genesis to DB",
blockHash = com.genesisHeader.rlpHash,
stateRoot = com.genesisHeader.stateRoot,
Expand All @@ -134,23 +134,23 @@ proc initializeDb(com: CommonRef) =
nonce = com.genesisHeader.nonce
doAssert(com.genesisHeader.number == 0.BlockNumber,
"can't commit genesis block with number > 0")
com.db.persistHeaderAndSetHead(com.genesisHeader,
txFrame.persistHeaderAndSetHead(com.genesisHeader,
startOfHistory=com.genesisHeader.parentHash).
expect("can persist genesis header")
doAssert(canonicalHeadHashKey().toOpenArray in kvt)
doAssert(canonicalHeadHashKey().toOpenArray in txFrame)

# The database must at least contain the base and head pointers - the base
# is implicitly considered finalized
let
baseNum = com.db.getSavedStateBlockNumber()
base = com.db.getBlockHeader(baseNum).valueOr:
baseNum = txFrame.getSavedStateBlockNumber()
base = txFrame.getBlockHeader(baseNum).valueOr:
fatal "Cannot load base block header",
baseNum, err = error
quit 1
finalized = com.db.finalizedHeader().valueOr:
finalized = txFrame.finalizedHeader().valueOr:
debug "No finalized block stored in database, reverting to base"
base
head = com.db.getCanonicalHead().valueOr:
head = txFrame.getCanonicalHead().valueOr:
fatal "Cannot load canonical block header",
err = error
quit 1
Expand Down Expand Up @@ -191,10 +191,12 @@ proc init(com : CommonRef,
time: Opt.some(genesis.timestamp)
)
fork = toHardFork(com.forkTransitionTable, forkDeterminer)
txFrame = db.baseTxFrame()

# Must not overwrite the global state on the single state DB
com.genesisHeader = db.getBlockHeader(0.BlockNumber).valueOr:
toGenesisHeader(genesis, fork, com.db)

com.genesisHeader = txFrame.getBlockHeader(0.BlockNumber).valueOr:
toGenesisHeader(genesis, fork, txFrame)

com.setForkId(com.genesisHeader)

Expand All @@ -203,13 +205,13 @@ proc init(com : CommonRef,

com.initializeDb()

proc isBlockAfterTtd(com: CommonRef, header: Header): bool =
proc isBlockAfterTtd(com: CommonRef, header: Header, txFrame: CoreDbTxRef): bool =
if com.config.terminalTotalDifficulty.isNone:
return false

let
ttd = com.config.terminalTotalDifficulty.get()
ptd = com.db.getScore(header.parentHash).valueOr:
ptd = txFrame.getScore(header.parentHash).valueOr:
return false
td = ptd + header.difficulty
ptd >= ttd and td >= ttd
Expand Down Expand Up @@ -321,15 +323,15 @@ func isCancunOrLater*(com: CommonRef, t: EthTime): bool =
func isPragueOrLater*(com: CommonRef, t: EthTime): bool =
com.config.pragueTime.isSome and t >= com.config.pragueTime.get

proc proofOfStake*(com: CommonRef, header: Header): bool =
proc proofOfStake*(com: CommonRef, header: Header, txFrame: CoreDbTxRef): bool =
if com.config.posBlock.isSome:
# see comments of posBlock in common/hardforks.nim
header.number >= com.config.posBlock.get
elif com.config.mergeNetsplitBlock.isSome:
header.number >= com.config.mergeNetsplitBlock.get
else:
# This costly check is only executed from test suite
com.isBlockAfterTtd(header)
com.isBlockAfterTtd(header, txFrame)

func depositContractAddress*(com: CommonRef): Address =
com.config.depositContractAddress.get(default(Address))
Expand Down
Loading
Loading