nimbus-eth1/tests/test_generalstate_json.nim

242 lines
7.1 KiB
Nim
Raw Permalink Normal View History

# Nimbus
# Copyright (c) 2018-2024 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)
# * 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.
import
std/[strutils, tables, json, os, sets],
./test_helpers, ./test_allowed_to_fail,
2022-12-02 04:39:12 +00:00
../nimbus/core/executor, test_config,
2019-11-13 14:49:39 +00:00
../nimbus/transaction,
../nimbus/[evm/state, evm/types],
../nimbus/db/ledger,
2022-12-02 04:39:12 +00:00
../nimbus/common/common,
../nimbus/utils/[utils, debug],
../nimbus/evm/tracer/legacy_tracer,
../nimbus/core/eip4844,
../tools/common/helpers as chp,
../tools/evmstate/helpers,
../tools/common/state_clearing,
2022-12-02 04:39:12 +00:00
eth/trie/trie_defs,
eth/common/transaction_utils,
unittest2,
2024-05-30 12:54:03 +00:00
stew/byteutils,
results
2019-03-18 01:55:02 +00:00
type
TestCtx = object
2019-03-18 01:55:02 +00:00
name: string
parent: Header
header: Header
2019-03-18 01:55:02 +00:00
pre: JsonNode
tx: Transaction
expectedHash: Hash32
expectedLogs: Hash32
chainConfig: ChainConfig
2019-03-18 01:55:02 +00:00
debugMode: bool
trace: bool
2019-03-21 09:01:26 +00:00
index: int
fork: string
2019-02-28 08:22:07 +00:00
var
trustedSetupLoaded = false
2019-03-18 14:18:04 +00:00
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: BaseVMState; blockNumber: BlockNumber): Hash32 =
2019-03-18 14:18:04 +00:00
if blockNumber >= vmState.blockNumber:
return default(Hash32)
2019-03-18 14:18:04 +00:00
elif blockNumber < 0:
return default(Hash32)
2019-03-18 14:18:04 +00:00
elif blockNumber < vmState.blockNumber - 256:
return default(Hash32)
2019-03-18 14:18:04 +00:00
else:
return keccak256(toBytes($blockNumber))
2019-03-18 14:18:04 +00:00
func normalizeFileName(x: string): string =
const invalidChars = ['/', '\\', '?', '%', '*', ':', '|', '"', '<', '>', ',', ';', '=']
result = newStringOfCap(x.len)
for c in x:
if c in invalidChars: result.add '_'
else: result.add c
proc dumpDebugData(ctx: TestCtx, vmState: BaseVMState, gasUsed: GasInt, success: bool) =
let tracerInst = LegacyTracer(vmState.tracer)
let tracingResult = if ctx.trace: tracerInst.getTracingResult() else: %[]
2019-03-18 01:55:02 +00:00
let debugData = %{
"gasUsed": %gasUsed,
"structLogs": tracingResult,
"accounts": vmState.dumpAccounts()
2019-03-18 01:55:02 +00:00
}
2019-03-21 09:01:26 +00:00
let status = if success: "_success" else: "_failed"
let fileName = normalizeFileName(ctx.name)
writeFile(fileName & "_" & ctx.fork & "_" & $ctx.index & status & ".json", debugData.pretty())
2019-03-18 01:55:02 +00:00
proc testFixtureIndexes(ctx: var TestCtx, testStatusIMPL: var TestStatus) =
2022-12-02 04:39:12 +00:00
let
com = CommonRef.new(newCoreDbRef DefaultDbMemory, ctx.chainConfig)
parent = Header(stateRoot: emptyRlpHash)
tracer = if ctx.trace:
newLegacyTracer({})
else:
LegacyTracer(nil)
if com.isCancunOrLater(ctx.header.timestamp):
if not trustedSetupLoaded:
let res = loadKzgTrustedSetup()
if res.isErr:
echo "FATAL: ", res.error
quit(QuitFailure)
trustedSetupLoaded = true
let vmState = BaseVMState.new(
parent = parent,
header = ctx.header,
com = com,
tracer = tracer,
storeSlotHash = ctx.trace,
2022-12-02 04:39:12 +00:00
)
2019-11-28 10:02:11 +00:00
2019-03-21 09:01:26 +00:00
var gasUsed: GasInt
let sender = ctx.tx.recoverSender().expect("valid signature")
2019-03-21 09:01:26 +00:00
vmState.mutateStateDB:
setupStateDB(ctx.pre, db)
# this is an important step when using `db/ledger`
# it will affect the account storage's location
# during the next call to `getComittedStorage`
db.persist()
2019-11-19 06:12:13 +00:00
let rc = vmState.processTransaction(
ctx.tx, sender, ctx.header)
if rc.isOk:
gasUsed = rc.value
let miner = ctx.header.coinbase
coinbaseStateClearing(vmState, miner)
block post:
let obtainedHash = vmState.readOnlyStateDB.getStateRoot()
check obtainedHash == ctx.expectedHash
2019-02-28 08:22:07 +00:00
let logEntries = vmState.getAndClearLogEntries()
let actualLogsHash = rlpHash(logEntries)
check(ctx.expectedLogs == actualLogsHash)
if ctx.debugMode:
let success = ctx.expectedLogs == actualLogsHash and obtainedHash == ctx.expectedHash
ctx.dumpDebugData(vmState, gasUsed, success)
2019-03-18 03:05:24 +00:00
proc testFixture(fixtures: JsonNode, testStatusIMPL: var TestStatus,
trace = false, debugMode = false) =
var ctx: TestCtx
var fixture: JsonNode
for label, child in fixtures:
fixture = child
ctx.name = label
break
ctx.pre = fixture["pre"]
ctx.parent = parseParentHeader(fixture["env"])
ctx.header = parseHeader(fixture["env"])
ctx.trace = trace
ctx.debugMode = debugMode
let
post = fixture["post"]
txData = fixture["transaction"]
conf = getConfiguration()
template prepareFork(forkName: string) =
try:
ctx.chainConfig = getChainConfig(forkName)
except ValueError as ex:
debugEcho ex.msg
testStatusIMPL = TestStatus.FAILED
return
template runSubTest(subTest: JsonNode) =
ctx.expectedHash = Hash32.fromJson(subTest["hash"])
ctx.expectedLogs = Hash32.fromJson(subTest["logs"])
ctx.tx = parseTx(txData, subTest["indexes"])
ctx.testFixtureIndexes(testStatusIMPL)
if conf.fork.len > 0:
if not post.hasKey(conf.fork):
debugEcho "selected fork not available: " & conf.fork
return
ctx.fork = conf.fork
let forkData = post[conf.fork]
prepareFork(conf.fork)
if conf.index.isNone:
for subTest in forkData:
runSubTest(subTest)
inc ctx.index
else:
ctx.index = conf.index.get()
if ctx.index > forkData.len or ctx.index < 0:
debugEcho "selected index out of range(0-$1), requested $2" %
[$forkData.len, $ctx.index]
return
let subTest = forkData[ctx.index]
runSubTest(subTest)
else:
for forkName, forkData in post:
prepareFork(forkName)
ctx.fork = forkName
ctx.index = 0
for subTest in forkData:
runSubTest(subTest)
inc ctx.index
2019-03-18 03:05:24 +00:00
2019-09-21 05:45:23 +00:00
proc generalStateJsonMain*(debugMode = false) =
const
legacyFolder = "eth_tests/LegacyTests/Constantinople/GeneralStateTests"
newFolder = "eth_tests/GeneralStateTests"
#newFolder = "eth_tests/EIPTests/StateTests"
2021-01-14 14:33:18 +00:00
let config = getConfiguration()
if config.testSubject == "" or not debugMode:
2019-03-18 01:55:02 +00:00
# run all test fixtures
2021-01-14 14:33:18 +00:00
if config.legacy:
suite "generalstate json tests":
jsonTest(legacyFolder, "GeneralStateTests", testFixture, skipGSTTests)
2021-01-14 14:33:18 +00:00
else:
suite "new generalstate json tests":
jsonTest(newFolder, "newGeneralStateTests", testFixture, skipNewGSTTests)
2019-03-18 01:55:02 +00:00
else:
# execute single test in debug mode
2019-03-18 03:05:24 +00:00
if config.testSubject.len == 0:
echo "missing test subject"
quit(QuitFailure)
let folder = if config.legacy: legacyFolder else: newFolder
let path = "tests" / "fixtures" / folder
2019-03-18 03:05:24 +00:00
let n = json.parseFile(path / config.testSubject)
2019-03-18 01:55:02 +00:00
var testStatusIMPL: TestStatus
testFixture(n, testStatusIMPL, config.trace, true)
2019-03-18 03:05:24 +00:00
when isMainModule:
import std/times
2019-03-18 03:05:24 +00:00
var message: string
let start = getTime()
2019-03-18 03:05:24 +00:00
## Processing command line arguments
if processArguments(message) != Success:
echo message
quit(QuitFailure)
else:
if len(message) > 0:
echo message
quit(QuitSuccess)
2019-09-21 05:45:23 +00:00
generalStateJsonMain(true)
let elpd = getTime() - start
echo "TIME: ", elpd