Skip to content

Commit

Permalink
aristo: fork support via layers/txframes
Browse files Browse the repository at this point in the history
This change reorganises how the database is accessed: instead holding a
"current frame" in the database object, a dag of frames is created based
on the "base frame" held in `AristoDbRef` and all database access
happens through this frame, which can be thought of as a consistent
point-in-time snapshot of the database based on a particular fork of the
chain.

In the code, "frame", "transaction" and "layer" is used to denote more
or less the same thing: a dag of stacked changes backed by the on-disk
database.

Although this is not a requirement, in practice each frame holds the
change set of a single block - as such, the frame and its ancestors
leading up to the on-disk state represents the state of the database
after that block has been applied.

"committing" means merging the changes to its parent frame so that the
difference between them is lost and only the cumulative changes remain -
this facility enables frames to be combined arbitrarily wherever they
are in the dag.

In particular, it becomes possible to consolidate a set of changes near
the base of the dag and commit those to disk without having to re-do the
in-memory frames built on top of them - this is useful for "flattening"
a set of changes during a base update and sending those to storage
without having to perform a block replay on top.

Looking at abstractions, a side effect of this change is that the KVT
and Aristo are brought closer together by considering them to be part of
the "same" atomic transaction set - the way the code gets organised,
applying a block and saving it to the kvt happens in the same "logical"
frame - therefore, discarding the frame discards both the aristo and kvt
changes at the same time - likewise, they are persisted to disk together
- this makes reasoning about the database somewhat easier but has the
downside of increased memory usage, something that perhaps will need
addressing in the future.

Because the code reasons more strictly about frames and the state of the
persisted database, it also makes it more visible where ForkedChain
should be used and where it is still missing - in particular, frames
represent a single branch of history while forkedchain manages multiple
parallel forks - user-facing services such as the RPC should use the
latter, ie until it has been finalized, a getBlock request should
consider all forks and not just the blocks in the canonical head branch.

Another advantage of this approach is that `AristoDbRef` conceptually
becomes more simple - removing its tracking of the "current" transaction
stack simplifies reasoning about what can go wrong since this state now
has to be passed around in the form of `AristoTxRef` - as such, many of
the tests and facilities in the code that were dealing with "stack
inconsistency" are now structurally prevented from happening. The test
suite will need significant refactoring after this change.

Once this change has been merged, there are several follow-ups to do:

* there's no mechanism for keeping frames up to date as they get
committed or rolled back - TODO
* naming is confused - many names for the same thing for legacy reason
* forkedchain support is still missing in lots of code
* clean up redundant logic based on previous designs - in particular the
debug and introspection code no longer makes sense
* the way change sets are stored will probably need revisiting - because
it's a stack of changes where each frame must be interrogated to find an
on-disk value, with a base distance of 128 we'll at minimum have to
perform 128 frame lookups for *every* database interaction - regardless,
the "dag-like" nature will stay
* dispose and commit are poorly defined and perhaps redundant - in
theory, one could simply let the GC collect abandoned frames etc, though
it's likely an explicit mechanism will remain useful, so they stay for
now

More about the changes:

* `AristoDbRef` gains a `txRef` field (todo: rename) that "more or less"
corresponds to the old `balancer` field
* `AristoDbRef.stack` is gone - instead, there's a chain of
`AristoTxRef` objects that hold their respective "layer" which has the
actual changes
* No more reasoning about "top" and "stack" - instead, each
`AristoTxRef` can be a "head" that "more or less" corresponds to the old
single-history `top` notion and its stack
* `level` still represents "distance to base" - it's computed from the
parent chain instead of being stored
* one has to be careful not to use frames where forkedchain was intended
- layers are only for a single branch of history!
  • Loading branch information
arnetheduck committed Dec 20, 2024
1 parent 59b9303 commit 776b2b4
Show file tree
Hide file tree
Showing 100 changed files with 1,693 additions and 2,484 deletions.
18 changes: 8 additions & 10 deletions hive_integration/nodocker/engine/node.nim
Original file line number Diff line number Diff line change
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 @@ -64,7 +62,7 @@ proc processBlock(
discard com.db.persistUncles(blk.uncles)

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

vmState.mutateStateDB:
Expand All @@ -75,10 +73,10 @@ proc processBlock(

ok()

proc getVmState(c: ChainRef, header: Header):
proc getVmState(c: ChainRef, header: Header, txFrame: CoreDbTxRef):
Result[BaseVMState, void] =
let vmState = BaseVMState()
if not vmState.init(header, c.com, storeSlotHash = false):
if not vmState.init(header, c.com, txFrame, storeSlotHash = false):
debug "Cannot initialise VmState",
number = header.number
return err()
Expand All @@ -94,17 +92,17 @@ proc setBlock*(c: ChainRef; blk: Block): Result[void, string] =

# Needed for figuring out whether KVT cleanup is due (see at the end)
let
vmState = c.getVmState(header).valueOr:
vmState = c.getVmState(header, txFrame).valueOr:
return err("no vmstate")
? 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
Expand Down
4 changes: 2 additions & 2 deletions nimbus/beacon/api_handler/api_exchangeconf.nim
Original file line number Diff line number Diff line change
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
3 changes: 2 additions & 1 deletion 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
db = com.db.baseTxFrame() # TODO forkedChain!
chain = ben.chain
blockHash = update.headBlockHash

Expand Down Expand Up @@ -125,6 +125,7 @@ proc forkchoiceUpdated*(ben: BeaconEngineRef,
let blockNumber = header.number
if header.difficulty > 0.u256 or blockNumber == 0'u64:
let
# TODO this chould be forkedchain!
td = db.getScore(blockHash)
ptd = db.getScore(header.parentHash)
ttd = com.ttd.get(high(UInt256))
Expand Down
8 changes: 4 additions & 4 deletions nimbus/beacon/api_handler/api_newpayload.nim
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ proc newPayload*(ben: BeaconEngineRef,

let
com = ben.com
db = com.db
db = com.db.baseTxFrame() # TODO this should be forkedchain!
timestamp = ethTime payload.timestamp
version = payload.version
requestsHash = calcRequestsHash(executionRequests)
Expand Down Expand Up @@ -185,7 +185,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(com.db, parent, ttd)
return acceptedStatus(blockHash)

trace "Inserting block without sethead",
Expand All @@ -195,10 +195,10 @@ proc newPayload*(ben: BeaconEngineRef,
warn "Error importing block",
number = header.number,
hash = blockHash.short,
parent = header.parentHash.short,
parent = header.parentHash.short,
error = vres.error()
ben.setInvalidAncestor(header, blockHash)
let blockHash = latestValidHash(db, parent, ttd)
let blockHash = latestValidHash(com.db, parent, ttd)
return invalidStatus(blockHash, vres.error())

info "New payload received and validated",
Expand Down
3 changes: 2 additions & 1 deletion nimbus/beacon/api_handler/api_utils.nim
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,8 @@ proc latestValidHash*(db: CoreDbRef,
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 = db.baseTxFrame().getScore(parent.parentHash).valueOr(0.u256)
if ptd >= ttd:
parent.blockHash
else:
Expand Down
34 changes: 18 additions & 16 deletions nimbus/common/common.nim
Original file line number Diff line number Diff line change
Expand Up @@ -125,10 +125,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 @@ -138,23 +138,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 @@ -196,10 +196,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)
com.pos.timestamp = genesis.timestamp
Expand All @@ -209,13 +211,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 @@ -325,15 +327,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
8 changes: 4 additions & 4 deletions nimbus/common/genesis.nim
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import

proc toGenesisHeader*(
g: Genesis;
db: CoreDbRef;
db: CoreDbTxRef;
fork: HardFork;
): Header =
## Initialise block chain DB accounts derived from the `genesis.alloc` table
Expand Down Expand Up @@ -81,16 +81,16 @@ proc toGenesisHeader*(
proc toGenesisHeader*(
genesis: Genesis;
fork: HardFork;
db = CoreDbRef(nil)): Header =
db = CoreDbTxRef(nil)): Header =
## Generate the genesis block header from the `genesis` and `config`
## argument value.
let
db = if db.isNil: AristoDbMemory.newCoreDbRef() else: db
db = if db.isNil: AristoDbMemory.newCoreDbRef().ctx.txFrameBegin(nil) else: db
toGenesisHeader(genesis, db, fork)

proc toGenesisHeader*(
params: NetworkParams;
db = CoreDbRef(nil)
db = CoreDbTxRef(nil)
): Header =
## Generate the genesis block header from the `genesis` and `config`
## argument value.
Expand Down
Loading

0 comments on commit 776b2b4

Please sign in to comment.