Fix eth/common related deprecation warnings for t8n and evmstate tools (#2711)

* Fix eth/common related deprecation warnings for t8n

* Fix eth/common related deprecation warnings for evmstate
This commit is contained in:
andri lim 2024-10-08 12:52:32 +07:00 committed by GitHub
parent 22134fcf4c
commit 6f9fc3eced
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 110 additions and 109 deletions

View File

@ -11,7 +11,7 @@
import import
std/[json, strutils, sets, tables, options, streams], std/[json, strutils, sets, tables, options, streams],
chronicles, chronicles,
eth/keys, eth/common/keys,
eth/common/transaction_utils, eth/common/transaction_utils,
stew/byteutils, stew/byteutils,
results, results,
@ -32,11 +32,11 @@ import
type type
StateContext = object StateContext = object
name: string name: string
parent: BlockHeader parent: Header
header: BlockHeader header: Header
tx: Transaction tx: Transaction
expectedHash: Hash256 expectedHash: Hash32
expectedLogs: Hash256 expectedLogs: Hash32
forkStr: string forkStr: string
chainConfig: ChainConfig chainConfig: ChainConfig
index: int index: int
@ -47,7 +47,7 @@ type
StateResult = object StateResult = object
name : string name : string
pass : bool pass : bool
root : Hash256 root : Hash32
fork : string fork : string
error: string error: string
state: StateDump state: StateDump
@ -65,10 +65,10 @@ proc toBytes(x: string): seq[byte] =
result = newSeq[byte](x.len) result = newSeq[byte](x.len)
for i in 0..<x.len: result[i] = x[i].byte for i in 0..<x.len: result[i] = x[i].byte
method getAncestorHash(vmState: TestVMState; blockNumber: BlockNumber): Hash256 = method getAncestorHash(vmState: TestVMState; blockNumber: BlockNumber): Hash32 =
keccakHash(toBytes($blockNumber)) keccak256(toBytes($blockNumber))
proc verifyResult(ctx: var StateContext, vmState: BaseVMState, obtainedHash: Hash256) = proc verifyResult(ctx: var StateContext, vmState: BaseVMState, obtainedHash: Hash32) =
ctx.error = "" ctx.error = ""
if obtainedHash != ctx.expectedHash: if obtainedHash != ctx.expectedHash:
ctx.error = "post state root mismatch: got $1, want $2" % ctx.error = "post state root mismatch: got $1, want $2" %
@ -99,7 +99,7 @@ proc writeResultToStdout(stateRes: seq[StateResult]) =
stdout.write(n.pretty) stdout.write(n.pretty)
stdout.write("\n") stdout.write("\n")
proc writeRootHashToStderr(stateRoot: Hash256) = proc writeRootHashToStderr(stateRoot: Hash32) =
let stateRoot = %{ let stateRoot = %{
"stateRoot": %(stateRoot) "stateRoot": %(stateRoot)
} }
@ -209,8 +209,8 @@ proc prepareAndRun(ctx: var StateContext, conf: StateConf): bool =
inc index inc index
template runSubTest(subTest: JsonNode) = template runSubTest(subTest: JsonNode) =
ctx.expectedHash = Hash256.fromJson(subTest["hash"]) ctx.expectedHash = Hash32.fromJson(subTest["hash"])
ctx.expectedLogs = Hash256.fromJson(subTest["logs"]) ctx.expectedLogs = Hash32.fromJson(subTest["logs"])
ctx.tx = parseTx(txData, subTest["indexes"]) ctx.tx = parseTx(txData, subTest["indexes"])
let res = ctx.runExecution(conf, pre) let res = ctx.runExecution(conf, pre)
stateRes.add res stateRes.add res

View File

@ -10,7 +10,9 @@
import import
std/[json, strutils], std/[json, strutils],
eth/[common, keys], eth/common/keys,
eth/common/headers,
eth/common/transactions,
eth/trie/trie_defs, eth/trie/trie_defs,
stint, stint,
stew/byteutils, stew/byteutils,
@ -18,8 +20,8 @@ import
../../nimbus/db/ledger, ../../nimbus/db/ledger,
../../nimbus/common/chain_config ../../nimbus/common/chain_config
template fromJson(T: type EthAddress, n: JsonNode): EthAddress = template fromJson(T: type Address, n: JsonNode): Address =
EthAddress.fromHex(n.getStr) Address.fromHex(n.getStr)
proc fromJson(T: type UInt256, n: JsonNode): UInt256 = proc fromJson(T: type UInt256, n: JsonNode): UInt256 =
# stTransactionTest/ValueOverflow.json # stTransactionTest/ValueOverflow.json
@ -33,10 +35,10 @@ proc fromJson(T: type UInt256, n: JsonNode): UInt256 =
template fromJson*(T: type Bytes32, n: JsonNode): Bytes32 = template fromJson*(T: type Bytes32, n: JsonNode): Bytes32 =
Bytes32(hexToByteArray(n.getStr, 32)) Bytes32(hexToByteArray(n.getStr, 32))
template fromJson*(T: type Hash256, n: JsonNode): Hash256 = template fromJson*(T: type Hash32, n: JsonNode): Hash32 =
Hash32(hexToByteArray(n.getStr, 32)) Hash32(hexToByteArray(n.getStr, 32))
proc fromJson(T: type Blob, n: JsonNode): Blob = proc fromJson(T: type seq[byte], n: JsonNode): T =
let hex = n.getStr let hex = n.getStr
if hex.len == 0: if hex.len == 0:
@[] @[]
@ -60,16 +62,16 @@ proc fromJson(T: type AccessList, n: JsonNode): AccessList =
for x in n: for x in n:
var ap = AccessPair( var ap = AccessPair(
address: EthAddress.fromJson(x["address"]) address: Address.fromJson(x["address"])
) )
let sks = x["storageKeys"] let sks = x["storageKeys"]
for sk in sks: for sk in sks:
ap.storageKeys.add Bytes32.fromHex(sk.getStr) ap.storageKeys.add Bytes32.fromHex(sk.getStr)
result.add ap result.add ap
proc fromJson(T: type VersionedHashes, list: JsonNode): VersionedHashes = proc fromJson(T: type seq[Hash32], list: JsonNode): T =
for x in list: for x in list:
result.add VersionedHash.fromHex(x.getStr) result.add Hash32.fromHex(x.getStr)
template required(T: type, nField: string): auto = template required(T: type, nField: string): auto =
fromJson(T, n[nField]) fromJson(T, n[nField])
@ -104,9 +106,9 @@ proc txType(n: JsonNode): TxType =
return TxEip2930 return TxEip2930
TxLegacy TxLegacy
proc parseHeader*(n: JsonNode): BlockHeader = proc parseHeader*(n: JsonNode): Header =
BlockHeader( Header(
coinbase : required(EthAddress, "currentCoinbase"), coinbase : required(Address, "currentCoinbase"),
difficulty : required(DifficultyInt, "currentDifficulty"), difficulty : required(DifficultyInt, "currentDifficulty"),
number : required(BlockNumber, "currentNumber"), number : required(BlockNumber, "currentNumber"),
gasLimit : required(GasInt, "currentGasLimit"), gasLimit : required(GasInt, "currentGasLimit"),
@ -114,13 +116,13 @@ proc parseHeader*(n: JsonNode): BlockHeader =
stateRoot : emptyRlpHash, stateRoot : emptyRlpHash,
mixHash : omitZero(Bytes32, "currentRandom"), mixHash : omitZero(Bytes32, "currentRandom"),
baseFeePerGas : optional(UInt256, "currentBaseFee"), baseFeePerGas : optional(UInt256, "currentBaseFee"),
withdrawalsRoot: optional(Hash256, "currentWithdrawalsRoot"), withdrawalsRoot: optional(Hash32, "currentWithdrawalsRoot"),
excessBlobGas : optional(uint64, "currentExcessBlobGas"), excessBlobGas : optional(uint64, "currentExcessBlobGas"),
parentBeaconBlockRoot: optional(Hash256, "currentBeaconRoot"), parentBeaconBlockRoot: optional(Hash32, "currentBeaconRoot"),
) )
proc parseParentHeader*(n: JsonNode): BlockHeader = proc parseParentHeader*(n: JsonNode): Header =
BlockHeader( Header(
stateRoot: emptyRlpHash, stateRoot: emptyRlpHash,
excessBlobGas: optional(uint64, "parentExcessBlobGas"), excessBlobGas: optional(uint64, "parentExcessBlobGas"),
blobGasUsed: optional(uint64, "parentBlobGasUsed"), blobGasUsed: optional(uint64, "parentBlobGasUsed"),
@ -132,19 +134,19 @@ proc parseTx*(n: JsonNode, dataIndex, gasIndex, valueIndex: int): Transaction =
nonce : required(AccountNonce, "nonce"), nonce : required(AccountNonce, "nonce"),
gasLimit: required(GasInt, "gasLimit", gasIndex), gasLimit: required(GasInt, "gasLimit", gasIndex),
value : required(UInt256, "value", valueIndex), value : required(UInt256, "value", valueIndex),
payload : required(Blob, "data", dataIndex), payload : required(seq[byte], "data", dataIndex),
chainId : ChainId(1), chainId : ChainId(1),
gasPrice: omitZero(GasInt, "gasPrice"), gasPrice: omitZero(GasInt, "gasPrice"),
maxFeePerGas : omitZero(GasInt, "maxFeePerGas"), maxFeePerGas : omitZero(GasInt, "maxFeePerGas"),
accessList : omitZero(AccessList, "accessLists", dataIndex), accessList : omitZero(AccessList, "accessLists", dataIndex),
maxPriorityFeePerGas: omitZero(GasInt, "maxPriorityFeePerGas"), maxPriorityFeePerGas: omitZero(GasInt, "maxPriorityFeePerGas"),
maxFeePerBlobGas : omitZero(UInt256, "maxFeePerBlobGas"), maxFeePerBlobGas : omitZero(UInt256, "maxFeePerBlobGas"),
versionedHashes : omitZero(VersionedHashes, "blobVersionedHashes") versionedHashes : omitZero(seq[Hash32], "blobVersionedHashes")
) )
let rawTo = n["to"].getStr let rawTo = n["to"].getStr
if rawTo != "": if rawTo != "":
tx.to = Opt.some(EthAddress.fromHex(rawTo)) tx.to = Opt.some(Address.fromHex(rawTo))
let secretKey = required(PrivateKey, "secretKey") let secretKey = required(PrivateKey, "secretKey")
signTransaction(tx, secretKey, false) signTransaction(tx, secretKey, false)
@ -163,15 +165,15 @@ proc setupStateDB*(wantedState: JsonNode, stateDB: LedgerRef) =
stateDB.setStorage(account, fromHex(UInt256, slot), fromHex(UInt256, value.getStr)) stateDB.setStorage(account, fromHex(UInt256, slot), fromHex(UInt256, value.getStr))
stateDB.setNonce(account, fromJson(AccountNonce, accountData["nonce"])) stateDB.setNonce(account, fromJson(AccountNonce, accountData["nonce"]))
stateDB.setCode(account, fromJson(Blob, accountData["code"])) stateDB.setCode(account, fromJson(seq[byte], accountData["code"]))
stateDB.setBalance(account, fromJson(UInt256, accountData["balance"])) stateDB.setBalance(account, fromJson(UInt256, accountData["balance"]))
iterator postState*(node: JsonNode): (EthAddress, GenesisAccount) = iterator postState*(node: JsonNode): (Address, GenesisAccount) =
for ac, accountData in node: for ac, accountData in node:
let account = EthAddress.fromHex(ac) let account = Address.fromHex(ac)
var ga = GenesisAccount( var ga = GenesisAccount(
nonce : fromJson(AccountNonce, accountData["nonce"]), nonce : fromJson(AccountNonce, accountData["nonce"]),
code : fromJson(Blob, accountData["code"]), code : fromJson(seq[byte], accountData["code"]),
balance: fromJson(UInt256, accountData["balance"]), balance: fromJson(UInt256, accountData["balance"]),
) )

View File

@ -8,12 +8,5 @@
# at your option. This file may not be copied, modified, or distributed except # at your option. This file may not be copied, modified, or distributed except
# according to those terms. # according to those terms.
if defined(evmc_enabled): # chronicles log output will intefere with t8n ouput
# evmcLoadVMShowDetail log output will intefere with t8n ouput switch("define", "chronicles_enabled=off")
switch("define", "chronicles_enabled=off")
else:
switch("define", "chronicles_enabled=off")
# TODO: redirect the logs to a custom stream?
# They are interfering with t8n_test
#switch("define", "chronicles_default_output_device=stderr")
#switch("define", "chronicles_runtime_filtering=on")

View File

@ -12,7 +12,9 @@ import
std/[json, strutils, tables], std/[json, strutils, tables],
stew/byteutils, stew/byteutils,
stint, stint,
eth/[common, rlp, keys], eth/common/eth_types_rlp,
eth/common/keys,
eth/common/blocks,
../../nimbus/transaction, ../../nimbus/transaction,
../../nimbus/common/chain_config, ../../nimbus/common/chain_config,
../common/helpers, ../common/helpers,
@ -33,13 +35,13 @@ proc parseHexOrInt[T](x: string): T =
else: else:
parseInt(x).T parseInt(x).T
proc fromJson(T: type EthAddress, n: JsonNode, field: string): EthAddress = proc fromJson(T: type Address, n: JsonNode, field: string): Address =
try: try:
EthAddress.fromHex(n[field].getStr()) Address.fromHex(n[field].getStr())
except ValueError: except ValueError:
raise newError(ErrorJson, "malformed Eth address " & n[field].getStr) raise newError(ErrorJson, "malformed Eth address " & n[field].getStr)
template fromJson(T: type Blob, n: JsonNode, field: string): Blob = template fromJson(T: type seq[byte], n: JsonNode, field: string): seq[byte] =
hexToSeqByte(n[field].getStr()) hexToSeqByte(n[field].getStr())
proc fromJson(T: type uint64, n: JsonNode, field: string): uint64 = proc fromJson(T: type uint64, n: JsonNode, field: string): uint64 =
@ -64,14 +66,14 @@ proc fromJson(T: type Bytes32, n: JsonNode): Bytes32 =
proc fromJson(T: type Bytes32, n: JsonNode, field: string): Bytes32 = proc fromJson(T: type Bytes32, n: JsonNode, field: string): Bytes32 =
fromJson(T, n[field]) fromJson(T, n[field])
proc fromJson(T: type Hash256, n: JsonNode): Hash256 = proc fromJson(T: type Hash32, n: JsonNode): Hash32 =
var num = n.getStr() var num = n.getStr()
num.removePrefix("0x") num.removePrefix("0x")
if num.len < 64: if num.len < 64:
num = repeat('0', 64 - num.len) & num num = repeat('0', 64 - num.len) & num
Hash32(hexToByteArray(num, 32)) Hash32(hexToByteArray(num, 32))
proc fromJson(T: type Hash256, n: JsonNode, field: string): Hash256 = proc fromJson(T: type Hash32, n: JsonNode, field: string): Hash32 =
fromJson(T, n[field]) fromJson(T, n[field])
template fromJson(T: type EthTime, n: JsonNode, field: string): EthTime = template fromJson(T: type EthTime, n: JsonNode, field: string): EthTime =
@ -84,7 +86,7 @@ proc fromJson(T: type AccessList, n: JsonNode, field: string): AccessList =
for x in z: for x in z:
var ap = AccessPair( var ap = AccessPair(
address: EthAddress.fromJson(x, "address") address: Address.fromJson(x, "address")
) )
let sks = x["storageKeys"] let sks = x["storageKeys"]
for sk in sks: for sk in sks:
@ -94,21 +96,21 @@ proc fromJson(T: type AccessList, n: JsonNode, field: string): AccessList =
proc fromJson(T: type Ommer, n: JsonNode): Ommer = proc fromJson(T: type Ommer, n: JsonNode): Ommer =
Ommer( Ommer(
delta: fromJson(uint64, n, "delta"), delta: fromJson(uint64, n, "delta"),
address: fromJson(EthAddress, n, "address") address: fromJson(Address, n, "address")
) )
proc fromJson(T: type Withdrawal, n: JsonNode): Withdrawal = proc fromJson(T: type Withdrawal, n: JsonNode): Withdrawal =
Withdrawal( Withdrawal(
index: fromJson(uint64, n, "index"), index: fromJson(uint64, n, "index"),
validatorIndex: fromJson(uint64, n, "validatorIndex"), validatorIndex: fromJson(uint64, n, "validatorIndex"),
address: fromJson(EthAddress, n, "address"), address: fromJson(Address, n, "address"),
amount: fromJson(uint64, n, "amount") amount: fromJson(uint64, n, "amount")
) )
proc fromJson(T: type Authorization, n: JsonNode): Authorization = proc fromJson(T: type Authorization, n: JsonNode): Authorization =
Authorization( Authorization(
chainId: fromJson(ChainId, n, "chainId"), chainId: fromJson(ChainId, n, "chainId"),
address: fromJson(EthAddress, n, "address"), address: fromJson(Address, n, "address"),
nonce: fromJson(uint64, n, "nonce"), nonce: fromJson(uint64, n, "nonce"),
yParity: fromJson(uint64, n, "yParity"), yParity: fromJson(uint64, n, "yParity"),
R: fromJson(UInt256, n, "R"), R: fromJson(UInt256, n, "R"),
@ -120,7 +122,7 @@ proc fromJson(T: type seq[Authorization], n: JsonNode, field: string): T =
for x in list: for x in list:
result.add Authorization.fromJson(x) result.add Authorization.fromJson(x)
proc fromJson(T: type VersionedHashes, n: JsonNode, field: string): VersionedHashes = proc fromJson(T: type seq[VersionedHash], n: JsonNode, field: string): T =
let list = n[field] let list = n[field]
for x in list: for x in list:
result.add VersionedHash.fromHex(x.getStr) result.add VersionedHash.fromHex(x.getStr)
@ -128,7 +130,7 @@ proc fromJson(T: type VersionedHashes, n: JsonNode, field: string): VersionedHas
template `gas=`(tx: var Transaction, x: GasInt) = template `gas=`(tx: var Transaction, x: GasInt) =
tx.gasLimit = x tx.gasLimit = x
template `input=`(tx: var Transaction, x: Blob) = template `input=`(tx: var Transaction, x: seq[byte]) =
tx.payload = x tx.payload = x
template `v=`(tx: var Transaction, x: uint64) = template `v=`(tx: var Transaction, x: uint64) =
@ -140,7 +142,7 @@ template `r=`(tx: var Transaction, x: UInt256) =
template `s=`(tx: var Transaction, x: UInt256) = template `s=`(tx: var Transaction, x: UInt256) =
tx.S = x tx.S = x
template `blobVersionedHashes=`(tx: var Transaction, x: VersionedHashes) = template `blobVersionedHashes=`(tx: var Transaction, x: seq[VersionedHash]) =
tx.versionedHashes = x tx.versionedHashes = x
template required(o: untyped, T: type, oField: untyped) = template required(o: untyped, T: type, oField: untyped) =
@ -161,10 +163,10 @@ template optional(o: untyped, T: type, oField: untyped) =
proc parseAlloc*(ctx: var TransContext, n: JsonNode) = proc parseAlloc*(ctx: var TransContext, n: JsonNode) =
for accAddr, acc in n: for accAddr, acc in n:
let address = EthAddress.fromHex(accAddr) let address = Address.fromHex(accAddr)
var ga = GenesisAccount() var ga = GenesisAccount()
if acc.hasKey("code"): if acc.hasKey("code"):
ga.code = Blob.fromJson(acc, "code") ga.code = seq[byte].fromJson(acc, "code")
if acc.hasKey("nonce"): if acc.hasKey("nonce"):
ga.nonce = AccountNonce.fromJson(acc, "nonce") ga.nonce = AccountNonce.fromJson(acc, "nonce")
if acc.hasKey("balance"): if acc.hasKey("balance"):
@ -178,7 +180,7 @@ proc parseAlloc*(ctx: var TransContext, n: JsonNode) =
ctx.alloc[address] = ga ctx.alloc[address] = ga
proc parseEnv*(ctx: var TransContext, n: JsonNode) = proc parseEnv*(ctx: var TransContext, n: JsonNode) =
required(ctx.env, EthAddress, currentCoinbase) required(ctx.env, Address, currentCoinbase)
required(ctx.env, GasInt, currentGasLimit) required(ctx.env, GasInt, currentGasLimit)
required(ctx.env, BlockNumber, currentNumber) required(ctx.env, BlockNumber, currentNumber)
required(ctx.env, EthTime, currentTimestamp) required(ctx.env, EthTime, currentTimestamp)
@ -187,7 +189,7 @@ proc parseEnv*(ctx: var TransContext, n: JsonNode) =
optional(ctx.env, DifficultyInt, parentDifficulty) optional(ctx.env, DifficultyInt, parentDifficulty)
omitZero(ctx.env, EthTime, parentTimestamp) omitZero(ctx.env, EthTime, parentTimestamp)
optional(ctx.env, UInt256, currentBaseFee) optional(ctx.env, UInt256, currentBaseFee)
omitZero(ctx.env, Hash256, parentUncleHash) omitZero(ctx.env, Hash32, parentUncleHash)
optional(ctx.env, UInt256, parentBaseFee) optional(ctx.env, UInt256, parentBaseFee)
optional(ctx.env, GasInt, parentGasUsed) optional(ctx.env, GasInt, parentGasUsed)
optional(ctx.env, GasInt, parentGasLimit) optional(ctx.env, GasInt, parentGasLimit)
@ -195,12 +197,12 @@ proc parseEnv*(ctx: var TransContext, n: JsonNode) =
optional(ctx.env, uint64, currentExcessBlobGas) optional(ctx.env, uint64, currentExcessBlobGas)
optional(ctx.env, uint64, parentBlobGasUsed) optional(ctx.env, uint64, parentBlobGasUsed)
optional(ctx.env, uint64, parentExcessBlobGas) optional(ctx.env, uint64, parentExcessBlobGas)
optional(ctx.env, Hash256, parentBeaconBlockRoot) optional(ctx.env, Hash32, parentBeaconBlockRoot)
if n.hasKey("blockHashes"): if n.hasKey("blockHashes"):
let w = n["blockHashes"] let w = n["blockHashes"]
for k, v in w: for k, v in w:
ctx.env.blockHashes[parseHexOrInt[uint64](k)] = Hash256.fromHex(v.getStr()) ctx.env.blockHashes[parseHexOrInt[uint64](k)] = Hash32.fromHex(v.getStr())
if n.hasKey("ommers"): if n.hasKey("ommers"):
let w = n["ommers"] let w = n["ommers"]
@ -224,10 +226,10 @@ proc parseTx(n: JsonNode, chainId: ChainID): Transaction =
required(tx, AccountNonce, nonce) required(tx, AccountNonce, nonce)
required(tx, GasInt, gas) required(tx, GasInt, gas)
required(tx, UInt256, value) required(tx, UInt256, value)
required(tx, Blob, input) required(tx, seq[byte], input)
if n.hasKey("to"): if n.hasKey("to"):
tx.to = Opt.some(EthAddress.fromJson(n, "to")) tx.to = Opt.some(Address.fromJson(n, "to"))
tx.chainId = chainId tx.chainId = chainId
case tx.txType case tx.txType
@ -248,7 +250,7 @@ proc parseTx(n: JsonNode, chainId: ChainID): Transaction =
required(tx, GasInt, maxFeePerGas) required(tx, GasInt, maxFeePerGas)
omitZero(tx, AccessList, accessList) omitZero(tx, AccessList, accessList)
required(tx, UInt256, maxFeePerBlobGas) required(tx, UInt256, maxFeePerBlobGas)
required(tx, VersionedHashes, blobVersionedHashes) required(tx, seq[VersionedHash], blobVersionedHashes)
of TxEip7702: of TxEip7702:
required(tx, ChainId, chainId) required(tx, ChainId, chainId)
required(tx, GasInt, maxPriorityFeePerGas) required(tx, GasInt, maxPriorityFeePerGas)
@ -261,7 +263,7 @@ proc parseTx(n: JsonNode, chainId: ChainID): Transaction =
eip155 = n["protected"].bval eip155 = n["protected"].bval
if n.hasKey("secretKey"): if n.hasKey("secretKey"):
let data = Blob.fromJson(n, "secretKey") let data = seq[byte].fromJson(n, "secretKey")
let secretKey = PrivateKey.fromRaw(data).tryGet let secretKey = PrivateKey.fromRaw(data).tryGet
signTransaction(tx, secretKey, eip155) signTransaction(tx, secretKey, eip155)
else: else:
@ -356,10 +358,10 @@ proc `@@`(x: uint64 | int64 | int): JsonNode =
proc `@@`(x: UInt256): JsonNode = proc `@@`(x: UInt256): JsonNode =
%("0x" & x.toHex) %("0x" & x.toHex)
proc `@@`(x: Hash256): JsonNode = proc `@@`(x: Hash32): JsonNode =
%("0x" & x.data.toHex) %("0x" & x.data.toHex)
proc `@@`*(x: Blob): JsonNode = proc `@@`*(x: seq[byte]): JsonNode =
%("0x" & x.toHex) %("0x" & x.toHex)
proc `@@`(x: bool): JsonNode = proc `@@`(x: bool): JsonNode =
@ -393,7 +395,7 @@ proc `@@`[K, V](x: Table[K, V]): JsonNode =
for k, v in x: for k, v in x:
result[k.to0xHex] = @@(v) result[k.to0xHex] = @@(v)
proc `@@`(x: BloomFilter): JsonNode = proc `@@`(x: Bloom): JsonNode =
%("0x" & toHex(x)) %("0x" & toHex(x))
proc `@@`(x: Log): JsonNode = proc `@@`(x: Log): JsonNode =
@ -405,7 +407,7 @@ proc `@@`(x: Log): JsonNode =
proc `@@`(x: TxReceipt): JsonNode = proc `@@`(x: TxReceipt): JsonNode =
result = %{ result = %{
"root" : if x.root == default(Hash256): %("0x") else: @@(x.root), "root" : if x.root == default(Hash32): %("0x") else: @@(x.root),
"status" : @@(x.status), "status" : @@(x.status),
"cumulativeGasUsed": @@(x.cumulativeGasUsed), "cumulativeGasUsed": @@(x.cumulativeGasUsed),
"logsBloom" : @@(x.logsBloom), "logsBloom" : @@(x.logsBloom),

View File

@ -40,7 +40,7 @@ type
alloc: GenesisAlloc alloc: GenesisAlloc
TestVMState = ref object of BaseVMState TestVMState = ref object of BaseVMState
blockHashes: Table[uint64, Hash256] blockHashes: Table[uint64, Hash32]
hashError: string hashError: string
proc init(_: type Dispatch): Dispatch = proc init(_: type Dispatch): Dispatch =
@ -85,13 +85,13 @@ proc dispatchOutput(ctx: var TransContext, conf: T8NConf, res: ExecOutput) =
stderr.write(dis.stderr.pretty) stderr.write(dis.stderr.pretty)
stderr.write("\n") stderr.write("\n")
proc calcWithdrawalsRoot(w: Opt[seq[Withdrawal]]): Opt[Hash256] = proc calcWithdrawalsRoot(w: Opt[seq[Withdrawal]]): Opt[Hash32] =
if w.isNone: if w.isNone:
return Opt.none(Hash256) return Opt.none(Hash32)
Opt.some calcWithdrawalsRoot(w.get) Opt.some calcWithdrawalsRoot(w.get)
proc envToHeader(env: EnvStruct): BlockHeader = proc envToHeader(env: EnvStruct): Header =
BlockHeader( Header(
coinbase : env.currentCoinbase, coinbase : env.currentCoinbase,
difficulty : env.currentDifficulty.get(0.u256), difficulty : env.currentDifficulty.get(0.u256),
mixHash : env.currentRandom.get(default(Bytes32)), mixHash : env.currentRandom.get(default(Bytes32)),
@ -130,7 +130,7 @@ proc toTxReceipt(rec: Receipt,
let contractAddress = genAddress(tx, sender) let contractAddress = genAddress(tx, sender)
TxReceipt( TxReceipt(
txType: tx.txType, txType: tx.txType,
root: if rec.isHash: rec.hash else: default(Hash256), root: if rec.isHash: rec.hash else: default(Hash32),
status: rec.status, status: rec.status,
cumulativeGasUsed: rec.cumulativeGasUsed, cumulativeGasUsed: rec.cumulativeGasUsed,
logsBloom: rec.logsBloom, logsBloom: rec.logsBloom,
@ -138,11 +138,11 @@ proc toTxReceipt(rec: Receipt,
transactionHash: rlpHash(tx), transactionHash: rlpHash(tx),
contractAddress: contractAddress, contractAddress: contractAddress,
gasUsed: gasUsed, gasUsed: gasUsed,
blockHash: default(Hash256), blockHash: default(Hash32),
transactionIndex: txIndex transactionIndex: txIndex
) )
proc calcLogsHash(receipts: openArray[Receipt]): Hash256 = proc calcLogsHash(receipts: openArray[Receipt]): Hash32 =
var logs: seq[Log] var logs: seq[Log]
for rec in receipts: for rec in receipts:
logs.add rec.logs logs.add rec.logs
@ -150,7 +150,7 @@ proc calcLogsHash(receipts: openArray[Receipt]): Hash256 =
proc defaultTraceStreamFilename(conf: T8NConf, proc defaultTraceStreamFilename(conf: T8NConf,
txIndex: int, txIndex: int,
txHash: Hash256): (string, string) = txHash: Hash32): (string, string) =
let let
txHash = "0x" & toLowerAscii($txHash) txHash = "0x" & toLowerAscii($txHash)
baseDir = if conf.outputBaseDir.len > 0: baseDir = if conf.outputBaseDir.len > 0:
@ -160,7 +160,7 @@ proc defaultTraceStreamFilename(conf: T8NConf,
fName = "$1/trace-$2-$3.jsonl" % [baseDir, $txIndex, txHash] fName = "$1/trace-$2-$3.jsonl" % [baseDir, $txIndex, txHash]
(baseDir, fName) (baseDir, fName)
proc defaultTraceStream(conf: T8NConf, txIndex: int, txHash: Hash256): Stream = proc defaultTraceStream(conf: T8NConf, txIndex: int, txHash: Hash32): Stream =
let (baseDir, fName) = defaultTraceStreamFilename(conf, txIndex, txHash) let (baseDir, fName) = defaultTraceStreamFilename(conf, txIndex, txHash)
createDir(baseDir) createDir(baseDir)
newFileStream(fName, fmWrite) newFileStream(fName, fmWrite)
@ -173,7 +173,7 @@ proc traceToFileStream(path: string, txIndex: int): Stream =
createDir(file.dir) createDir(file.dir)
newFileStream(fName, fmWrite) newFileStream(fName, fmWrite)
proc setupTrace(conf: T8NConf, txIndex: int, txHash: Hash256, vmState: BaseVMState) = proc setupTrace(conf: T8NConf, txIndex: int, txHash: Hash32, vmState: BaseVMState) =
var tracerFlags = { var tracerFlags = {
TracerFlags.DisableMemory, TracerFlags.DisableMemory,
TracerFlags.DisableStorage, TracerFlags.DisableStorage,
@ -214,7 +214,7 @@ proc closeTrace(vmState: BaseVMState) =
proc exec(ctx: var TransContext, proc exec(ctx: var TransContext,
vmState: BaseVMState, vmState: BaseVMState,
stateReward: Option[UInt256], stateReward: Option[UInt256],
header: BlockHeader, header: Header,
conf: T8NConf): ExecOutput = conf: T8NConf): ExecOutput =
let txList = ctx.parseTxs(vmState.com.chainId) let txList = ctx.parseTxs(vmState.com.chainId)
@ -242,7 +242,7 @@ proc exec(ctx: var TransContext,
prevNumber = ctx.env.currentNumber - 1 prevNumber = ctx.env.currentNumber - 1
prevHash = ctx.env.blockHashes.getOrDefault(prevNumber) prevHash = ctx.env.blockHashes.getOrDefault(prevNumber)
if prevHash == static(default(Hash256)): if prevHash == static(default(Hash32)):
raise newError(ErrorConfig, "previous block hash not found for block number: " & $prevNumber) raise newError(ErrorConfig, "previous block hash not found for block number: " & $prevNumber)
vmState.processParentBlockHash(prevHash).isOkOr: vmState.processParentBlockHash(prevHash).isOkOr:
@ -394,10 +394,10 @@ proc setupAlloc(stateDB: LedgerRef, alloc: GenesisAlloc) =
for slot, value in acc.storage: for slot, value in acc.storage:
stateDB.setStorage(accAddr, slot, value) stateDB.setStorage(accAddr, slot, value)
method getAncestorHash(vmState: TestVMState; blockNumber: BlockNumber): Hash256 = method getAncestorHash(vmState: TestVMState; blockNumber: BlockNumber): Hash32 =
# we can't raise exception here, it'll mess with EVM exception handler. # we can't raise exception here, it'll mess with EVM exception handler.
# so, store the exception for later using `hashError` # so, store the exception for later using `hashError`
var h = default(Hash256) var h = default(Hash32)
if vmState.blockHashes.len == 0: if vmState.blockHashes.len == 0:
vmState.hashError = "getAncestorHash(" & vmState.hashError = "getAncestorHash(" &
$blockNumber & ") invoked, no blockhashes provided" $blockNumber & ") invoked, no blockhashes provided"
@ -465,12 +465,12 @@ proc transitionAction*(ctx: var TransContext, conf: T8NConf) =
let n = json.parseFile(conf.inputTxs) let n = json.parseFile(conf.inputTxs)
ctx.parseTxs(n) ctx.parseTxs(n)
let uncleHash = if ctx.env.parentUncleHash == default(Hash256): let uncleHash = if ctx.env.parentUncleHash == default(Hash32):
EMPTY_UNCLE_HASH EMPTY_UNCLE_HASH
else: else:
ctx.env.parentUncleHash ctx.env.parentUncleHash
let parent = BlockHeader( let parent = Header(
stateRoot: emptyRlpHash, stateRoot: emptyRlpHash,
timestamp: ctx.env.parentTimestamp, timestamp: ctx.env.parentTimestamp,
difficulty: ctx.env.parentDifficulty.get(0.u256), difficulty: ctx.env.parentDifficulty.get(0.u256),
@ -502,7 +502,7 @@ proc transitionAction*(ctx: var TransContext, conf: T8NConf) =
raise newError(ErrorConfig, res.error) raise newError(ErrorConfig, res.error)
else: else:
# un-set it if it has been set too early # un-set it if it has been set too early
ctx.env.parentBeaconBlockRoot = Opt.none(Hash256) ctx.env.parentBeaconBlockRoot = Opt.none(Hash32)
let isMerged = config.terminalTotalDifficulty.isSome and let isMerged = config.terminalTotalDifficulty.isSome and
config.terminalTotalDifficulty.value == 0.u256 config.terminalTotalDifficulty.value == 0.u256

View File

@ -10,7 +10,11 @@
import import
std/[tables, json], std/[tables, json],
eth/common, eth/common/blocks,
eth/common/receipts,
eth/rlp,
results,
stint,
../../nimbus/common/chain_config, ../../nimbus/common/chain_config,
../common/types ../common/types
@ -25,21 +29,21 @@ type
Ommer* = object Ommer* = object
delta*: uint64 delta*: uint64
address*: EthAddress address*: Address
EnvStruct* = object EnvStruct* = object
currentCoinbase*: EthAddress currentCoinbase*: Address
currentDifficulty*: Opt[DifficultyInt] currentDifficulty*: Opt[UInt256]
currentRandom*: Opt[Bytes32] currentRandom*: Opt[Bytes32]
parentDifficulty*: Opt[DifficultyInt] parentDifficulty*: Opt[UInt256]
currentGasLimit*: GasInt currentGasLimit*: GasInt
currentNumber*: BlockNumber currentNumber*: BlockNumber
currentTimestamp*: EthTime currentTimestamp*: EthTime
parentTimestamp*: EthTime parentTimestamp*: EthTime
blockHashes*: Table[uint64, Hash256] blockHashes*: Table[uint64, Hash32]
ommers*: seq[Ommer] ommers*: seq[Ommer]
currentBaseFee*: Opt[UInt256] currentBaseFee*: Opt[UInt256]
parentUncleHash*: Hash256 parentUncleHash*: Hash32
parentBaseFee*: Opt[UInt256] parentBaseFee*: Opt[UInt256]
parentGasUsed*: Opt[GasInt] parentGasUsed*: Opt[GasInt]
parentGasLimit*: Opt[GasInt] parentGasLimit*: Opt[GasInt]
@ -48,7 +52,7 @@ type
currentExcessBlobGas*: Opt[uint64] currentExcessBlobGas*: Opt[uint64]
parentBlobGasUsed*: Opt[uint64] parentBlobGasUsed*: Opt[uint64]
parentExcessBlobGas*: Opt[uint64] parentExcessBlobGas*: Opt[uint64]
parentBeaconBlockRoot*: Opt[Hash256] parentBeaconBlockRoot*: Opt[Hash32]
TxsType* = enum TxsType* = enum
TxsNone TxsNone
@ -72,34 +76,34 @@ type
TxReceipt* = object TxReceipt* = object
txType*: TxType txType*: TxType
root*: Hash256 root*: Hash32
status*: bool status*: bool
cumulativeGasUsed*: GasInt cumulativeGasUsed*: GasInt
logsBloom*: BloomFilter logsBloom*: Bloom
logs*: seq[Log] logs*: seq[Log]
transactionHash*: Hash256 transactionHash*: Hash32
contractAddress*: EthAddress contractAddress*: Address
gasUsed*: GasInt gasUsed*: GasInt
blockHash*: Hash256 blockHash*: Hash32
transactionIndex*: int transactionIndex*: int
# ExecutionResult contains the execution status after running a state test, any # ExecutionResult contains the execution status after running a state test, any
# error that might have occurred and a dump of the final state if requested. # error that might have occurred and a dump of the final state if requested.
ExecutionResult* = object ExecutionResult* = object
stateRoot*: Hash256 stateRoot*: Hash32
txRoot*: Hash256 txRoot*: Hash32
receiptsRoot*: Hash256 receiptsRoot*: Hash32
logsHash*: Hash256 logsHash*: Hash32
logsBloom*: BloomFilter logsBloom*: Bloom
receipts*: seq[TxReceipt] receipts*: seq[TxReceipt]
rejected*: seq[RejectedTx] rejected*: seq[RejectedTx]
currentDifficulty*: Opt[DifficultyInt] currentDifficulty*: Opt[UInt256]
gasUsed*: GasInt gasUsed*: GasInt
currentBaseFee*: Opt[UInt256] currentBaseFee*: Opt[UInt256]
withdrawalsRoot*: Opt[Hash256] withdrawalsRoot*: Opt[Hash32]
blobGasUsed*: Opt[uint64] blobGasUsed*: Opt[uint64]
currentExcessBlobGas*: Opt[uint64] currentExcessBlobGas*: Opt[uint64]
requestsRoot*: Opt[Hash256] requestsRoot*: Opt[Hash32]
depositRequests*: Opt[seq[DepositRequest]] depositRequests*: Opt[seq[DepositRequest]]
withdrawalRequests*: Opt[seq[WithdrawalRequest]] withdrawalRequests*: Opt[seq[WithdrawalRequest]]
consolidationRequests*: Opt[seq[ConsolidationRequest]] consolidationRequests*: Opt[seq[ConsolidationRequest]]