nimbus-eth1/tests/test_txpool2.nim

355 lines
9.2 KiB
Nim
Raw Normal View History

2023-11-01 03:32:09 +00:00
# Nimbus
# Copyright (c) 2022-2024 Status Research & Development GmbH
2023-11-01 03:32:09 +00: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.
import
std/tables,
eth/[keys],
2024-05-30 12:54:03 +00:00
stew/byteutils, results, unittest2,
../nimbus/db/ledger,
2022-12-02 04:39:12 +00:00
../nimbus/core/chain,
../nimbus/[config, transaction, constants],
../nimbus/core/tx_pool,
../nimbus/core/casper,
2022-12-02 04:39:12 +00:00
../nimbus/common/common,
../nimbus/utils/utils,
../nimbus/vm_types,
./test_txpool/helpers,
./macro_assembler
const
2022-04-04 08:34:59 +00:00
baseDir = [".", "tests"]
repoDir = [".", "customgenesis"]
genesisFile = "merge.json"
type
TestEnv = object
nonce : uint64
chainId : ChainId
vaultKey: PrivateKey
conf : NimbusConf
2022-12-02 04:39:12 +00:00
com : CommonRef
chain : ChainRef
xp : TxPoolRef
const
signerKeyHex = "9c647b8b7c4e7c3490668fb6c11473619db80c93704c70893d3813af4090c39c"
vaultKeyHex = "63b508a03c3b5937ceb903af8b1b0c191012ef6eb7e9c3fb7afa94e5d214d376"
recipient = hexToByteArray[20]("0000000000000000000000000000000000000318")
2022-04-04 02:01:39 +00:00
feeRecipient = hexToByteArray[20]("0000000000000000000000000000000000000212")
contractCode = evmByteCode:
PrevRandao # VAL
Push1 "0x11" # KEY
Sstore # OP
Stop
proc privKey(keyHex: string): PrivateKey =
let kRes = PrivateKey.fromHex(keyHex)
if kRes.isErr:
echo kRes.error
quit(QuitFailure)
kRes.get()
func makeTx(
t: var TestEnv, recipient: EthAddress, amount: UInt256,
payload: openArray[byte] = []): Transaction =
const
gasLimit = 75000.GasInt
gasPrice = 30.gwei
let tx = Transaction(
txType : TxLegacy,
chainId : t.chainId,
nonce : AccountNonce(t.nonce),
gasPrice: gasPrice,
gasLimit: gasLimit,
to : some(recipient),
value : amount,
payload : @payload
)
inc t.nonce
signTransaction(tx, t.vaultKey, t.chainId, eip155 = true)
func signTxWithNonce(
t: TestEnv, tx: Transaction, nonce: AccountNonce): Transaction =
var tx = tx
tx.nonce = nonce
signTransaction(tx, t.vaultKey, t.chainId, eip155 = true)
proc initEnv(envFork: HardFork): TestEnv =
var
conf = makeConfig(@[
2022-04-04 08:34:59 +00:00
"--custom-network:" & genesisFile.findFilePath(baseDir,repoDir).value
])
conf.networkParams.genesis.alloc[recipient] = GenesisAccount(
code: contractCode
)
if envFork >= MergeFork:
conf.networkParams.config.terminalTotalDifficulty = some(100.u256)
if envFork >= Shanghai:
conf.networkParams.config.shanghaiTime = some(0.EthTime)
if envFork >= Cancun:
conf.networkParams.config.cancunTime = some(0.EthTime)
let
2022-12-02 04:39:12 +00:00
com = CommonRef.new(
newCoreDbRef DefaultDbMemory,
conf.networkId,
conf.networkParams
)
2022-12-02 04:39:12 +00:00
chain = newChain(com)
2022-12-02 04:39:12 +00:00
com.initializeEmptyDb()
result = TestEnv(
conf: conf,
2022-12-02 04:39:12 +00:00
com: com,
chain: chain,
xp: TxPoolRef.new(com),
vaultKey: privKey(vaultKeyHex),
chainId: conf.networkParams.config.chainId,
nonce: 0'u64
)
const
amount = 1000.u256
slot = 0x11.u256
prevRandao = EMPTY_UNCLE_HASH # it can be any valid hash
proc runTxPoolPosTest() =
var
env = initEnv(MergeFork)
var
tx = env.makeTx(recipient, amount)
xp = env.xp
2022-12-02 04:39:12 +00:00
com = env.com
chain = env.chain
body: BlockBody
blk: EthBlock
suite "Test TxPool with PoS block":
test "TxPool addLocal":
let res = xp.addLocal(PooledTransaction(tx: tx), force = true)
check res.isOk
if res.isErr:
debugEcho res.error
return
test "TxPool jobCommit":
check xp.nItems.total == 1
test "TxPool ethBlock":
com.pos.prevRandao = prevRandao
com.pos.feeRecipient = feeRecipient
com.pos.timestamp = EthTime.now()
let r = xp.assembleBlock()
if r.isErr:
debugEcho r.error
check false
return
blk = r.get.blk
2022-12-02 04:39:12 +00:00
check com.isBlockAfterTtd(blk.header)
body = BlockBody(
transactions: blk.txs,
uncles: blk.uncles
)
check blk.txs.len == 1
test "PoS persistBlocks":
Consolidate block type for block processing (#2325) This PR consolidates the split header-body sequences into a single EthBlock sequence and cleans up the fallout from that which significantly reduces block processing overhead during import thanks to less garbage collection and fewer copies of things all around. Notably, since the number of headers must always match the number of bodies, we also get rid of a pointless degree of freedom that in the future could introduce unnecessary bugs. * only read header and body from era file * avoid several unnecessary copies along the block processing way * simplify signatures, cleaning up unused arguemnts and returns * use `stew/assign2` in a few strategic places where the generated nim assignent is slow and add a few `move` to work around poor analysis in nim 1.6 (will need to be revisited for 2.0) ``` stats-20240607_2223-a814aa0b.csv vs stats-20240608_0714-21c1d0a9.csv bps_x bps_y tps_x tps_y bpsd tpsd timed block_number (498305, 713245] 1,540.52 1,809.73 2,361.58 2775.340189 17.63% 17.63% -14.92% (713245, 928185] 730.36 865.26 1,715.90 2028.973852 18.01% 18.01% -15.21% (928185, 1143126] 663.03 789.10 2,529.26 3032.490771 19.79% 19.79% -16.28% (1143126, 1358066] 393.46 508.05 2,152.50 2777.578119 29.13% 29.13% -22.50% (1358066, 1573007] 370.88 440.72 2,351.31 2791.896052 18.81% 18.81% -15.80% (1573007, 1787947] 283.65 335.11 2,068.93 2441.373402 17.60% 17.60% -14.91% (1787947, 2002888] 287.29 342.11 2,078.39 2474.179448 18.99% 18.99% -15.91% (2002888, 2217828] 293.38 343.16 2,208.83 2584.77457 17.16% 17.16% -14.61% (2217828, 2432769] 140.09 167.86 1,081.87 1296.336926 18.82% 18.82% -15.80% blocks: 1934464, baseline: 3h13m1s, contender: 2h43m47s bpsd (mean): 19.55% tpsd (mean): 19.55% Time (total): -29m13s, -15.14% ```
2024-06-09 14:32:20 +00:00
let rr = chain.persistBlocks([EthBlock.init(blk.header, body)])
check rr.isOk()
test "validate TxPool prevRandao setter":
var sdb = LedgerRef.init(com.db, blk.header.stateRoot)
let val = sdb.getStorage(recipient, slot)
let randao = Hash256(data: val.toBytesBE)
check randao == prevRandao
2022-04-04 02:01:39 +00:00
test "feeRecipient rewarded":
check blk.header.coinbase == feeRecipient
var sdb = LedgerRef.init(com.db, blk.header.stateRoot)
2022-04-04 02:01:39 +00:00
let bal = sdb.getBalance(feeRecipient)
check not bal.isZero
proc runTxPoolBlobhashTest() =
var
env = initEnv(Cancun)
var
tx1 = env.makeTx(recipient, amount)
tx2 = env.makeTx(recipient, amount)
xp = env.xp
com = env.com
chain = env.chain
body: BlockBody
blk: EthBlock
suite "Test TxPool with blobhash block":
test "TxPool addLocal":
let res = xp.addLocal(PooledTransaction(tx: tx1), force = true)
check res.isOk
if res.isErr:
debugEcho res.error
return
let res2 = xp.addLocal(PooledTransaction(tx: tx2), force = true)
check res2.isOk
test "TxPool jobCommit":
check xp.nItems.total == 2
test "TxPool ethBlock":
com.pos.prevRandao = prevRandao
com.pos.feeRecipient = feeRecipient
com.pos.timestamp = EthTime.now()
let r = xp.assembleBlock()
if r.isErr:
debugEcho r.error
check false
return
blk = r.get.blk
check com.isBlockAfterTtd(blk.header)
body = BlockBody(
transactions: blk.txs,
uncles: blk.uncles,
withdrawals: some[seq[Withdrawal]](@[])
)
check blk.txs.len == 2
test "Blobhash persistBlocks":
Consolidate block type for block processing (#2325) This PR consolidates the split header-body sequences into a single EthBlock sequence and cleans up the fallout from that which significantly reduces block processing overhead during import thanks to less garbage collection and fewer copies of things all around. Notably, since the number of headers must always match the number of bodies, we also get rid of a pointless degree of freedom that in the future could introduce unnecessary bugs. * only read header and body from era file * avoid several unnecessary copies along the block processing way * simplify signatures, cleaning up unused arguemnts and returns * use `stew/assign2` in a few strategic places where the generated nim assignent is slow and add a few `move` to work around poor analysis in nim 1.6 (will need to be revisited for 2.0) ``` stats-20240607_2223-a814aa0b.csv vs stats-20240608_0714-21c1d0a9.csv bps_x bps_y tps_x tps_y bpsd tpsd timed block_number (498305, 713245] 1,540.52 1,809.73 2,361.58 2775.340189 17.63% 17.63% -14.92% (713245, 928185] 730.36 865.26 1,715.90 2028.973852 18.01% 18.01% -15.21% (928185, 1143126] 663.03 789.10 2,529.26 3032.490771 19.79% 19.79% -16.28% (1143126, 1358066] 393.46 508.05 2,152.50 2777.578119 29.13% 29.13% -22.50% (1358066, 1573007] 370.88 440.72 2,351.31 2791.896052 18.81% 18.81% -15.80% (1573007, 1787947] 283.65 335.11 2,068.93 2441.373402 17.60% 17.60% -14.91% (1787947, 2002888] 287.29 342.11 2,078.39 2474.179448 18.99% 18.99% -15.91% (2002888, 2217828] 293.38 343.16 2,208.83 2584.77457 17.16% 17.16% -14.61% (2217828, 2432769] 140.09 167.86 1,081.87 1296.336926 18.82% 18.82% -15.80% blocks: 1934464, baseline: 3h13m1s, contender: 2h43m47s bpsd (mean): 19.55% tpsd (mean): 19.55% Time (total): -29m13s, -15.14% ```
2024-06-09 14:32:20 +00:00
let rr = chain.persistBlocks([EthBlock.init(blk.header, body)])
check rr.isOk()
test "validate TxPool prevRandao setter":
var sdb = LedgerRef.init(com.db, blk.header.stateRoot)
let val = sdb.getStorage(recipient, slot)
let randao = Hash256(data: val.toBytesBE)
check randao == prevRandao
test "feeRecipient rewarded":
check blk.header.coinbase == feeRecipient
var sdb = LedgerRef.init(com.db, blk.header.stateRoot)
let bal = sdb.getBalance(feeRecipient)
check not bal.isZero
test "add tx with nonce too low":
let
tx3 = env.makeTx(recipient, amount)
tx4 = env.signTxWithNonce(tx3, AccountNonce(env.nonce-2))
xp = env.xp
check xp.smartHead(blk.header)
let res = xp.addLocal(PooledTransaction(tx: tx4), force = true)
check res.isOk
if res.isErr:
debugEcho res.error
return
check inPoolAndOk(xp, rlpHash(tx4)) == false
proc runTxHeadDelta(noisy = true) =
2022-04-04 08:34:59 +00:00
## see github.com/status-im/nimbus-eth1/issues/1031
suite "TxPool: Synthesising blocks (covers issue #1031)":
test "Packing and adding multiple blocks to chain":
2022-04-04 08:34:59 +00:00
var
env = initEnv(MergeFork)
2022-04-04 08:34:59 +00:00
xp = env.xp
2022-12-02 04:39:12 +00:00
com = env.com
2022-04-04 08:34:59 +00:00
chain = env.chain
2022-12-02 04:39:12 +00:00
head = com.db.getCanonicalHead()
2022-04-04 08:34:59 +00:00
timestamp = head.timestamp
const
txPerblock = 20
numBlocks = 10
# setTraceLevel()
block:
2022-04-04 08:34:59 +00:00
for n in 0..<numBlocks:
for tn in 0..<txPerblock:
let tx = env.makeTx(recipient, amount)
# Instead of `add()`, the functions `addRemote()` or `addLocal()`
# also would do.
xp.add(PooledTransaction(tx: tx))
2022-04-04 08:34:59 +00:00
noisy.say "***", "txDB",
2022-04-04 08:34:59 +00:00
&" n={n}",
# pending/staged/packed : total/disposed
&" stats={xp.nItems.pp}"
2022-04-04 08:34:59 +00:00
timestamp = timestamp + 1
com.pos.prevRandao = prevRandao
com.pos.timestamp = timestamp
com.pos.feeRecipient = feeRecipient
let r = xp.assembleBlock()
if r.isErr:
debugEcho r.error
check false
return
let blk = r.get.blk
2022-12-02 04:39:12 +00:00
check com.isBlockAfterTtd(blk.header)
2022-04-04 08:34:59 +00:00
let body = BlockBody(
transactions: blk.txs,
uncles: blk.uncles)
# Commit to block chain
Consolidate block type for block processing (#2325) This PR consolidates the split header-body sequences into a single EthBlock sequence and cleans up the fallout from that which significantly reduces block processing overhead during import thanks to less garbage collection and fewer copies of things all around. Notably, since the number of headers must always match the number of bodies, we also get rid of a pointless degree of freedom that in the future could introduce unnecessary bugs. * only read header and body from era file * avoid several unnecessary copies along the block processing way * simplify signatures, cleaning up unused arguemnts and returns * use `stew/assign2` in a few strategic places where the generated nim assignent is slow and add a few `move` to work around poor analysis in nim 1.6 (will need to be revisited for 2.0) ``` stats-20240607_2223-a814aa0b.csv vs stats-20240608_0714-21c1d0a9.csv bps_x bps_y tps_x tps_y bpsd tpsd timed block_number (498305, 713245] 1,540.52 1,809.73 2,361.58 2775.340189 17.63% 17.63% -14.92% (713245, 928185] 730.36 865.26 1,715.90 2028.973852 18.01% 18.01% -15.21% (928185, 1143126] 663.03 789.10 2,529.26 3032.490771 19.79% 19.79% -16.28% (1143126, 1358066] 393.46 508.05 2,152.50 2777.578119 29.13% 29.13% -22.50% (1358066, 1573007] 370.88 440.72 2,351.31 2791.896052 18.81% 18.81% -15.80% (1573007, 1787947] 283.65 335.11 2,068.93 2441.373402 17.60% 17.60% -14.91% (1787947, 2002888] 287.29 342.11 2,078.39 2474.179448 18.99% 18.99% -15.91% (2002888, 2217828] 293.38 343.16 2,208.83 2584.77457 17.16% 17.16% -14.61% (2217828, 2432769] 140.09 167.86 1,081.87 1296.336926 18.82% 18.82% -15.80% blocks: 1934464, baseline: 3h13m1s, contender: 2h43m47s bpsd (mean): 19.55% tpsd (mean): 19.55% Time (total): -29m13s, -15.14% ```
2024-06-09 14:32:20 +00:00
check chain.persistBlocks([EthBlock.init(blk.header, body)]).isOk
2022-04-04 08:34:59 +00:00
# Synchronise TxPool against new chain head, register txs differences.
# In this particular case, these differences will simply flush the
# packer bucket.
check xp.smartHead(blk.header)
# Move TxPool chain head to new chain head and apply delta jobs
check xp.nItems.staged == 0
check xp.nItems.packed == 0
setErrorLevel() # in case we set trace level
2022-04-04 08:34:59 +00:00
2022-12-02 04:39:12 +00:00
check com.syncCurrent == 10.toBlockNumber
head = com.db.getBlockHeader(com.syncCurrent)
2022-04-04 08:34:59 +00:00
let
sdb = LedgerRef.init(com.db, head.stateRoot)
2022-04-04 08:34:59 +00:00
expected = u256(txPerblock * numBlocks) * amount
balance = sdb.getBalance(recipient)
check balance == expected
proc txPool2Main*() =
2022-04-04 08:34:59 +00:00
const
noisy = defined(debug)
setErrorLevel() # mute logger
runTxPoolPosTest()
runTxPoolBlobhashTest()
noisy.runTxHeadDelta
when isMainModule:
txPool2Main()
2022-04-04 08:34:59 +00:00
# End