nimbus-eth1/tools/evmstate/evmstate.nim

276 lines
7.3 KiB
Nim
Raw Normal View History

2022-12-10 19:53:24 +07:00
# Nimbus
aristo: fork support via layers/txframes (#2960) * aristo: fork support via layers/txframes 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! * fix layer vtop after rollback * engine fix * Fix test_txpool * Fix test_rpc * Fix copyright year * fix simulator * Fix copyright year * Fix copyright year * Fix tracer * Fix infinite recursion bug * Remove aristo and kvt empty files * Fic copyright year * Fix fc chain_kvt * ForkedChain refactoring * Fix merge master conflict * Fix copyright year * Reparent txFrame * Fix test * Fix txFrame reparent again * Cleanup and fix test * UpdateBase bugfix and fix test * Fixe newPayload bug discovered by hive * Fix engine api fcu * Clean up call template, chain_kvt, andn txguid * Fix copyright year * work around base block loading issue * Add test * Fix updateHead bug * Fix updateBase bug * Change func commitBase to proc commitBase * Touch up and fix debug mode crash --------- Co-authored-by: jangko <jangko128@gmail.com>
2025-02-06 08:04:50 +01:00
# Copyright (c) 2022-2025 Status Research & Development GmbH
2022-12-10 19:53:24 +07:00
# Licensed under either of
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
# http://www.apache.org/licenses/LICENSE-2.0)
# * MIT license ([LICENSE-MIT](LICENSE-MIT) or
# http://opensource.org/licenses/MIT)
# at your option. This file may not be copied, modified, or distributed except
# according to those terms.
2022-10-26 22:46:13 +07:00
import
std/[json, strutils, sets, tables, options, streams],
chronicles,
eth/common/keys,
eth/common/transaction_utils,
2024-05-30 14:54:03 +02:00
stew/byteutils,
results,
2022-10-26 22:46:13 +07:00
stint,
../../execution_chain/[evm/types, evm/state],
../../execution_chain/db/ledger,
../../execution_chain/transaction,
../../execution_chain/core/executor,
../../execution_chain/common/common,
../../execution_chain/evm/tracer/json_tracer,
../../execution_chain/core/eip4844,
../../execution_chain/utils/state_dump,
../common/helpers as chp,
"."/[config, helpers],
../common/state_clearing
2022-10-26 22:46:13 +07:00
type
StateContext = object
name: string
parent: Header
header: Header
2022-10-26 22:46:13 +07:00
tx: Transaction
expectedHash: Hash32
expectedLogs: Hash32
2023-02-23 09:15:58 +07:00
forkStr: string
chainConfig: ChainConfig
2022-10-26 22:46:13 +07:00
index: int
tracerFlags: set[TracerFlags]
error: string
StateResult = object
name : string
pass : bool
root : Hash32
2022-10-26 22:46:13 +07:00
fork : string
error: string
state: StateDump
2022-12-15 10:46:28 +07:00
TestVMState = ref object of BaseVMState
2022-10-26 22:46:13 +07:00
proc extractNameAndFixture(ctx: var StateContext, n: JsonNode): JsonNode =
for label, child in n:
result = child
ctx.name = label
return
doAssert(false, "unreachable")
proc toBytes(x: string): seq[byte] =
result = newSeq[byte](x.len)
for i in 0..<x.len: result[i] = x[i].byte
method getAncestorHash(vmState: TestVMState; blockNumber: BlockNumber): Hash32 =
keccak256(toBytes($blockNumber))
2022-10-26 22:46:13 +07:00
proc verifyResult(ctx: var StateContext, vmState: BaseVMState, obtainedHash: Hash32) =
ctx.error = ""
2022-10-26 22:46:13 +07:00
if obtainedHash != ctx.expectedHash:
ctx.error = "post state root mismatch: got $1, want $2" %
[($obtainedHash).toLowerAscii, $ctx.expectedHash]
2022-10-26 22:46:13 +07:00
return
let logEntries = vmState.getAndClearLogEntries()
let actualLogsHash = rlpHash(logEntries)
if actualLogsHash != ctx.expectedLogs:
ctx.error = "post state log hash mismatch: got $1, want $2" %
[($actualLogsHash).toLowerAscii, $ctx.expectedLogs]
2022-10-26 22:46:13 +07:00
return
proc writeResultToStdout(stateRes: seq[StateResult]) =
var n = newJArray()
for res in stateRes:
let z = %{
"name" : %(res.name),
"pass" : %(res.pass),
"stateRoot" : %(res.root),
2022-10-26 22:46:13 +07:00
"fork" : %(res.fork),
"error": %(res.error)
}
if res.state.isNil.not:
z["state"] = %(res.state)
n.add(z)
stdout.write(n.pretty)
stdout.write("\n")
proc writeRootHashToStderr(stateRoot: Hash32) =
let stateRoot = %{
"stateRoot": %(stateRoot)
}
stderr.writeLine($stateRoot)
2022-10-26 22:46:13 +07:00
proc runExecution(ctx: var StateContext, conf: StateConf, pre: JsonNode): StateResult =
let
com = CommonRef.new(newCoreDbRef DefaultDbMemory, nil, ctx.chainConfig)
stream = newFileStream(stderr)
tracer = if conf.jsonEnabled:
newJsonTracer(stream, ctx.tracerFlags, conf.pretty)
else:
JsonTracer(nil)
2022-10-26 22:46:13 +07:00
2022-12-15 10:46:28 +07:00
let vmState = TestVMState()
vmState.init(
parent = ctx.parent,
header = ctx.header,
com = com,
aristo: fork support via layers/txframes (#2960) * aristo: fork support via layers/txframes 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! * fix layer vtop after rollback * engine fix * Fix test_txpool * Fix test_rpc * Fix copyright year * fix simulator * Fix copyright year * Fix copyright year * Fix tracer * Fix infinite recursion bug * Remove aristo and kvt empty files * Fic copyright year * Fix fc chain_kvt * ForkedChain refactoring * Fix merge master conflict * Fix copyright year * Reparent txFrame * Fix test * Fix txFrame reparent again * Cleanup and fix test * UpdateBase bugfix and fix test * Fixe newPayload bug discovered by hive * Fix engine api fcu * Clean up call template, chain_kvt, andn txguid * Fix copyright year * work around base block loading issue * Add test * Fix updateHead bug * Fix updateBase bug * Change func commitBase to proc commitBase * Touch up and fix debug mode crash --------- Co-authored-by: jangko <jangko128@gmail.com>
2025-02-06 08:04:50 +01:00
txFrame = com.db.baseTxFrame(),
tracer = tracer)
2022-10-26 22:46:13 +07:00
var gasUsed: GasInt
let sender = ctx.tx.recoverSender().expect("valid signature")
2022-10-26 22:46:13 +07:00
vmState.mutateLedger:
setupLedger(pre, db)
db.persist(clearEmptyAccount = false) # settle accounts storage
2022-10-26 22:46:13 +07:00
defer:
let stateRoot = vmState.readOnlyLedger.getStateRoot()
ctx.verifyResult(vmState, stateRoot)
2022-10-26 22:46:13 +07:00
result = StateResult(
name : ctx.name,
pass : ctx.error.len == 0,
root : stateRoot,
2023-02-23 09:15:58 +07:00
fork : ctx.forkStr,
2022-10-26 22:46:13 +07:00
error: ctx.error
)
if conf.dumpEnabled:
result.state = dumpState(vmState.ledger)
2022-10-26 22:46:13 +07:00
if conf.jsonEnabled:
writeRootHashToStderr(stateRoot)
2022-10-26 22:46:13 +07:00
try:
let rc = vmState.processTransaction(
ctx.tx, sender, ctx.header)
if rc.isOk:
gasUsed = rc.value
coinbaseStateClearing(vmState, ctx.header.coinbase)
except CatchableError as ex:
echo "FATAL: ", ex.msg
quit(QuitFailure)
except AssertionDefect as ex:
echo "FATAL: ", ex.msg
quit(QuitFailure)
2022-10-26 22:46:13 +07:00
proc toTracerFlags(conf: StateConf): set[TracerFlags] =
2022-10-26 22:46:13 +07:00
result = {
TracerFlags.DisableStateDiff
2022-10-26 22:46:13 +07:00
}
if conf.disableMemory : result.incl TracerFlags.DisableMemory
if conf.disableStack : result.incl TracerFlags.DisableStack
2022-10-26 22:46:13 +07:00
if conf.disableReturnData: result.incl TracerFlags.DisableReturnData
if conf.disableStorage : result.incl TracerFlags.DisableStorage
template hasError(ctx: StateContext): bool =
ctx.error.len > 0
proc prepareAndRun(inputFile: string, conf: StateConf): bool =
var
ctx: StateContext
2022-10-26 22:46:13 +07:00
let
fixture = json.parseFile(inputFile)
2022-10-26 22:46:13 +07:00
n = ctx.extractNameAndFixture(fixture)
txData = n["transaction"]
post = n["post"]
pre = n["pre"]
ctx.parent = parseParentHeader(n["env"])
2022-10-26 22:46:13 +07:00
ctx.header = parseHeader(n["env"])
if conf.debugEnabled or conf.jsonEnabled:
ctx.tracerFlags = toTracerFlags(conf)
var
stateRes = newSeqOfCap[StateResult](post.len)
index = 1
hasError = false
template prepareFork(forkName: string) =
try:
2023-02-23 09:15:58 +07:00
ctx.forkStr = forkName
ctx.chainConfig = getChainConfig(forkName)
except ValueError as ex:
debugEcho ex.msg
return false
2022-10-26 22:46:13 +07:00
ctx.index = index
inc index
template runSubTest(subTest: JsonNode) =
ctx.expectedHash = Hash32.fromJson(subTest["hash"])
ctx.expectedLogs = Hash32.fromJson(subTest["logs"])
2022-10-26 22:46:13 +07:00
ctx.tx = parseTx(txData, subTest["indexes"])
let res = ctx.runExecution(conf, pre)
stateRes.add res
hasError = hasError or ctx.hasError
if conf.fork.len > 0:
if not post.hasKey(conf.fork):
stdout.writeLine("selected fork not available: " & conf.fork)
return false
let forkData = post[conf.fork]
prepareFork(conf.fork)
if conf.index.isNone:
for subTest in forkData:
runSubTest(subTest)
else:
let index = conf.index.get()
if index > forkData.len or index < 0:
stdout.writeLine("selected index out of range(0-$1), requested $2" %
[$forkData.len, $index])
return false
let subTest = forkData[index]
runSubTest(subTest)
else:
for forkName, forkData in post:
prepareFork(forkName)
for subTest in forkData:
runSubTest(subTest)
writeResultToStdout(stateRes)
not hasError
when defined(chronicles_runtime_filtering):
type Lev = chronicles.LogLevel
proc toLogLevel(v: int): Lev =
case v
of 1: Lev.ERROR
of 2: Lev.WARN
of 3: Lev.INFO
of 4: Lev.DEBUG
of 5: Lev.TRACE
else: Lev.NONE
proc setVerbosity(v: int) =
let level = v.toLogLevel
setLogLevel(level)
2022-10-26 22:46:13 +07:00
proc main() =
let conf = StateConf.init()
when defined(chronicles_runtime_filtering):
setVerbosity(conf.verbosity)
loadKzgTrustedSetup().isOkOr:
echo "FATAL: ", error
2022-10-26 22:46:13 +07:00
quit(QuitFailure)
if conf.inputFile.len > 0:
if not prepareAndRun(conf.inputFile, conf):
quit(QuitFailure)
else:
var noError = true
for inputFile in lines(stdin):
let res = prepareAndRun(inputFile, conf)
noError = noError and res
if not noError:
quit(QuitFailure)
2022-10-26 22:46:13 +07:00
main()