diff --git a/Makefile b/Makefile index 1406acb4a..82810d020 100644 --- a/Makefile +++ b/Makefile @@ -137,6 +137,7 @@ GIT_SUBMODULE_UPDATE := git -c submodule."vendor/nimbus-eth2".update=none submod git submodule update --init vendor/sepolia; \ git submodule update --init vendor/gnosis-chain-configs; \ git submodule update --init --recursive vendor/nim-kzg4844; \ + git submodule update --init vendor/mainnet; \ cd ../.. .DEFAULT: diff --git a/fluffy/eth_data/era1.nim b/fluffy/eth_data/era1.nim index d4006fd18..2f4f670eb 100644 --- a/fluffy/eth_data/era1.nim +++ b/fluffy/eth_data/era1.nim @@ -20,7 +20,7 @@ import ../network/history/accumulator from nimcrypto/hash import fromHex -from ../../nimbus/utils/utils import calcTxRoot, calcReceiptRoot +from ../../nimbus/utils/utils import calcTxRoot, calcReceiptsRoot export e2store.readRecord @@ -475,7 +475,7 @@ proc verify*(f: Era1File): Result[Digest, string] = if blockHeader.ommersHash != ommershHash: return err("Invalid ommers hash") - if blockHeader.receiptRoot != calcReceiptRoot(receipts): + if blockHeader.receiptsRoot != calcReceiptsRoot(receipts): return err("Invalid receipts root") headerRecords.add( diff --git a/fluffy/eth_data/history_data_json_store.nim b/fluffy/eth_data/history_data_json_store.nim index f564313f7..c7bd8b562 100644 --- a/fluffy/eth_data/history_data_json_store.nim +++ b/fluffy/eth_data/history_data_json_store.nim @@ -210,9 +210,8 @@ proc writeHeaderRecord*( writer: var JsonWriter, header: BlockHeader ) {.raises: [IOError].} = let - dataRecord = HeaderRecord( - header: rlp.encode(header).to0xHex(), number: header.blockNumber.truncate(uint64) - ) + dataRecord = + HeaderRecord(header: rlp.encode(header).to0xHex(), number: header.number) headerHash = to0xHex(rlpHash(header).data) @@ -226,7 +225,7 @@ proc writeBlockRecord*( header: rlp.encode(header).to0xHex(), body: encode(body).to0xHex(), receipts: encode(receipts).to0xHex(), - number: header.blockNumber.truncate(uint64), + number: header.number, ) headerHash = to0xHex(rlpHash(header).data) diff --git a/fluffy/eth_data/history_data_seeding.nim b/fluffy/eth_data/history_data_seeding.nim index 6c6f1b29d..3b5bddcad 100644 --- a/fluffy/eth_data/history_data_seeding.nim +++ b/fluffy/eth_data/history_data_seeding.nim @@ -280,7 +280,7 @@ iterator headersWithProof*( ).encode() headerWithProof = buildHeaderWithProof(blockHeader, epochAccumulator).valueOr: - raiseAssert "Failed to build header with proof: " & $blockHeader.blockNumber + raiseAssert "Failed to build header with proof: " & $blockHeader.number contentValue = SSZ.encode(headerWithProof) diff --git a/fluffy/network/history/accumulator.nim b/fluffy/network/history/accumulator.nim index 9244b8d77..c42b136eb 100644 --- a/fluffy/network/history/accumulator.nim +++ b/fluffy/network/history/accumulator.nim @@ -82,8 +82,7 @@ func getEpochAccumulatorRoot*(headerRecords: openArray[HeaderRecord]): Digest = func updateAccumulator*(a: var Accumulator, header: BlockHeader) = doAssert( - header.blockNumber.truncate(uint64) < mergeBlockNumber, - "No post merge blocks for header accumulator", + header.number < mergeBlockNumber, "No post merge blocks for header accumulator" ) let lastTotalDifficulty = @@ -126,9 +125,8 @@ func getEpochIndex*(blockNumber: uint64): uint64 = blockNumber div epochSize func getEpochIndex*(header: BlockHeader): uint64 = - let blockNumber = header.blockNumber.truncate(uint64) ## Get the index for the historical epochs - getEpochIndex(blockNumber) + getEpochIndex(header.number) func getHeaderRecordIndex*(blockNumber: uint64, epochIndex: uint64): uint64 = ## Get the relative header index for the epoch accumulator @@ -136,13 +134,13 @@ func getHeaderRecordIndex*(blockNumber: uint64, epochIndex: uint64): uint64 = func getHeaderRecordIndex*(header: BlockHeader, epochIndex: uint64): uint64 = ## Get the relative header index for the epoch accumulator - getHeaderRecordIndex(header.blockNumber.truncate(uint64), epochIndex) + getHeaderRecordIndex(header.number, epochIndex) func isPreMerge*(blockNumber: uint64): bool = blockNumber < mergeBlockNumber func isPreMerge*(header: BlockHeader): bool = - isPreMerge(header.blockNumber.truncate(uint64)) + isPreMerge(header.number) func verifyProof( a: FinishedAccumulator, header: BlockHeader, proof: openArray[Digest] diff --git a/fluffy/network/history/history_network.nim b/fluffy/network/history/history_network.nim index b4dbee48e..dc9261870 100644 --- a/fluffy/network/history/history_network.nim +++ b/fluffy/network/history/history_network.nim @@ -98,7 +98,7 @@ func fromPortalBlockBody*( BlockBody( transactions: transactions, uncles: @[], # Uncles must be empty: TODO where validation? - withdrawals: some(withdrawals), + withdrawals: Opt.some(withdrawals), ) ) except RlpError as e: @@ -192,7 +192,7 @@ proc calcRootHash(items: Transactions | PortalReceipts | Withdrawals): Hash256 = var tr = initHexaryTrie(newMemoryDB(), isPruning = false) for i, item in items: try: - tr.put(rlp.encode(i), item.asSeq()) + tr.put(rlp.encode(i.uint), item.asSeq()) except CatchableError as e: # tr.put now is a generic interface to whatever underlying db # and it can raise exception if the backend db is something like aristo @@ -305,7 +305,7 @@ proc validateBlockBodyBytes*( let body = ?decodeSsz(bytes, PortalBlockBodyShanghai) ?validateBlockBody(body, header) BlockBody.fromPortalBlockBody(body) - elif isPoSBlock(chainConfig, header.blockNumber.truncate(uint64)): + elif isPoSBlock(chainConfig, header.number): if header.withdrawalsRoot.isSome(): return err("Expected no withdrawalsRoot for pre Shanghai block") elif header.ommersHash != EMPTY_UNCLE_HASH: @@ -374,7 +374,7 @@ proc get( BlockBody.fromPortalBlockBodyOrRaise( decodeSszOrRaise(encoded, PortalBlockBodyShanghai) ) - elif isPoSBlock(chainConfig, header.blockNumber.truncate(uint64)): + elif isPoSBlock(chainConfig, header.number): BlockBody.fromPortalBlockBodyOrRaise( decodeSszOrRaise(encoded, PortalBlockBodyLegacy) ) @@ -532,7 +532,7 @@ proc getBlock*(n: HistoryNetwork, hash: BlockHash): Future[Opt[Block]] {.async.} proc getReceipts*( n: HistoryNetwork, hash: BlockHash, header: BlockHeader ): Future[Opt[seq[Receipt]]] {.async.} = - if header.receiptRoot == EMPTY_ROOT_HASH: + if header.receiptsRoot == EMPTY_ROOT_HASH: # Short path for empty receipts indicated by receipts root return Opt.some(newSeq[Receipt]()) @@ -554,7 +554,7 @@ proc getReceipts*( receiptsContent = (await n.portalProtocol.contentLookup(contentKey, contentId)).valueOr: warn "Failed fetching receipts from the network" return Opt.none(seq[Receipt]) - receipts = validateReceiptsBytes(receiptsContent.content, header.receiptRoot).valueOr: + receipts = validateReceiptsBytes(receiptsContent.content, header.receiptsRoot).valueOr: warn "Validation of receipts failed", error continue @@ -671,7 +671,7 @@ proc validateContent( warn "Failed getting canonical header for receipts" return false - let res = validateReceiptsBytes(content, header.receiptRoot) + let res = validateReceiptsBytes(content, header.receiptsRoot) if res.isErr(): warn "Failed validating receipts", error = res.error return false diff --git a/fluffy/network/wire/portal_stream.nim b/fluffy/network/wire/portal_stream.nim index d1b47f63e..5fc46feff 100644 --- a/fluffy/network/wire/portal_stream.nim +++ b/fluffy/network/wire/portal_stream.nim @@ -141,7 +141,7 @@ proc connectTo*( ): Future[Result[UtpSocket[NodeAddress], string]] {.async.} = let connectRes = await stream.transport.connectTo(nodeAddress, connectionId) if connectRes.isErr(): - case connectRes.error.kind + case connectRes.error of SocketAlreadyExists: # This means that there is already a socket to this nodeAddress with given # connection id. This means that a peer sent us a connection id which is @@ -161,14 +161,16 @@ proc connectTo*( proc writeContentRequest( socket: UtpSocket[NodeAddress], stream: PortalStream, request: ContentRequest -) {.async.} = +) {.async: (raises: [CancelledError]).} = let dataWritten = await socket.write(request.content) if dataWritten.isErr(): debug "Error writing requested data", error = dataWritten.error await socket.closeWait() -proc readVarint(socket: UtpSocket[NodeAddress]): Future[Opt[uint32]] {.async.} = +proc readVarint( + socket: UtpSocket[NodeAddress] +): Future[Opt[uint32]] {.async: (raises: [CancelledError]).} = var buffer: array[5, byte] for i in 0 ..< len(buffer): @@ -186,7 +188,9 @@ proc readVarint(socket: UtpSocket[NodeAddress]): Future[Opt[uint32]] {.async.} = else: return err() -proc readContentItem(socket: UtpSocket[NodeAddress]): Future[Opt[seq[byte]]] {.async.} = +proc readContentItem( + socket: UtpSocket[NodeAddress] +): Future[Opt[seq[byte]]] {.async: (raises: [CancelledError]).} = let len = await socket.readVarint() if len.isOk(): @@ -200,7 +204,7 @@ proc readContentItem(socket: UtpSocket[NodeAddress]): Future[Opt[seq[byte]]] {.a proc readContentOffer( socket: UtpSocket[NodeAddress], stream: PortalStream, offer: ContentOffer -) {.async.} = +) {.async: (raises: [CancelledError]).} = # Read number of content items according to amount of ContentKeys accepted. # This will either end with a FIN, or because the read action times out or # because the number of expected items was read (if this happens and no FIN @@ -220,7 +224,7 @@ proc readContentOffer( for i in 0 ..< amount: let contentItemFut = socket.readContentItem() if await contentItemFut.withTimeout(stream.contentReadTimeout): - let contentItem = contentItemFut.read + let contentItem = await contentItemFut if contentItem.isOk(): contentItems.add(contentItem.get()) @@ -291,7 +295,7 @@ proc allowedConnection( proc handleIncomingConnection( server: UtpRouter[NodeAddress], socket: UtpSocket[NodeAddress] -): Future[void] = +): Future[void] {.async: (raw: true, raises: []).} = let manager = getUserData[NodeAddress, StreamManager](server) for stream in manager.streams: @@ -303,14 +307,14 @@ proc handleIncomingConnection( request.nodeId == socket.remoteAddress.nodeId: let fut = socket.writeContentRequest(stream, request) stream.contentRequests.del(i) - return fut + return noCancel(fut) for i, offer in stream.contentOffers: if offer.connectionId == socket.connectionId and offer.nodeId == socket.remoteAddress.nodeId: let fut = socket.readContentOffer(stream, offer) stream.contentOffers.del(i) - return fut + return noCancel(fut) # TODO: Is there a scenario where this can happen, # considering `allowRegisteredIdCallback`? If not, doAssert? diff --git a/fluffy/rpc/rpc_eth_api.nim b/fluffy/rpc/rpc_eth_api.nim index 17726db0b..09b772d48 100644 --- a/fluffy/rpc/rpc_eth_api.nim +++ b/fluffy/rpc/rpc_eth_api.nim @@ -50,23 +50,23 @@ func init*( txIndex: int, ): T {.raises: [ValidationError].} = TransactionObject( - blockHash: some(w3Hash header.blockHash), - blockNumber: some(eth_api_types.BlockNumber(header.blockNumber.truncate(uint64))), + blockHash: Opt.some(w3Hash header.blockHash), + blockNumber: Opt.some(eth_api_types.BlockNumber(header.number)), `from`: w3Addr tx.getSender(), gas: Quantity(tx.gasLimit), gasPrice: Quantity(tx.gasPrice), hash: w3Hash tx.rlpHash, input: tx.payload, nonce: Quantity(tx.nonce), - to: some(w3Addr tx.destination), - transactionIndex: some(Quantity(txIndex)), + to: Opt.some(w3Addr tx.destination), + transactionIndex: Opt.some(Quantity(txIndex)), value: tx.value, v: Quantity(tx.V), r: tx.R, s: tx.S, - `type`: some(Quantity(tx.txType)), - maxFeePerGas: some(Quantity(tx.maxFee)), - maxPriorityFeePerGas: some(Quantity(tx.maxPriorityFee)), + `type`: Opt.some(Quantity(tx.txType)), + maxFeePerGas: Opt.some(Quantity(tx.maxFeePerGas)), + maxPriorityFeePerGas: Opt.some(Quantity(tx.maxPriorityFeePerGas)), ) # Note: Similar as `populateBlockObject` from rpc_utils, but lacking the @@ -81,15 +81,15 @@ func init*( let blockHash = header.blockHash var blockObject = BlockObject( - number: eth_api_types.BlockNumber(header.blockNumber.truncate(uint64)), + number: eth_api_types.BlockNumber(header.number), hash: w3Hash blockHash, parentHash: w3Hash header.parentHash, - nonce: some(FixedBytes[8](header.nonce)), + nonce: Opt.some(FixedBytes[8](header.nonce)), sha3Uncles: w3Hash header.ommersHash, - logsBloom: FixedBytes[256] header.bloom, + logsBloom: FixedBytes[256] header.logsBloom, transactionsRoot: w3Hash header.txRoot, stateRoot: w3Hash header.stateRoot, - receiptsRoot: w3Hash header.receiptRoot, + receiptsRoot: w3Hash header.receiptsRoot, miner: w3Addr header.coinbase, difficulty: header.difficulty, extraData: HistoricExtraData header.extraData, @@ -97,9 +97,9 @@ func init*( # https://playground.open-rpc.org/?schemaUrl=https://raw.githubusercontent.com/ethereum/eth1.0-apis/assembled-spec/openrpc.json # So we should probably change `BlockObject`. totalDifficulty: UInt256.low(), - gasLimit: Quantity(header.gasLimit.uint64), - gasUsed: Quantity(header.gasUsed.uint64), - timestamp: Quantity(header.timestamp.uint64), + gasLimit: Quantity(header.gasLimit), + gasUsed: Quantity(header.gasUsed), + timestamp: Quantity(header.timestamp), ) let size = sizeof(BlockHeader) - sizeof(Blob) + header.extraData.len @@ -212,7 +212,7 @@ proc installEthApiHandlers*( rpcServerWithProxy.rpc("eth_getBlockByHash") do( data: eth_api_types.Hash256, fullTransactions: bool - ) -> Option[BlockObject]: + ) -> Opt[BlockObject]: ## Returns information about a block by hash. ## ## data: Hash of a block. @@ -223,13 +223,13 @@ proc installEthApiHandlers*( let blockHash = data.toHash() (header, body) = (await historyNetwork.getBlock(blockHash)).valueOr: - return none(BlockObject) + return Opt.none(BlockObject) - return some(BlockObject.init(header, body, fullTransactions)) + return Opt.some(BlockObject.init(header, body, fullTransactions)) rpcServerWithProxy.rpc("eth_getBlockByNumber") do( quantityTag: RtBlockIdentifier, fullTransactions: bool - ) -> Option[BlockObject]: + ) -> Opt[BlockObject]: if quantityTag.kind == bidAlias: let tag = quantityTag.alias.toLowerAscii case tag @@ -250,9 +250,9 @@ proc installEthApiHandlers*( let blockHash = forkyStore.optimistic_header.execution.block_hash (header, body) = (await historyNetwork.getBlock(blockHash)).valueOr: - return none(BlockObject) + return Opt.none(BlockObject) - return some(BlockObject.init(header, body, fullTransactions)) + return Opt.some(BlockObject.init(header, body, fullTransactions)) else: raise newException(ValueError, "Not available before Capella - not synced?") of "finalized": @@ -264,9 +264,9 @@ proc installEthApiHandlers*( let blockHash = forkyStore.finalized_header.execution.block_hash (header, body) = (await historyNetwork.getBlock(blockHash)).valueOr: - return none(BlockObject) + return Opt.none(BlockObject) - return some(BlockObject.init(header, body, fullTransactions)) + return Opt.some(BlockObject.init(header, body, fullTransactions)) else: raise newException(ValueError, "Not available before Capella - not synced?") of "pending": @@ -275,15 +275,15 @@ proc installEthApiHandlers*( raise newException(ValueError, "Unsupported block tag " & tag) else: let - blockNumber = quantityTag.number.uint64.toBlockNumber + blockNumber = quantityTag.number.uint64.u256 maybeBlock = (await historyNetwork.getBlock(blockNumber)).valueOr: raise newException(ValueError, error) if maybeBlock.isNone(): - return none(BlockObject) + return Opt.none(BlockObject) else: let (header, body) = maybeBlock.get() - return some(BlockObject.init(header, body, fullTransactions)) + return Opt.some(BlockObject.init(header, body, fullTransactions)) rpcServerWithProxy.rpc("eth_getBlockTransactionCountByHash") do( data: eth_api_types.Hash256 @@ -309,7 +309,7 @@ proc installEthApiHandlers*( # from from the block with that block hash. The Canonical Indices Network # would need to be implemented to get this information. # rpcServerWithProxy.rpc("eth_getTransactionReceipt") do( - # data: EthHashStr) -> Option[ReceiptObject]: + # data: EthHashStr) -> Opt[ReceiptObject]: rpcServerWithProxy.rpc("eth_getLogs") do( filterOptions: FilterOptions diff --git a/fluffy/scripts/test_portal_testnet.nim b/fluffy/scripts/test_portal_testnet.nim index f9b2087ac..3455f71f4 100644 --- a/fluffy/scripts/test_portal_testnet.nim +++ b/fluffy/scripts/test_portal_testnet.nim @@ -305,7 +305,7 @@ procSuite "Portal testnet tests": doAssert(tx.kind == tohTx) check tx.tx.blockHash.get == w3Hash hash - let filterOptions = FilterOptions(blockHash: some(w3Hash hash)) + let filterOptions = FilterOptions(blockHash: Opt.some(w3Hash hash)) let logs = await retryUntil( proc(): Future[seq[LogObject]] {.async.} = @@ -326,7 +326,7 @@ procSuite "Portal testnet tests": for l in logs: check: - l.blockHash == some(w3Hash hash) + l.blockHash == Opt.some(w3Hash hash) # TODO: Check ommersHash, need the headers and not just the hashes # for uncle in blockObj.uncles: diff --git a/fluffy/tests/portal_spec_tests/mainnet/test_accumulator_root.nim b/fluffy/tests/portal_spec_tests/mainnet/test_accumulator_root.nim index 702cc045f..f9eea9a6b 100644 --- a/fluffy/tests/portal_spec_tests/mainnet/test_accumulator_root.nim +++ b/fluffy/tests/portal_spec_tests/mainnet/test_accumulator_root.nim @@ -43,7 +43,7 @@ suite "Header Accumulator Root": let res = v.readBlockHeader() check res.isOk() let header = res.get() - headers[header.blockNumber.truncate(int)] = header + headers[header.number] = header var accumulator: Accumulator diff --git a/fluffy/tests/portal_spec_tests/mainnet/test_history_content.nim b/fluffy/tests/portal_spec_tests/mainnet/test_history_content.nim index 57ee72d2d..1d9f37004 100644 --- a/fluffy/tests/portal_spec_tests/mainnet/test_history_content.nim +++ b/fluffy/tests/portal_spec_tests/mainnet/test_history_content.nim @@ -48,10 +48,9 @@ suite "History Content Encodings": # Go over all content keys and headers with generated proofs and compare # them with the ones from the test vectors. let - blockNumber = blockHeaders[i].blockNumber - contentKeyEncoded = content[blockNumber.toString()].content_key.hexToSeqByte() - contentValueEncoded = - content[blockNumber.toString()].content_value.hexToSeqByte() + blockNumber = blockHeaders[i].number + contentKeyEncoded = content[$blockNumber].content_key.hexToSeqByte() + contentValueEncoded = content[$blockNumber].content_value.hexToSeqByte() check: contentKeyEncoded == headerContentKey @@ -210,7 +209,7 @@ suite "History Content Encodings": check contentKey.isOk() # Decode (SSZ + RLP decode step) and validate receipts - let contentValue = validateReceiptsBytes(contentValueEncoded, header.receiptRoot) + let contentValue = validateReceiptsBytes(contentValueEncoded, header.receiptsRoot) check contentValue.isOk() # Encode content diff --git a/fluffy/tests/portal_spec_tests/mainnet/test_history_content_validation.nim b/fluffy/tests/portal_spec_tests/mainnet/test_history_content_validation.nim index 8fdf8c2fa..b579fb7fc 100644 --- a/fluffy/tests/portal_spec_tests/mainnet/test_history_content_validation.nim +++ b/fluffy/tests/portal_spec_tests/mainnet/test_history_content_validation.nim @@ -46,7 +46,7 @@ suite "History Network Content Validation": blockBody = validateBlockBodyBytes(blockBodyBytes, blockHeader).expect( "Should be Valid decoded block body" ) - receipts = validateReceiptsBytes(receiptsBytes, blockHeader.receiptRoot).expect( + receipts = validateReceiptsBytes(receiptsBytes, blockHeader.receiptsRoot).expect( "Should be Valid decoded receipts" ) @@ -98,16 +98,16 @@ suite "History Network Content Validation": check validateBlockBodyBytes(modifiedBodyBytes, blockHeader).isErr() test "Valid Receipts": - check validateReceiptsBytes(receiptsBytes, blockHeader.receiptRoot).isOk() + check validateReceiptsBytes(receiptsBytes, blockHeader.receiptsRoot).isOk() test "Malformed Receipts": let malformedBytes = receiptsBytes[10 .. receiptsBytes.high] - check validateReceiptsBytes(malformedBytes, blockHeader.receiptRoot).isErr() + check validateReceiptsBytes(malformedBytes, blockHeader.receiptsRoot).isErr() test "Invalid Receipts - Modified Receipts List": var modifiedReceipts = receipts[1 .. receipts.high] let modifiedReceiptsBytes = encode(modifiedReceipts) - check validateReceiptsBytes(modifiedReceiptsBytes, blockHeader.receiptRoot).isErr() + check validateReceiptsBytes(modifiedReceiptsBytes, blockHeader.receiptsRoot).isErr() diff --git a/fluffy/tests/test_accumulator.nim b/fluffy/tests/test_accumulator.nim index 94bae7395..3814d8feb 100644 --- a/fluffy/tests/test_accumulator.nim +++ b/fluffy/tests/test_accumulator.nim @@ -41,7 +41,7 @@ suite "Header Accumulator": # Note: These test headers will not be a blockchain, as the parent hashes # are not properly filled in. That's fine however for this test, as that # is not the way the headers are verified with the accumulator. - headers.add(BlockHeader(blockNumber: i.stuint(256), difficulty: 1.stuint(256))) + headers.add(BlockHeader(number: i, difficulty: 1.stuint(256))) let accumulatorRes = buildAccumulatorData(headers) check accumulatorRes.isOk() @@ -58,7 +58,7 @@ suite "Header Accumulator": block: # Test invalid headers # Post merge block number must fail (> than latest header in accumulator) var proof: AccumulatorProof - let header = BlockHeader(blockNumber: mergeBlockNumber.stuint(256)) + let header = BlockHeader(number: mergeBlockNumber) check verifyAccumulatorProof(accumulator, header, proof).isErr() # Test altered block headers by altering the difficulty @@ -67,7 +67,7 @@ suite "Header Accumulator": check: proof.isOk() # Alter the block header so the proof no longer matches - let header = BlockHeader(blockNumber: i.stuint(256), difficulty: 2.stuint(256)) + let header = BlockHeader(number: i.uint64, difficulty: 2.stuint(256)) check verifyAccumulatorProof(accumulator, header, proof.get()).isErr() @@ -83,7 +83,7 @@ suite "Header Accumulator": var headers: seq[BlockHeader] for i in 0 ..< amount: - headers.add(BlockHeader(blockNumber: i.stuint(256), difficulty: 1.stuint(256))) + headers.add(BlockHeader(number: i, difficulty: 1.stuint(256))) let accumulatorRes = buildAccumulator(headers) @@ -98,7 +98,7 @@ suite "Header Accumulator": headers: seq[BlockHeader] for i in 0 ..< amount: - let header = BlockHeader(blockNumber: u256(i), difficulty: u256(1)) + let header = BlockHeader(number: i, difficulty: u256(1)) headers.add(header) headerHashes.add(header.blockHash()) diff --git a/fluffy/tests/test_helpers.nim b/fluffy/tests/test_helpers.nim index ba276ff9e..4a170066d 100644 --- a/fluffy/tests/test_helpers.nim +++ b/fluffy/tests/test_helpers.nim @@ -57,7 +57,7 @@ func buildAccumulator*(headers: seq[BlockHeader]): Result[FinishedAccumulator, s for header in headers: updateAccumulator(accumulator, header) - if header.blockNumber.truncate(uint64) == mergeBlockNumber - 1: + if header.number == mergeBlockNumber - 1: return ok(finishAccumulator(accumulator)) err("Not enough headers provided to finish the accumulator") @@ -73,7 +73,7 @@ func buildAccumulatorData*( if accumulator.currentEpoch.len() == epochSize: epochAccumulators.add(accumulator.currentEpoch) - if header.blockNumber.truncate(uint64) == mergeBlockNumber - 1: + if header.number == mergeBlockNumber - 1: epochAccumulators.add(accumulator.currentEpoch) return ok((finishAccumulator(accumulator), epochAccumulators)) diff --git a/fluffy/tests/test_history_network.nim b/fluffy/tests/test_history_network.nim index 58dbbfbce..99e303ae7 100644 --- a/fluffy/tests/test_history_network.nim +++ b/fluffy/tests/test_history_network.nim @@ -52,7 +52,7 @@ proc createEmptyHeaders(fromNum: int, toNum: int): seq[BlockHeader] = var headers: seq[BlockHeader] for i in fromNum .. toNum: var bh = BlockHeader() - bh.blockNumber = u256(i) + bh.number = BlockNumber(i) bh.difficulty = u256(i) # empty so that we won't care about creating fake block bodies bh.ommersHash = EMPTY_UNCLE_HASH diff --git a/fluffy/tools/beacon_lc_bridge/beacon_lc_bridge.nim b/fluffy/tools/beacon_lc_bridge/beacon_lc_bridge.nim index 786b0d03b..2e5f72fff 100644 --- a/fluffy/tools/beacon_lc_bridge/beacon_lc_bridge.nim +++ b/fluffy/tools/beacon_lc_bridge/beacon_lc_bridge.nim @@ -114,7 +114,6 @@ proc asPortalBlockData*( ): (common_types.BlockHash, BlockHeaderWithProof, PortalBlockBodyLegacy) = let txRoot = calculateTransactionData(payload.transactions) - withdrawalsRoot = options.none(Hash256) header = etypes.BlockHeader( parentHash: payload.parentHash.asEthHash, @@ -122,20 +121,20 @@ proc asPortalBlockData*( coinbase: EthAddress payload.feeRecipient, stateRoot: payload.stateRoot.asEthHash, txRoot: txRoot, - receiptRoot: payload.receiptsRoot.asEthHash, - bloom: distinctBase(payload.logsBloom), + receiptsRoot: payload.receiptsRoot.asEthHash, + logsBloom: distinctBase(payload.logsBloom), difficulty: default(DifficultyInt), - blockNumber: payload.blockNumber.distinctBase.u256, + number: payload.blockNumber.distinctBase, gasLimit: payload.gasLimit.unsafeQuantityToInt64, gasUsed: payload.gasUsed.unsafeQuantityToInt64, timestamp: payload.timestamp.EthTime, extraData: bytes payload.extraData, - mixDigest: payload.prevRandao.asEthHash, + mixHash: payload.prevRandao.asEthHash, nonce: default(BlockNonce), - fee: some(payload.baseFeePerGas), - withdrawalsRoot: withdrawalsRoot, - blobGasUsed: options.none(uint64), - excessBlobGas: options.none(uint64), + baseFeePerGas: Opt.some(payload.baseFeePerGas), + withdrawalsRoot: Opt.none(Hash256), + blobGasUsed: Opt.none(uint64), + excessBlobGas: Opt.none(uint64), ) headerWithProof = BlockHeaderWithProof( @@ -158,7 +157,7 @@ proc asPortalBlockData*( ): (common_types.BlockHash, BlockHeaderWithProof, PortalBlockBodyShanghai) = let txRoot = calculateTransactionData(payload.transactions) - withdrawalsRoot = some(calculateWithdrawalsRoot(payload.withdrawals)) + withdrawalsRoot = Opt.some(calculateWithdrawalsRoot(payload.withdrawals)) # TODO: adjust blobGasUsed & excessBlobGas according to deneb fork! header = etypes.BlockHeader( @@ -167,20 +166,20 @@ proc asPortalBlockData*( coinbase: EthAddress payload.feeRecipient, stateRoot: payload.stateRoot.asEthHash, txRoot: txRoot, - receiptRoot: payload.receiptsRoot.asEthHash, - bloom: distinctBase(payload.logsBloom), + receiptsRoot: payload.receiptsRoot.asEthHash, + logsBloom: distinctBase(payload.logsBloom), difficulty: default(DifficultyInt), - blockNumber: payload.blockNumber.distinctBase.u256, + number: payload.blockNumber.distinctBase, gasLimit: payload.gasLimit.unsafeQuantityToInt64, gasUsed: payload.gasUsed.unsafeQuantityToInt64, timestamp: payload.timestamp.EthTime, extraData: bytes payload.extraData, - mixDigest: payload.prevRandao.asEthHash, + mixHash: payload.prevRandao.asEthHash, nonce: default(BlockNonce), - fee: some(payload.baseFeePerGas), + baseFeePerGas: Opt.some(payload.baseFeePerGas), withdrawalsRoot: withdrawalsRoot, - blobGasUsed: options.none(uint64), - excessBlobGas: options.none(uint64), + blobGasUsed: Opt.none(uint64), + excessBlobGas: Opt.none(uint64), ) headerWithProof = BlockHeaderWithProof( diff --git a/fluffy/tools/eth_data_exporter.nim b/fluffy/tools/eth_data_exporter.nim index 2a454493d..26ceb86d1 100644 --- a/fluffy/tools/eth_data_exporter.nim +++ b/fluffy/tools/eth_data_exporter.nim @@ -57,24 +57,22 @@ import # Need to be selective due to the `Block` type conflict from downloader from ../network/history/history_network import encode -from ../../nimbus/utils/utils import calcTxRoot, calcReceiptRoot +from ../../nimbus/utils/utils import calcTxRoot, calcreceiptsRoot chronicles.formatIt(IoErrorCode): $it proc downloadHeader(client: RpcClient, i: uint64): BlockHeader = - let blockNumber = u256(i) try: - let jsonHeader = requestHeader(blockNumber, some(client)) + let jsonHeader = requestHeader(i, some(client)) parseBlockHeader(jsonHeader) except CatchableError as e: fatal "Error while requesting BlockHeader", error = e.msg, number = i quit 1 proc downloadBlock(i: uint64, client: RpcClient): Block = - let num = u256(i) try: - return requestBlock(num, flags = {DownloadReceipts}, client = some(client)) + return requestBlock(i, flags = {DownloadReceipts}, client = some(client)) except CatchableError as e: fatal "Error while requesting Block", error = e.msg, number = i quit 1 @@ -248,9 +246,7 @@ proc cmdExportEra1(config: ExporterConf) = # TODO: Not sure about the errors that can occur here. But the whole # block requests over json-rpc should be reworked here (and can be # used in the bridge also then) - requestBlock( - blockNumber.u256, flags = {DownloadReceipts}, client = some(client) - ) + requestBlock(blockNumber, flags = {DownloadReceipts}, client = some(client)) except CatchableError as e: error "Failed retrieving block, skip creation of era1 file", blockNumber, era, error = e.msg @@ -406,7 +402,7 @@ when isMainModule: headerHash = to0xHex(rlpHash(blockHeader).data) debug "Header decoded successfully", - hash = headerHash, blockNumber = blockHeader.blockNumber + hash = headerHash, blockNumber = blockHeader.number else: warn "Skipping record, not a block header", typ = toHex(header.typ) @@ -464,10 +460,10 @@ when isMainModule: return err("Invalid block header in " & file & ": " & e.msg) # Quick sanity check - if blockHeader.blockNumber.truncate(uint64) != i * epochSize + count: + if blockHeader.number != i * epochSize + count: fatal "Incorrect block headers in file", file = file, - blockNumber = blockHeader.blockNumber, + blockNumber = blockHeader.number, expectedBlockNumber = i * epochSize + count quit 1 @@ -478,7 +474,7 @@ when isMainModule: # a header for the next epoch (or on finishing the epoch). if writeEpochAccumulators: if accumulator.currentEpoch.len() == epochSize or - blockHeader.blockNumber.truncate(uint64) == mergeBlockNumber - 1: + blockHeader.number == mergeBlockNumber - 1: let file = try: dataDir / &"mainnet-epoch-accumulator-{i.uint64:05}.ssz" @@ -495,7 +491,7 @@ when isMainModule: info "Updated an epoch", epoch = i count.inc() - if blockHeader.blockNumber.truncate(uint64) == mergeBlockNumber - 1: + if blockHeader.number == mergeBlockNumber - 1: let finishedAccumulator = finishAccumulator(accumulator) info "Updated last epoch, finished building master accumulator", epoch = i diff --git a/fluffy/tools/portal_bridge/portal_bridge_history.nim b/fluffy/tools/portal_bridge/portal_bridge_history.nim index 9852cba35..06c2ca1ac 100644 --- a/fluffy/tools/portal_bridge/portal_bridge_history.nim +++ b/fluffy/tools/portal_bridge/portal_bridge_history.nim @@ -61,7 +61,7 @@ func asPortalBlock( (headerWithProof, portalBody) -func asTxType(quantity: Option[Quantity]): Result[TxType, string] = +func asTxType(quantity: Opt[Quantity]): Result[TxType, string] = let value = quantity.get(0.Quantity).uint8 var txType: TxType if not checkedEnumAssign(txType, value): @@ -91,7 +91,7 @@ func asReceipt(receiptObject: ReceiptObject): Result[Receipt, string] = isHash: false, status: status == 1, cumulativeGasUsed: cumulativeGasUsed, - bloom: BloomFilter(receiptObject.logsBloom), + logsBloom: BloomFilter(receiptObject.logsBloom), logs: logs, ) ) @@ -102,7 +102,7 @@ func asReceipt(receiptObject: ReceiptObject): Result[Receipt, string] = isHash: true, hash: ethHash receiptObject.root.get(), cumulativeGasUsed: cumulativeGasUsed, - bloom: BloomFilter(receiptObject.logsBloom), + logsBloom: BloomFilter(receiptObject.logsBloom), logs: logs, ) ) @@ -260,7 +260,7 @@ proc runLatestLoop( if validateBlockBody(body, ethBlock.header).isErr(): error "Block body is invalid" continue - if validateReceipts(portalReceipts, ethBlock.header.receiptRoot).isErr(): + if validateReceipts(portalReceipts, ethBlock.header.receiptsRoot).isErr(): error "Receipts root is invalid" continue @@ -507,7 +507,7 @@ proc runBackfillLoopAuditMode( error "Invalid hex for block receipts content", error = e.msg break receiptsBlock - validateReceiptsBytes(content, header.receiptRoot).isOkOr: + validateReceiptsBytes(content, header.receiptsRoot).isOkOr: error "Block receipts are invalid", error break receiptsBlock diff --git a/fluffy/tools/utp_testing/utp_test_app.nim b/fluffy/tools/utp_testing/utp_test_app.nim index 3e32e79ed..6ec55905b 100644 --- a/fluffy/tools/utp_testing/utp_test_app.nim +++ b/fluffy/tools/utp_testing/utp_test_app.nim @@ -116,8 +116,12 @@ proc buildAcceptConnection( t: ref Table[SKey, UtpSocket[NodeAddress]] ): AcceptConnectionCallback[NodeAddress] = return ( - proc(server: UtpRouter[NodeAddress], client: UtpSocket[NodeAddress]): Future[void] = - let fut = newFuture[void]() + proc( + server: UtpRouter[NodeAddress], client: UtpSocket[NodeAddress] + ): Future[void] {.async: (raw: true, raises: []).} = + let fut = noCancel Future[void].Raising([CancelledError]).init( + "utp_test_app.AcceptConnectionCallback" + ) let key = client.socketKey.toSKey() t[key] = client fut.complete() diff --git a/hive_integration/nodocker/consensus/consensus_sim.nim b/hive_integration/nodocker/consensus/consensus_sim.nim index 1a681bb7d..83e0c72df 100644 --- a/hive_integration/nodocker/consensus/consensus_sim.nim +++ b/hive_integration/nodocker/consensus/consensus_sim.nim @@ -41,7 +41,7 @@ proc processChainData(cd: ChainData): TestStatus = else: trace "block hash not equal", got=blockHash, - number=head.blockNumber, + number=head.number, expected=cd.lastBlockHash TestStatus.Failed diff --git a/hive_integration/nodocker/engine/base_spec.nim b/hive_integration/nodocker/engine/base_spec.nim index 0a6a670c3..b081fa506 100644 --- a/hive_integration/nodocker/engine/base_spec.nim +++ b/hive_integration/nodocker/engine/base_spec.nim @@ -1,5 +1,5 @@ # Nimbus -# Copyright (c) 2023 Status Research & Development GmbH +# Copyright (c) 2023-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) @@ -9,7 +9,6 @@ # according to those terms. import - std/[options], eth/common, ./clmock, ./types, @@ -31,7 +30,7 @@ proc configureCLMock*(s: BaseSpec, cl: CLMocker) = if s.safeSlotsToImportOptimistically != 0: cl.safeSlotsToImportOptimistically = s.safeSlotsToImportOptimistically - cl.blockTimestampIncrement = some(s.getBlockTimeIncrements()) + cl.blockTimestampIncrement = Opt.some(s.getBlockTimeIncrements()) func getMainFork*(s: BaseSpec): EngineFork = let mainFork = s.mainFork @@ -75,10 +74,10 @@ method getForkConfig*(s: BaseSpec): ChainConfig {.base.} = # Cannot configure a fork before Shanghai if previousForkTime != 0: return nil - forkConfig.shanghaiTime = some(forkTime.EthTime) + forkConfig.shanghaiTime = Opt.some(forkTime.EthTime) elif mainFork == ForkCancun: - forkConfig.shanghaiTime = some(previousForkTime.EthTime) - forkConfig.cancunTime = some(forkTime.EthTime) + forkConfig.shanghaiTime = Opt.some(previousForkTime.EthTime) + forkConfig.cancunTime = Opt.some(forkTime.EthTime) else: doAssert(false, "unknown fork: " & $mainFork) diff --git a/hive_integration/nodocker/engine/cancun/customizer.nim b/hive_integration/nodocker/engine/cancun/customizer.nim index 650c355f9..84dcb0307 100644 --- a/hive_integration/nodocker/engine/cancun/customizer.nim +++ b/hive_integration/nodocker/engine/cancun/customizer.nim @@ -29,7 +29,7 @@ method setEngineAPIVersionResolver*(cust: EngineAPIVersionResolver, v: CommonRef cust.com = v method forkchoiceUpdatedVersion*(cust: EngineAPIVersionResolver, - headTimestamp: uint64, payloadAttributesTimestamp: Option[uint64] = none(uint64)): Version {.base, gcsafe.} = + headTimestamp: uint64, payloadAttributesTimestamp: Opt[uint64] = Opt.none(uint64)): Version {.base, gcsafe.} = let ts = if payloadAttributesTimestamp.isNone: headTimestamp.EthTime else: payloadAttributesTimestamp.get().EthTime if cust.com.isCancunOrLater(ts): @@ -69,7 +69,7 @@ method getExpectedError*(cust: GetPayloadCustomizer): int {.base, gcsafe.} = type BaseGetPayloadCustomizer* = ref object of GetPayloadCustomizer - customPayloadID*: Option[PayloadID] + customPayloadID*: Opt[PayloadID] expectedError* : int method getPayloadID(cust: BaseGetPayloadCustomizer, @@ -105,12 +105,12 @@ method getPayloadAttributes*(cust: PayloadAttributesCustomizer, basePayloadAttri type BasePayloadAttributesCustomizer* = ref object of PayloadAttributesCustomizer - timestamp* : Option[uint64] - prevRandao* : Option[common.Hash256] - suggestedFeeRecipient* : Option[common.EthAddress] - withdrawals* : Option[seq[Withdrawal]] + timestamp* : Opt[uint64] + prevRandao* : Opt[common.Hash256] + suggestedFeeRecipient* : Opt[common.EthAddress] + withdrawals* : Opt[seq[Withdrawal]] removeWithdrawals* : bool - beaconRoot* : Option[common.Hash256] + beaconRoot* : Opt[common.Hash256] removeBeaconRoot* : bool method getPayloadAttributes(cust: BasePayloadAttributesCustomizer, basePayloadAttributes: PayloadAttributes): PayloadAttributes = @@ -132,12 +132,12 @@ method getPayloadAttributes(cust: BasePayloadAttributesCustomizer, basePayloadAt customPayloadAttributes.suggestedFeeRecipient = w3Addr cust.suggestedFeeRecipient.get if cust.removeWithdrawals: - customPayloadAttributes.withdrawals = none(seq[WithdrawalV1]) + customPayloadAttributes.withdrawals = Opt.none(seq[WithdrawalV1]) elif cust.withdrawals.isSome: customPayloadAttributes.withdrawals = w3Withdrawals cust.withdrawals if cust.removeBeaconRoot: - customPayloadAttributes.parentBeaconBlockRoot = none(Web3Hash) + customPayloadAttributes.parentBeaconBlockRoot = Opt.none(Web3Hash) elif cust.beaconRoot.isSome: customPayloadAttributes.parentBeaconBlockRoot = w3Hash cust.beaconRoot @@ -174,7 +174,7 @@ type UpgradeForkchoiceUpdatedVersion* = ref object of BaseForkchoiceUpdatedCustomizer method forkchoiceUpdatedVersion(cust: UpgradeForkchoiceUpdatedVersion, headTimestamp: - uint64, payloadAttributesTimestamp: Option[uint64] = none(uint64)): Version = + uint64, payloadAttributesTimestamp: Opt[uint64] = Opt.none(uint64)): Version = let version = procCall forkchoiceUpdatedVersion(EngineAPIVersionResolver(cust), headTimestamp, payloadAttributesTimestamp) doAssert(version != Version.high, "cannot upgrade version " & $Version.high) version.succ @@ -184,7 +184,7 @@ type DowngradeForkchoiceUpdatedVersion* = ref object of BaseForkchoiceUpdatedCustomizer method forkchoiceUpdatedVersion(cust: DowngradeForkchoiceUpdatedVersion, headTimestamp: uint64, - payloadAttributesTimestamp: Option[uint64] = none(uint64)): Version = + payloadAttributesTimestamp: Opt[uint64] = Opt.none(uint64)): Version = let version = procCall forkchoiceUpdatedVersion(EngineAPIVersionResolver(cust), headTimestamp, payloadAttributesTimestamp) doAssert(version != Version.V1, "cannot downgrade version 1") version.pred @@ -200,13 +200,13 @@ method getPayloadAttributes(cust: TimestampDeltaPayloadAttributesCustomizer, bas type VersionedHashesCustomizer* = ref object of RootRef - blobs*: Option[seq[BlobID]] + blobs*: Opt[seq[BlobID]] hashVersions*: seq[byte] method getVersionedHashes*(cust: VersionedHashesCustomizer, - baseVersionedHashes: openArray[common.Hash256]): Option[seq[common.Hash256]] {.base, gcsafe.} = + baseVersionedHashes: openArray[common.Hash256]): Opt[seq[common.Hash256]] {.base, gcsafe.} = if cust.blobs.isNone: - return none(seq[common.Hash256]) + return Opt.none(seq[common.Hash256]) let blobs = cust.blobs.get var v = newSeq[common.Hash256](blobs.len) @@ -216,7 +216,7 @@ method getVersionedHashes*(cust: VersionedHashesCustomizer, if cust.hashVersions.len > i: version = cust.hashVersions[i] v[i] = blobID.getVersionedHash(version) - some(v) + Opt.some(v) method description*(cust: VersionedHashesCustomizer): string {.base, gcsafe.} = result = "VersionedHashes: " @@ -232,33 +232,33 @@ type IncreaseVersionVersionedHashes* = ref object of VersionedHashesCustomizer method getVersionedHashes(cust: IncreaseVersionVersionedHashes, - baseVersionedHashes: openArray[common.Hash256]): Option[seq[common.Hash256]] = + baseVersionedHashes: openArray[common.Hash256]): Opt[seq[common.Hash256]] = doAssert(baseVersionedHashes.len > 0, "no versioned hashes available for modification") var v = newSeq[common.Hash256](baseVersionedHashes.len) for i, h in baseVersionedHashes: v[i] = h v[i].data[0] = v[i].data[0] + 1 - some(v) + Opt.some(v) type CorruptVersionedHashes* = ref object of VersionedHashesCustomizer method getVersionedHashes(cust: CorruptVersionedHashes, - baseVersionedHashes: openArray[common.Hash256]): Option[seq[common.Hash256]] = + baseVersionedHashes: openArray[common.Hash256]): Opt[seq[common.Hash256]] = doAssert(baseVersionedHashes.len > 0, "no versioned hashes available for modification") var v = newSeq[common.Hash256](baseVersionedHashes.len) for i, h in baseVersionedHashes: v[i] = h v[i].data[h.data.len-1] = v[i].data[h.data.len-1] + 1 - some(v) + Opt.some(v) type RemoveVersionedHash* = ref object of VersionedHashesCustomizer method getVersionedHashes(cust: RemoveVersionedHash, - baseVersionedHashes: openArray[common.Hash256]): Option[seq[common.Hash256]] = + baseVersionedHashes: openArray[common.Hash256]): Opt[seq[common.Hash256]] = doAssert(baseVersionedHashes.len > 0, "no versioned hashes available for modification") var v = newSeq[common.Hash256](baseVersionedHashes.len - 1) @@ -266,13 +266,13 @@ method getVersionedHashes(cust: RemoveVersionedHash, if i < baseVersionedHashes.len-1: v[i] = h v[i].data[h.data.len-1] = v[i].data[h.data.len-1] + 1 - some(v) + Opt.some(v) type ExtraVersionedHash* = ref object of VersionedHashesCustomizer method getVersionedHashes(cust: ExtraVersionedHash, - baseVersionedHashes: openArray[common.Hash256]): Option[seq[common.Hash256]] = + baseVersionedHashes: openArray[common.Hash256]): Opt[seq[common.Hash256]] = var v = newSeq[common.Hash256](baseVersionedHashes.len + 1) for i, h in baseVersionedHashes: v[i] = h @@ -280,7 +280,7 @@ method getVersionedHashes(cust: ExtraVersionedHash, var extraHash = common.Hash256.randomBytes() extraHash.data[0] = VERSIONED_HASH_VERSION_KZG v[^1] = extraHash - some(v) + Opt.some(v) type PayloadCustomizer* = ref object of EngineAPIVersionResolver @@ -304,27 +304,27 @@ method getExpectInvalidStatus*(cust: NewPayloadCustomizer): bool {.base, gcsafe. type CustomPayloadData* = object - parentHash* : Option[common.Hash256] - feeRecipient* : Option[common.EthAddress] - stateRoot* : Option[common.Hash256] - receiptsRoot* : Option[common.Hash256] - logsBloom* : Option[BloomFilter] - prevRandao* : Option[common.Hash256] - number* : Option[uint64] - gasLimit* : Option[GasInt] - gasUsed* : Option[GasInt] - timestamp* : Option[uint64] - extraData* : Option[common.Blob] - baseFeePerGas* : Option[UInt256] - blockHash* : Option[common.Hash256] - transactions* : Option[seq[Transaction]] - withdrawals* : Option[seq[Withdrawal]] + parentHash* : Opt[common.Hash256] + feeRecipient* : Opt[common.EthAddress] + stateRoot* : Opt[common.Hash256] + receiptsRoot* : Opt[common.Hash256] + logsBloom* : Opt[BloomFilter] + prevRandao* : Opt[common.Hash256] + number* : Opt[uint64] + gasLimit* : Opt[GasInt] + gasUsed* : Opt[GasInt] + timestamp* : Opt[uint64] + extraData* : Opt[common.Blob] + baseFeePerGas* : Opt[UInt256] + blockHash* : Opt[common.Hash256] + transactions* : Opt[seq[Transaction]] + withdrawals* : Opt[seq[Withdrawal]] removeWithdrawals* : bool - blobGasUsed* : Option[uint64] + blobGasUsed* : Opt[uint64] removeBlobGasUsed* : bool - excessBlobGas* : Option[uint64] + excessBlobGas* : Opt[uint64] removeExcessBlobGas* : bool - parentBeaconRoot* : Option[common.Hash256] + parentBeaconRoot* : Opt[common.Hash256] removeParentBeaconRoot* : bool versionedHashesCustomizer*: VersionedHashesCustomizer @@ -351,16 +351,16 @@ proc customizePayload*(cust: CustomPayloadData, data: ExecutableData): Executabl customHeader.stateRoot = cust.stateRoot.get if cust.receiptsRoot.isSome: - customHeader.receiptRoot = cust.receiptsRoot.get + customHeader.receiptsRoot = cust.receiptsRoot.get if cust.logsBloom.isSome: - customHeader.bloom = cust.logsBloom.get + customHeader.logsBloom = cust.logsBloom.get if cust.prevRandao.isSome: - customHeader.mixDigest = cust.prevRandao.get + customHeader.mixHash = cust.prevRandao.get if cust.number.isSome: - customHeader.blockNumber = cust.number.get.u256 + customHeader.number = cust.number.get if cust.gasLimit.isSome: customHeader.gasLimit = cust.gasLimit.get @@ -375,26 +375,26 @@ proc customizePayload*(cust: CustomPayloadData, data: ExecutableData): Executabl customHeader.extraData = cust.extraData.get if cust.baseFeePerGas.isSome: - customHeader.fee = cust.baseFeePerGas + customHeader.baseFeePerGas = cust.baseFeePerGas if cust.removeWithdrawals: - customHeader.withdrawalsRoot = none(common.Hash256) + customHeader.withdrawalsRoot = Opt.none(common.Hash256) elif cust.withdrawals.isSome: let h = calcWithdrawalsRoot(cust.withdrawals.get) - customHeader.withdrawalsRoot = some(h) + customHeader.withdrawalsRoot = Opt.some(h) if cust.removeBlobGasUsed: - customHeader.blobGasUsed = none(uint64) + customHeader.blobGasUsed = Opt.none(uint64) elif cust.blobGasUsed.isSome: customHeader.blobGasUsed = cust.blobGasUsed if cust.removeExcessBlobGas: - customHeader.excessBlobGas = none(uint64) + customHeader.excessBlobGas = Opt.none(uint64) elif cust.excessBlobGas.isSome: customHeader.excessBlobGas = cust.excessBlobGas if cust.removeParentBeaconRoot: - customHeader.parentBeaconBlockRoot = none(common.Hash256) + customHeader.parentBeaconBlockRoot = Opt.none(common.Hash256) elif cust.parentBeaconRoot.isSome: customHeader.parentBeaconBlockRoot = cust.parentBeaconRoot @@ -408,7 +408,7 @@ proc customizePayload*(cust: CustomPayloadData, data: ExecutableData): Executabl ) if cust.removeWithdrawals: - blk.withdrawals = none(seq[Withdrawal]) + blk.withdrawals = Opt.none(seq[Withdrawal]) elif cust.withdrawals.isSome: blk.withdrawals = cust.withdrawals elif data.basePayload.withdrawals.isSome: @@ -454,7 +454,7 @@ method newPayloadVersion(cust: DowngradeNewPayloadVersion, timestamp: uint64): V proc customizePayloadTransactions*(data: ExecutableData, customTransactions: openArray[Transaction]): ExecutableData = let cpd = CustomPayloadData( - transactions: some(@customTransactions), + transactions: Opt.some(@customTransactions), ) customizePayload(cpd, data) @@ -533,15 +533,15 @@ type ExtraVersionedHashes InvalidWithdrawals -func scramble(data: Web3Hash): Option[common.Hash256] = +func scramble(data: Web3Hash): Opt[common.Hash256] = var h = ethHash data h.data[^1] = byte(255 - h.data[^1]) - some(h) + Opt.some(h) -func scramble(data: common.Hash256): Option[common.Hash256] = +func scramble(data: common.Hash256): Opt[common.Hash256] = var h = data h.data[0] = byte(255 - h.data[0]) - some(h) + Opt.some(h) # This function generates an invalid payload by taking a base payload and modifying the specified field such that it ends up being invalid. # One small consideration is that the payload needs to contain transactions and specially transactions using the PREVRANDAO opcode for all the fields to be compatible with this function. @@ -565,29 +565,29 @@ proc generateInvalidPayload*(sender: TxSender, data: ExecutableData, payloadFiel of InvalidNumber: let modNumber = basePayload.blockNumber.uint64 - 1 customPayloadMod = CustomPayloadData( - number: some(modNumber), + number: Opt.some(modNumber), ) of InvalidGasLimit: let modGasLimit = basePayload.gasLimit.GasInt * 2 customPayloadMod = CustomPayloadData( - gasLimit: some(modGasLimit), + gasLimit: Opt.some(modGasLimit), ) of InvalidGasUsed: let modGasUsed = basePayload.gasUsed.GasInt - 1 customPayloadMod = CustomPayloadData( - gasUsed: some(modGasUsed), + gasUsed: Opt.some(modGasUsed), ) of InvalidTimestamp: let modTimestamp = basePayload.timestamp.uint64 - 1 customPayloadMod = CustomPayloadData( - timestamp: some(modTimestamp), + timestamp: Opt.some(modTimestamp), ) of InvalidPrevRandao: # This option potentially requires a transaction that uses the PREVRANDAO opcode. # Otherwise the payload will still be valid. let randomHash = common.Hash256.randomBytes() customPayloadMod = CustomPayloadData( - prevRandao: some(randomHash), + prevRandao: Opt.some(randomHash), ) of InvalidParentBeaconBlockRoot: doAssert(data.beaconRoot.isSome, @@ -599,19 +599,19 @@ proc generateInvalidPayload*(sender: TxSender, data: ExecutableData, payloadFiel doAssert(basePayload.blobGasUsed.isSome, "no blob gas used available for modification") let modBlobGasUsed = basePayload.blobGasUsed.get.uint64 + 1 customPayloadMod = CustomPayloadData( - blobGasUsed: some(modBlobGasUsed), + blobGasUsed: Opt.some(modBlobGasUsed), ) of InvalidBlobCountGasUsed: doAssert(basePayload.blobGasUsed.isSome, "no blob gas used available for modification") let modBlobGasUsed = basePayload.blobGasUsed.get.uint64 + GAS_PER_BLOB customPayloadMod = CustomPayloadData( - blobGasUsed: some(modBlobGasUsed), + blobGasUsed: Opt.some(modBlobGasUsed), ) of InvalidExcessBlobGas: doAssert(basePayload.excessBlobGas.isSome, "no excess blob gas available for modification") let modExcessBlobGas = basePayload.excessBlobGas.get.uint64 + 1 customPayloadMod = CustomPayloadData( - excessBlobGas: some(modExcessBlobGas), + excessBlobGas: Opt.some(modExcessBlobGas), ) of InvalidVersionedHashesVersion: doAssert(data.versionedHashes.isSome, "no versioned hashes available for modification") @@ -640,7 +640,7 @@ proc generateInvalidPayload*(sender: TxSender, data: ExecutableData, payloadFiel of RemoveTransaction: let emptyTxs = newSeq[Transaction]() customPayloadMod = CustomPayloadData( - transactions: some(emptyTxs), + transactions: Opt.some(emptyTxs), ) of InvalidTransactionSignature, InvalidTransactionNonce, @@ -657,26 +657,26 @@ proc generateInvalidPayload*(sender: TxSender, data: ExecutableData, payloadFiel case payloadField of InvalidTransactionSignature: var sig = CustSig(R: baseTx.R - 1.u256) - custTx.signature = some(sig) + custTx.signature = Opt.some(sig) of InvalidTransactionNonce: - custTx.nonce = some(baseTx.nonce - 1) + custTx.nonce = Opt.some(baseTx.nonce - 1) of InvalidTransactionGas: - custTx.gas = some(0.GasInt) + custTx.gas = Opt.some(0.GasInt) of InvalidTransactionGasPrice: - custTx.gasPriceOrGasFeeCap = some(0.GasInt) + custTx.gasPriceOrGasFeeCap = Opt.some(0.GasInt) of InvalidTransactionGasTipPrice: - custTx.gasTipCap = some(gasTipPrice.GasInt * 2.GasInt) + custTx.gasTipCap = Opt.some(gasTipPrice.GasInt * 2.GasInt) of InvalidTransactionValue: # Vault account initially has 0x123450000000000000000, so this value should overflow - custTx.value = some(UInt256.fromHex("0x123450000000000000001")) + custTx.value = Opt.some(UInt256.fromHex("0x123450000000000000001")) of InvalidTransactionChainID: - custTx.chainId = some(ChainId(baseTx.chainId.uint64 + 1)) + custTx.chainId = Opt.some(ChainId(baseTx.chainId.uint64 + 1)) else: discard let acc = sender.getNextAccount() let modifiedTx = sender.customizeTransaction(acc, baseTx, custTx) customPayloadMod = CustomPayloadData( - transactions: some(@[modifiedTx]), + transactions: Opt.some(@[modifiedTx]), ) customPayloadMod.customizePayload(data) diff --git a/hive_integration/nodocker/engine/cancun/helpers.nim b/hive_integration/nodocker/engine/cancun/helpers.nim index 7ebabe312..cab059c12 100644 --- a/hive_integration/nodocker/engine/cancun/helpers.nim +++ b/hive_integration/nodocker/engine/cancun/helpers.nim @@ -14,7 +14,7 @@ import eth/[common, rlp], eth/common/eth_types_rlp, chronicles, - stew/[results, byteutils], + stew/byteutils, kzg4844/kzg_ex as kzg, ../types, ../engine_client, @@ -112,11 +112,11 @@ proc verifyTransactionFromNode*(client: RpcClient, tx: Transaction): Result[void if returnedTx.chainId.get.uint64 != tx.chainId.uint64: return err("chain id mismatch: $1 != $2" % [$returnedTx.chainId.get.uint64, $tx.chainId.uint64]) - if returnedTx.maxFeePerGas != tx.maxFee: - return err("max fee per gas mismatch: $1 != $2" % [$returnedTx.maxFeePerGas, $tx.maxFee]) + if returnedTx.maxFeePerGas != tx.maxFeePerGas: + return err("max fee per gas mismatch: $1 != $2" % [$returnedTx.maxFeePerGas, $tx.maxFeePerGas]) - if returnedTx.maxPriorityFeePerGas != tx.maxPriorityFee: - return err("max priority fee per gas mismatch: $1 != $2" % [$returnedTx.maxPriorityFeePerGas, $tx.maxPriorityFee]) + if returnedTx.maxPriorityFeePerGas != tx.maxPriorityFeePerGas: + return err("max priority fee per gas mismatch: $1 != $2" % [$returnedTx.maxPriorityFeePerGas, $tx.maxPriorityFeePerGas]) if returnedTx.maxFeePerBlobGas.isNone: return err("expect maxFeePerBlobGas is some") @@ -198,7 +198,7 @@ proc verifyBeaconRootStorage*(client: RpcClient, payload: ExecutionPayload): boo # Read the storage keys from the stateful precompile that stores the beacon roots and verify # that the beacon root is the same as the one in the payload let - blockNumber = u256 payload.blockNumber + blockNumber = payload.blockNumber.uint64 precompileAddress = BEACON_ROOTS_ADDRESS (timestampKey, beaconRootKey) = beaconRootStorageIndexes(payload.timestamp.uint64) @@ -210,7 +210,7 @@ proc verifyBeaconRootStorage*(client: RpcClient, payload: ExecutionPayload): boo if r.get.u256 != payload.timestamp.uint64.u256: error "verifyBeaconRootStorage storage 1", - expect=payload.timestamp.uint64.u256, + expect=payload.timestamp.uint64, get=r.get.u256 return false diff --git a/hive_integration/nodocker/engine/cancun/step_newpayloads.nim b/hive_integration/nodocker/engine/cancun/step_newpayloads.nim index d906101cc..0d977775e 100644 --- a/hive_integration/nodocker/engine/cancun/step_newpayloads.nim +++ b/hive_integration/nodocker/engine/cancun/step_newpayloads.nim @@ -52,9 +52,9 @@ proc verifyPayload(step: NewPayloads, com: CommonRef, client: RpcClient, blobTxsInPayload: openArray[Transaction], - shouldOverrideBuilder: Option[bool], + shouldOverrideBuilder: Opt[bool], payload: ExecutionPayload, - previousPayload = none(ExecutionPayload)): bool = + previousPayload = Opt.none(ExecutionPayload)): bool = var parentExcessBlobGas = 0'u64 @@ -70,8 +70,8 @@ proc verifyPayload(step: NewPayloads, let parent = common.BlockHeader( - excessBlobGas: some(parentExcessBlobGas), - blobGasUsed: some(parentBlobGasUsed) + excessBlobGas: Opt.some(parentExcessBlobGas), + blobGasUsed: Opt.some(parentBlobGasUsed) ) expectedExcessBlobGas = calcExcessBlobGas(parent) @@ -223,12 +223,12 @@ method execute*(step: NewPayloads, ctx: CancunTestContext): bool = timestamp = env.clMock.latestHeader.timestamp.uint64 payloadAttributes = step.fcUOnPayloadRequest.getPayloadAttributes(payloadAttributes) - let version = step.fcUOnPayloadRequest.forkchoiceUpdatedVersion(timestamp, some(payloadAttributes.timestamp.uint64)) + let version = step.fcUOnPayloadRequest.forkchoiceUpdatedVersion(timestamp, Opt.some(payloadAttributes.timestamp.uint64)) if step.fcUOnPayloadRequest.getExpectInvalidStatus(): expectedStatus = PayloadExecutionStatus.invalid - let r = env.engine.client.forkchoiceUpdated(version, forkchoiceState, some(payloadAttributes)) + let r = env.engine.client.forkchoiceUpdated(version, forkchoiceState, Opt.some(payloadAttributes)) if expectedError != 0: r.expectErrorCode(expectedError, step.expectationDescription) else: @@ -353,7 +353,7 @@ method execute*(step: NewPayloads, ctx: CancunTestContext): bool = let blobData = res.get if not step.verifyPayload(env.engine.com, env.engine.client, blobData.txs, env.clMock.latestShouldOverrideBuilder, - payload, some(shadow.prevPayload)): + payload, Opt.some(shadow.prevPayload)): fatal "Error verifying payload", payload=shadow.p+1, count=shadow.payloadCount return false diff --git a/hive_integration/nodocker/engine/cancun/step_sendblobtx.nim b/hive_integration/nodocker/engine/cancun/step_sendblobtx.nim index 271794bd6..dd7b6e790 100644 --- a/hive_integration/nodocker/engine/cancun/step_sendblobtx.nim +++ b/hive_integration/nodocker/engine/cancun/step_sendblobtx.nim @@ -60,7 +60,7 @@ method execute*(step: SendBlobTransactions, ctx: CancunTestContext): bool = # Send the blob transactions for _ in 0.. bn: return false @@ -226,7 +225,7 @@ func getNextBlockTimestamp(cl: CLMocker): EthTime = return EthTime cl.transitionPayloadTimestamp.get return cl.latestHeader.timestamp + cl.getTimestampIncrement() -func setNextWithdrawals(cl: CLMocker, nextWithdrawals: Option[seq[WithdrawalV1]]) = +func setNextWithdrawals(cl: CLMocker, nextWithdrawals: Opt[seq[WithdrawalV1]]) = cl.nextWithdrawals = nextWithdrawals func isShanghai(cl: CLMocker, timestamp: Quantity): bool = @@ -259,7 +258,7 @@ proc pickNextPayloadProducer(cl: CLMocker): bool = let latestHeader = res.get let lastBlockHash = latestHeader.blockHash if cl.latestHeader.blockHash != lastBlockHash or - cl.latestHeadNumber != latestHeader.blockNumber.truncate(uint64): + cl.latestHeadNumber != latestHeader.number: # Selected client latest block hash does not match canonical chain, try again cl.nextBlockProducer = nil continue @@ -285,16 +284,16 @@ proc generatePayloadAttributes(cl: CLMocker) = if cl.isCancun(timestamp): # Write a deterministic hash based on the block number let beaconRoot = timestampToBeaconRoot(timestamp) - cl.latestPayloadAttributes.parentBeaconBlockRoot = some(beaconRoot) + cl.latestPayloadAttributes.parentBeaconBlockRoot = Opt.some(beaconRoot) # Save random value - let number = cl.latestHeader.blockNumber.truncate(uint64) + 1 + let number = cl.latestHeader.number + 1 cl.prevRandaoHistory[number] = nextPrevRandao proc requestNextPayload(cl: CLMocker): bool = let version = cl.latestPayloadAttributes.version let client = cl.nextBlockProducer.client - let res = client.forkchoiceUpdated(version, cl.latestForkchoice, some(cl.latestPayloadAttributes)) + let res = client.forkchoiceUpdated(version, cl.latestForkchoice, Opt.some(cl.latestPayloadAttributes)) if res.isErr: error "CLMocker: Could not send forkchoiceUpdated", version=version, msg=res.error return false @@ -371,10 +370,10 @@ proc getNextPayload(cl: CLMocker): bool = get=cl.latestHeader.blockHash return false - if cl.latestPayloadBuilt.blockNumber.uint64.toBlockNumber != cl.latestHeader.blockNumber + 1.toBlockNumber: + if cl.latestPayloadBuilt.blockNumber.uint64 != cl.latestHeader.number + 1'u64: error "CLMocker: Incorrect Number on payload built", expect=cl.latestPayloadBuilt.blockNumber.uint64, - get=cl.latestHeader.blockNumber+1.toBlockNumber + get=cl.latestHeader.number+1'u64 return false return true @@ -459,7 +458,7 @@ proc broadcastForkchoiceUpdated(cl: CLMocker, version: Version, update: ForkchoiceStateV1): Result[ForkchoiceUpdatedResponse, string] = - eng.client.forkchoiceUpdated(version, update, none(PayloadAttributes)) + eng.client.forkchoiceUpdated(version, update, Opt.none(PayloadAttributes)) proc broadcastForkchoiceUpdated*(cl: CLMocker, version: Version, @@ -522,7 +521,7 @@ proc makeNextWithdrawals(cl: CLMocker): seq[WithdrawalV1] = withdrawalIndex += 1 withdrawals[i] = WithdrawalV1( index: w3Qty withdrawalIndex, - validatorIndex: w3Qty i, + validatorIndex: Quantity i, address: w3Address i, amount: w3Qty 100'u64, ) @@ -532,7 +531,7 @@ proc makeNextWithdrawals(cl: CLMocker): seq[WithdrawalV1] = proc produceSingleBlock*(cl: CLMocker, cb: BlockProcessCallbacks): bool {.gcsafe.} = doAssert(cl.ttdReached) - cl.currentPayloadNumber = cl.latestHeader.blockNumber.truncate(uint64) + 1'u64 + cl.currentPayloadNumber = cl.latestHeader.number + 1'u64 if not cl.pickNextPayloadProducer(): return false @@ -540,7 +539,7 @@ proc produceSingleBlock*(cl: CLMocker, cb: BlockProcessCallbacks): bool {.gcsafe # `OnPayloadProducerSelected` callback if cl.nextWithdrawals.isNone: let nw = cl.makeNextWithdrawals() - cl.setNextWithdrawals(some(nw)) + cl.setNextWithdrawals(Opt.some(nw)) if cb.onPayloadProducerSelected != nil: if not cb.onPayloadProducerSelected(): @@ -557,7 +556,7 @@ proc produceSingleBlock*(cl: CLMocker, cb: BlockProcessCallbacks): bool {.gcsafe if not cl.requestNextPayload(): return false - cl.setNextWithdrawals(none(seq[WithdrawalV1])) + cl.setNextWithdrawals(Opt.none(seq[WithdrawalV1])) if cb.onRequestNextPayload != nil: if not cb.onRequestNextPayload(): @@ -624,8 +623,8 @@ proc produceSingleBlock*(cl: CLMocker, cb: BlockProcessCallbacks): bool {.gcsafe # Broadcast forkchoice updated with new FinalizedBlock to all clients # Save the number of the first PoS block if cl.firstPoSBlockNumber.isNone: - let number = cl.latestHeader.blockNumber.truncate(uint64) + 1 - cl.firstPoSBlockNumber = some(number) + let number = cl.latestHeader.number + 1 + cl.firstPoSBlockNumber = Opt.some(number) # Save the header of the latest block in the PoS chain cl.latestHeadNumber = cl.latestHeadNumber + 1 @@ -655,9 +654,9 @@ proc produceSingleBlock*(cl: CLMocker, cb: BlockProcessCallbacks): bool {.gcsafe return false # mixHash == prevRandao - if newHeader.mixDigest != cl.prevRandaoHistory[cl.latestHeadNumber]: + if newHeader.mixHash != cl.prevRandaoHistory[cl.latestHeadNumber]: error "CLMocker: Client produced a new header with incorrect mixHash", - get = newHeader.mixDigest.data.toHex, + get = newHeader.mixHash.data.toHex, expect = cl.prevRandaoHistory[cl.latestHeadNumber].data.toHex return false @@ -675,7 +674,7 @@ proc produceSingleBlock*(cl: CLMocker, cb: BlockProcessCallbacks): bool {.gcsafe cl.latestHeader = newHeader cl.headerHistory[cl.latestHeadNumber] = cl.latestHeader - echo "CLMocker: New block produced: number=", newHeader.blockNumber, + echo "CLMocker: New block produced: number=", newHeader.number, " hash=", newHeader.blockHash return true diff --git a/hive_integration/nodocker/engine/engine/bad_hash.nim b/hive_integration/nodocker/engine/engine/bad_hash.nim index 0c5349058..57efa7c6d 100644 --- a/hive_integration/nodocker/engine/engine/bad_hash.nim +++ b/hive_integration/nodocker/engine/engine/bad_hash.nim @@ -1,5 +1,5 @@ # Nimbus -# Copyright (c) 2023 Status Research & Development GmbH +# Copyright (c) 2023-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) @@ -128,7 +128,7 @@ method execute(cs: BadHashOnNewPayload, env: TestEnv): bool = # Run test after the new payload has been obtained onGetPayload: proc(): bool = var customizer = CustomPayloadData( - parentHash: some(ethHash shadow.payload.blockHash), + parentHash: Opt.some(ethHash shadow.payload.blockHash), ) shadow.payload = customizer.customizePayload(env.clMock.latestExecutableData) diff --git a/hive_integration/nodocker/engine/engine/fork_id.nim b/hive_integration/nodocker/engine/engine/fork_id.nim index 2a982b1b2..60304ca07 100644 --- a/hive_integration/nodocker/engine/engine/fork_id.nim +++ b/hive_integration/nodocker/engine/engine/fork_id.nim @@ -40,7 +40,7 @@ method getForkConfig*(cs: ForkIDSpec): ChainConfig = # Merge fork happen at block 0 let mainFork = cs.getMainFork() if mainFork == ForkParis: - forkConfig.mergeForkBlock = some(0.u256) + forkConfig.mergeForkBlock = Opt.some(0'u64) return forkConfig method execute(cs: ForkIDSpec, env: TestEnv): bool = diff --git a/hive_integration/nodocker/engine/engine/forkchoice.nim b/hive_integration/nodocker/engine/engine/forkchoice.nim index 9498e4f44..6c918352f 100644 --- a/hive_integration/nodocker/engine/engine/forkchoice.nim +++ b/hive_integration/nodocker/engine/engine/forkchoice.nim @@ -49,11 +49,11 @@ method execute(cs: InconsistentForkchoiceTest, env: TestEnv): bool = onGetPayload: proc(): bool = # Generate and send an alternative side chain var customData = CustomPayloadData( - extraData: some(@[0x01.byte]) + extraData: Opt.some(@[0x01.byte]) ) if shadow.alt.len > 0: - customData.parentHash = some(ethHash shadow.alt[^1].blockHash) + customData.parentHash = Opt.some(ethHash shadow.alt[^1].blockHash) let altPayload = customData.customizePayload(env.clMock.latestExecutableData) shadow.alt.add altPayload @@ -140,9 +140,9 @@ method execute(cs: ForkchoiceUpdatedUnknownBlockHashTest, env: TestEnv): bool = payloadAttributes.timestamp = w3Qty(payloadAttributes.timestamp, 1) # Test again using PayloadAttributes, should also return SYNCING and no PayloadID - r = env.engine.client.forkchoiceUpdated(version, fcu, some(payloadAttributes)) + r = env.engine.client.forkchoiceUpdated(version, fcu, Opt.some(payloadAttributes)) r.expectPayloadStatus(PayloadExecutionStatus.syncing) - r.expectPayloadID(none(PayloadID)) + r.expectPayloadID(Opt.none(PayloadID)) else: let pbRes = env.clMock.produceSingleBlock(BlockProcessCallbacks( # Run test after a new payload has been broadcast @@ -167,7 +167,7 @@ method execute(cs: ForkchoiceUpdatedUnknownBlockHashTest, env: TestEnv): bool = payloadAttributes.suggestedFeeRecipient = w3Address() # Test again using PayloadAttributes, should also return INVALID and no PayloadID - r = env.engine.client.forkchoiceUpdated(version, fcu, some(payloadAttributes)) + r = env.engine.client.forkchoiceUpdated(version, fcu, Opt.some(payloadAttributes)) r.expectError() return true )) diff --git a/hive_integration/nodocker/engine/engine/invalid_ancestor.nim b/hive_integration/nodocker/engine/engine/invalid_ancestor.nim index bbf094b6c..9fa8d69b8 100644 --- a/hive_integration/nodocker/engine/engine/invalid_ancestor.nim +++ b/hive_integration/nodocker/engine/engine/invalid_ancestor.nim @@ -73,7 +73,7 @@ method execute(cs: InvalidMissingAncestorReOrgTest, env: TestEnv): bool = # Send the transaction to the globals.PrevRandaoContractAddr let eng = env.clMock.nextBlockProducer let ok = env.sendNextTx(eng, BaseTx( - recipient: some(prevRandaoContractAddr), + recipient: Opt.some(prevRandaoContractAddr), amount: 1.u256, txType: cs.txType, gasLimit: 75000, @@ -86,8 +86,8 @@ method execute(cs: InvalidMissingAncestorReOrgTest, env: TestEnv): bool = onGetPayload: proc(): bool = # Insert extraData to ensure we deviate from the main payload, which contains empty extradata let customizer = CustomPayloadData( - parentHash: some(ethHash shadow.payloads[^1].blockHash), - extraData: some(@[0x01.byte]), + parentHash: Opt.some(ethHash shadow.payloads[^1].blockHash), + extraData: Opt.some(@[0x01.byte]), ) var sidePayload = customizer.customizePayload(env.clMock.latestExecutableData) @@ -244,7 +244,7 @@ method execute(cs: InvalidMissingAncestorReOrgSyncTest, env: TestEnv): bool = if not cs.emptyTransactions: # Send the transaction to the globals.PrevRandaoContractAddr let tc = BaseTx( - recipient: some(prevRandaoContractAddr), + recipient: Opt.some(prevRandaoContractAddr), amount: 1.u256, txType: cs.txType, gasLimit: 75000, @@ -259,8 +259,8 @@ method execute(cs: InvalidMissingAncestorReOrgSyncTest, env: TestEnv): bool = # Insert extraData to ensure we deviate from the main payload, which contains empty extradata pHash = shadow.payloads[^1].blockHash customizer = CustomPayloadData( - parentHash: some(ethHash pHash), - extraData: some(@[0x01.byte]), + parentHash: Opt.some(ethHash pHash), + extraData: Opt.some(@[0x01.byte]), ) sidePayload = customizer.customizePayload(env.clMock.latestExecutableData) @@ -273,7 +273,7 @@ method execute(cs: InvalidMissingAncestorReOrgSyncTest, env: TestEnv): bool = #if shadow.payloads.len == cs.invalidIndex: # var uncle *types.Block # if cs.invalidField == InvalidOmmers: - # let number = sideBlock.blockNumber.uint64-1 + # let number = sideBlock.number.uint64-1 # doAssert(env.clMock.executedPayloadHistory.hasKey(number), "FAIL: Unable to get uncle block") # let unclePayload = env.clMock.executedPayloadHistory[number] # # Uncle is a PoS payload @@ -340,7 +340,7 @@ method execute(cs: InvalidMissingAncestorReOrgSyncTest, env: TestEnv): bool = fatal "TEST ISSUE - Secondary Node has invalid blockHash", got=head.blockHash.short, want=shadow.payloads[shadow.n-1].blockHash.short, - gotNum=head.blockNumber, + gotNum=head.number, wantNum=shadow.payloads[shadow.n].blockNumber info "Secondary Node has correct block" @@ -356,7 +356,7 @@ method execute(cs: InvalidMissingAncestorReOrgSyncTest, env: TestEnv): bool = let head = res.get info "Latest block on main client before sync", hash=head.blockHash.short, - number=head.blockNumber + number=head.number # If we are syncing through p2p, we need to keep polling until the client syncs the missing payloads let period = chronos.milliseconds(500) @@ -390,8 +390,8 @@ method execute(cs: InvalidMissingAncestorReOrgSyncTest, env: TestEnv): bool = fatal "Unable to get latest block: ", msg=res.error # Print last shadow.n blocks, for debugging - let latestNumber = res.get.blockNumber.truncate(int64) - var k = latestNumber - int64(shadow.n) + let latestNumber = res.get.number + var k = latestNumber - uint64(shadow.n) if k < 0: k = 0 while k <= latestNumber: diff --git a/hive_integration/nodocker/engine/engine/invalid_payload.nim b/hive_integration/nodocker/engine/engine/invalid_payload.nim index 59b60cba4..5e8d1b957 100644 --- a/hive_integration/nodocker/engine/engine/invalid_payload.nim +++ b/hive_integration/nodocker/engine/engine/invalid_payload.nim @@ -74,7 +74,7 @@ method execute(cs: InvalidPayloadTestCase, env: TestEnv): bool = let ok = env.sendNextTx( eng, BaseTx( - recipient: some(prevRandaoContractAddr), + recipient: Opt.some(prevRandaoContractAddr), amount: 1.u256, txType: cs.txType, gasLimit: 75000.GasInt, @@ -173,7 +173,7 @@ method execute(cs: InvalidPayloadTestCase, env: TestEnv): bool = # (payloadStatus: (status: INVALID, latestValidHash: null, validationError: errorMessage | null), payloadId: null) # obtained from the Payload validation process if the payload is deemed INVALID version = env.engine.version(shadow.alteredPayload.timestamp) - let s = env.engine.client.forkchoiceUpdated(version, fcState, some(attr)) + let s = env.engine.client.forkchoiceUpdated(version, fcState, Opt.some(attr)) if not cs.syncing: # Execution specification: # (payloadStatus: (status: INVALID, latestValidHash: null, validationError: errorMessage | null), payloadId: null) @@ -261,7 +261,7 @@ method execute(cs: InvalidPayloadTestCase, env: TestEnv): bool = return true let customizer = CustomPayloadData( - parentHash: some(ethHash shadow.alteredPayload.blockHash), + parentHash: Opt.some(ethHash shadow.alteredPayload.blockHash), ) let followUpAlteredPayload = customizer.customizePayload(env.clMock.latestExecutableData) @@ -332,12 +332,12 @@ method execute(cs: PayloadBuildAfterInvalidPayloadTest, env: TestEnv): bool = # Get a payload from the invalid payload producer and invalidate it let customizer = BasePayloadAttributesCustomizer( - prevRandao: some(common.Hash256()), - suggestedFeerecipient: some(ZeroAddr), + prevRandao: Opt.some(common.Hash256()), + suggestedFeerecipient: Opt.some(ZeroAddr), ) payloadAttributes = customizer.getPayloadAttributes(env.clMock.latestPayloadAttributes) version = env.engine.version(env.clMock.latestHeader.timestamp) - r = invalidPayloadProducer.client.forkchoiceUpdated(version, env.clMock.latestForkchoice, some(payloadAttributes)) + r = invalidPayloadProducer.client.forkchoiceUpdated(version, env.clMock.latestForkchoice, Opt.some(payloadAttributes)) r.expectPayloadStatus(PayloadExecutionStatus.valid) # Wait for the payload to be produced by the EL @@ -352,8 +352,8 @@ method execute(cs: PayloadBuildAfterInvalidPayloadTest, env: TestEnv): bool = let basePayload = s.get.executionPayload var src = ExecutableData(basePayload: basePayload) if versione == Version.V3: - src.beaconRoot = some(common.Hash256()) - src.versionedHashes = some(collectBlobHashes(basePayload.transactions)) + src.beaconRoot = Opt.some(common.Hash256()) + src.versionedHashes = Opt.some(collectBlobHashes(basePayload.transactions)) inv_p = env.generateInvalidPayload(src, InvalidStateRoot) @@ -407,7 +407,7 @@ method execute(cs: InvalidTxChainIDTest, env: TestEnv): bool = # Run test after a new payload has been broadcast onPayloadAttributesGenerated: proc(): bool = let txCreator = BaseTx( - recipient: some(prevRandaoContractAddr), + recipient: Opt.some(prevRandaoContractAddr), amount: 1.u256, txType: cs.txType, gasLimit: 75000, @@ -427,7 +427,7 @@ method execute(cs: InvalidTxChainIDTest, env: TestEnv): bool = chainId = eng.com.chainId let txCustomizerData = CustomTransactionData( - chainID: some((chainId.uint64 + 1'u64).ChainId) + chainID: Opt.some((chainId.uint64 + 1'u64).ChainId) ) shadow.invalidTx = tx diff --git a/hive_integration/nodocker/engine/engine/misc.nim b/hive_integration/nodocker/engine/engine/misc.nim index eb24339f6..6272f4d76 100644 --- a/hive_integration/nodocker/engine/engine/misc.nim +++ b/hive_integration/nodocker/engine/engine/misc.nim @@ -1,5 +1,5 @@ # Nimbus -# Copyright (c) 2023 Status Research & Development GmbH +# Copyright (c) 2023-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) @@ -28,10 +28,10 @@ method getForkConfig*(cs: NonZeroPreMergeFork): ChainConfig = let forkConfig = procCall getForkConfig(BaseSpec(cs)) if forkConfig.isNil: return nil - + # Merge fork & pre-merge happen at block 1 - forkConfig.londonBlock = some(1.u256) - forkConfig.mergeForkBlock = some(1.u256) + forkConfig.londonBlock = Opt.some(1'u64) + forkConfig.mergeForkBlock = Opt.some(1'u64) # Post-merge fork happens at block 2 let mainFork = BaseSpec(cs).getMainFork() diff --git a/hive_integration/nodocker/engine/engine/payload_attributes.nim b/hive_integration/nodocker/engine/engine/payload_attributes.nim index 9fb926282..448f80c1e 100644 --- a/hive_integration/nodocker/engine/engine/payload_attributes.nim +++ b/hive_integration/nodocker/engine/engine/payload_attributes.nim @@ -66,11 +66,11 @@ method execute(cs: InvalidPayloadAttributesTest, env: TestEnv): bool = let version = env.engine.version(env.clMock.latestPayloadBuilt.timestamp) if cs.syncing: # If we are SYNCING, the outcome should be SYNCING regardless of the validity of the payload atttributes - let r = env.engine.client.forkchoiceUpdated(version, fcu, some(attr)) + let r = env.engine.client.forkchoiceUpdated(version, fcu, Opt.some(attr)) r.expectPayloadStatus(PayloadExecutionStatus.syncing) - r.expectPayloadID(none(PayloadID)) + r.expectPayloadID(Opt.none(PayloadID)) else: - let r = env.engine.client.forkchoiceUpdated(version, fcu, some(attr)) + let r = env.engine.client.forkchoiceUpdated(version, fcu, Opt.some(attr)) r.expectErrorCode(engineApiInvalidPayloadAttributes) # Check that the forkchoice was applied, regardless of the error diff --git a/hive_integration/nodocker/engine/engine/payload_execution.nim b/hive_integration/nodocker/engine/engine/payload_execution.nim index 79211930d..4facbf05a 100644 --- a/hive_integration/nodocker/engine/engine/payload_execution.nim +++ b/hive_integration/nodocker/engine/engine/payload_execution.nim @@ -117,7 +117,7 @@ method execute(cs: InOrderPayloadExecutionTest, env: TestEnv): bool = # We send the transactions after we got the Payload ID, before the CLMocker gets the prepared Payload onPayloadProducerSelected: proc(): bool = let tc = BaseTx( - recipient: some(shadow.recipient), + recipient: Opt.some(shadow.recipient), amount: shadow.amountPerTx, txType: cs.txType, gasLimit: 75000, @@ -220,7 +220,7 @@ method execute(cs: MultiplePayloadsExtendingCanonicalChainTest, env: TestEnv): b onPayloadProducerSelected: proc(): bool = let recipient = EthAddress.randomBytes() let tc = BaseTx( - recipient: some(recipient), + recipient: Opt.some(recipient), txType: cs.txType, gasLimit: 75000, ) @@ -245,7 +245,7 @@ method execute(cs: MultiplePayloadsExtendingCanonicalChainTest, env: TestEnv): b for i in 0.. 0: # Reasoning: Most of the clients do not re-add blob transactions to the pool # after a re-org, so we need to wait until the next tx is sent to actually # verify. - shadow.tx = some(shadow.nextTx) + shadow.tx = Opt.some(shadow.nextTx) return true )) testCond pbRes @@ -426,7 +426,7 @@ method execute(cs: ReOrgBackToCanonicalTest, env: TestEnv): bool = attr.prevRandao = Web3Hash.randomBytes() var version = env.engine.version(env.clMock.latestHeader.timestamp) - let r = env.engine.client.forkchoiceUpdated(version, env.clMock.latestForkchoice, some(attr)) + let r = env.engine.client.forkchoiceUpdated(version, env.clMock.latestForkchoice, Opt.some(attr)) r.expectNoError() testCond r.get.payloadID.isSome: fatal "No payload ID returned by forkchoiceUpdated" @@ -447,7 +447,7 @@ method execute(cs: ReOrgBackToCanonicalTest, env: TestEnv): bool = onPayloadProducerSelected: proc(): bool = # Send a transaction on each payload of the canonical chain let tc = BaseTx( - recipient: some(ZeroAddr), + recipient: Opt.some(ZeroAddr), amount: 1.u256, txType: cs.txType, gasLimit: 75000, @@ -533,7 +533,7 @@ method execute(cs: ReOrgBackFromSyncingTest, env: TestEnv): bool = onPayloadProducerSelected: proc(): bool = # Send a transaction on each payload of the canonical chain let tc = BaseTx( - recipient: some(ZeroAddr), + recipient: Opt.some(ZeroAddr), amount: 1.u256, txType: cs.txType, gasLimit: 75000, @@ -554,8 +554,8 @@ method execute(cs: ReOrgBackFromSyncingTest, env: TestEnv): bool = altParentHash = shadow.payloads[^1].blockHash let customizer = CustomPayloadData( - parentHash: some(ethHash altParentHash), - extraData: some(@[0x01.byte]), + parentHash: Opt.some(ethHash altParentHash), + extraData: Opt.some(@[0x01.byte]), ) let payload = customizer.customizePayload(env.clMock.latestExecutableData) @@ -629,7 +629,7 @@ method execute(cs: ReOrgPrevValidatedPayloadOnSideChainTest, env: TestEnv): bool onPayloadProducerSelected: proc(): bool = # Send a transaction on each payload of the canonical chain let tc = BaseTx( - recipient: some(ZeroAddr), + recipient: Opt.some(ZeroAddr), amount: 1.u256, txType: cs.txType, gasLimit: 75000, @@ -646,11 +646,11 @@ method execute(cs: ReOrgPrevValidatedPayloadOnSideChainTest, env: TestEnv): bool # The side chain will consist simply of the same payloads with extra data appended var customData = CustomPayloadData( - extraData: some(toSeq("side")), + extraData: Opt.some(toSeq("side")), ) if len(shadow.payloads) > 0: - customData.parentHash = some(ethHash shadow.payloads[^1].blockHash) + customData.parentHash = Opt.some(ethHash shadow.payloads[^1].blockHash) let payload = customData.customizePayload(env.clMock.latestExecutableData) shadow.payloads.add payload @@ -673,8 +673,8 @@ method execute(cs: ReOrgPrevValidatedPayloadOnSideChainTest, env: TestEnv): bool suggestedFeeRecipient = ethAddress(0x12, 0x34) let payloadAttributesCustomizer = BasePayloadAttributesCustomizer( - prevRandao: some(prevRandao), - suggestedFeerecipient: some(suggestedFeeRecipient), + prevRandao: Opt.some(prevRandao), + suggestedFeerecipient: Opt.some(suggestedFeeRecipient), ) let reOrgPayload = shadow.payloads[^2] @@ -687,7 +687,7 @@ method execute(cs: ReOrgPrevValidatedPayloadOnSideChainTest, env: TestEnv): bool ) var version = env.engine.version(reOrgPayload.timestamp) - let r = env.engine.client.forkchoiceUpdated(version, fcu, some(newPayloadAttributes)) + let r = env.engine.client.forkchoiceUpdated(version, fcu, Opt.some(newPayloadAttributes)) r.expectPayloadStatus(PayloadExecutionStatus.valid) r.expectLatestValidHash(reOrgPayload.blockHash) @@ -745,8 +745,8 @@ method execute(cs: SafeReOrgToSideChainTest, env: TestEnv): bool = altParentHash = shadow.payloads[^1].blockHash let customizer = CustomPayloadData( - parentHash: some(ethHash altParentHash), - extraData: some(@[0x01.byte]), + parentHash: Opt.some(ethHash altParentHash), + extraData: Opt.some(@[0x01.byte]), ) let payload = customizer.customizePayload(env.clMock.latestExecutableData) diff --git a/hive_integration/nodocker/engine/engine/rpc.nim b/hive_integration/nodocker/engine/engine/rpc.nim index 7c6749931..ad0c9faa6 100644 --- a/hive_integration/nodocker/engine/engine/rpc.nim +++ b/hive_integration/nodocker/engine/engine/rpc.nim @@ -57,7 +57,7 @@ method execute(cs: BlockStatus, env: TestEnv): bool = var callbacks = BlockProcessCallbacks( onPayloadProducerSelected: proc(): bool = let tc = BaseTx( - recipient: some(ZeroAddr), + recipient: Opt.some(ZeroAddr), amount: 1.u256, txType: cs.txType, gasLimit: 75000, diff --git a/hive_integration/nodocker/engine/engine/suggested_fee_recipient.nim b/hive_integration/nodocker/engine/engine/suggested_fee_recipient.nim index f5e38d7ec..6f0d36ae1 100644 --- a/hive_integration/nodocker/engine/engine/suggested_fee_recipient.nim +++ b/hive_integration/nodocker/engine/engine/suggested_fee_recipient.nim @@ -42,7 +42,7 @@ method execute(cs: SuggestedFeeRecipientTest, env: TestEnv): bool = # Send multiple transactions for i in 0..= ws.forkHeight: + if latestPayloadNumber >= ws.forkHeight.uint64: # Shanghai r.expectStorageEqual(WARM_COINBASE_ADDRESS, 100.u256.w3FixedBytes) # WARM_STORAGE_READ_COST - p.expectStorageEqual(PUSH0_ADDRESS, latestPayloadNumber.w3FixedBytes) # tx succeeded + p.expectStorageEqual(PUSH0_ADDRESS, latestPayloadNumber.u256.w3FixedBytes) # tx succeeded else: # Pre-Shanghai r.expectStorageEqual(WARM_COINBASE_ADDRESS, 2600.u256.w3FixedBytes) # COLD_ACCOUNT_ACCESS_COST @@ -218,11 +217,11 @@ proc execute*(ws: WDBaseSpec, env: TestEnv): bool = # Genesis should not contain `withdrawalsRoot` either let r = env.client.latestHeader() - r.expectWithdrawalsRoot(none(common.Hash256)) + r.expectWithdrawalsRoot(Opt.none(common.Hash256)) else: # Genesis is post shanghai, it should contain EmptyWithdrawalsRoot let r = env.client.latestHeader() - r.expectWithdrawalsRoot(some(EMPTY_ROOT_HASH)) + r.expectWithdrawalsRoot(Opt.some(EMPTY_ROOT_HASH)) # Produce any blocks necessary to reach withdrawals fork var pbRes = env.clMock.produceBlocks(ws.getPreWithdrawalsBlockCount, BlockProcessCallbacks( @@ -234,7 +233,7 @@ proc execute*(ws: WDBaseSpec, env: TestEnv): bool = let ok = env.sendNextTx( env.clMock.nextBlockProducer, BaseTx( - recipient: some(destAddr), + recipient: Opt.some(destAddr), amount: 1.u256, txType: ws.txType, gasLimit: 75000.GasInt, @@ -250,11 +249,11 @@ proc execute*(ws: WDBaseSpec, env: TestEnv): bool = ForkchoiceStateV1( headBlockHash: w3Hash env.clMock.latestHeader, ), - some(PayloadAttributes( + Opt.some(PayloadAttributes( timestamp: w3Qty(env.clMock.latestHeader.timestamp, ws.getBlockTimeIncrements()), prevRandao: w3PrevRandao(), suggestedFeeRecipient: w3Address(), - withdrawals: some(newSeq[WithdrawalV1]()), + withdrawals: Opt.some(newSeq[WithdrawalV1]()), )) ) let expectationDescription = "Sent pre-shanghai Forkchoice using ForkchoiceUpdatedV2 + Withdrawals, error is expected" @@ -266,11 +265,11 @@ proc execute*(ws: WDBaseSpec, env: TestEnv): bool = ForkchoiceStateV1( headBlockHash: w3Hash env.clMock.latestHeader, ), - some(PayloadAttributes( + Opt.some(PayloadAttributes( timestamp: w3Qty(env.clMock.latestHeader.timestamp, ws.getBlockTimeIncrements()), prevRandao: w3PrevRandao(), suggestedFeeRecipient: w3Address(), - withdrawals: none(seq[WithdrawalV1]), + withdrawals: Opt.none(seq[WithdrawalV1]), )) ) let expectationDescription2 = "Sent pre-shanghai Forkchoice ForkchoiceUpdatedV2 + null withdrawals, no error is expected" @@ -289,7 +288,7 @@ proc execute*(ws: WDBaseSpec, env: TestEnv): bool = # `withdrawals`, it should fail. let emptyWithdrawalsList = newSeq[Withdrawal]() let customizer = CustomPayloadData( - withdrawals: some(emptyWithdrawalsList), + withdrawals: Opt.some(emptyWithdrawalsList), parentBeaconRoot: ethHash env.clMock.latestPayloadAttributes.parentBeaconBlockRoot ) let payloadPlusWithdrawals = customizer.customizePayload(env.clMock.latestExecutableData).basePayload @@ -310,7 +309,7 @@ proc execute*(ws: WDBaseSpec, env: TestEnv): bool = let r = env.client.latestHeader() #r.ExpectationDescription = "Requested "latest" block expecting block to contain #" withdrawalRoot=nil, because (block %d).timestamp < shanghaiTime - r.expectWithdrawalsRoot(none(common.Hash256)) + r.expectWithdrawalsRoot(Opt.none(common.Hash256)) return true , onForkchoiceBroadcast: proc(): bool = @@ -338,11 +337,11 @@ proc execute*(ws: WDBaseSpec, env: TestEnv): bool = ForkchoiceStateV1( headBlockHash: w3Hash env.clMock.latestHeader, ), - some(PayloadAttributes( + Opt.some(PayloadAttributes( timestamp: w3Qty(env.clMock.latestHeader.timestamp, ws.getBlockTimeIncrements()), prevRandao: w3PrevRandao(), suggestedFeeRecipient: w3Address(), - withdrawals: none(seq[WithdrawalV1]), + withdrawals: Opt.none(seq[WithdrawalV1]), )) ) let expectationDescription = "Sent shanghai fcu using PayloadAttributesV1, error is expected" @@ -350,7 +349,7 @@ proc execute*(ws: WDBaseSpec, env: TestEnv): bool = # Send some withdrawals let wfb = ws.generateWithdrawalsForBlock(nextIndex, startAccount) - env.clMock.nextWithdrawals = some(w3Withdrawals wfb.wds) + env.clMock.nextWithdrawals = Opt.some(w3Withdrawals wfb.wds) ws.wdHistory.put(env.clMock.currentPayloadNumber, wfb.wds) # Send some transactions @@ -361,7 +360,7 @@ proc execute*(ws: WDBaseSpec, env: TestEnv): bool = let ok = env.sendNextTx( env.clMock.nextBlockProducer, BaseTx( - recipient: some(destAddr), + recipient: Opt.some(destAddr), amount: 1.u256, txType: ws.txType, gasLimit: 75000.GasInt, @@ -468,7 +467,7 @@ proc execute*(ws: WDBaseSpec, env: TestEnv): bool = r.expectBalanceEqual(expectedAccountBalance) let wds = ws.wdHistory.getWithdrawals(env.clMock.latestExecutedPayload.blockNumber.uint64) - let expectedWithdrawalsRoot = some(calcWithdrawalsRoot(wds.list)) + let expectedWithdrawalsRoot = Opt.some(calcWithdrawalsRoot(wds.list)) # Check the correct withdrawal root on `latest` block let r = env.client.latestHeader() @@ -492,16 +491,16 @@ proc execute*(ws: WDBaseSpec, env: TestEnv): bool = if not ws.skipBaseVerifications: let maxBlock = env.clMock.latestExecutedPayload.blockNumber.uint64 for bn in 0..maxBlock: - let res = ws.wdHistory.verifyWithdrawals(bn, some(bn.u256), env.client) + let res = ws.wdHistory.verifyWithdrawals(bn, Opt.some(bn), env.client) testCond res.isOk: error "verify wd error", msg=res.error # Check the correct withdrawal root on past blocks let r = env.client.headerByNumber(bn) - var expectedWithdrawalsRoot: Option[common.Hash256] + var expectedWithdrawalsRoot: Opt[common.Hash256] if bn >= ws.forkHeight.uint64: let wds = ws.wdHistory.getWithdrawals(bn) - expectedWithdrawalsRoot = some(calcWithdrawalsRoot(wds.list)) + expectedWithdrawalsRoot = Opt.some(calcWithdrawalsRoot(wds.list)) #r.ExpectationDescription = fmt.Sprintf(` # Requested block %d to verify withdrawalsRoot with the @@ -511,6 +510,6 @@ proc execute*(ws: WDBaseSpec, env: TestEnv): bool = # Verify on `latest` let bnu = env.clMock.latestExecutedPayload.blockNumber.uint64 - let res = ws.wdHistory.verifyWithdrawals(bnu, none(UInt256), env.client) + let res = ws.wdHistory.verifyWithdrawals(bnu, Opt.none(uint64), env.client) testCond res.isOk: error "verify wd error", msg=res.error diff --git a/hive_integration/nodocker/engine/withdrawals/wd_block_value_spec.nim b/hive_integration/nodocker/engine/withdrawals/wd_block_value_spec.nim index b314bacd1..333d41edb 100644 --- a/hive_integration/nodocker/engine/withdrawals/wd_block_value_spec.nim +++ b/hive_integration/nodocker/engine/withdrawals/wd_block_value_spec.nim @@ -41,7 +41,7 @@ proc execute*(ws: BlockValueSpec, env: TestEnv): bool = let rec = r.get - txTip = tx.effectiveGasTip(blk.header.baseFee) + txTip = tx.effectiveGasTip(blk.header.baseFeePerGas) totalValue += txTip.uint64.u256 * rec.gasUsed.u256 diff --git a/hive_integration/nodocker/engine/withdrawals/wd_history.nim b/hive_integration/nodocker/engine/withdrawals/wd_history.nim index 92bbe8d31..67f2c94d3 100644 --- a/hive_integration/nodocker/engine/withdrawals/wd_history.nim +++ b/hive_integration/nodocker/engine/withdrawals/wd_history.nim @@ -10,9 +10,10 @@ import std/[tables, sets, strutils], - eth/common/eth_types, + eth/common/eth_types as common, json_rpc/[rpcclient], - stew/[byteutils, results], + stew/byteutils, + results, ../engine_client, ../../../../nimbus/utils/utils, ../../../../nimbus/beacon/web3_eth_conv @@ -78,7 +79,9 @@ func getWithdrawnAccounts*(wh: WDHistory, blockHeight: uint64): Table[EthAddress result[wd.address] = wd.weiAmount # Verify all withdrawals on a client at a given height -proc verifyWithdrawals*(wh: WDHistory, blockNumber: uint64, rpcBlock: Option[UInt256], client: RpcClient): Result[void, string] = +proc verifyWithdrawals*(wh: WDHistory, blockNumber: uint64, + rpcBlock: Opt[common.BlockNumber], + client: RpcClient): Result[void, string] = let accounts = wh.getWithdrawnAccounts(blockNumber) for account, expectedBalance in accounts: let res = if rpcBlock.isSome: diff --git a/hive_integration/nodocker/engine/withdrawals/wd_max_init_code_spec.nim b/hive_integration/nodocker/engine/withdrawals/wd_max_init_code_spec.nim index 4d2648022..ffd2b0e11 100644 --- a/hive_integration/nodocker/engine/withdrawals/wd_max_init_code_spec.nim +++ b/hive_integration/nodocker/engine/withdrawals/wd_max_init_code_spec.nim @@ -112,7 +112,7 @@ proc execute*(ws: MaxInitcodeSizeSpec, env: TestEnv): bool = # Customize the payload to include a tx with an invalid initcode let customizer = CustomPayloadData( parentBeaconRoot: ethHash env.clMock.latestPayloadAttributes.parentBeaconBlockRoot, - transactions: some( @[invalidTx.tx] ), + transactions: Opt.some( @[invalidTx.tx] ), ) let customPayload = customizer.customizePayload(env.clMock.latestExecutableData).basePayload diff --git a/hive_integration/nodocker/engine/withdrawals/wd_reorg_spec.nim b/hive_integration/nodocker/engine/withdrawals/wd_reorg_spec.nim index f58fac662..3ea133cd3 100644 --- a/hive_integration/nodocker/engine/withdrawals/wd_reorg_spec.nim +++ b/hive_integration/nodocker/engine/withdrawals/wd_reorg_spec.nim @@ -41,7 +41,7 @@ type sidechain : Table[uint64, ExecutionPayload] payloadId : PayloadID height : uint64 - attr : Option[PayloadAttributes] + attr : Opt[PayloadAttributes] Canonical = ref object startAccount: UInt256 @@ -100,12 +100,12 @@ proc execute*(ws: ReorgSpec, env: TestEnv): bool = let numBlocks = ws.getPreWithdrawalsBlockCount()+ws.wdBlockCount let pbRes = env.clMock.produceBlocks(numBlocks, BlockProcessCallbacks( onPayloadProducerSelected: proc(): bool = - env.clMock.nextWithdrawals = none(seq[WithdrawalV1]) + env.clMock.nextWithdrawals = Opt.none(seq[WithdrawalV1]) if env.clMock.currentPayloadNumber >= ws.forkHeight.uint64: # Prepare some withdrawals let wfb = ws.generateWithdrawalsForBlock(canonical.nextIndex, canonical.startAccount) - env.clMock.nextWithdrawals = some(w3Withdrawals wfb.wds) + env.clMock.nextWithdrawals = Opt.some(w3Withdrawals wfb.wds) canonical.nextIndex = wfb.nextIndex ws.wdHistory.put(env.clMock.currentPayloadNumber, wfb.wds) @@ -128,7 +128,7 @@ proc execute*(ws: ReorgSpec, env: TestEnv): bool = # Send transactions to be included in the payload let txs = env.makeTxs( BaseTx( - recipient: some(prevRandaoContractAddr), + recipient: Opt.some(prevRandaoContractAddr), amount: 1.u256, txType: ws.txType, gasLimit: 75000.GasInt, @@ -170,12 +170,12 @@ proc execute*(ws: ReorgSpec, env: TestEnv): bool = testCond rr.isOk: error "sidechain wd", msg=rr.error - attr.withdrawals = some(w3Withdrawals rr.get) + attr.withdrawals = Opt.some(w3Withdrawals rr.get) info "Requesting sidechain payload", number=env.clMock.currentPayloadNumber - sidechain.attr = some(attr) + sidechain.attr = Opt.some(attr) let r = sec.client.forkchoiceUpdated(fcState, attr) r.expectNoError() r.expectPayloadStatus(PayloadExecutionStatus.valid) @@ -237,13 +237,13 @@ proc execute*(ws: ReorgSpec, env: TestEnv): bool = timestamp: w3Qty(sidechain.sidechain[sidechain.height].timestamp, ws.getSidechainBlockTimeIncrements()), prevRandao: env.clMock.latestPayloadAttributes.prevRandao, suggestedFeeRecipient: env.clMock.latestPayloadAttributes.suggestedFeeRecipient, - withdrawals: some(w3Withdrawals wds), + withdrawals: Opt.some(w3Withdrawals wds), ) fcState = ForkchoiceStateV1( headBlockHash: sidechain.sidechain[sidechain.height].blockHash, ) - let r = sec.client.forkchoiceUpdatedV2(fcState, some(attr)) + let r = sec.client.forkchoiceUpdatedV2(fcState, Opt.some(attr)) r.expectPayloadStatus(PayloadExecutionStatus.valid) let p = sec.client.getPayloadV2(r.get().payloadID.get) @@ -262,7 +262,7 @@ proc execute*(ws: ReorgSpec, env: TestEnv): bool = sidechain.sidechain[sidechain.height] = executionPayload(z.executionPayload) # Check the withdrawals on the latest - let res = ws.wdHistory.verifyWithdrawals(sidechain.height, none(UInt256), env.client) + let res = ws.wdHistory.verifyWithdrawals(sidechain.height, Opt.none(uint64), env.client) testCond res.isOk if ws.reOrgViaSync: @@ -322,7 +322,7 @@ proc execute*(ws: ReorgSpec, env: TestEnv): bool = # Verify withdrawals changed - let r2 = sidechain.wdHistory.verifyWithdrawals(sidechain.height, none(UInt256), env.client) + let r2 = sidechain.wdHistory.verifyWithdrawals(sidechain.height, Opt.none(uint64), env.client) testCond r2.isOk # Verify all balances of accounts in the original chain didn't increase @@ -330,7 +330,7 @@ proc execute*(ws: ReorgSpec, env: TestEnv): bool = # We are using different accounts credited between the canonical chain # and the fork. # We check on `latest`. - let r3 = ws.wdHistory.verifyWithdrawals(uint64(ws.forkHeight-1), none(UInt256), env.client) + let r3 = ws.wdHistory.verifyWithdrawals(uint64(ws.forkHeight-1), Opt.none(uint64), env.client) testCond r3.isOk # Re-Org back to the canonical chain diff --git a/hive_integration/nodocker/engine/withdrawals/wd_sync_spec.nim b/hive_integration/nodocker/engine/withdrawals/wd_sync_spec.nim index 50a73ed92..34f667683 100644 --- a/hive_integration/nodocker/engine/withdrawals/wd_sync_spec.nim +++ b/hive_integration/nodocker/engine/withdrawals/wd_sync_spec.nim @@ -1,5 +1,5 @@ # Nimbus -# Copyright (c) 2023 Status Research & Development GmbH +# Copyright (c) 2023-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) @@ -72,8 +72,8 @@ proc execute*(ws: SyncSpec, env: TestEnv): bool = if not ok: return false - let bn = env.clMock.latestHeader.blockNumber.truncate(uint64) - let res = ws.wdHistory.verifyWithdrawals(bn, none(UInt256), sec.client) + let bn = env.clMock.latestHeader.number + let res = ws.wdHistory.verifyWithdrawals(bn, Opt.none(uint64), sec.client) if res.isErr: error "wd history error", msg=res.error return false diff --git a/hive_integration/nodocker/pyspec/pyspec_sim.nim b/hive_integration/nodocker/pyspec/pyspec_sim.nim index 7c1d3645d..fe964b785 100644 --- a/hive_integration/nodocker/pyspec/pyspec_sim.nim +++ b/hive_integration/nodocker/pyspec/pyspec_sim.nim @@ -8,8 +8,8 @@ # those terms. import - std/[os, json, strutils, times, typetraits, options], - stew/[byteutils, results], + std/[os, json, strutils, times, typetraits], + stew/byteutils, eth/common, json_rpc/rpcclient, web3/execution_types, @@ -37,7 +37,7 @@ type Payload = object badBlock: bool payload: ExecutionPayload - beaconRoot: Option[common.Hash256] + beaconRoot: Opt[common.Hash256] proc getPayload(node: JsonNode): Payload = try: diff --git a/hive_integration/nodocker/rpc/client.nim b/hive_integration/nodocker/rpc/client.nim index 0d203540b..410971490 100644 --- a/hive_integration/nodocker/rpc/client.nim +++ b/hive_integration/nodocker/rpc/client.nim @@ -67,7 +67,7 @@ proc txReceipt*(client: RpcClient, txHash: common.Hash256): Future[Option[Receip status : rc.status.isSome, hash : ethHash rc.root.get(w3Hash()), cumulativeGasUsed: rc.cumulativeGasUsed.GasInt, - bloom : BloomFilter(rc.logsBloom), + logsBloom : BloomFilter(rc.logsBloom), logs : toLogs(rc.logs) ) result = some(rec) diff --git a/hive_integration/nodocker/rpc/vault.nim b/hive_integration/nodocker/rpc/vault.nim index 17d3e1c59..aa8292411 100644 --- a/hive_integration/nodocker/rpc/vault.nim +++ b/hive_integration/nodocker/rpc/vault.nim @@ -88,7 +88,7 @@ proc makeFundingTx*( nonce : v.nextNonce(), gasPrice: v.gasPrice, gasLimit: GasInt(75000), - to : some(predeployedVaultAddr), + to : Opt.some(predeployedVaultAddr), value : 0.u256, payload : sendSome(recipient, amount) ) @@ -111,7 +111,7 @@ proc signTx*(v: Vault, nonce : nonce, gasPrice: gasPrice, gasLimit: gasLimit, - to : some(recipient), + to : Opt.some(recipient), value : amount, payload : payload ) diff --git a/nimbus/beacon/api_handler/api_exchangeconf.nim b/nimbus/beacon/api_handler/api_exchangeconf.nim index 20a62151b..06d4e838b 100644 --- a/nimbus/beacon/api_handler/api_exchangeconf.nim +++ b/nimbus/beacon/api_handler/api_exchangeconf.nim @@ -1,5 +1,5 @@ # Nimbus -# Copyright (c) 2023 Status Research & Development GmbH +# Copyright (c) 2023-2024 Status Research & Development GmbH # Licensed under either of # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) # * MIT license ([LICENSE-MIT](LICENSE-MIT)) @@ -40,7 +40,7 @@ proc exchangeConf*(ben: BeaconEngineRef, $ttd.get, $conf.terminalTotalDifficulty]) let - terminalBlockNumber = u256 conf.terminalBlockNumber + terminalBlockNumber = common.BlockNumber conf.terminalBlockNumber terminalBlockHash = ethHash conf.terminalBlockHash if terminalBlockHash != common.Hash256(): @@ -62,10 +62,10 @@ proc exchangeConf*(ben: BeaconEngineRef, return TransitionConfigurationV1( terminalTotalDifficulty: ttd.get, terminalBlockHash : w3Hash headerHash, - terminalBlockNumber : w3Qty header.blockNumber + terminalBlockNumber : w3Qty header.number ) - if terminalBlockNumber.isZero.not: + if terminalBlockNumber != 0'u64: raise newException(ValueError, "invalid terminal block number: $1" % [ $terminalBlockNumber]) diff --git a/nimbus/beacon/api_handler/api_forkchoice.nim b/nimbus/beacon/api_handler/api_forkchoice.nim index b7416c337..3bc71e401 100644 --- a/nimbus/beacon/api_handler/api_forkchoice.nim +++ b/nimbus/beacon/api_handler/api_forkchoice.nim @@ -72,7 +72,7 @@ template validateHeaderTimestamp(header, com, apiVersion) = proc forkchoiceUpdated*(ben: BeaconEngineRef, apiVersion: Version, update: ForkchoiceStateV1, - attrsOpt: Option[PayloadAttributes]): + attrsOpt: Opt[PayloadAttributes]): ForkchoiceUpdatedResponse = let com = ben.com @@ -111,7 +111,7 @@ proc forkchoiceUpdated*(ben: BeaconEngineRef, # TODO: cancel downloader info "Forkchoice requested sync to new head", - number = header.blockNumber, + number = header.number, hash = blockHash.short # Update sync header (if any) @@ -126,11 +126,11 @@ proc forkchoiceUpdated*(ben: BeaconEngineRef, # Disable terminal PoW block conditions validation for fCUV2 and later. # https://github.com/ethereum/execution-apis/blob/v1.0.0-beta.4/src/engine/shanghai.md#specification-1 if apiVersion == Version.V1: - let blockNumber = header.blockNumber.truncate(uint64) + let blockNumber = header.number if header.difficulty > 0.u256 or blockNumber == 0'u64: var td, ptd: DifficultyInt - ttd = com.ttd.get(high(common.BlockNumber)) + ttd = com.ttd.get(high(UInt256)) if not db.getTd(blockHash, td) or (blockNumber > 0'u64 and not db.getTd(header.parentHash, ptd)): error "TDs unavailable for TTD check", @@ -156,11 +156,11 @@ proc forkchoiceUpdated*(ben: BeaconEngineRef, # See point 2 of fCUV1 specification # https://github.com/ethereum/execution-apis/blob/v1.0.0-beta.4/src/engine/paris.md#specification-1 var canonHash: common.Hash256 - if db.getBlockHash(header.blockNumber, canonHash) and canonHash == blockHash: + if db.getBlockHash(header.number, canonHash) and canonHash == blockHash: notice "Ignoring beacon update to old head", blockHash=blockHash.short, - blockNumber=header.blockNumber - return validFCU(none(PayloadID), blockHash) + blockNumber=header.number + return validFCU(Opt.none(PayloadID), blockHash) chain.setCanonical(header).isOkOr: return invalidFCU(error, com, header) @@ -179,14 +179,14 @@ proc forkchoiceUpdated*(ben: BeaconEngineRef, hash=finalizedBlockHash.short raise invalidForkChoiceState("finalized block header not available") var finalHash: common.Hash256 - if not db.getBlockHash(finalBlock.blockNumber, finalHash): + if not db.getBlockHash(finalBlock.number, finalHash): warn "Final block not in canonical chain", - number=finalBlock.blockNumber, + number=finalBlock.number, hash=finalizedBlockHash.short raise invalidForkChoiceState("finalized block hash not available") if finalHash != finalizedBlockHash: warn "Final block not in canonical chain", - number=finalBlock.blockNumber, + number=finalBlock.number, expect=finalizedBlockHash.short, get=finalHash.short raise invalidForkChoiceState("finalized block not canonical") @@ -200,13 +200,13 @@ proc forkchoiceUpdated*(ben: BeaconEngineRef, hash = safeBlockHash.short raise invalidForkChoiceState("safe head not available") var safeHash: common.Hash256 - if not db.getBlockHash(safeBlock.blockNumber, safeHash): + if not db.getBlockHash(safeBlock.number, safeHash): warn "Safe block hash not available in database", hash = safeHash.short raise invalidForkChoiceState("safe block hash not available") if safeHash != safeBlockHash: warn "Safe block not in canonical chain", - blockNumber=safeBlock.blockNumber, + blockNumber=safeBlock.number, expect=safeBlockHash.short, get=safeHash.short raise invalidForkChoiceState("safe head not canonical") @@ -231,6 +231,6 @@ proc forkchoiceUpdated*(ben: BeaconEngineRef, hash = bundle.executionPayload.blockHash.short, number = bundle.executionPayload.blockNumber - return validFCU(some(id), blockHash) + return validFCU(Opt.some(id), blockHash) - return validFCU(none(PayloadID), blockHash) + return validFCU(Opt.none(PayloadID), blockHash) diff --git a/nimbus/beacon/api_handler/api_getbodies.nim b/nimbus/beacon/api_handler/api_getbodies.nim index 3b663d429..d38495476 100644 --- a/nimbus/beacon/api_handler/api_getbodies.nim +++ b/nimbus/beacon/api_handler/api_getbodies.nim @@ -1,5 +1,5 @@ # Nimbus -# Copyright (c) 2023 Status Research & Development GmbH +# Copyright (c) 2023-2024 Status Research & Development GmbH # Licensed under either of # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) # * MIT license ([LICENSE-MIT](LICENSE-MIT)) @@ -23,11 +23,11 @@ const proc getPayloadBodyByHeader(db: CoreDbRef, header: common.BlockHeader, - output: var seq[Option[ExecutionPayloadBodyV1]]) = + output: var seq[Opt[ExecutionPayloadBodyV1]]) = var body: common.BlockBody if not db.getBlockBody(header, body): - output.add none(ExecutionPayloadBodyV1) + output.add Opt.none(ExecutionPayloadBodyV1) return let txs = w3Txs body.transactions @@ -37,20 +37,20 @@ proc getPayloadBodyByHeader(db: CoreDbRef, wds.add w3Withdrawal(w) output.add( - some(ExecutionPayloadBodyV1( + Opt.some(ExecutionPayloadBodyV1( transactions: txs, # pre Shanghai block return null withdrawals # post Shanghai block return at least empty slice withdrawals: if header.withdrawalsRoot.isSome: - some(wds) + Opt.some(wds) else: - none(seq[WithdrawalV1]) + Opt.none(seq[WithdrawalV1]) )) ) proc getPayloadBodiesByHash*(ben: BeaconEngineRef, hashes: seq[Web3Hash]): - seq[Option[ExecutionPayloadBodyV1]] = + seq[Opt[ExecutionPayloadBodyV1]] = if hashes.len > maxBodyRequest: raise tooLargeRequest("request exceeds max allowed " & $maxBodyRequest) @@ -58,13 +58,13 @@ proc getPayloadBodiesByHash*(ben: BeaconEngineRef, var header: common.BlockHeader for h in hashes: if not db.getBlockHeader(ethHash h, header): - result.add none(ExecutionPayloadBodyV1) + result.add Opt.none(ExecutionPayloadBodyV1) continue db.getPayloadBodyByHeader(header, result) proc getPayloadBodiesByRange*(ben: BeaconEngineRef, start: uint64, count: uint64): - seq[Option[ExecutionPayloadBodyV1]] = + seq[Opt[ExecutionPayloadBodyV1]] = if start == 0: raise invalidParams("start block should greater than zero") @@ -77,7 +77,7 @@ proc getPayloadBodiesByRange*(ben: BeaconEngineRef, let com = ben.com db = com.db - current = com.syncCurrent.truncate(uint64) + current = com.syncCurrent var header: common.BlockHeader @@ -87,7 +87,7 @@ proc getPayloadBodiesByRange*(ben: BeaconEngineRef, last = current for bn in start..last: - if not db.getBlockHeader(bn.toBlockNumber, header): - result.add none(ExecutionPayloadBodyV1) + if not db.getBlockHeader(bn, header): + result.add Opt.none(ExecutionPayloadBodyV1) continue db.getPayloadBodyByHeader(header, result) diff --git a/nimbus/beacon/api_handler/api_getpayload.nim b/nimbus/beacon/api_handler/api_getpayload.nim index 3b733c620..439086fcb 100644 --- a/nimbus/beacon/api_handler/api_getpayload.nim +++ b/nimbus/beacon/api_handler/api_getpayload.nim @@ -26,7 +26,7 @@ proc getPayload*(ben: BeaconEngineRef, var payloadGeneric: ExecutionPayload var blockValue: UInt256 - var blobsBundle: Option[BlobsBundleV1] + var blobsBundle: Opt[BlobsBundleV1] if not ben.get(id, blockValue, payloadGeneric, blobsBundle): raise unknownPayload("Unknown payload") @@ -50,7 +50,7 @@ proc getPayloadV3*(ben: BeaconEngineRef, id: PayloadID): GetPayloadV3Response = var payloadGeneric: ExecutionPayload var blockValue: UInt256 - var blobsBundle: Option[BlobsBundleV1] + var blobsBundle: Opt[BlobsBundleV1] if not ben.get(id, blockValue, payloadGeneric, blobsBundle): raise unknownPayload("Unknown payload") @@ -78,7 +78,7 @@ proc getPayloadV4*(ben: BeaconEngineRef, id: PayloadID): GetPayloadV4Response = var payloadGeneric: ExecutionPayload var blockValue: UInt256 - var blobsBundle: Option[BlobsBundleV1] + var blobsBundle: Opt[BlobsBundleV1] if not ben.get(id, blockValue, payloadGeneric, blobsBundle): raise unknownPayload("Unknown payload") diff --git a/nimbus/beacon/api_handler/api_newpayload.nim b/nimbus/beacon/api_handler/api_newpayload.nim index 7873e043c..18579b76b 100644 --- a/nimbus/beacon/api_handler/api_newpayload.nim +++ b/nimbus/beacon/api_handler/api_newpayload.nim @@ -94,8 +94,8 @@ template validatePayload(apiVersion, version, payload) = proc newPayload*(ben: BeaconEngineRef, apiVersion: Version, payload: ExecutionPayload, - versionedHashes = none(seq[Web3Hash]), - beaconRoot = none(Web3Hash)): PayloadStatusV1 = + versionedHashes = Opt.none(seq[Web3Hash]), + beaconRoot = Opt.none(Web3Hash)): PayloadStatusV1 = trace "Engine API request received", meth = "newPayload", @@ -133,7 +133,7 @@ proc newPayload*(ben: BeaconEngineRef, # return a fake success. if db.getBlockHeader(blockHash, header): warn "Ignoring already known beacon payload", - number = header.blockNumber, hash = blockHash.short + number = header.number, hash = blockHash.short return validStatus(blockHash) # If this block was rejected previously, keep rejecting it @@ -153,19 +153,19 @@ proc newPayload*(ben: BeaconEngineRef, # We have an existing parent, do some sanity checks to avoid the beacon client # triggering too early - let ttd = com.ttd.get(high(common.BlockNumber)) + let ttd = com.ttd.get(high(UInt256)) if version == Version.V1: let td = db.getScore(header.parentHash).valueOr: 0.u256 if (not com.forkGTE(MergeFork)) and td < ttd: warn "Ignoring pre-merge payload", - number = header.blockNumber, hash = blockHash, td, ttd + number = header.number, hash = blockHash, td, ttd return invalidStatus() if header.timestamp <= parent.timestamp: warn "Invalid timestamp", - number = header.blockNumber, parentNumber = parent.blockNumber, + number = header.number, parentNumber = parent.number, parent = parent.timestamp, header = header.timestamp return invalidStatus(parent.blockHash, "Invalid timestamp") @@ -181,12 +181,12 @@ proc newPayload*(ben: BeaconEngineRef, ben.put(blockHash, header) warn "State not available, ignoring new payload", hash = blockHash, - number = header.blockNumber + number = header.number let blockHash = latestValidHash(db, parent, ttd) return acceptedStatus(blockHash) trace "Inserting block without sethead", - hash = blockHash, number = header.blockNumber + hash = blockHash, number = header.number let vres = ben.chain.insertBlockWithoutSetHead(blk) if vres.isErr: ben.setInvalidAncestor(header, blockHash) diff --git a/nimbus/beacon/api_handler/api_utils.nim b/nimbus/beacon/api_handler/api_utils.nim index b2c0bb205..d9d3ebbd9 100644 --- a/nimbus/beacon/api_handler/api_utils.nim +++ b/nimbus/beacon/api_handler/api_utils.nim @@ -60,15 +60,15 @@ proc validateBlockHash*(header: common.BlockHeader, let res = PayloadStatusV1( status: status, - validationError: some("blockhash mismatch, want $1, got $2" % [ + validationError: Opt.some("blockhash mismatch, want $1, got $2" % [ $wantHash, $gotHash]) ) return err(res) return ok() -template toValidHash*(x: common.Hash256): Option[Web3Hash] = - some(w3Hash x) +template toValidHash*(x: common.Hash256): Opt[Web3Hash] = + Opt.some(w3Hash x) proc simpleFCU*(status: PayloadStatusV1): ForkchoiceUpdatedResponse = ForkchoiceUpdatedResponse(payloadStatus: status) @@ -81,7 +81,7 @@ proc simpleFCU*(status: PayloadExecutionStatus, ForkchoiceUpdatedResponse( payloadStatus: PayloadStatusV1( status: status, - validationError: some(msg) + validationError: Opt.some(msg) ) ) @@ -92,11 +92,11 @@ proc invalidFCU*( PayloadStatusV1( status: PayloadExecutionStatus.invalid, latestValidHash: toValidHash(hash), - validationError: some validationError + validationError: Opt.some validationError ) ) -proc validFCU*(id: Option[PayloadID], +proc validFCU*(id: Opt[PayloadID], validHash: common.Hash256): ForkchoiceUpdatedResponse = ForkchoiceUpdatedResponse( payloadStatus: PayloadStatusV1( @@ -110,7 +110,7 @@ proc invalidStatus*(validHash: common.Hash256, msg: string): PayloadStatusV1 = PayloadStatusV1( status: PayloadExecutionStatus.invalid, latestValidHash: toValidHash(validHash), - validationError: some(msg) + validationError: Opt.some(msg) ) proc invalidStatus*(validHash = common.Hash256()): PayloadStatusV1 = @@ -193,7 +193,7 @@ proc invalidFCU*(validationError: string, return invalidFCU(validationError) let blockHash = try: - latestValidHash(com.db, parent, com.ttd.get(high(common.BlockNumber))) + latestValidHash(com.db, parent, com.ttd.get(high(UInt256))) except RlpError: default(common.Hash256) diff --git a/nimbus/beacon/beacon_engine.nim b/nimbus/beacon/beacon_engine.nim index 178cdbfa7..7ad9bf08e 100644 --- a/nimbus/beacon/beacon_engine.nim +++ b/nimbus/beacon/beacon_engine.nim @@ -132,12 +132,12 @@ proc put*(ben: BeaconEngineRef, proc put*(ben: BeaconEngineRef, id: PayloadID, blockValue: UInt256, payload: ExecutionPayload, - blobsBundle: Option[BlobsBundleV1]) = + blobsBundle: Opt[BlobsBundleV1]) = ben.queue.put(id, blockValue, payload, blobsBundle) proc put*(ben: BeaconEngineRef, id: PayloadID, blockValue: UInt256, payload: SomeExecutionPayload, - blobsBundle: Option[BlobsBundleV1]) = + blobsBundle: Opt[BlobsBundleV1]) = doAssert blobsBundle.isNone == (payload is ExecutionPayloadV1 | ExecutionPayloadV2) ben.queue.put(id, blockValue, payload, blobsBundle) @@ -146,7 +146,7 @@ proc put*(ben: BeaconEngineRef, id: PayloadID, blockValue: UInt256, payload: ExecutionPayloadV1 | ExecutionPayloadV2) = ben.queue.put( - id, blockValue, payload, blobsBundle = options.none(BlobsBundleV1)) + id, blockValue, payload, blobsBundle = Opt.none(BlobsBundleV1)) # ------------------------------------------------------------------------------ # Public functions, getters @@ -177,7 +177,7 @@ proc get*(ben: BeaconEngineRef, hash: common.Hash256, proc get*(ben: BeaconEngineRef, id: PayloadID, blockValue: var UInt256, payload: var ExecutionPayload, - blobsBundle: var Option[BlobsBundleV1]): bool = + blobsBundle: var Opt[BlobsBundleV1]): bool = ben.queue.get(id, blockValue, payload, blobsBundle) proc get*(ben: BeaconEngineRef, id: PayloadID, @@ -207,7 +207,7 @@ proc get*(ben: BeaconEngineRef, id: PayloadID, type ExecutionPayloadAndBlobsBundle* = object executionPayload*: ExecutionPayload - blobsBundle*: Option[BlobsBundleV1] + blobsBundle*: Opt[BlobsBundleV1] proc generatePayload*(ben: BeaconEngineRef, attrs: PayloadAttributes): @@ -243,10 +243,10 @@ proc generatePayload*(ben: BeaconEngineRef, if bundle.blk.header.extraData.len > 32: return err "extraData length should not exceed 32 bytes" - var blobsBundle: Option[BlobsBundleV1] + var blobsBundle: Opt[BlobsBundleV1] if bundle.blobsBundle.isSome: template blobData: untyped = bundle.blobsBundle.get - blobsBundle = options.some BlobsBundleV1( + blobsBundle = Opt.some BlobsBundleV1( commitments: blobData.commitments.mapIt it.Web3KZGCommitment, proofs: blobData.proofs.mapIt it.Web3KZGProof, blobs: blobData.blobs.mapIt it.Web3Blob) @@ -272,7 +272,7 @@ proc checkInvalidAncestor*(ben: BeaconEngineRef, inc ben.invalidBlocksHits.mgetOrPut(badHash, 0) if ben.invalidBlocksHits.getOrDefault(badHash) >= invalidBlockHitEviction: warn "Too many bad block import attempt, trying", - number=invalid.blockNumber, hash=badHash.short + number=invalid.number, hash=badHash.short ben.invalidBlocksHits.del(badHash) @@ -289,7 +289,7 @@ proc checkInvalidAncestor*(ben: BeaconEngineRef, # Not too many failures yet, mark the head of the invalid chain as invalid if check != head: warn "Marked new chain head as invalid", - hash=head, badnumber=invalid.blockNumber, badhash=badHash + hash=head, badnumber=invalid.number, badhash=badHash if ben.invalidTipsets.len >= invalidTipsetsCap: let size = invalidTipsetsCap - ben.invalidTipsets.len diff --git a/nimbus/beacon/payload_conv.nim b/nimbus/beacon/payload_conv.nim index dc36e9602..d2c82aad8 100644 --- a/nimbus/beacon/payload_conv.nim +++ b/nimbus/beacon/payload_conv.nim @@ -24,11 +24,11 @@ func wdRoot(list: openArray[WithdrawalV1]): common.Hash256 {.noSideEffect.}: calcWithdrawalsRoot(ethWithdrawals list) -func wdRoot(x: Option[seq[WithdrawalV1]]): Option[common.Hash256] +func wdRoot(x: Opt[seq[WithdrawalV1]]): Opt[common.Hash256] {.gcsafe, raises:[].} = {.noSideEffect.}: - if x.isNone: none(common.Hash256) - else: some(wdRoot x.get) + if x.isNone: Opt.none(common.Hash256) + else: Opt.some(wdRoot x.get) func txRoot(list: openArray[Web3Tx]): common.Hash256 {.gcsafe, raises:[RlpError].} = @@ -46,15 +46,15 @@ func executionPayload*(blk: EthBlock): ExecutionPayload = parentHash : w3Hash blk.header.parentHash, feeRecipient : w3Addr blk.header.coinbase, stateRoot : w3Hash blk.header.stateRoot, - receiptsRoot : w3Hash blk.header.receiptRoot, - logsBloom : w3Bloom blk.header.bloom, + receiptsRoot : w3Hash blk.header.receiptsRoot, + logsBloom : w3Bloom blk.header.logsBloom, prevRandao : w3PrevRandao blk.header.prevRandao, - blockNumber : w3Qty blk.header.blockNumber, + blockNumber : w3Qty blk.header.number, gasLimit : w3Qty blk.header.gasLimit, gasUsed : w3Qty blk.header.gasUsed, timestamp : w3Qty blk.header.timestamp, extraData : w3ExtraData blk.header.extraData, - baseFeePerGas: blk.header.fee.get(0.u256), + baseFeePerGas: blk.header.baseFeePerGas.get(0.u256), blockHash : w3Hash blk.header, transactions : w3Txs blk.txs, withdrawals : w3Withdrawals blk.withdrawals, @@ -67,22 +67,22 @@ func executionPayloadV1V2*(blk: EthBlock): ExecutionPayloadV1OrV2 = parentHash : w3Hash blk.header.parentHash, feeRecipient : w3Addr blk.header.coinbase, stateRoot : w3Hash blk.header.stateRoot, - receiptsRoot : w3Hash blk.header.receiptRoot, - logsBloom : w3Bloom blk.header.bloom, + receiptsRoot : w3Hash blk.header.receiptsRoot, + logsBloom : w3Bloom blk.header.logsBloom, prevRandao : w3PrevRandao blk.header.prevRandao, - blockNumber : w3Qty blk.header.blockNumber, + blockNumber : w3Qty blk.header.number, gasLimit : w3Qty blk.header.gasLimit, gasUsed : w3Qty blk.header.gasUsed, timestamp : w3Qty blk.header.timestamp, extraData : w3ExtraData blk.header.extraData, - baseFeePerGas: blk.header.fee.get(0.u256), + baseFeePerGas: blk.header.baseFeePerGas.get(0.u256), blockHash : w3Hash blk.header, transactions : w3Txs blk.txs, withdrawals : w3Withdrawals blk.withdrawals, ) func blockHeader*(p: ExecutionPayload, - beaconRoot: Option[common.Hash256]): + beaconRoot: Opt[common.Hash256]): common.BlockHeader {.gcsafe, raises:[RlpError].} = common.BlockHeader( parentHash : ethHash p.parentHash, @@ -90,17 +90,17 @@ func blockHeader*(p: ExecutionPayload, coinbase : ethAddr p.feeRecipient, stateRoot : ethHash p.stateRoot, txRoot : txRoot p.transactions, - receiptRoot : ethHash p.receiptsRoot, - bloom : ethBloom p.logsBloom, + receiptsRoot : ethHash p.receiptsRoot, + logsBloom : ethBloom p.logsBloom, difficulty : 0.u256, - blockNumber : u256 p.blockNumber, + number : common.BlockNumber(p.blockNumber), gasLimit : ethGasInt p.gasLimit, gasUsed : ethGasInt p.gasUsed, timestamp : ethTime p.timestamp, extraData : ethBlob p.extraData, - mixDigest : ethHash p.prevRandao, + mixHash : ethHash p.prevRandao, nonce : default(BlockNonce), - fee : some(p.baseFeePerGas), + baseFeePerGas : Opt.some(p.baseFeePerGas), withdrawalsRoot: wdRoot p.withdrawals, blobGasUsed : u64(p.blobGasUsed), excessBlobGas : u64(p.excessBlobGas), @@ -116,7 +116,7 @@ func blockBody*(p: ExecutionPayload): ) func ethBlock*(p: ExecutionPayload, - beaconRoot: Option[common.Hash256]): + beaconRoot: Opt[common.Hash256]): common.EthBlock {.gcsafe, raises:[RlpError].} = common.EthBlock( header : blockHeader(p, beaconRoot), diff --git a/nimbus/beacon/payload_queue.nim b/nimbus/beacon/payload_queue.nim index 07bf1cbd4..bda70e7f8 100644 --- a/nimbus/beacon/payload_queue.nim +++ b/nimbus/beacon/payload_queue.nim @@ -35,7 +35,7 @@ type id: PayloadID payload: ExecutionPayload blockValue: UInt256 - blobsBundle: Option[BlobsBundleV1] + blobsBundle: Opt[BlobsBundleV1] HeaderItem = object hash: common.Hash256 @@ -73,13 +73,13 @@ proc put*(api: var PayloadQueue, proc put*(api: var PayloadQueue, id: PayloadID, blockValue: UInt256, payload: ExecutionPayload, - blobsBundle: Option[BlobsBundleV1]) = + blobsBundle: Opt[BlobsBundleV1]) = api.payloadQueue.put(PayloadItem(id: id, payload: payload, blockValue: blockValue, blobsBundle: blobsBundle)) proc put*(api: var PayloadQueue, id: PayloadID, blockValue: UInt256, payload: SomeExecutionPayload, - blobsBundle: Option[BlobsBundleV1]) = + blobsBundle: Opt[BlobsBundleV1]) = doAssert blobsBundle.isNone == (payload is ExecutionPayloadV1 | ExecutionPayloadV2) api.put(id, blockValue, payload.executionPayload, blobsBundle = blobsBundle) @@ -87,7 +87,7 @@ proc put*(api: var PayloadQueue, id: PayloadID, proc put*(api: var PayloadQueue, id: PayloadID, blockValue: UInt256, payload: ExecutionPayloadV1 | ExecutionPayloadV2) = - api.put(id, blockValue, payload, blobsBundle = options.none(BlobsBundleV1)) + api.put(id, blockValue, payload, blobsBundle = Opt.none(BlobsBundleV1)) # ------------------------------------------------------------------------------ # Public functions, getters @@ -104,7 +104,7 @@ proc get*(api: PayloadQueue, hash: common.Hash256, proc get*(api: PayloadQueue, id: PayloadID, blockValue: var UInt256, payload: var ExecutionPayload, - blobsBundle: var Option[BlobsBundleV1]): bool = + blobsBundle: var Opt[BlobsBundleV1]): bool = for x in api.payloadQueue: if x.id == id: payload = x.payload @@ -118,7 +118,7 @@ proc get*(api: PayloadQueue, id: PayloadID, payload: var ExecutionPayloadV1): bool = var p: ExecutionPayload - blobsBundleOpt: Option[BlobsBundleV1] + blobsBundleOpt: Opt[BlobsBundleV1] let found = api.get(id, blockValue, p, blobsBundleOpt) if found: doAssert(p.version == Version.V1) @@ -131,7 +131,7 @@ proc get*(api: PayloadQueue, id: PayloadID, payload: var ExecutionPayloadV2): bool = var p: ExecutionPayload - blobsBundleOpt: Option[BlobsBundleV1] + blobsBundleOpt: Opt[BlobsBundleV1] let found = api.get(id, blockValue, p, blobsBundleOpt) if found: doAssert(p.version == Version.V2) @@ -145,7 +145,7 @@ proc get*(api: PayloadQueue, id: PayloadID, blobsBundle: var BlobsBundleV1): bool = var p: ExecutionPayload - blobsBundleOpt: Option[BlobsBundleV1] + blobsBundleOpt: Opt[BlobsBundleV1] let found = api.get(id, blockValue, p, blobsBundleOpt) if found: doAssert(p.version == Version.V3) @@ -159,7 +159,7 @@ proc get*(api: PayloadQueue, id: PayloadID, payload: var ExecutionPayloadV1OrV2): bool = var p: ExecutionPayload - blobsBundleOpt: Option[BlobsBundleV1] + blobsBundleOpt: Opt[BlobsBundleV1] let found = api.get(id, blockValue, p, blobsBundleOpt) if found: doAssert(p.version in {Version.V1, Version.V2}) diff --git a/nimbus/beacon/web3_eth_conv.nim b/nimbus/beacon/web3_eth_conv.nim index f231b332b..d512dfa0c 100644 --- a/nimbus/beacon/web3_eth_conv.nim +++ b/nimbus/beacon/web3_eth_conv.nim @@ -8,7 +8,7 @@ # those terms. import - std/[options, typetraits], + std/[typetraits], web3/primitives as web3types, web3/eth_api_types, web3/engine_api_types, @@ -41,15 +41,15 @@ type # Pretty printers # ------------------------------------------------------------------------------ -proc `$`*(x: Option[common.Hash256]): string = +proc `$`*(x: Opt[common.Hash256]): string = if x.isNone: "none" else: x.get().data.toHex -proc `$`*(x: Option[Web3Hash]): string = +proc `$`*(x: Opt[Web3Hash]): string = if x.isNone: "none" else: x.get().toHex -proc `$`*(x: Option[PayloadID]): string = +proc `$`*(x: Opt[PayloadID]): string = if x.isNone: "none" else: x.get().toHex @@ -80,9 +80,9 @@ func w3Hash*(): Web3Hash = template unsafeQuantityToInt64*(q: Web3Quantity): int64 = int64 q -func u64*(x: Option[Web3Quantity]): Option[uint64] = - if x.isNone: none(uint64) - else: some(uint64 x.get) +func u64*(x: Opt[Web3Quantity]): Opt[uint64] = + if x.isNone: Opt.none(uint64) + else: Opt.some(uint64 x.get) func u256*(x: Web3Quantity): UInt256 = u256(x.uint64) @@ -99,24 +99,24 @@ func ethTime*(x: Web3Quantity): common.EthTime = func ethHash*(x: Web3PrevRandao): common.Hash256 = common.Hash256(data: distinctBase x) -func ethHash*(x: Option[Web3Hash]): Option[common.Hash256] = - if x.isNone: none(common.Hash256) - else: some(ethHash x.get) +func ethHash*(x: Opt[Web3Hash]): Opt[common.Hash256] = + if x.isNone: Opt.none(common.Hash256) + else: Opt.some(ethHash x.get) func ethHashes*(list: openArray[Web3Hash]): seq[common.Hash256] = for x in list: result.add ethHash(x) -func ethHashes*(list: Option[seq[Web3Hash]]): Option[seq[common.Hash256]] = - if list.isNone: none(seq[common.Hash256]) - else: some ethHashes(list.get) +func ethHashes*(list: Opt[seq[Web3Hash]]): Opt[seq[common.Hash256]] = + if list.isNone: Opt.none(seq[common.Hash256]) + else: Opt.some ethHashes(list.get) func ethAddr*(x: Web3Address): common.EthAddress = EthAddress x -func ethAddr*(x: Option[Web3Address]): Option[common.EthAddress] = - if x.isNone: none(common.EthAddress) - else: some(EthAddress x.get) +func ethAddr*(x: Opt[Web3Address]): Opt[common.EthAddress] = + if x.isNone: Opt.none(common.EthAddress) + else: Opt.some(EthAddress x.get) func ethAddrs*(list: openArray[Web3Address]): seq[common.EthAddress] = for x in list: @@ -143,10 +143,10 @@ func ethWithdrawals*(list: openArray[WithdrawalV1]): for x in list: result.add ethWithdrawal(x) -func ethWithdrawals*(x: Option[seq[WithdrawalV1]]): - Option[seq[common.Withdrawal]] = - if x.isNone: none(seq[common.Withdrawal]) - else: some(ethWithdrawals x.get) +func ethWithdrawals*(x: Opt[seq[WithdrawalV1]]): + Opt[seq[common.Withdrawal]] = + if x.isNone: Opt.none(seq[common.Withdrawal]) + else: Opt.some(ethWithdrawals x.get) func ethTx*(x: Web3Tx): common.Transaction {.gcsafe, raises:[RlpError].} = result = rlp.decode(distinctBase x, common.Transaction) @@ -168,7 +168,7 @@ func ethAccessList*(list: openArray[AccessTuple]): common.AccessList = storageKeys: storageKeys x.storageKeys, ) -func ethAccessList*(x: Option[seq[AccessTuple]]): common.AccessList = +func ethAccessList*(x: Opt[seq[AccessTuple]]): common.AccessList = if x.isSome: return ethAccessList(x.get) @@ -183,18 +183,18 @@ func w3Hashes*(list: openArray[common.Hash256]): seq[Web3Hash] = for x in list: result.add Web3Hash x.data -func w3Hashes*(z: Option[seq[common.Hash256]]): Option[seq[Web3Hash]] = - if z.isNone: none(seq[Web3Hash]) +func w3Hashes*(z: Opt[seq[common.Hash256]]): Opt[seq[Web3Hash]] = + if z.isNone: Opt.none(seq[Web3Hash]) else: let list = z.get var v = newSeqOfCap[Web3Hash](list.len) for x in list: v.add Web3Hash x.data - some(v) + Opt.some(v) -func w3Hash*(x: Option[common.Hash256]): Option[BlockHash] = - if x.isNone: none(BlockHash) - else: some(BlockHash x.get.data) +func w3Hash*(x: Opt[common.Hash256]): Opt[BlockHash] = + if x.isNone: Opt.none(BlockHash) + else: Opt.some(BlockHash x.get.data) func w3Hash*(x: common.BlockHeader): BlockHash = BlockHash rlpHash(x).data @@ -216,9 +216,6 @@ func w3PrevRandao*(x: common.Hash256): Web3PrevRandao = func w3Qty*(x: UInt256): Web3Quantity = Web3Quantity x.truncate(uint64) -func w3Qty*(x: common.GasInt): Web3Quantity = - Web3Quantity x.uint64 - func w3Qty*(x: common.EthTime): Web3Quantity = Web3Quantity x.uint64 @@ -234,16 +231,19 @@ func w3Qty*(x: Web3Quantity, y: EthTime): Web3Quantity = func w3Qty*(x: Web3Quantity, y: uint64): Web3Quantity = Web3Quantity(x.uint64 + y) -func w3Qty*(x: Option[uint64]): Option[Web3Quantity] = - if x.isNone: none(Web3Quantity) - else: some(Web3Quantity x.get) +func w3Qty*(x: Opt[uint64]): Opt[Web3Quantity] = + if x.isNone: Opt.none(Web3Quantity) + else: Opt.some(Web3Quantity x.get) func w3Qty*(x: uint64): Web3Quantity = Web3Quantity(x) -func w3BlockNumber*(x: Option[uint64]): Option[Web3BlockNumber] = - if x.isNone: none(Web3BlockNumber) - else: some(Web3BlockNumber x.get) +func w3Qty*(x: int64): Web3Quantity = + Web3Quantity(x) + +func w3BlockNumber*(x: Opt[uint64]): Opt[Web3BlockNumber] = + if x.isNone: Opt.none(Web3BlockNumber) + else: Opt.some(Web3BlockNumber x.get) func w3BlockNumber*(x: uint64): Web3BlockNumber = Web3BlockNumber(x) @@ -270,10 +270,10 @@ func w3Withdrawals*(list: openArray[common.Withdrawal]): seq[WithdrawalV1] = for x in list: result.add w3Withdrawal(x) -func w3Withdrawals*(x: Option[seq[common.Withdrawal]]): - Option[seq[WithdrawalV1]] = - if x.isNone: none(seq[WithdrawalV1]) - else: some(w3Withdrawals x.get) +func w3Withdrawals*(x: Opt[seq[common.Withdrawal]]): + Opt[seq[WithdrawalV1]] = + if x.isNone: Opt.none(seq[WithdrawalV1]) + else: Opt.some(w3Withdrawals x.get) func w3Tx*(tx: common.Transaction): Web3Tx = Web3Tx rlp.encode(tx) diff --git a/nimbus/common/chain_config.nim b/nimbus/common/chain_config.nim index 0abeaa139..8b0d6ea52 100644 --- a/nimbus/common/chain_config.nim +++ b/nimbus/common/chain_config.nim @@ -10,10 +10,10 @@ {.push raises: [].} import - std/[tables, strutils, options, times, macros], + std/[tables, strutils, times, macros], eth/[common, rlp, p2p], stint, stew/[byteutils], json_serialization, chronicles, - json_serialization/std/options as jsoptions, + json_serialization/stew/results, json_serialization/lexer, "."/[genesis_alloc, hardforks] @@ -33,10 +33,10 @@ type number* : BlockNumber gasUser* : GasInt parentHash* : Hash256 - baseFeePerGas*: Option[UInt256] # EIP-1559 - blobGasUsed* : Option[uint64] # EIP-4844 - excessBlobGas*: Option[uint64] # EIP-4844 - parentBeaconBlockRoot*: Option[Hash256] # EIP-4788 + baseFeePerGas*: Opt[UInt256] # EIP-1559 + blobGasUsed* : Opt[uint64] # EIP-4844 + excessBlobGas*: Opt[uint64] # EIP-4844 + parentBeaconBlockRoot*: Opt[Hash256] # EIP-4788 GenesisAlloc* = Table[EthAddress, GenesisAccount] GenesisStorage* = Table[UInt256, UInt256] @@ -77,7 +77,7 @@ derefType(ChainConfig).useDefaultReaderIn JGenesis # ------------------------------------------------------------------------------ # used by chronicles json writer -proc writeValue(writer: var JsonWriter, value: Option[EthTime]) +proc writeValue(writer: var JsonWriter, value: Opt[EthTime]) {.gcsafe, raises: [IOError].} = mixin writeValue @@ -225,10 +225,11 @@ proc readValue(reader: var JsonReader[JGenesis], value: var EthTime) if data.len > 2 and data[1] == 'x': value = fromHex[int64](data).EthTime else: + # TODO: use safer uint64 parser value = parseInt(data).EthTime # but shanghaiTime and cancunTime in config is in int literal -proc readValue(reader: var JsonReader[JGenesis], value: var Option[EthTime]) +proc readValue(reader: var JsonReader[JGenesis], value: var Opt[EthTime]) {.gcsafe, raises: [IOError, JsonReaderError].} = if reader.tokKind == JsonValueKind.Null: reset value @@ -237,7 +238,7 @@ proc readValue(reader: var JsonReader[JGenesis], value: var Option[EthTime]) # both readValue(GasInt/AccountNonce) will be called if # we use readValue(int64/uint64) let val = EthTime reader.parseInt(uint64) - value = some val + value = Opt.some val proc readValue(reader: var JsonReader[JGenesis], value: var seq[byte]) {.gcsafe, raises: [SerializationError, IOError].} = @@ -254,10 +255,18 @@ proc readValue(reader: var JsonReader[JGenesis], value: var EthAddress) wrapError: value = parseAddress(reader.readValue(string)) -proc readValue(reader: var JsonReader[JGenesis], value: var AccountNonce) +proc readValue(reader: var JsonReader[JGenesis], value: var uint64) {.gcsafe, raises: [SerializationError, IOError].} = wrapError: - value = fromHex[uint64](reader.readValue(string)) + if reader.tokKind == JsonValueKind.Number: + value = reader.parseInt(uint64) + else: + let data = reader.readValue(string) + if data.len > 2 and data[1] == 'x': + value = fromHex[uint64](data) + else: + # TODO: use safer uint64 parser + value = parseInt(data).uint64 proc readValue(reader: var JsonReader[JGenesis], value: var GenesisStorage) {.gcsafe, raises: [SerializationError, IOError].} = @@ -447,69 +456,69 @@ func chainConfigForNetwork*(id: NetworkId): ChainConfig = consensusType: ConsensusType.POW, chainId: MainNet.ChainId, # Genesis (Frontier): # 2015-07-30 15:26:13 UTC - # Frontier Thawing: 200_000.toBlockNumber, # 2015-09-07 21:33:09 UTC - homesteadBlock: some(1_150_000.toBlockNumber), # 2016-03-14 18:49:53 UTC - daoForkBlock: some(1_920_000.toBlockNumber), # 2016-07-20 13:20:40 UTC + # Frontier Thawing: 200_000.BlockNumber, # 2015-09-07 21:33:09 UTC + homesteadBlock: Opt.some(1_150_000.BlockNumber), # 2016-03-14 18:49:53 UTC + daoForkBlock: Opt.some(1_920_000.BlockNumber), # 2016-07-20 13:20:40 UTC daoForkSupport: true, - eip150Block: some(2_463_000.toBlockNumber), # 2016-10-18 13:19:31 UTC + eip150Block: Opt.some(2_463_000.BlockNumber), # 2016-10-18 13:19:31 UTC eip150Hash: toDigest("2086799aeebeae135c246c65021c82b4e15a2c451340993aacfd2751886514f0"), - eip155Block: some(2_675_000.toBlockNumber), # Same as EIP-158 - eip158Block: some(2_675_000.toBlockNumber), # 2016-11-22 16:15:44 UTC - byzantiumBlock: some(4_370_000.toBlockNumber), # 2017-10-16 05:22:11 UTC - constantinopleBlock: some(7_280_000.toBlockNumber), # Skipped on Mainnet - petersburgBlock: some(7_280_000.toBlockNumber), # 2019-02-28 19:52:04 UTC - istanbulBlock: some(9_069_000.toBlockNumber), # 2019-12-08 00:25:09 UTC - muirGlacierBlock: some(9_200_000.toBlockNumber), # 2020-01-02 08:30:49 UTC - berlinBlock: some(12_244_000.toBlockNumber), # 2021-04-15 10:07:03 UTC - londonBlock: some(12_965_000.toBlockNumber), # 2021-08-05 12:33:42 UTC - arrowGlacierBlock: some(13_773_000.toBlockNumber), # 2021-12-09 19:55:23 UTC - grayGlacierBlock: some(15_050_000.toBlockNumber), # 2022-06-30 10:54:04 UTC - terminalTotalDifficulty: some(mainNetTTD), - shanghaiTime: some(1_681_338_455.EthTime), # 2023-04-12 10:27:35 UTC - cancunTime: some(1_710_338_135.EthTime) # 2024-03-13 13:55:35 UTC + eip155Block: Opt.some(2_675_000.BlockNumber), # Same as EIP-158 + eip158Block: Opt.some(2_675_000.BlockNumber), # 2016-11-22 16:15:44 UTC + byzantiumBlock: Opt.some(4_370_000.BlockNumber), # 2017-10-16 05:22:11 UTC + constantinopleBlock: Opt.some(7_280_000.BlockNumber), # Skipped on Mainnet + petersburgBlock: Opt.some(7_280_000.BlockNumber), # 2019-02-28 19:52:04 UTC + istanbulBlock: Opt.some(9_069_000.BlockNumber), # 2019-12-08 00:25:09 UTC + muirGlacierBlock: Opt.some(9_200_000.BlockNumber), # 2020-01-02 08:30:49 UTC + berlinBlock: Opt.some(12_244_000.BlockNumber), # 2021-04-15 10:07:03 UTC + londonBlock: Opt.some(12_965_000.BlockNumber), # 2021-08-05 12:33:42 UTC + arrowGlacierBlock: Opt.some(13_773_000.BlockNumber), # 2021-12-09 19:55:23 UTC + grayGlacierBlock: Opt.some(15_050_000.BlockNumber), # 2022-06-30 10:54:04 UTC + terminalTotalDifficulty: Opt.some(mainNetTTD), + shanghaiTime: Opt.some(1_681_338_455.EthTime), # 2023-04-12 10:27:35 UTC + cancunTime: Opt.some(1_710_338_135.EthTime), # 2024-03-13 13:55:35 UTC ) of SepoliaNet: const sepoliaTTD = parse("17000000000000000",UInt256) ChainConfig( consensusType: ConsensusType.POW, chainId: SepoliaNet.ChainId, - homesteadBlock: some(0.toBlockNumber), + homesteadBlock: Opt.some(0.BlockNumber), daoForkSupport: false, - eip150Block: some(0.toBlockNumber), + eip150Block: Opt.some(0.BlockNumber), eip150Hash: toDigest("0000000000000000000000000000000000000000000000000000000000000000"), - eip155Block: some(0.toBlockNumber), - eip158Block: some(0.toBlockNumber), - byzantiumBlock: some(0.toBlockNumber), - constantinopleBlock: some(0.toBlockNumber), - petersburgBlock: some(0.toBlockNumber), - istanbulBlock: some(0.toBlockNumber), - muirGlacierBlock: some(0.toBlockNumber), - berlinBlock: some(0.toBlockNumber), - londonBlock: some(0.toBlockNumber), - mergeForkBlock: some(1735371.toBlockNumber), - terminalTotalDifficulty: some(sepoliaTTD), - shanghaiTime: some(1_677_557_088.EthTime), - cancunTime: some(1_706_655_072.EthTime), # 2024-01-30 22:51:12 + eip155Block: Opt.some(0.BlockNumber), + eip158Block: Opt.some(0.BlockNumber), + byzantiumBlock: Opt.some(0.BlockNumber), + constantinopleBlock: Opt.some(0.BlockNumber), + petersburgBlock: Opt.some(0.BlockNumber), + istanbulBlock: Opt.some(0.BlockNumber), + muirGlacierBlock: Opt.some(0.BlockNumber), + berlinBlock: Opt.some(0.BlockNumber), + londonBlock: Opt.some(0.BlockNumber), + mergeForkBlock: Opt.some(1735371.BlockNumber), + terminalTotalDifficulty: Opt.some(sepoliaTTD), + shanghaiTime: Opt.some(1_677_557_088.EthTime), + cancunTime: Opt.some(1_706_655_072.EthTime), # 2024-01-30 22:51:12 ) of HoleskyNet: ChainConfig( consensusType: ConsensusType.POS, chainId: HoleskyNet.ChainId, - homesteadBlock: some(0.toBlockNumber), - eip150Block: some(0.toBlockNumber), - eip155Block: some(0.toBlockNumber), - eip158Block: some(0.toBlockNumber), - byzantiumBlock: some(0.toBlockNumber), - constantinopleBlock: some(0.toBlockNumber), - petersburgBlock: some(0.toBlockNumber), - istanbulBlock: some(0.toBlockNumber), - berlinBlock: some(0.toBlockNumber), - londonBlock: some(0.toBlockNumber), - mergeForkBlock: some(0.toBlockNumber), - terminalTotalDifficulty: some(0.u256), - terminalTotalDifficultyPassed: some(true), - shanghaiTime: some(1_696_000_704.EthTime), - cancunTime: some(1_707_305_664.EthTime), # 2024-02-07 11:34:24 + homesteadBlock: Opt.some(0.BlockNumber), + eip150Block: Opt.some(0.BlockNumber), + eip155Block: Opt.some(0.BlockNumber), + eip158Block: Opt.some(0.BlockNumber), + byzantiumBlock: Opt.some(0.BlockNumber), + constantinopleBlock: Opt.some(0.BlockNumber), + petersburgBlock: Opt.some(0.BlockNumber), + istanbulBlock: Opt.some(0.BlockNumber), + berlinBlock: Opt.some(0.BlockNumber), + londonBlock: Opt.some(0.BlockNumber), + mergeForkBlock: Opt.some(0.BlockNumber), + terminalTotalDifficulty: Opt.some(0.u256), + terminalTotalDifficultyPassed: Opt.some(true), + shanghaiTime: Opt.some(1_696_000_704.EthTime), + cancunTime: Opt.some(1_707_305_664.EthTime), # 2024-02-07 11:34:24 ) else: ChainConfig() diff --git a/nimbus/common/common.nim b/nimbus/common/common.nim index 13d2fcd07..915f50cf3 100644 --- a/nimbus/common/common.nim +++ b/nimbus/common/common.nim @@ -10,7 +10,6 @@ {.push raises: [].} import - std/[options], chronicles, eth/trie/trie_defs, ../core/[pow, casper], @@ -24,7 +23,6 @@ export core_db, constants, errors, - options, evmforks, hardforks, genesis, @@ -159,13 +157,13 @@ proc init(com : CommonRef, # by setForkId if genesis.isNil.not: com.hardForkTransition(ForkDeterminationInfo( - blockNumber: 0.toBlockNumber, + number: 0.BlockNumber, td: Opt.some(0.u256), time: Opt.some(genesis.timestamp) )) # Must not overwrite the global state on the single state DB - if not db.getBlockHeader(0.toBlockNumber, com.genesisHeader): + if not db.getBlockHeader(0.BlockNumber, com.genesisHeader): com.genesisHeader = toGenesisHeader(genesis, com.currentFork, com.db) @@ -173,7 +171,7 @@ proc init(com : CommonRef, com.pos.timestamp = genesis.timestamp else: com.hardForkTransition(ForkDeterminationInfo( - blockNumber: 0.toBlockNumber, + number: 0.BlockNumber, td: Opt.some(0.u256), time: Opt.some(TimeZero) )) @@ -191,7 +189,7 @@ proc getTd(com: CommonRef, blockHash: Hash256): Opt[DifficultyInt] = func needTdForHardForkDetermination(com: CommonRef): bool = let t = com.forkTransitionTable.mergeForkTransitionThreshold - t.ttdPassed.isNone and t.blockNumber.isNone and t.ttd.isSome + t.ttdPassed.isNone and t.number.isNone and t.ttd.isSome proc getTdIfNecessary(com: CommonRef, blockHash: Hash256): Opt[DifficultyInt] = if needTdForHardForkDetermination(com): @@ -288,7 +286,7 @@ func hardForkTransition*( td: Opt[DifficultyInt], time: Opt[EthTime]) = com.hardForkTransition(ForkDeterminationInfo( - blockNumber: number, time: time, td: td)) + number: number, time: time, td: td)) proc hardForkTransition*( com: CommonRef, @@ -301,7 +299,7 @@ proc hardForkTransition*( com: CommonRef, header: BlockHeader) {.gcsafe, raises: [].} = com.hardForkTransition( - header.parentHash, header.blockNumber, Opt.some(header.timestamp)) + header.parentHash, header.number, Opt.some(header.timestamp)) func toEVMFork*(com: CommonRef, forkDeterminer: ForkDeterminationInfo): EVMFork = ## similar to toFork, but produce EVMFork @@ -333,7 +331,7 @@ func forkId*(com: CommonRef, head, time: uint64): ForkID {.gcsafe.} = func forkId*(com: CommonRef, head: BlockNumber, time: EthTime): ForkID {.gcsafe.} = ## EIP 2364/2124 - com.forkIdCalculator.newID(head.truncate(uint64), time.uint64) + com.forkIdCalculator.newID(head, time.uint64) func isEIP155*(com: CommonRef, number: BlockNumber): bool = com.config.eip155Block.isSome and number >= com.config.eip155Block.get @@ -370,7 +368,7 @@ proc initializeEmptyDb*(com: CommonRef) = kvt.hasKey(key).expect "valid bool" if canonicalHeadHashKey().toOpenArray notin kvt: info "Writing genesis to DB" - doAssert(com.genesisHeader.blockNumber.isZero, + doAssert(com.genesisHeader.number == 0.BlockNumber, "can't commit genesis block with number > 0") doAssert(com.db.persistHeader(com.genesisHeader, com.consensusType == ConsensusType.POS, @@ -412,19 +410,19 @@ func db*(com: CommonRef): CoreDbRef = func consensus*(com: CommonRef): ConsensusType = com.consensusType -func eip150Block*(com: CommonRef): Option[BlockNumber] = +func eip150Block*(com: CommonRef): Opt[BlockNumber] = com.config.eip150Block func eip150Hash*(com: CommonRef): Hash256 = com.config.eip150Hash -func daoForkBlock*(com: CommonRef): Option[BlockNumber] = +func daoForkBlock*(com: CommonRef): Opt[BlockNumber] = com.config.daoForkBlock func daoForkSupport*(com: CommonRef): bool = com.config.daoForkSupport -func ttd*(com: CommonRef): Option[DifficultyInt] = +func ttd*(com: CommonRef): Opt[DifficultyInt] = com.config.terminalTotalDifficulty func ttdPassed*(com: CommonRef): bool = @@ -483,7 +481,7 @@ func `startOfHistory=`*(com: CommonRef, val: Hash256) = ## Setter com.startOfHistory = val -func setTTD*(com: CommonRef, ttd: Option[DifficultyInt]) = +func setTTD*(com: CommonRef, ttd: Opt[DifficultyInt]) = ## useful for testing com.config.terminalTotalDifficulty = ttd # rebuild the MergeFork piece of the forkTransitionTable diff --git a/nimbus/common/genesis.nim b/nimbus/common/genesis.nim index 9dfede952..728fa4592 100644 --- a/nimbus/common/genesis.nim +++ b/nimbus/common/genesis.nim @@ -111,19 +111,19 @@ proc toGenesisHeader*( extraData: g.extraData, gasLimit: g.gasLimit, difficulty: g.difficulty, - mixDigest: g.mixHash, + mixHash: g.mixHash, coinbase: g.coinbase, stateRoot: sdb.rootHash(), parentHash: GENESIS_PARENT_HASH, txRoot: EMPTY_ROOT_HASH, - receiptRoot: EMPTY_ROOT_HASH, + receiptsRoot: EMPTY_ROOT_HASH, ommersHash: EMPTY_UNCLE_HASH ) if g.baseFeePerGas.isSome: - result.baseFee = g.baseFeePerGas.get() + result.baseFeePerGas = Opt.some(g.baseFeePerGas.get) elif fork >= London: - result.baseFee = EIP1559_INITIAL_BASE_FEE.u256 + result.baseFeePerGas = Opt.some(EIP1559_INITIAL_BASE_FEE) if g.gasLimit == 0: result.gasLimit = GENESIS_GAS_LIMIT @@ -132,12 +132,12 @@ proc toGenesisHeader*( result.difficulty = GENESIS_DIFFICULTY if fork >= Shanghai: - result.withdrawalsRoot = some(EMPTY_ROOT_HASH) + result.withdrawalsRoot = Opt.some(EMPTY_ROOT_HASH) if fork >= Cancun: - result.blobGasUsed = g.blobGasUsed.get(0'u64).some - result.excessBlobGas = g.excessBlobGas.get(0'u64).some - result.parentBeaconBlockRoot = g.parentBeaconBlockRoot.get(Hash256()).some + result.blobGasUsed = Opt.some g.blobGasUsed.get(0'u64) + result.excessBlobGas = Opt.some g.excessBlobGas.get(0'u64) + result.parentBeaconBlockRoot = Opt.some g.parentBeaconBlockRoot.get(Hash256()) proc toGenesisHeader*( genesis: Genesis; @@ -159,7 +159,7 @@ proc toGenesisHeader*( ## Generate the genesis block header from the `genesis` and `config` ## argument value. let map = toForkTransitionTable(params.config) - let fork = map.toHardFork(forkDeterminationInfo(0.toBlockNumber, params.genesis.timestamp)) + let fork = map.toHardFork(forkDeterminationInfo(0.BlockNumber, params.genesis.timestamp)) toGenesisHeader(params.genesis, fork, db) # ------------------------------------------------------------------------------ diff --git a/nimbus/common/hardforks.nim b/nimbus/common/hardforks.nim index fb0bf8b8d..126dda6a7 100644 --- a/nimbus/common/hardforks.nim +++ b/nimbus/common/hardforks.nim @@ -8,9 +8,8 @@ # those terms. import - std/[options, strutils], + std/[strutils], eth/common, - results, stew/endians2, json_serialization, ../utils/utils, @@ -55,14 +54,14 @@ const firstTimeBasedFork* = Shanghai type MergeForkTransitionThreshold* = object - blockNumber*: Option[BlockNumber] - ttd*: Option[DifficultyInt] - ttdPassed*: Option[bool] + number*: Opt[BlockNumber] + ttd*: Opt[DifficultyInt] + ttdPassed*: Opt[bool] ForkTransitionTable* = object - blockNumberThresholds*: array[Frontier..GrayGlacier, Option[BlockNumber]] + blockNumberThresholds*: array[Frontier..GrayGlacier, Opt[BlockNumber]] mergeForkTransitionThreshold*: MergeForkTransitionThreshold - timeThresholds*: array[Shanghai..Prague, Option[EthTime]] + timeThresholds*: array[Shanghai..Prague, Opt[EthTime]] # Starting with Shanghai, forking is based on timestamp # rather than block number. @@ -80,7 +79,7 @@ type # it makes sense to allow time to be optional. See the # comment below on forkDeterminationInfo. ForkDeterminationInfo* = object - blockNumber*: BlockNumber + number*: BlockNumber time*: Opt[EthTime] td*: Opt[DifficultyInt] @@ -90,15 +89,15 @@ func forkDeterminationInfo*(n: BlockNumber): ForkDeterminationInfo = # like various tests, where we only have block number and the tests are # meant for pre-Merge forks, so maybe those are okay. ForkDeterminationInfo( - blockNumber: n, time: Opt.none(EthTime), td: Opt.none(DifficultyInt)) + number: n, time: Opt.none(EthTime), td: Opt.none(DifficultyInt)) func forkDeterminationInfo*(n: BlockNumber, t: EthTime): ForkDeterminationInfo = ForkDeterminationInfo( - blockNumber: n, time: Opt.some(t), td: Opt.none(DifficultyInt)) + number: n, time: Opt.some(t), td: Opt.none(DifficultyInt)) func forkDeterminationInfo*(header: BlockHeader): ForkDeterminationInfo = # FIXME-Adam-mightAlsoNeedTTD? - forkDeterminationInfo(header.blockNumber, header.timestamp) + forkDeterminationInfo(header.number, header.timestamp) func adjustForNextBlock*(n: BlockNumber): BlockNumber = n + 1 @@ -114,7 +113,7 @@ func adjustForNextBlock*(t: EthTime): EthTime = func adjustForNextBlock*(f: ForkDeterminationInfo): ForkDeterminationInfo = ForkDeterminationInfo( - blockNumber: adjustForNextBlock(f.blockNumber), + number: adjustForNextBlock(f.number), time: f.time.map(adjustForNextBlock), td: f.td ) @@ -127,15 +126,15 @@ func adjustForNextBlock*(f: ForkDeterminationInfo): ForkDeterminationInfo = # Shanghai. func isGTETransitionThreshold*(map: ForkTransitionTable, forkDeterminer: ForkDeterminationInfo, fork: HardFork): bool = if fork <= lastPurelyBlockNumberBasedFork: - map.blockNumberThresholds[fork].isSome and forkDeterminer.blockNumber >= map.blockNumberThresholds[fork].get + map.blockNumberThresholds[fork].isSome and forkDeterminer.number >= map.blockNumberThresholds[fork].get elif fork == MergeFork: # MergeFork is a special case that can use either block number or ttd; # ttdPassed > block number > ttd takes precedence. let t = map.mergeForkTransitionThreshold if t.ttdPassed.isSome: t.ttdPassed.get - elif t.blockNumber.isSome: - forkDeterminer.blockNumber >= t.blockNumber.get + elif t.number.isSome: + forkDeterminer.number >= t.number.get elif t.ttd.isSome and forkDeterminer.td.isSome: forkDeterminer.td.get >= t.ttd.get else: @@ -150,34 +149,34 @@ type # please update forkBlockField constant too ChainConfig* = ref object chainId* : ChainId - homesteadBlock* : Option[BlockNumber] - daoForkBlock* : Option[BlockNumber] + homesteadBlock* : Opt[BlockNumber] + daoForkBlock* : Opt[BlockNumber] daoForkSupport* : bool - eip150Block* : Option[BlockNumber] + eip150Block* : Opt[BlockNumber] eip150Hash* : Hash256 - eip155Block* : Option[BlockNumber] - eip158Block* : Option[BlockNumber] - byzantiumBlock* : Option[BlockNumber] - constantinopleBlock*: Option[BlockNumber] - petersburgBlock* : Option[BlockNumber] - istanbulBlock* : Option[BlockNumber] - muirGlacierBlock* : Option[BlockNumber] - berlinBlock* : Option[BlockNumber] - londonBlock* : Option[BlockNumber] - arrowGlacierBlock* : Option[BlockNumber] - grayGlacierBlock* : Option[BlockNumber] + eip155Block* : Opt[BlockNumber] + eip158Block* : Opt[BlockNumber] + byzantiumBlock* : Opt[BlockNumber] + constantinopleBlock*: Opt[BlockNumber] + petersburgBlock* : Opt[BlockNumber] + istanbulBlock* : Opt[BlockNumber] + muirGlacierBlock* : Opt[BlockNumber] + berlinBlock* : Opt[BlockNumber] + londonBlock* : Opt[BlockNumber] + arrowGlacierBlock* : Opt[BlockNumber] + grayGlacierBlock* : Opt[BlockNumber] # mergeNetsplitBlock is an alias to mergeForkBlock # and is used for geth compatibility layer - mergeNetsplitBlock* : Option[BlockNumber] + mergeNetsplitBlock* : Opt[BlockNumber] - mergeForkBlock* : Option[BlockNumber] - shanghaiTime* : Option[EthTime] - cancunTime* : Option[EthTime] - pragueTime* : Option[EthTime] + mergeForkBlock* : Opt[BlockNumber] + shanghaiTime* : Opt[EthTime] + cancunTime* : Opt[EthTime] + pragueTime* : Opt[EthTime] - terminalTotalDifficulty*: Option[UInt256] - terminalTotalDifficultyPassed*: Option[bool] + terminalTotalDifficulty*: Opt[UInt256] + terminalTotalDifficultyPassed*: Opt[bool] consensusType* {.dontSerialize.} : ConsensusType @@ -185,10 +184,10 @@ type # are in a valid order. BlockNumberBasedForkOptional* = object name*: string - number*: Option[BlockNumber] + number*: Opt[BlockNumber] TimeBasedForkOptional* = object name*: string - time*: Option[EthTime] + time*: Opt[EthTime] func countTimeFields(): int {.compileTime.} = var z = ChainConfig() @@ -240,7 +239,7 @@ const func mergeForkTransitionThreshold*(conf: ChainConfig): MergeForkTransitionThreshold = MergeForkTransitionThreshold( - blockNumber: conf.mergeForkBlock, + number: conf.mergeForkBlock, ttd: conf.terminalTotalDifficulty, ttdPassed: conf.terminalTotalDifficultyPassed ) @@ -250,7 +249,7 @@ func toForkTransitionTable*(conf: ChainConfig): ForkTransitionTable = # field names, but it doesn't seem worthwhile anymore # (now that there's irregularity due to block-based vs # timestamp-based forking). - result.blockNumberThresholds[Frontier ] = some(0.toBlockNumber) + result.blockNumberThresholds[Frontier ] = Opt.some(0.BlockNumber) result.blockNumberThresholds[Homestead ] = conf.homesteadBlock result.blockNumberThresholds[DAOFork ] = conf.daoForkBlock result.blockNumberThresholds[Tangerine ] = conf.eip150Block @@ -285,7 +284,7 @@ func populateFromForkTransitionTable*(conf: ChainConfig, t: ForkTransitionTable) conf.arrowGlacierBlock = t.blockNumberThresholds[HardFork.ArrowGlacier] conf.grayGlacierBlock = t.blockNumberThresholds[HardFork.GrayGlacier] - conf.mergeForkBlock = t.mergeForkTransitionThreshold.blockNumber + conf.mergeForkBlock = t.mergeForkTransitionThreshold.number conf.terminalTotalDifficulty = t.mergeForkTransitionThreshold.ttd conf.terminalTotalDifficultyPassed = t.mergeForkTransitionThreshold.ttdPassed @@ -388,15 +387,15 @@ func initForkIdCalculator*(map: ForkTransitionTable, var forksByBlock: seq[uint64] for fork, val in map.blockNumberThresholds: if val.isNone: continue - let val64 = val.get.truncate(uint64) + let val64 = val.get if forksByBlock.len == 0: forksByBlock.add val64 elif forksByBlock[^1] != val64: # Deduplicate fork identifiers applying multiple forks forksByBlock.add val64 - if map.mergeForkTransitionThreshold.blockNumber.isSome: - let val64 = map.mergeForkTransitionThreshold.blockNumber.get.truncate(uint64) + if map.mergeForkTransitionThreshold.number.isSome: + let val64 = map.mergeForkTransitionThreshold.number.get if forksByBlock.len == 0: forksByBlock.add val64 elif forksByBlock[^1] != val64: diff --git a/nimbus/constants.nim b/nimbus/constants.nim index ca43ea4e6..d4006a10d 100644 --- a/nimbus/constants.nim +++ b/nimbus/constants.nim @@ -1,5 +1,5 @@ # Nimbus -# Copyright (c) 2018-2023 Status Research & Development GmbH +# 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) @@ -36,10 +36,10 @@ const UNCLE_DEPTH_PENALTY_FACTOR* = 8.u256 - MAX_UNCLE_DEPTH* = 6.u256 + MAX_UNCLE_DEPTH* = 6 MAX_UNCLES* = 2 - GENESIS_BLOCK_NUMBER* = 0.toBlockNumber + GENESIS_BLOCK_NUMBER* = 0.BlockNumber GENESIS_DIFFICULTY* = 131_072.u256 GENESIS_GAS_LIMIT* = 3_141_592 GENESIS_PARENT_HASH* = ZERO_HASH256 @@ -55,7 +55,7 @@ const GAS_MOD_EXP_QUADRATIC_DENOMINATOR* = 20.u256 - MAX_PREV_HEADER_DEPTH* = 256.toBlockNumber + MAX_PREV_HEADER_DEPTH* = 256'u64 MaxCallDepth* = 1024 SECPK1_N* = UInt256.fromHex("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141") diff --git a/nimbus/core/chain/chain_desc.nim b/nimbus/core/chain/chain_desc.nim index 420c64b5f..4ed5a71e8 100644 --- a/nimbus/core/chain/chain_desc.nim +++ b/nimbus/core/chain/chain_desc.nim @@ -111,10 +111,6 @@ proc `verifyFrom=`*(c: ChainRef; verifyFrom: BlockNumber) = ## `true`. c.verifyFrom = verifyFrom -proc `verifyFrom=`*(c: ChainRef; verifyFrom: uint64) = - ## Variant of `verifyFrom=` - c.verifyFrom = verifyFrom.u256 - # ------------------------------------------------------------------------------ # End # ------------------------------------------------------------------------------ diff --git a/nimbus/core/chain/persist_blocks.nim b/nimbus/core/chain/persist_blocks.nim index 9c7a1f706..e3e2d94d9 100644 --- a/nimbus/core/chain/persist_blocks.nim +++ b/nimbus/core/chain/persist_blocks.nim @@ -39,10 +39,11 @@ type PersistStats = tuple[blocks: int, txs: int, gas: GasInt] -const CleanUpEpoch = 30_000.toBlockNumber - ## Regular checks for history clean up (applies to single state DB). This - ## is mainly a debugging/testing feature so that the database can be held - ## a bit smaller. It is not applicable to a full node. +const + CleanUpEpoch = 30_000.BlockNumber + ## Regular checks for history clean up (applies to single state DB). This + ## is mainly a debugging/testing feature so that the database can be held + ## a bit smaller. It is not applicable to a full node. # ------------------------------------------------------------------------------ # Private @@ -82,8 +83,8 @@ proc persistBlocksImpl( let vmState = ?c.getVmState(blocks[0].header) let - fromBlock = blocks[0].header.blockNumber - toBlock = blocks[blocks.high()].header.blockNumber + fromBlock = blocks[0].header.number + toBlock = blocks[blocks.high()].header.number trace "Persisting blocks", fromBlock, toBlock var @@ -96,10 +97,10 @@ proc persistBlocksImpl( c.com.hardForkTransition(header) if not vmState.reinit(header): - debug "Cannot update VmState", blockNumber = header.blockNumber - return err("Cannot update VmState to block " & $header.blockNumber) + debug "Cannot update VmState", blockNumber = header.number + return err("Cannot update VmState to block " & $header.number) - if c.extraValidation and c.verifyFrom <= header.blockNumber: + if c.extraValidation and c.verifyFrom <= header.number: # TODO: how to checkseal from here ?c.com.validateHeaderAndKinship(blk, checkSealOK = false) @@ -118,7 +119,7 @@ proc persistBlocksImpl( return err("Could not persist header") if NoSaveTxs notin flags: - c.db.persistTransactions(header.blockNumber, blk.transactions) + c.db.persistTransactions(header.number, blk.transactions) if NoSaveReceipts notin flags: c.db.persistReceipts(vmState.receipts) @@ -129,7 +130,7 @@ proc persistBlocksImpl( # update currentBlock *after* we persist it # so the rpc return consistent result # between eth_blockNumber and eth_syncing - c.com.syncCurrent = header.blockNumber + c.com.syncCurrent = header.number txs += blk.transactions.len gas += blk.header.gasUsed diff --git a/nimbus/core/executor/calculate_reward.nim b/nimbus/core/executor/calculate_reward.nim index 75d004181..d666d99c5 100644 --- a/nimbus/core/executor/calculate_reward.nim +++ b/nimbus/core/executor/calculate_reward.nim @@ -22,8 +22,8 @@ proc calculateReward*(vmState: BaseVMState; account: EthAddress; var mainReward = blockReward for uncle in uncles: - var uncleReward = uncle.blockNumber.u256 + 8.u256 - uncleReward -= number + var uncleReward = uncle.number.u256 + 8.u256 + uncleReward -= number.u256 uncleReward = uncleReward * blockReward uncleReward = uncleReward div 8.u256 vmState.mutateStateDB: @@ -36,6 +36,6 @@ proc calculateReward*(vmState: BaseVMState; account: EthAddress; proc calculateReward*(vmState: BaseVMState; header: BlockHeader; uncles: openArray[BlockHeader]) = - vmState.calculateReward(header.coinbase, header.blockNumber, uncles) + vmState.calculateReward(header.coinbase, header.number, uncles) # End diff --git a/nimbus/core/executor/executor_helpers.nim b/nimbus/core/executor/executor_helpers.nim index 542f83b48..b4f8ae188 100644 --- a/nimbus/core/executor/executor_helpers.nim +++ b/nimbus/core/executor/executor_helpers.nim @@ -1,5 +1,5 @@ # Nimbus -# Copyright (c) 2018-2023 Status Research & Development GmbH +# 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) @@ -61,7 +61,7 @@ proc makeReceipt*(vmState: BaseVMState; txType: TxType): Receipt = rec.receiptType = txType rec.cumulativeGasUsed = vmState.cumulativeGasUsed rec.logs = vmState.getAndClearLogEntries() - rec.bloom = logsBloom(rec.logs).value.toBytesBE + rec.logsBloom = logsBloom(rec.logs).value.toBytesBE rec # ------------------------------------------------------------------------------ diff --git a/nimbus/core/executor/process_block.nim b/nimbus/core/executor/process_block.nim index c30de7791..46e991b13 100644 --- a/nimbus/core/executor/process_block.nim +++ b/nimbus/core/executor/process_block.nim @@ -47,7 +47,7 @@ proc procBlkPreamble(vmState: BaseVMState, blk: EthBlock): Result[void, string] template header(): BlockHeader = blk.header - if vmState.com.daoForkSupport and vmState.com.daoForkBlock.get == header.blockNumber: + if vmState.com.daoForkSupport and vmState.com.daoForkBlock.get == header.number: vmState.mutateStateDB: db.applyDAOHardFork() @@ -112,23 +112,23 @@ proc procBlkEpilogue(vmState: BaseVMState, header: BlockHeader): Result[void, st if header.stateRoot != stateDB.rootHash: # TODO replace logging with better error debug "wrong state root in block", - blockNumber = header.blockNumber, + blockNumber = header.number, expected = header.stateRoot, actual = stateDB.rootHash, arrivedFrom = vmState.com.db.getCanonicalHead().stateRoot return err("stateRoot mismatch") let bloom = createBloom(vmState.receipts) - if header.bloom != bloom: + if header.logsBloom != bloom: return err("bloom mismatch") - let receiptRoot = calcReceiptRoot(vmState.receipts) - if header.receiptRoot != receiptRoot: + let receiptsRoot = calcReceiptsRoot(vmState.receipts) + if header.receiptsRoot != receiptsRoot: # TODO replace logging with better error debug "wrong receiptRoot in block", - blockNumber = header.blockNumber, - actual = receiptRoot, - expected = header.receiptRoot + blockNumber = header.number, + actual = receiptsRoot, + expected = header.receiptsRoot return err("receiptRoot mismatch") ok() diff --git a/nimbus/core/executor/process_transaction.nim b/nimbus/core/executor/process_transaction.nim index 08fd7b274..e80a742e0 100644 --- a/nimbus/core/executor/process_transaction.nim +++ b/nimbus/core/executor/process_transaction.nim @@ -32,7 +32,7 @@ proc eip1559BaseFee(header: BlockHeader; fork: EVMFork): UInt256 = ## function just plays safe. In particular, the `test_general_state_json.nim` ## module modifies this block header `baseFee` field unconditionally :(. if FkLondon <= fork: - result = header.baseFee + result = header.baseFeePerGas.get(0.u256) proc commitOrRollbackDependingOnGasUsed( vmState: BaseVMState; @@ -79,7 +79,7 @@ proc processTransactionImpl( baseFee256 = header.eip1559BaseFee(fork) baseFee = baseFee256.truncate(GasInt) tx = eip1559TxNormalization(tx, baseFee) - priorityFee = min(tx.maxPriorityFee, tx.maxFee - baseFee) + priorityFee = min(tx.maxPriorityFeePerGas, tx.maxFeePerGas - baseFee) excessBlobGas = header.excessBlobGas.get(0'u64) # Return failure unless explicitely set `ok()` diff --git a/nimbus/core/gaslimit.nim b/nimbus/core/gaslimit.nim index f4c5a58f0..b4236f43a 100644 --- a/nimbus/core/gaslimit.nim +++ b/nimbus/core/gaslimit.nim @@ -58,8 +58,8 @@ proc calcEip1599BaseFee*(com: CommonRef; parent: BlockHeader): UInt256 = # If the current block is the first EIP-1559 block, return the # initial base fee. - if com.isLondon(parent.blockNumber): - eip1559.calcEip1599BaseFee(parent.gasLimit, parent.gasUsed, parent.baseFee) + if com.isLondon(parent.number): + eip1559.calcEip1599BaseFee(parent.gasLimit, parent.gasUsed, parent.baseFeePerGas.get(0.u256)) else: EIP1559_INITIAL_BASE_FEE @@ -68,7 +68,7 @@ proc verifyEip1559Header(com: CommonRef; parent, header: BlockHeader): Result[void, string] {.raises: [].} = ## Verify that the gas limit remains within allowed bounds - let limit = if com.isLondon(parent.blockNumber): + let limit = if com.isLondon(parent.number): parent.gasLimit else: parent.gasLimit * EIP1559_ELASTICITY_MULTIPLIER @@ -76,7 +76,7 @@ proc verifyEip1559Header(com: CommonRef; if rc.isErr: return rc - let headerBaseFee = header.baseFee + let headerBaseFee = header.baseFeePerGas.get(0.u256) # Verify the header is not malformed if headerBaseFee.isZero: return err("Post EIP-1559 header expected to have base fee") @@ -86,8 +86,8 @@ proc verifyEip1559Header(com: CommonRef; if headerBaseFee != expectedBaseFee: try: return err(&"invalid baseFee: have {expectedBaseFee}, "& - &"want {header.baseFee}, " & - &"parent.baseFee {parent.baseFee}, "& + &"want {header.baseFeePerGas}, " & + &"parent.baseFee {parent.baseFeePerGas}, "& &"parent.gasUsed {parent.gasUsed}") except ValueError: # TODO deprecate-strformat @@ -98,10 +98,11 @@ proc verifyEip1559Header(com: CommonRef; proc validateGasLimitOrBaseFee*(com: CommonRef; header, parent: BlockHeader): Result[void, string] = - if not com.isLondon(header.blockNumber): + if not com.isLondon(header.number): # Verify BaseFee not present before EIP-1559 fork. - if not header.baseFee.isZero: - return err("invalid baseFee before London fork: have " & $header.baseFee & ", want <0>") + let baseFeePerGas = header.baseFeePerGas.get(0.u256) + if not baseFeePerGas.isZero: + return err("invalid baseFee before London fork: have " & $baseFeePerGas & ", want <0>") let rc = com.validateGasLimit(header) if rc.isErr: return rc diff --git a/nimbus/core/pow.nim b/nimbus/core/pow.nim index 0e17fac37..e711f7fc2 100644 --- a/nimbus/core/pow.nim +++ b/nimbus/core/pow.nim @@ -27,16 +27,16 @@ type PowDigest = tuple ##\ ## Return value from the `hashimotoLight()` function mixDigest: Hash256 - value: Hash256 + value : Hash256 PowSpecs* = object ##\ ## Relevant block header parts for PoW mining & verifying. This object ## might be more useful for testing and debugging than for production. - blockNumber*: BlockNumber + number* : BlockNumber miningHash*: Hash256 - nonce: BlockNonce - mixDigest*: Hash256 - difficulty: DifficultyInt + nonce : BlockNonce + mixHash* : Hash256 + difficulty : DifficultyInt PowHeader = object ##\ ## Stolen from `p2p/validate.MiningHeader` @@ -45,10 +45,10 @@ type coinbase : EthAddress stateRoot : Hash256 txRoot : Hash256 - receiptRoot : Hash256 - bloom : common.BloomFilter + receiptsRoot: Hash256 + logsBloom : common.BloomFilter difficulty : DifficultyInt - blockNumber : BlockNumber + number : BlockNumber gasLimit : GasInt gasUsed : GasInt timestamp : EthTime @@ -69,24 +69,24 @@ type func append(w: var RlpWriter; specs: PowSpecs) = ## RLP support w.startList(5) - w.append(HashOrNum(isHash: false, number: specs.blockNumber)) + w.append(HashOrNum(isHash: false, number: specs.number)) w.append(HashOrNum(isHash: true, hash: specs.miningHash)) w.append(specs.nonce.toUint) - w.append(HashOrNum(isHash: true, hash: specs.mixDigest)) + w.append(HashOrNum(isHash: true, hash: specs.mixHash)) w.append(specs.difficulty) func read(rlp: var Rlp; Q: type PowSpecs): Q {.raises: [RlpError].} = ## RLP support rlp.tryEnterList() - result.blockNumber = rlp.read(HashOrNum).number + result.number = rlp.read(HashOrNum).number result.miningHash = rlp.read(HashOrNum).hash result.nonce = rlp.read(uint64).toBlockNonce - result.mixDigest = rlp.read(HashOrNum).hash + result.mixHash = rlp.read(HashOrNum).hash result.difficulty = rlp.read(DifficultyInt) func rlpTextEncode(specs: PowSpecs): string = - "specs #" & $specs.blockNumber & " " & rlp.encode(specs).toHex + "specs #" & $specs.number & " " & rlp.encode(specs).toHex func decodeRlpText(data: string): PowSpecs {.raises: [CatchableError].} = @@ -108,10 +108,10 @@ func miningHash(header: BlockHeader): Hash256 = coinbase: header.coinbase, stateRoot: header.stateRoot, txRoot: header.txRoot, - receiptRoot: header.receiptRoot, - bloom: header.bloom, + receiptsRoot:header.receiptsRoot, + logsBloom: header.logsBloom, difficulty: header.difficulty, - blockNumber: header.blockNumber, + number: header.number, gasLimit: header.gasLimit, gasUsed: header.gasUsed, timestamp: header.timestamp, @@ -148,10 +148,10 @@ func getPowSpecs*(header: BlockHeader): PowSpecs = ## for mining or pow verification. This function might be more useful for ## testing and debugging than for production. PowSpecs( - blockNumber: header.blockNumber, + number: header.number, miningHash: header.miningHash, nonce: header.nonce, - mixDigest: header.mixDigest, + mixHash: header.mixHash, difficulty: header.difficulty) func getPowCacheLookup*(tm: PowRef; @@ -178,7 +178,7 @@ func getPowCacheLookup*(tm: PowRef; func getPowDigest(tm: PowRef; blockNumber: BlockNumber; powHeaderDigest: Hash256; nonce: BlockNonce): PowDigest = - ## Calculate the expected value of `header.mixDigest` using the + ## Calculate the expected value of `header.mixHash` using the ## `hashimotoLight()` library method. let ds = tm.lightByEpoch.get(blockNumber) @@ -187,11 +187,11 @@ func getPowDigest(tm: PowRef; blockNumber: BlockNumber; func getPowDigest*(tm: PowRef; header: BlockHeader): PowDigest = ## Variant of `getPowDigest()` - tm.getPowDigest(header.blockNumber, header.miningHash, header.nonce) + tm.getPowDigest(header.number, header.miningHash, header.nonce) func getPowDigest*(tm: PowRef; specs: PowSpecs): PowDigest = ## Variant of `getPowDigest()` - tm.getPowDigest(specs.blockNumber, specs.miningHash, specs.nonce) + tm.getPowDigest(specs.number, specs.miningHash, specs.nonce) # ------------------------------------------------------------------------------ # Public functions, debugging & testing diff --git a/nimbus/core/pow/difficulty.nim b/nimbus/core/pow/difficulty.nim index e6fc3e33b..2526c5805 100644 --- a/nimbus/core/pow/difficulty.nim +++ b/nimbus/core/pow/difficulty.nim @@ -1,5 +1,5 @@ # Nimbus -# Copyright (c) 2018-2023 Status Research & Development GmbH +# 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) @@ -56,7 +56,7 @@ func calcDifficultyFrontier*(timeStamp: EthTime, parent: BlockHeader): Difficult diff = max(diff, MinimumDifficultyU) - var periodCount = parent.blockNumber + bigOne + var periodCount = parent.number.u256 + bigOne difficultyBomb(periodCount) result = diff @@ -91,7 +91,7 @@ func calcDifficultyHomestead*(timeStamp: EthTime, parent: BlockHeader): Difficul var diff = cast[UInt256](max(x, MinimumDifficultyI)) # for the exponential factor - var periodCount = parent.blockNumber + bigOne + var periodCount = parent.number.u256 + bigOne difficultyBomb(periodCount) result = diff @@ -138,8 +138,8 @@ func makeDifficultyCalculator(bombDelay: static[int], timeStamp: EthTime, parent # calculate a fake block number for the ice-age delay # Specification: https:#eips.ethereum.org/EIPS/eip-1234 var periodCount: UInt256 - if parent.blockNumber >= bombDelayFromParent: - periodCount = parent.blockNumber - bombDelayFromParent + if parent.number.u256 >= bombDelayFromParent: + periodCount = parent.number.u256 - bombDelayFromParent difficultyBomb(periodCount) diff --git a/nimbus/core/pow/header.nim b/nimbus/core/pow/header.nim index c8f4ecbe4..2fed9b71b 100644 --- a/nimbus/core/pow/header.nim +++ b/nimbus/core/pow/header.nim @@ -1,5 +1,5 @@ # Nimbus -# Copyright (c) 2018 Status Research & Development GmbH +# 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) @@ -15,7 +15,7 @@ export BlockHeader proc hasUncles*(header: BlockHeader): bool = header.ommersHash != EMPTY_UNCLE_HASH proc `$`*(header: BlockHeader): string = - result = &"BlockHeader(timestamp: {header.timestamp} difficulty: {header.difficulty} blockNumber: {header.blockNumber} gasLimit: {header.gasLimit})" + result = &"BlockHeader(timestamp: {header.timestamp} difficulty: {header.difficulty} blockNumber: {header.number} gasLimit: {header.gasLimit})" # CalcGasLimit computes the gas limit of the next block after parent. It aims # to keep the baseline gas above the provided floor, and increase it towards the diff --git a/nimbus/core/pow/pow_cache.nim b/nimbus/core/pow/pow_cache.nim index dadf524eb..519e4c804 100644 --- a/nimbus/core/pow/pow_cache.nim +++ b/nimbus/core/pow/pow_cache.nim @@ -1,5 +1,5 @@ # Nimbus -# Copyright (c) 2018 Status Research & Development GmbH +# 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) @@ -45,7 +45,7 @@ const # ------------------------------------------------------------------------------ proc toKey(bn: BlockNumber): uint64 = - bn.truncate(uint64) div EPOCH_LENGTH + bn div EPOCH_LENGTH # ------------------------------------------------------------------------------ # Public functions, constructor diff --git a/nimbus/core/tx_pool.nim b/nimbus/core/tx_pool.nim index 9d622cf6c..6d41a4ad5 100644 --- a/nimbus/core/tx_pool.nim +++ b/nimbus/core/tx_pool.nim @@ -423,7 +423,7 @@ ## import - std/[options, sequtils, tables], + std/[sequtils, tables], ./tx_pool/[tx_chain, tx_desc, tx_info, tx_item], ./tx_pool/tx_tabs, ./tx_pool/tx_tasks/[ @@ -609,7 +609,7 @@ func dirtyBuckets*(xp: TxPoolRef): bool = type EthBlockAndBlobsBundle* = object blk*: EthBlock - blobsBundle*: Option[BlobsBundle] + blobsBundle*: Opt[BlobsBundle] proc assembleBlock*( xp: TxPoolRef, @@ -621,7 +621,7 @@ proc assembleBlock*( ## uninitialised: ## ## * *extraData*: Blob - ## * *mixDigest*: Hash256 + ## * *mixHash*: Hash256 ## * *nonce*: BlockNonce ## ## Note that this getter runs *ad hoc* all the txs through the VM in @@ -649,7 +649,7 @@ proc assembleBlock*( let com = xp.chain.com if com.forkGTE(Shanghai): - blk.withdrawals = some(com.pos.withdrawals) + blk.withdrawals = Opt.some(com.pos.withdrawals) if not com.forkGTE(Cancun) and blobsBundle.commitments.len > 0: return err("PooledTransaction contains blobs prior to Cancun") @@ -657,13 +657,13 @@ proc assembleBlock*( if com.forkGTE(Cancun): doAssert blobsBundle.commitments.len == blobsBundle.blobs.len doAssert blobsBundle.proofs.len == blobsBundle.blobs.len - options.some blobsBundle + Opt.some blobsBundle else: - options.none BlobsBundle + Opt.none BlobsBundle if someBaseFee: # make sure baseFee always has something - blk.header.fee = some(blk.header.fee.get(0.u256)) + blk.header.baseFeePerGas = Opt.some(blk.header.baseFeePerGas.get(0.u256)) ok EthBlockAndBlobsBundle( blk: blk, diff --git a/nimbus/core/tx_pool/tx_chain.nim b/nimbus/core/tx_pool/tx_chain.nim index f4871e2b9..490bac56d 100644 --- a/nimbus/core/tx_pool/tx_chain.nim +++ b/nimbus/core/tx_pool/tx_chain.nim @@ -53,9 +53,9 @@ type txRoot: Hash256 ## `rootHash` after packing stateRoot: Hash256 ## `stateRoot` after packing blobGasUsed: - Option[uint64] ## EIP-4844 block blobGasUsed + Opt[uint64] ## EIP-4844 block blobGasUsed excessBlobGas: - Option[uint64] ## EIP-4844 block excessBlobGas + Opt[uint64] ## EIP-4844 block excessBlobGas TxChainRef* = ref object ##\ ## State cache of the transaction environment for creating a new\ @@ -85,7 +85,7 @@ func getTimestamp(dh: TxChainRef, parent: BlockHeader): EthTime = func feeRecipient*(dh: TxChainRef): EthAddress -proc resetTxEnv(dh: TxChainRef; parent: BlockHeader; fee: Option[UInt256]) +proc resetTxEnv(dh: TxChainRef; parent: BlockHeader; baseFeePerGas: Opt[UInt256]) {.gcsafe,raises: [].} = dh.txEnv.reset @@ -94,7 +94,7 @@ proc resetTxEnv(dh: TxChainRef; parent: BlockHeader; fee: Option[UInt256]) let timestamp = dh.getTimestamp(parent) dh.com.hardForkTransition( - parent.blockHash, parent.blockNumber+1, Opt.some(timestamp)) + parent.blockHash, parent.number+1, Opt.some(timestamp)) dh.prepareHeader(parent, timestamp) # we don't consider PoS difficulty here @@ -102,7 +102,7 @@ proc resetTxEnv(dh: TxChainRef; parent: BlockHeader; fee: Option[UInt256]) let blockCtx = BlockContext( timestamp : dh.prepHeader.timestamp, gasLimit : (if dh.maxMode: dh.limits.maxLimit else: dh.limits.trgLimit), - fee : fee, + baseFeePerGas: baseFeePerGas, prevRandao : dh.prepHeader.prevRandao, difficulty : dh.prepHeader.difficulty, coinbase : dh.feeRecipient, @@ -116,8 +116,8 @@ proc resetTxEnv(dh: TxChainRef; parent: BlockHeader; fee: Option[UInt256]) dh.txEnv.txRoot = EMPTY_ROOT_HASH dh.txEnv.stateRoot = dh.txEnv.vmState.parent.stateRoot - dh.txEnv.blobGasUsed = none(uint64) - dh.txEnv.excessBlobGas = none(uint64) + dh.txEnv.blobGasUsed = Opt.none(uint64) + dh.txEnv.excessBlobGas = Opt.none(uint64) proc update(dh: TxChainRef; parent: BlockHeader) {.gcsafe,raises: [].} = @@ -126,10 +126,10 @@ proc update(dh: TxChainRef; parent: BlockHeader) timestamp = dh.getTimestamp(parent) db = dh.com.db acc = LedgerRef.init(db, parent.stateRoot) - fee = if dh.com.isLondon(parent.blockNumber + 1, timestamp): - some(dh.com.baseFeeGet(parent).uint64.u256) + fee = if dh.com.isLondon(parent.number + 1, timestamp): + Opt.some(dh.com.baseFeeGet(parent).uint64.u256) else: - UInt256.none() + Opt.none UInt256 # Keep a separate accounts descriptor positioned at the sync point dh.roAcc = ReadOnlyStateDB(acc) @@ -179,37 +179,37 @@ proc getHeader*(dh: TxChainRef): BlockHeader else: dh.txEnv.receipts[^1].cumulativeGasUsed result = BlockHeader( - parentHash: dh.txEnv.vmState.parent.blockHash, - ommersHash: EMPTY_UNCLE_HASH, - coinbase: dh.prepHeader.coinbase, - stateRoot: dh.txEnv.stateRoot, - txRoot: dh.txEnv.txRoot, - receiptRoot: dh.txEnv.receipts.calcReceiptRoot, - bloom: dh.txEnv.receipts.createBloom, - difficulty: dh.prepHeader.difficulty, - blockNumber: dh.txEnv.vmState.blockNumber, - gasLimit: dh.txEnv.vmState.blockCtx.gasLimit, - gasUsed: gasUsed, - timestamp: dh.prepHeader.timestamp, - # extraData: Blob # signing data - # mixDigest: Hash256 # mining hash for given difficulty - # nonce: BlockNonce # mining free vaiable - fee: dh.txEnv.vmState.blockCtx.fee, - blobGasUsed: dh.txEnv.blobGasUsed, + parentHash: dh.txEnv.vmState.parent.blockHash, + ommersHash: EMPTY_UNCLE_HASH, + coinbase: dh.prepHeader.coinbase, + stateRoot: dh.txEnv.stateRoot, + txRoot: dh.txEnv.txRoot, + receiptsRoot: dh.txEnv.receipts.calcReceiptsRoot, + logsBloom: dh.txEnv.receipts.createBloom, + difficulty: dh.prepHeader.difficulty, + number: dh.txEnv.vmState.blockNumber, + gasLimit: dh.txEnv.vmState.blockCtx.gasLimit, + gasUsed: gasUsed, + timestamp: dh.prepHeader.timestamp, + # extraData: Blob # signing data + # mixHash: Hash256 # mining hash for given difficulty + # nonce: BlockNonce # mining free vaiable + baseFeePerGas: dh.txEnv.vmState.blockCtx.baseFeePerGas, + blobGasUsed: dh.txEnv.blobGasUsed, excessBlobGas: dh.txEnv.excessBlobGas) if dh.com.forkGTE(Shanghai): - result.withdrawalsRoot = some(calcWithdrawalsRoot(dh.com.pos.withdrawals)) + result.withdrawalsRoot = Opt.some(calcWithdrawalsRoot(dh.com.pos.withdrawals)) if dh.com.forkGTE(Cancun): - result.parentBeaconBlockRoot = some(dh.com.pos.parentBeaconBlockRoot) + result.parentBeaconBlockRoot = Opt.some(dh.com.pos.parentBeaconBlockRoot) dh.prepareForSeal(result) proc clearAccounts*(dh: TxChainRef) {.gcsafe,raises: [].} = ## Reset transaction environment, e.g. before packing a new block - dh.resetTxEnv(dh.txEnv.vmState.parent, dh.txEnv.vmState.blockCtx.fee) + dh.resetTxEnv(dh.txEnv.vmState.parent, dh.txEnv.vmState.blockCtx.baseFeePerGas) # ------------------------------------------------------------------------------ # Public functions, getters @@ -242,8 +242,8 @@ func feeRecipient*(dh: TxChainRef): EthAddress = func baseFee*(dh: TxChainRef): GasPrice = ## Getter, baseFee for the next bock header. This value is auto-generated ## when a new insertion point is set via `head=`. - if dh.txEnv.vmState.blockCtx.fee.isSome: - dh.txEnv.vmState.blockCtx.fee.get.truncate(uint64).GasPrice + if dh.txEnv.vmState.blockCtx.baseFeePerGas.isSome: + dh.txEnv.vmState.blockCtx.baseFeePerGas.get.truncate(uint64).GasPrice else: 0.GasPrice @@ -294,9 +294,9 @@ func `baseFee=`*(dh: TxChainRef; val: GasPrice) = ## function would be called in exceptional cases only as this parameter is ## determined by the `head=` update. if 0 < val or dh.com.isLondon(dh.txEnv.vmState.blockNumber): - dh.txEnv.vmState.blockCtx.fee = some(val.uint64.u256) + dh.txEnv.vmState.blockCtx.baseFeePerGas = Opt.some(val.uint64.u256) else: - dh.txEnv.vmState.blockCtx.fee = UInt256.none() + dh.txEnv.vmState.blockCtx.baseFeePerGas = Opt.none UInt256 proc `head=`*(dh: TxChainRef; val: BlockHeader) {.gcsafe,raises: [].} = @@ -342,11 +342,11 @@ func `txRoot=`*(dh: TxChainRef; val: Hash256) = ## Setter dh.txEnv.txRoot = val -func `excessBlobGas=`*(dh: TxChainRef; val: Option[uint64]) = +func `excessBlobGas=`*(dh: TxChainRef; val: Opt[uint64]) = ## Setter dh.txEnv.excessBlobGas = val -func `blobGasUsed=`*(dh: TxChainRef; val: Option[uint64]) = +func `blobGasUsed=`*(dh: TxChainRef; val: Opt[uint64]) = ## Setter dh.txEnv.blobGasUsed = val diff --git a/nimbus/core/tx_pool/tx_chain/tx_basefee.nim b/nimbus/core/tx_pool/tx_chain/tx_basefee.nim index 029fbdc9f..385311786 100644 --- a/nimbus/core/tx_pool/tx_chain/tx_basefee.nim +++ b/nimbus/core/tx_pool/tx_chain/tx_basefee.nim @@ -1,5 +1,5 @@ # Nimbus -# Copyright (c) 2018 Status Research & Development GmbH +# 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) @@ -51,7 +51,7 @@ proc baseFeeGet*(com: CommonRef; parent: BlockHeader): GasPrice = # or truncate the result? calcEip1599BaseFee(parent.gasLimit, parent.gasUsed, - parent.baseFee).truncate(uint64).GasPrice + parent.baseFeePerGas.get(0.u256)).truncate(uint64).GasPrice # ------------------------------------------------------------------------------ # End diff --git a/nimbus/core/tx_pool/tx_chain/tx_gaslimits.nim b/nimbus/core/tx_pool/tx_chain/tx_gaslimits.nim index e0cc1dc32..e2cd372f4 100644 --- a/nimbus/core/tx_pool/tx_chain/tx_gaslimits.nim +++ b/nimbus/core/tx_pool/tx_chain/tx_gaslimits.nim @@ -1,5 +1,5 @@ # Nimbus -# Copyright (c) 2018 Status Research & Development GmbH +# 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) @@ -95,7 +95,7 @@ proc gasLimitsGet*(com: CommonRef; parent: BlockHeader; parentLimit: GasInt; ## Calculate gas limits for the next block header. result.gasLimit = parentLimit - if com.isLondon(parent.blockNumber+1): + if com.isLondon(parent.number+1): result.setPostLondonLimits else: result.setPreLondonLimits @@ -108,9 +108,9 @@ proc gasLimitsGet*(com: CommonRef; parent: BlockHeader; parentLimit: GasInt; result.trgLimit, (result.maxLimit * pc.hwmMax + 50) div 100) # override trgLimit, see https://github.com/status-im/nimbus-eth1/issues/1032 - if com.isLondon(parent.blockNumber+1): + if com.isLondon(parent.number+1): var parentGasLimit = parent.gasLimit - if not com.isLondon(parent.blockNumber): + if not com.isLondon(parent.number): # Bump by 2x parentGasLimit = parent.gasLimit * EIP1559_ELASTICITY_MULTIPLIER result.trgLimit = calcGasLimit1559(parentGasLimit, desiredLimit = pc.gasCeil) diff --git a/nimbus/core/tx_pool/tx_item.nim b/nimbus/core/tx_pool/tx_item.nim index 9a12ef7c9..e89e27f36 100644 --- a/nimbus/core/tx_pool/tx_item.nim +++ b/nimbus/core/tx_pool/tx_item.nim @@ -168,7 +168,7 @@ proc effectiveGasTip*(tx: Transaction; baseFee: GasPrice): GasPriceEx = (tx.gasPrice - baseFee.int64).GasPriceEx else: # London, EIP1559 - min(tx.maxPriorityFee, tx.maxFee - baseFee.int64).GasPriceEx + min(tx.maxPriorityFeePerGas, tx.maxFeePerGas - baseFee.int64).GasPriceEx proc effectiveGasTip*(tx: Transaction; baseFee: UInt256): GasPriceEx = ## Variant of `effectiveGasTip()` diff --git a/nimbus/core/tx_pool/tx_tabs/tx_sender.nim b/nimbus/core/tx_pool/tx_tabs/tx_sender.nim index 3c4fca54e..f3cdc17fa 100644 --- a/nimbus/core/tx_pool/tx_tabs/tx_sender.nim +++ b/nimbus/core/tx_pool/tx_tabs/tx_sender.nim @@ -15,7 +15,6 @@ ## import - std/[math], ../tx_info, ../tx_item, eth/[common], diff --git a/nimbus/core/tx_pool/tx_tasks/tx_classify.nim b/nimbus/core/tx_pool/tx_tasks/tx_classify.nim index dedb6a240..42199cec1 100644 --- a/nimbus/core/tx_pool/tx_tasks/tx_classify.nim +++ b/nimbus/core/tx_pool/tx_tasks/tx_classify.nim @@ -107,9 +107,9 @@ proc txFeesCovered(xp: TxPoolRef; item: TxItemRef): bool = ## Ensure that the user was willing to at least pay the base fee ## And to at least pay the current data gasprice if item.tx.txType >= TxEip1559: - if item.tx.maxFee.GasPriceEx < xp.chain.baseFee: + if item.tx.maxFeePerGas.GasPriceEx < xp.chain.baseFee: debug "invalid tx: maxFee is smaller than baseFee", - maxFee = item.tx.maxFee, + maxFee = item.tx.maxFeePerGas, baseFee = xp.chain.baseFee return false @@ -168,7 +168,7 @@ proc txPostLondonAcceptableTipAndFees(xp: TxPoolRef; item: TxItemRef): bool = return false if stageItems1559MinFee in xp.pFlags: - if item.tx.maxFee.GasPriceEx < xp.pMinFeePrice: + if item.tx.maxFeePerGas.GasPriceEx < xp.pMinFeePrice: return false true diff --git a/nimbus/core/tx_pool/tx_tasks/tx_head.nim b/nimbus/core/tx_pool/tx_tasks/tx_head.nim index aeb53bca6..8b4fd725c 100644 --- a/nimbus/core/tx_pool/tx_tasks/tx_head.nim +++ b/nimbus/core/tx_pool/tx_tasks/tx_head.nim @@ -133,22 +133,22 @@ proc headDiff*(xp: TxPoolRef; # sanity check warn "Tx-pool head forward for non-existing header", newHead = newHash, - newNumber = newHead.blockNumber + newNumber = newHead.number return err(txInfoErrForwardHeadMissing) if not db.getBlockHeader(curHash, ignHeader): # This can happen if a `setHead()` is performed, where we have discarded # the old head from the chain. - if curHead.blockNumber <= newHead.blockNumber: + if curHead.number <= newHead.number: warn "Tx-pool head forward from detached current header", curHead = curHash, - curNumber = curHead.blockNumber + curNumber = curHead.number return err(txInfoErrAncestorMissing) debug "Tx-pool reset with detached current head", curHeader = curHash, - curNumber = curHead.blockNumber, + curNumber = curHead.number, newHeader = newHash, - newNumber = newHead.blockNumber + newNumber = newHead.number return err(txInfoErrChainHeadMissing) # Equalise block numbers between branches (typically, these btanches @@ -161,7 +161,7 @@ proc headDiff*(xp: TxPoolRef; newBranchHead = newHead newBranchHash = newHash - if newHead.blockNumber < curHead.blockNumber: + if newHead.number < curHead.number: # # new head block number smaller than the current head one # @@ -178,7 +178,7 @@ proc headDiff*(xp: TxPoolRef; # + txs of blocks with numbers between #new..#current need to be # re-inserted into the pool # - while newHead.blockNumber < curBranchHead.blockNumber: + while newHead.number < curBranchHead.number: xp.insert(txDiffs, curBranchHash) let tmpHead = curBranchHead # cache value for error logging @@ -187,7 +187,7 @@ proc headDiff*(xp: TxPoolRef; if not db.getBlockHeader(curBranchHash, curBranchHead): error "Unrooted old chain seen by tx-pool", curBranchHead = tmpHash, - curBranchNumber = tmpHead.blockNumber + curBranchNumber = tmpHead.number return err(txInfoErrUnrootedCurChain) else: # @@ -206,7 +206,7 @@ proc headDiff*(xp: TxPoolRef; # + txs of blocks with numbers between #current..#new need to be # deleted from the pool (as they are on the block chain, now) # - while curHead.blockNumber < newBranchHead.blockNumber: + while curHead.number < newBranchHead.number: xp.remove(txDiffs, newBranchHash) let tmpHead = newBranchHead # cache value for error logging @@ -215,7 +215,7 @@ proc headDiff*(xp: TxPoolRef; if not db.getBlockHeader(newBranchHash, newBranchHead): error "Unrooted new chain seen by tx-pool", newBranchHead = tmpHash, - newBranchNumber = tmpHead.blockNumber + newBranchNumber = tmpHead.number return err(txInfoErrUnrootedNewChain) # simultaneously step back until junction-head (aka common ancestor) while @@ -231,7 +231,7 @@ proc headDiff*(xp: TxPoolRef; if not db.getBlockHeader(curBranchHash, curBranchHead): error "Unrooted old chain seen by tx-pool", curBranchHead = tmpHash, - curBranchNumber = tmpHead.blockNumber + curBranchNumber = tmpHead.number return err(txInfoErrUnrootedCurChain) block: xp.remove(txDiffs, newBranchHash) @@ -242,7 +242,7 @@ proc headDiff*(xp: TxPoolRef; if not db.getBlockHeader(newBranchHash, newBranchHead): error "Unrooted new chain seen by tx-pool", newBranchHead = tmpHash, - newBranchNumber = tmpHead.blockNumber + newBranchNumber = tmpHead.number return err(txInfoErrUnrootedNewChain) # figure out difference sets diff --git a/nimbus/core/tx_pool/tx_tasks/tx_packer.nim b/nimbus/core/tx_pool/tx_tasks/tx_packer.nim index 77ecc4354..615836c55 100644 --- a/nimbus/core/tx_pool/tx_tasks/tx_packer.nim +++ b/nimbus/core/tx_pool/tx_tasks/tx_packer.nim @@ -159,7 +159,7 @@ proc vmExecInit(xp: TxPoolRef): Result[TxPackerStateRef, string] xp.chain.maxMode = (packItemsMaxGasLimit in xp.pFlags) if xp.chain.com.daoForkSupport and - xp.chain.com.daoForkBlock.get == xp.chain.head.blockNumber + 1: + xp.chain.com.daoForkBlock.get == xp.chain.head.number + 1: xp.chain.vmState.mutateStateDB: db.applyDAOHardFork() @@ -261,8 +261,8 @@ proc vmExecCommit(pst: TxPackerStateRef) if vmState.com.forkGTE(Cancun): # EIP-4844 - xp.chain.excessBlobGas = some(vmState.blockCtx.excessBlobGas) - xp.chain.blobGasUsed = some(pst.blobGasUsed) + xp.chain.excessBlobGas = Opt.some(vmState.blockCtx.excessBlobGas) + xp.chain.blobGasUsed = Opt.some(pst.blobGasUsed) proc balanceDelta: UInt256 = let postBalance = vmState.readOnlyStateDB.getBalance(xp.chain.feeRecipient) diff --git a/nimbus/core/validate.nim b/nimbus/core/validate.nim index 48cee646d..73d4c5058 100644 --- a/nimbus/core/validate.nim +++ b/nimbus/core/validate.nim @@ -39,18 +39,18 @@ const proc validateSeal(pow: PowRef; header: BlockHeader): Result[void,string] = try: - let (expMixDigest, miningValue) = pow.getPowDigest(header) + let (expmixHash, miningValue) = pow.getPowDigest(header) - if expMixDigest != header.mixDigest: + if expmixHash != header.mixHash: let miningHash = header.getPowSpecs.miningHash - (size, cachedHash) = try: pow.getPowCacheLookup(header.blockNumber) + (size, cachedHash) = try: pow.getPowCacheLookup(header.number) except KeyError: return err("Unknown block") except CatchableError as e: return err(e.msg) return err("mixHash mismatch. actual=$1, expected=$2," & " blockNumber=$3, miningHash=$4, nonce=$5, difficulty=$6," & " size=$7, cachedHash=$8" % [ - $header.mixDigest, $expMixDigest, $header.blockNumber, + $header.mixHash, $expmixHash, $header.number, $miningHash, header.nonce.toHex, $header.difficulty, $size, $cachedHash]) @@ -77,7 +77,7 @@ proc validateHeader( # Blocks with block numbers in the range [1_920_000, 1_920_009] # MUST have DAOForkBlockExtra let daoForkBlock = com.daoForkBlock.get - let DAOHigh = daoForkBlock + DAOForkExtraRange.u256 + let DAOHigh = daoForkBlock + DAOForkExtraRange daoForkBlock <= blockNumber and blockNumber < DAOHigh @@ -90,19 +90,19 @@ proc validateHeader( if header.gasUsed < 0 or header.gasUsed > header.gasLimit: return err("gasUsed should be non negative and smaller or equal gasLimit") - if header.blockNumber != parentHeader.blockNumber + 1: + if header.number != parentHeader.number + 1: return err("Blocks must be numbered consecutively") if header.timestamp <= parentHeader.timestamp: return err("timestamp must be strictly later than parent") - if com.daoForkSupport and inDAOExtraRange(header.blockNumber): + if com.daoForkSupport and inDAOExtraRange(header.number): if header.extraData != daoForkBlockExtraData: return err("header extra data should be marked DAO") if com.consensus == ConsensusType.POS: # EIP-4399 and EIP-3675 - # no need to check mixDigest because EIP-4399 override this field + # no need to check mixHash because EIP-4399 override this field # checking rule if not header.difficulty.isZero: @@ -185,7 +185,7 @@ proc validateUncles(com: CommonRef; header: BlockHeader; (uncle.parentHash == header.parentHash): return err("Uncle's parent is not an ancestor") - if uncle.blockNumber >= header.blockNumber: + if uncle.number >= header.number: return err("uncle block number larger than current block number") # check uncle against own parent @@ -215,9 +215,9 @@ proc validateUncles(com: CommonRef; header: BlockHeader; func gasCost*(tx: Transaction): UInt256 = if tx.txType >= TxEip4844: - tx.gasLimit.u256 * tx.maxFee.u256 + tx.getTotalBlobGas.u256 * tx.maxFeePerBlobGas.u256 + tx.gasLimit.u256 * tx.maxFeePerGas.u256 + tx.getTotalBlobGas.u256 * tx.maxFeePerBlobGas elif tx.txType >= TxEip1559: - tx.gasLimit.u256 * tx.maxFee.u256 + tx.gasLimit.u256 * tx.maxFeePerGas.u256 else: tx.gasLimit.u256 * tx.gasPrice.u256 @@ -241,9 +241,9 @@ proc validateTxBasic*( try: # The total must be the larger of the two - if tx.maxFee < tx.maxPriorityFee: + if tx.maxFeePerGas < tx.maxPriorityFeePerGas: return err("invalid tx: maxFee is smaller than maPriorityFee. maxFee=$1, maxPriorityFee=$2" % [ - $tx.maxFee, $tx.maxPriorityFee]) + $tx.maxFeePerGas, $tx.maxPriorityFeePerGas]) if tx.gasLimit < tx.intrinsicGas(fork): return err("invalid tx: not enough gas to perform calculation. avail=$1, require=$2" % [ @@ -322,9 +322,9 @@ proc validateTransaction*( $maxLimit, $tx.gasLimit]) # ensure that the user was willing to at least pay the base fee - if tx.maxFee < baseFee.truncate(int64): + if tx.maxFeePerGas < baseFee.truncate(GasInt): return err("invalid tx: maxFee is smaller than baseFee. maxFee=$1, baseFee=$2" % [ - $tx.maxFee, $baseFee]) + $tx.maxFeePerGas, $baseFee]) # the signer must be able to fully afford the transaction let gasCost = tx.gasCost() diff --git a/nimbus/core/withdrawals.nim b/nimbus/core/withdrawals.nim index 2eae50a1d..e0553351c 100644 --- a/nimbus/core/withdrawals.nim +++ b/nimbus/core/withdrawals.nim @@ -14,7 +14,7 @@ import results, ../common/common # https://eips.ethereum.org/EIPS/eip-4895 proc validateWithdrawals*( - com: CommonRef, header: BlockHeader, withdrawals: Option[seq[Withdrawal]] + com: CommonRef, header: BlockHeader, withdrawals: Opt[seq[Withdrawal]] ): Result[void, string] = if com.forkGTE(Shanghai): if header.withdrawalsRoot.isNone: @@ -24,7 +24,7 @@ proc validateWithdrawals*( else: try: if withdrawals.get.calcWithdrawalsRoot != header.withdrawalsRoot.get: - return err("Mismatched withdrawalsRoot blockNumber =" & $header.blockNumber) + return err("Mismatched withdrawalsRoot blockNumber =" & $header.number) except RlpError as ex: return err(ex.msg) else: diff --git a/nimbus/db/aristo/aristo_desc/desc_identifiers.nim b/nimbus/db/aristo/aristo_desc/desc_identifiers.nim index 658336fc5..7ab6573ae 100644 --- a/nimbus/db/aristo/aristo_desc/desc_identifiers.nim +++ b/nimbus/db/aristo/aristo_desc/desc_identifiers.nim @@ -300,10 +300,14 @@ func to*(key: Hash256; T: type HashKey): T = else: T(len: 32, buf: key.data) -func to*(n: SomeUnsignedInt|UInt256; T: type PathID): T = +func to*(n: SomeUnsignedInt; T: type PathID): T = ## Representation of a scalar as `PathID` (preserving full information) T(pfx: n.u256, length: 64) +func to*(n: UInt256; T: type PathID): T = + ## Representation of a scalar as `PathID` (preserving full information) + T(pfx: n, length: 64) + # ------------------------------------------------------------------------------ # Public helpers: Miscellaneous mappings # ------------------------------------------------------------------------------ diff --git a/nimbus/db/core_db/backend/aristo_db.nim b/nimbus/db/core_db/backend/aristo_db.nim index 4a2a40c65..43ce88abd 100644 --- a/nimbus/db/core_db/backend/aristo_db.nim +++ b/nimbus/db/core_db/backend/aristo_db.nim @@ -13,7 +13,6 @@ import std/tables, eth/common, - results, ../../aristo as use_ari, ../../aristo/aristo_walk, ../../kvt as use_kvt, @@ -134,11 +133,11 @@ proc baseMethods(db: AristoCoreDbRef): CoreDbBaseFns = db.tracer.push(flags) CoreDxCaptRef(methods: db.tracer.cptMethods) - proc persistent(bn: Option[BlockNumber]): CoreDbRc[void] = + proc persistent(bn: Opt[BlockNumber]): CoreDbRc[void] = const info = "persistentFn()" let sid = if bn.isNone: 0u64 - else: bn.unsafeGet.truncate(uint64) + else: bn.unsafeGet ? kBase.persistent info ? aBase.persistent(sid, info) ok() @@ -183,7 +182,7 @@ proc baseMethods(db: AristoCoreDbRef): CoreDbBaseFns = newCaptureFn: proc(flags: set[CoreDbCaptFlags]): CoreDbRc[CoreDxCaptRef] = ok(db.bless flags.tracerSetup()), - persistentFn: proc(bn: Option[BlockNumber]): CoreDbRc[void] = + persistentFn: proc(bn: Opt[BlockNumber]): CoreDbRc[void] = persistent(bn)) # ------------------------------------------------------------------------------ @@ -247,8 +246,8 @@ proc toAristoSavedStateBlockNumber*( if not mBe.isNil and mBe.parent.isAristo: let rc = mBe.parent.AristoCoreDbRef.adbBase.getSavedState() if rc.isOk: - return (rc.value.src.to(Hash256), rc.value.serial.toBlockNumber) - (EMPTY_ROOT_HASH, 0.toBlockNumber) + return (rc.value.src.to(Hash256), rc.value.serial.BlockNumber) + (EMPTY_ROOT_HASH, 0.BlockNumber) # ------------------------------------------------------------------------------ # Public aristo iterators diff --git a/nimbus/db/core_db/backend/aristo_db/handlers_aristo.nim b/nimbus/db/core_db/backend/aristo_db/handlers_aristo.nim index 72a157514..d59621388 100644 --- a/nimbus/db/core_db/backend/aristo_db/handlers_aristo.nim +++ b/nimbus/db/core_db/backend/aristo_db/handlers_aristo.nim @@ -11,11 +11,10 @@ {.push raises: [].} import - std/[options, strutils, typetraits], + std/[strutils, typetraits], chronicles, eth/[common, trie/nibbles], stew/byteutils, - results, ../../../aristo, ../../../aristo/aristo_desc, ../../base, @@ -433,7 +432,7 @@ proc ctxMethods(cCtx: AristoCoreDbCtxRef): CoreDbCtxFns = proc ctxNewCol( colType: CoreDbColType; colState: Hash256; - address: Option[EthAddress]; + address: Opt[EthAddress]; ): CoreDbRc[CoreDbColRef] = const info = "ctx/newColFn()" @@ -533,7 +532,7 @@ proc ctxMethods(cCtx: AristoCoreDbCtxRef): CoreDbCtxFns = newColFn: proc( col: CoreDbColType; colState: Hash256; - address: Option[EthAddress]; + address: Opt[EthAddress]; ): CoreDbRc[CoreDbColRef] = ctxNewCol(col, colState, address), diff --git a/nimbus/db/core_db/base.nim b/nimbus/db/core_db/base.nim index a521c76b9..e4dab1370 100644 --- a/nimbus/db/core_db/base.nim +++ b/nimbus/db/core_db/base.nim @@ -11,10 +11,8 @@ {.push raises: [].} import - std/options, chronicles, eth/common, - results, "../.."/[constants, errors], ./base/[api_tracking, base_desc] @@ -418,7 +416,7 @@ proc newColumn*( ctx: CoreDbCtxRef; colType: CoreDbColType; colState: Hash256; - address = none(EthAddress); + address = Opt.none(EthAddress); ): CoreDbRc[CoreDbColRef] = ## Retrieve a new column descriptor. ## @@ -463,7 +461,7 @@ proc newColumn*( ## Shortcut for `ctx.newColumn(CtStorage,colState,some(address))`. ## ctx.setTrackNewApi CtxNewColFn - result = ctx.methods.newColFn(CtStorage, colState, some(address)) + result = ctx.methods.newColFn(CtStorage, colState, Opt.some(address)) ctx.ifTrackNewApi: debug newApiTxt, api, elapsed, colState, address, result proc newColumn*( @@ -476,7 +474,7 @@ proc newColumn*( ## ctx.setTrackNewApi CtxNewColFn result = ctx.methods.newColFn( - CtStorage, EMPTY_ROOT_HASH, some(address)).valueOr: + CtStorage, EMPTY_ROOT_HASH, Opt.some(address)).valueOr: raiseAssert error.prettyText() ctx.ifTrackNewApi: debug newApiTxt, api, elapsed, address, result @@ -533,7 +531,7 @@ proc getMpt*( proc getMpt*( ctx: CoreDbCtxRef; colType: CoreDbColType; - address = none(EthAddress); + address = Opt.none(EthAddress); ): CoreDxMptRef = ## Shortcut for `getMpt(col)` where the `col` argument is ## `db.getColumn(colType,EMPTY_ROOT_HASH).value`. This function will always @@ -830,7 +828,7 @@ proc persistent*( ## is no transaction pending. ## db.setTrackNewApi BasePersistentFn - result = db.methods.persistentFn none(BlockNumber) + result = db.methods.persistentFn Opt.none(BlockNumber) db.ifTrackNewApi: debug newApiTxt, api, elapsed, result proc persistent*( @@ -859,7 +857,7 @@ proc persistent*( ## db.persistent(stateBlockNumber) ## db.setTrackNewApi BasePersistentFn - result = db.methods.persistentFn some(blockNumber) + result = db.methods.persistentFn Opt.some(blockNumber) db.ifTrackNewApi: debug newApiTxt, api, elapsed, blockNumber, result proc newTransaction*(db: CoreDbRef): CoreDxTxRef = @@ -1013,7 +1011,7 @@ when ProvideLegacyAPI: db.setTrackLegaApi LegaNewMptFn let trie = db.ctx.methods.newColFn( - CtGeneric, root, none(EthAddress)).valueOr: + CtGeneric, root, Opt.none(EthAddress)).valueOr: raiseAssert error.prettyText() & ": " & $api mpt = db.ctx.getMpt(trie).valueOr: raiseAssert error.prettyText() & ": " & $api @@ -1022,7 +1020,7 @@ when ProvideLegacyAPI: proc mptPrune*(db: CoreDbRef): CoreDbMptRef = db.setTrackLegaApi LegaNewMptFn - result = db.ctx.getMpt(CtGeneric, none(EthAddress)).CoreDbMptRef + result = db.ctx.getMpt(CtGeneric, Opt.none(EthAddress)).CoreDbMptRef db.ifTrackLegaApi: debug legaApiTxt, api, elapsed # ---------------- @@ -1036,7 +1034,7 @@ when ProvideLegacyAPI: db.setTrackLegaApi LegaNewPhkFn let trie = db.ctx.methods.newColFn( - CtGeneric, root, none(EthAddress)).valueOr: + CtGeneric, root, Opt.none(EthAddress)).valueOr: raiseAssert error.prettyText() & ": " & $api phk = db.ctx.getMpt(trie).valueOr: raiseAssert error.prettyText() & ": " & $api @@ -1046,7 +1044,7 @@ when ProvideLegacyAPI: proc phkPrune*(db: CoreDbRef): CoreDbPhkRef = db.setTrackLegaApi LegaNewPhkFn result = db.ctx.getMpt( - CtGeneric, none(EthAddress)).toCoreDxPhkRef.CoreDbPhkRef + CtGeneric, Opt.none(EthAddress)).toCoreDxPhkRef.CoreDbPhkRef db.ifTrackLegaApi: debug legaApiTxt, api, elapsed # ---------------- diff --git a/nimbus/db/core_db/base/base_desc.nim b/nimbus/db/core_db/base/base_desc.nim index cc4381513..f342267f9 100644 --- a/nimbus/db/core_db/base/base_desc.nim +++ b/nimbus/db/core_db/base/base_desc.nim @@ -13,7 +13,6 @@ import std/tables, eth/common, - results, ../../aristo/aristo_profile from ../../aristo @@ -113,7 +112,7 @@ type proc(flgs: set[CoreDbCaptFlags]): CoreDbRc[CoreDxCaptRef] {.noRaise.} CoreDbBaseGetCaptFn* = proc(): CoreDbRc[CoreDxCaptRef] {.noRaise.} CoreDbBasePersistentFn* = - proc(bn: Option[BlockNumber]): CoreDbRc[void] {.noRaise.} + proc(bn: Opt[BlockNumber]): CoreDbRc[void] {.noRaise.} CoreDbBaseFns* = object destroyFn*: CoreDbBaseDestroyFn @@ -166,7 +165,7 @@ type CoreDbCtxFromTxFn* = proc(root: Hash256; kind: CoreDbColType): CoreDbRc[CoreDbCtxRef] {.noRaise.} CoreDbCtxNewColFn* = proc( - colType: CoreDbColType; colState: Hash256; address: Option[EthAddress]; + colType: CoreDbColType; colState: Hash256; address: Opt[EthAddress]; ): CoreDbRc[CoreDbColRef] {.noRaise.} CoreDbCtxGetMptFn* = proc( root: CoreDbColRef): CoreDbRc[CoreDxMptRef] {.noRaise.} diff --git a/nimbus/db/core_db/core_apps_newapi.nim b/nimbus/db/core_db/core_apps_newapi.nim index c62d1249c..4c069c9e4 100644 --- a/nimbus/db/core_db/core_apps_newapi.nim +++ b/nimbus/db/core_db/core_apps_newapi.nim @@ -14,10 +14,9 @@ {.push raises: [].} import - std/[algorithm, options, sequtils], + std/[algorithm, sequtils], chronicles, eth/[common, rlp], - results, stew/byteutils, "../.."/[errors, constants], ".."/[aristo, storage_types], @@ -30,7 +29,7 @@ logScope: type TransactionKey = tuple blockNumber: BlockNumber - index: int + index: uint const extraTraceMessages = false @@ -101,7 +100,7 @@ iterator findNewAncestors( var h = header var orig: BlockHeader while true: - if db.getBlockHeader(h.blockNumber, orig) and orig.rlpHash == h.rlpHash: + if db.getBlockHeader(h.number, orig) and orig.rlpHash == h.rlpHash: break yield h @@ -135,7 +134,7 @@ iterator getBlockTransactionData*( warn logTxt "getBlockTransactionData()", transactionRoot, action="newMpt()", col=($$col), error=($$error) break body - var transactionIdx = 0 + var transactionIdx = 0'u64 while true: let transactionKey = rlp.encode(transactionIdx) let data = transactionDb.fetch(transactionKey).valueOr: @@ -186,7 +185,7 @@ iterator getWithdrawalsData*( break body var idx = 0 while true: - let wdKey = rlp.encode(idx) + let wdKey = rlp.encode(idx.uint) let data = wddb.fetch(wdKey).valueOr: if error.error != MptNotFound: warn logTxt "getWithdrawalsData()", @@ -198,30 +197,30 @@ iterator getWithdrawalsData*( iterator getReceipts*( db: CoreDbRef; - receiptRoot: Hash256; + receiptsRoot: Hash256; ): Receipt {.gcsafe, raises: [RlpError].} = block body: - if receiptRoot == EMPTY_ROOT_HASH: + if receiptsRoot == EMPTY_ROOT_HASH: break body let ctx = db.ctx - col = ctx.newColumn(CtReceipts, receiptRoot).valueOr: + col = ctx.newColumn(CtReceipts, receiptsRoot).valueOr: warn logTxt "getWithdrawalsData()", - receiptRoot, action="newColumn()", error=($$error) + receiptsRoot, action="newColumn()", error=($$error) break body receiptDb = ctx.getMpt(col).valueOr: warn logTxt "getWithdrawalsData()", - receiptRoot, action="getMpt()", col=($$col), error=($$error) + receiptsRoot, action="getMpt()", col=($$col), error=($$error) break body var receiptIdx = 0 while true: - let receiptKey = rlp.encode(receiptIdx) + let receiptKey = rlp.encode(receiptIdx.uint) let receiptData = receiptDb.fetch(receiptKey).valueOr: if error.error != MptNotFound: warn logTxt "getWithdrawalsData()", - receiptRoot, receiptKey, action="hasKey()", error=($$error) + receiptsRoot, receiptKey, action="hasKey()", error=($$error) break body yield rlp.decode(receiptData, Receipt) inc receiptIdx @@ -249,13 +248,13 @@ proc setAsCanonicalChainHead( # TODO This code handles reorgs - this should be moved elsewhere because we'll # be handling reorgs mainly in-memory - if header.blockNumber == 0 or + if header.number == 0 or db.getCanonicalHeaderHash().valueOr(Hash256()) != header.parentHash: var newCanonicalHeaders = sequtils.toSeq(db.findNewAncestors(header)) reverse(newCanonicalHeaders) for h in newCanonicalHeaders: var oldHash: Hash256 - if not db.getBlockHash(h.blockNumber, oldHash): + if not db.getBlockHash(h.number, oldHash): break try: @@ -268,7 +267,7 @@ proc setAsCanonicalChainHead( for h in newCanonicalHeaders: # TODO don't recompute block hash - db.addBlockNumberToHashLookup(h.blockNumber, h.blockHash) + db.addBlockNumberToHashLookup(h.number, h.blockHash) let canonicalHeadHash = canonicalHeadHashKey() db.newKvt.put(canonicalHeadHash.toOpenArray, rlp.encode(headerHash)).isOkOr: @@ -290,7 +289,7 @@ proc markCanonicalChain( # mark current header as canonical let kvt = db.newKvt() - key = blockNumberToHashKey(currHeader.blockNumber) + key = blockNumberToHashKey(currHeader.number) kvt.put(key.toOpenArray, rlp.encode(currHash)).isOkOr: warn logTxt "markCanonicalChain()", key, action="put()", error=($$error) return false @@ -305,7 +304,7 @@ proc markCanonicalChain( return false while currHash != Hash256(): - let key = blockNumberToHashKey(currHeader.blockNumber) + let key = blockNumberToHashKey(currHeader.number) let data = kvt.getOrEmpty(key.toOpenArray).valueOr: warn logTxt "markCanonicalChain()", key, action="get()", error=($$error) return false @@ -459,7 +458,7 @@ proc getBlockHeader*( proc getBlockHeaderWithHash*( db: CoreDbRef; n: BlockNumber; - ): Option[(BlockHeader, Hash256)] = + ): Opt[(BlockHeader, Hash256)] = ## Returns the block header and its hash, with the given number in the ## canonical chain. Hash is returned to avoid recomputing it var hash: Hash256 @@ -467,13 +466,13 @@ proc getBlockHeaderWithHash*( # Note: this will throw if header is not present. var header: BlockHeader if db.getBlockHeader(hash, header): - return some((header, hash)) + return Opt.some((header, hash)) else: # this should not happen, but if it happen lets fail laudly as this means # something is super wrong raiseAssert("Corrupted database. Mapping number->hash present, without header in database") else: - return none[(BlockHeader, Hash256)]() + return Opt.none((BlockHeader, Hash256)) proc getBlockHeader*( db: CoreDbRef; @@ -521,11 +520,11 @@ proc headTotalDifficulty*( proc getAncestorsHashes*( db: CoreDbRef; - limit: UInt256; + limit: BlockNumber; header: BlockHeader; ): seq[Hash256] {.gcsafe, raises: [BlockNotFound].} = - var ancestorCount = min(header.blockNumber, limit).truncate(int) + var ancestorCount = min(header.number, limit) var h = header result = newSeq[Hash256](ancestorCount) @@ -558,11 +557,11 @@ proc persistTransactions*( for idx, tx in transactions: let - encodedKey = rlp.encode(idx) + encodedKey = rlp.encode(idx.uint) encodedTx = rlp.encode(tx) txHash = keccakHash(encodedTx) blockKey = transactionHashToBlockKey(txHash) - txKey: TransactionKey = (blockNumber, idx) + txKey: TransactionKey = (blockNumber, idx.uint) mpt.merge(encodedKey, encodedTx).isOkOr: warn logTxt info, idx, action="merge()", error=($$error) return @@ -591,7 +590,7 @@ proc forgetHistory*( proc getTransaction*( db: CoreDbRef; txRoot: Hash256; - txIndex: int; + txIndex: uint64; res: var Transaction; ): bool = const @@ -634,7 +633,7 @@ proc getTransactionCount*( return 0 var txCount = 0 while true: - let hasPath = mpt.hasPath(rlp.encode(txCount)).valueOr: + let hasPath = mpt.hasPath(rlp.encode(txCount.uint)).valueOr: warn logTxt info, txCount, action="hasPath()", error=($$error) return 0 if hasPath: @@ -684,7 +683,7 @@ proc persistWithdrawals*( let mpt = db.ctx.getMpt(CtWithdrawals) for idx, wd in withdrawals: - mpt.merge(rlp.encode(idx), rlp.encode(wd)).isOkOr: + mpt.merge(rlp.encode(idx.uint), rlp.encode(wd)).isOkOr: warn logTxt info, idx, action="merge()", error=($$error) return @@ -721,7 +720,7 @@ proc getBlockBody*( output.uncles = db.getUncles(header.ommersHash) if header.withdrawalsRoot.isSome: - output.withdrawals = some(db.getWithdrawals(header.withdrawalsRoot.get)) + output.withdrawals = Opt.some(db.getWithdrawals(header.withdrawalsRoot.get)) true @@ -790,7 +789,7 @@ proc getUncleHashes*( proc getTransactionKey*( db: CoreDbRef; transactionHash: Hash256; - ): tuple[blockNumber: BlockNumber, index: int] + ): tuple[blockNumber: BlockNumber, index: uint64] {.gcsafe, raises: [RlpError].} = let txKey = transactionHashToBlockKey(transactionHash) @@ -798,9 +797,9 @@ proc getTransactionKey*( if error.error == KvtNotFound: warn logTxt "getTransactionKey()", transactionHash, action="get()", `error`=($$error) - return (0.toBlockNumber, -1) + return (0.BlockNumber, 0) let key = rlp.decode(tx, TransactionKey) - (key.blockNumber, key.index) + (key.blockNumber, key.index.uint64) proc headerExists*(db: CoreDbRef; blockHash: Hash256): bool = ## Returns True if the header with the given block hash is in our DB. @@ -855,16 +854,16 @@ proc persistReceipts*( let mpt = db.ctx.getMpt(CtReceipts) for idx, rec in receipts: - mpt.merge(rlp.encode(idx), rlp.encode(rec)).isOkOr: + mpt.merge(rlp.encode(idx.uint), rlp.encode(rec)).isOkOr: warn logTxt info, idx, action="merge()", error=($$error) proc getReceipts*( db: CoreDbRef; - receiptRoot: Hash256; + receiptsRoot: Hash256; ): seq[Receipt] {.gcsafe, raises: [RlpError].} = var receipts = newSeq[Receipt]() - for r in db.getReceipts(receiptRoot): + for r in db.getReceipts(receiptsRoot): receipts.add(r) return receipts @@ -918,7 +917,7 @@ proc persistHeader*( if not db.persistScore(blockHash, score): return false - db.addBlockNumberToHashLookup(header.blockNumber, blockHash) + db.addBlockNumberToHashLookup(header.number, blockHash) true proc persistHeader*( diff --git a/nimbus/db/storage_types.nim b/nimbus/db/storage_types.nim index 18749a39c..a603c0f46 100644 --- a/nimbus/db/storage_types.nim +++ b/nimbus/db/storage_types.nim @@ -135,4 +135,3 @@ template toOpenArray*(k: DbKey): openArray[byte] = func `==`*(a, b: DbKey): bool {.inline.} = a.toOpenArray == b.toOpenArray - diff --git a/nimbus/evm/computation.nim b/nimbus/evm/computation.nim index 0d3b3a030..e78270677 100644 --- a/nimbus/evm/computation.nim +++ b/nimbus/evm/computation.nim @@ -68,15 +68,22 @@ template getCoinbase*(c: Computation): EthAddress = template getTimestamp*(c: Computation): uint64 = when evmc_enabled: + # TODO: + # while the choice of using int64 in evmc will not affect + # normal evm/evmc operations. + # the reason why cast[uint64] is being used here because + # some of the tests will fail if the value from test vector overflow + # see setupTxContext of host_services.nim too + # block timestamp overflow should be checked before entering EVM cast[uint64](c.host.getTxContext().block_timestamp) else: c.vmState.blockCtx.timestamp.uint64 template getBlockNumber*(c: Computation): UInt256 = when evmc_enabled: - c.host.getBlockNumber() + c.host.getBlockNumber().u256 else: - c.vmState.blockNumber.blockNumberToVmWord + c.vmState.blockNumber.u256 template getDifficulty*(c: Computation): DifficultyInt = when evmc_enabled: @@ -94,7 +101,7 @@ template getBaseFee*(c: Computation): UInt256 = when evmc_enabled: UInt256.fromEvmc c.host.getTxContext().block_base_fee else: - c.vmState.blockCtx.fee.get(0.u256) + c.vmState.blockCtx.baseFeePerGas.get(0.u256) template getChainId*(c: Computation): uint64 = when evmc_enabled: @@ -132,10 +139,10 @@ template getBlobBaseFee*(c: Computation): UInt256 = else: c.vmState.txCtx.blobBaseFee -proc getBlockHash*(c: Computation, number: UInt256): Hash256 = +proc getBlockHash*(c: Computation, number: BlockNumber): Hash256 = when evmc_enabled: let - blockNumber = c.host.getTxContext().block_number.u256 + blockNumber = BlockNumber c.host.getTxContext().block_number ancestorDepth = blockNumber - number - 1 if ancestorDepth >= constants.MAX_PREV_HEADER_DEPTH: return Hash256() @@ -150,7 +157,7 @@ proc getBlockHash*(c: Computation, number: UInt256): Hash256 = return Hash256() if number >= blockNumber: return Hash256() - c.vmState.getAncestorHash(number.vmWordToBlockNumber) + c.vmState.getAncestorHash(number) template accountExists*(c: Computation, address: EthAddress): bool = when evmc_enabled: @@ -395,6 +402,8 @@ proc execSelfDestruct*(c: Computation, beneficiary: EthAddress) = func addLogEntry*(c: Computation, log: Log) = c.vmState.stateDB.addLogEntry(log) +# some gasRefunded operations still relying +# on negative number func getGasRefund*(c: Computation): GasInt = if c.isSuccess: result = c.gasMeter.gasRefunded diff --git a/nimbus/evm/evmc_api.nim b/nimbus/evm/evmc_api.nim index 172726b6a..9f84b8bd5 100644 --- a/nimbus/evm/evmc_api.nim +++ b/nimbus/evm/evmc_api.nim @@ -107,8 +107,8 @@ proc init*(x: typedesc[HostContext], host: ptr nimbus_host_interface, context: e proc getTxContext*(ctx: HostContext): nimbus_tx_context = ctx.host.get_tx_context(ctx.context) -proc getBlockHash*(ctx: HostContext, number: UInt256): Hash256 = - ctx.host.get_block_hash(ctx.context, number.truncate(int64)) +proc getBlockHash*(ctx: HostContext, number: BlockNumber): Hash256 = + ctx.host.get_block_hash(ctx.context, number.int64) proc accountExists*(ctx: HostContext, address: EthAddress): bool = ctx.host.account_exists(ctx.context, address) @@ -175,8 +175,8 @@ proc setTransientStorage*(ctx: HostContext, address: EthAddress, # The following two templates put here because the stupid style checker # complaints about block_number vs blockNumber and chain_id vs chainId # if they are written directly in computation.nim -template getBlockNumber*(ctx: HostContext): UInt256 = - ctx.getTxContext().block_number.u256 +template getBlockNumber*(ctx: HostContext): uint64 = + ctx.getTxContext().block_number.uint64 template getChainId*(ctx: HostContext): uint64 = UInt256.fromEvmc(ctx.getTxContext().chain_id).truncate(uint64) diff --git a/nimbus/evm/interpreter/gas_costs.nim b/nimbus/evm/interpreter/gas_costs.nim index 08426d2d7..099e7b368 100644 --- a/nimbus/evm/interpreter/gas_costs.nim +++ b/nimbus/evm/interpreter/gas_costs.nim @@ -241,8 +241,8 @@ template gasCosts(fork: EVMFork, prefix, ResultGasCostsName: untyped) = # M(currentMemSize, f, l) = currentMemSize let - prevWords: int64 = currentMemSize.wordCount - newWords: int64 = (memOffset + memLength).wordCount + prevWords = GasInt currentMemSize.wordCount + newWords = GasInt (memOffset + memLength).wordCount if memLength == 0 or newWords <= prevWords: # Special subcase of memory-expansion cost @@ -321,8 +321,9 @@ template gasCosts(fork: EVMFork, prefix, ResultGasCostsName: untyped) = when defined(evmc_enabled): const c = SstoreCost[fork] let sc = c[gasParams.s_status] - res.gasCost = sc.gasCost - res.gasRefund = sc.gasRefund + res.gasCost = GasInt sc.gasCost + # refund is used in host_services.setStorage + # res.gasRefund = sc.gasRefund ok(res) else: when fork >= FkBerlin: @@ -759,7 +760,7 @@ template gasCosts(fork: EVMFork, prefix, ResultGasCostsName: untyped) = const BaseGasFees: GasFeeSchedule = [ # Fee Schedule for the initial Ethereum forks - GasZero: 0'i64, + GasZero: 0.GasInt, GasBase: 2, GasVeryLow: 3, GasLow: 5, @@ -937,32 +938,32 @@ proc forkToSchedule*(fork: EVMFork): GasCosts = const ## Precompile costs - GasSHA256* = 60 - GasSHA256Word* = 12 - GasRIPEMD160* = 600 - GasRIPEMD160Word* = 120 - GasIdentity* = 15 - GasIdentityWord* = 3 - GasECRecover* = 3000 - GasECAdd* = 500 - GasECAddIstanbul* = 150 - GasECMul* = 40000 - GasECMulIstanbul* = 6000 - GasECPairingBase* = 100000 - GasECPairingBaseIstanbul* = 45000 - GasECPairingPerPoint* = 80000 - GasECPairingPerPointIstanbul* = 34000 + GasSHA256* = GasInt 60 + GasSHA256Word* = GasInt 12 + GasRIPEMD160* = GasInt 600 + GasRIPEMD160Word* = GasInt 120 + GasIdentity* = GasInt 15 + GasIdentityWord* = GasInt 3 + GasECRecover* = GasInt 3000 + GasECAdd* = GasInt 500 + GasECAddIstanbul* = GasInt 150 + GasECMul* = GasInt 40000 + GasECMulIstanbul* = GasInt 6000 + GasECPairingBase* = GasInt 100000 + GasECPairingBaseIstanbul* = GasInt 45000 + GasECPairingPerPoint* = GasInt 80000 + GasECPairingPerPointIstanbul* = GasInt 34000 # The Yellow Paper is special casing the GasQuadDivisor. # It is defined in Appendix G with the other GasFeeKind constants # instead of Appendix E for precompiled contracts GasQuadDivisor* = 20 GasQuadDivisorEIP2565* = 3 # https://eips.ethereum.org/EIPS/eip-2537 - Bls12381G1AddGas* = 500 - Bls12381G1MulGas* = 12000 - Bls12381G2AddGas* = 800 - Bls12381G2MulGas* = 45000 - Bls12381PairingBaseGas* = 115000 - Bls12381PairingPerPairGas* = 23000 - Bls12381MapG1Gas* = 5500 - Bls12381MapG2Gas* = 110000 + Bls12381G1AddGas* = GasInt 500 + Bls12381G1MulGas* = GasInt 12000 + Bls12381G2AddGas* = GasInt 800 + Bls12381G2MulGas* = GasInt 45000 + Bls12381PairingBaseGas* = GasInt 115000 + Bls12381PairingPerPairGas* = GasInt 23000 + Bls12381MapG1Gas* = GasInt 5500 + Bls12381MapG2Gas* = GasInt 110000 diff --git a/nimbus/evm/interpreter/gas_meter.nim b/nimbus/evm/interpreter/gas_meter.nim index efef40956..61fda5d62 100644 --- a/nimbus/evm/interpreter/gas_meter.nim +++ b/nimbus/evm/interpreter/gas_meter.nim @@ -28,5 +28,7 @@ func consumeGas*(gasMeter: var GasMeter; amount: GasInt; reason: string): EvmRes func returnGas*(gasMeter: var GasMeter; amount: GasInt) = gasMeter.gasRemaining += amount +# some gasRefunded operations still relying +# on negative number func refundGas*(gasMeter: var GasMeter; amount: GasInt) = gasMeter.gasRefunded += amount diff --git a/nimbus/evm/interpreter/op_handlers/oph_blockdata.nim b/nimbus/evm/interpreter/op_handlers/oph_blockdata.nim index 313b81270..6d7dfed1a 100644 --- a/nimbus/evm/interpreter/op_handlers/oph_blockdata.nim +++ b/nimbus/evm/interpreter/op_handlers/oph_blockdata.nim @@ -35,7 +35,7 @@ const let cpt = k.cpt blockNumber = ? cpt.stack.popInt() - blockHash = cpt.getBlockHash(blockNumber) + blockHash = cpt.getBlockHash(blockNumber.truncate(BlockNumber)) cpt.stack.push blockHash diff --git a/nimbus/evm/interpreter/op_handlers/oph_call.nim b/nimbus/evm/interpreter/op_handlers/oph_call.nim index d4083e6a7..ab08ce3c6 100644 --- a/nimbus/evm/interpreter/op_handlers/oph_call.nim +++ b/nimbus/evm/interpreter/op_handlers/oph_call.nim @@ -162,7 +162,7 @@ when evmc_enabled: ? c.memory.write(p.memOutPos, c.returnData.toOpenArray(0, actualOutputSize - 1)) - c.gasMeter.returnGas(c.res.gas_left) + c.gasMeter.returnGas(GasInt c.res.gas_left) if c.res.status_code == EVMC_SUCCESS: ? c.stack.top(1) diff --git a/nimbus/evm/interpreter/op_handlers/oph_create.nim b/nimbus/evm/interpreter/op_handlers/oph_create.nim index 8bcb7b421..711163feb 100644 --- a/nimbus/evm/interpreter/op_handlers/oph_create.nim +++ b/nimbus/evm/interpreter/op_handlers/oph_create.nim @@ -45,7 +45,7 @@ when not defined(evmc_enabled): when evmc_enabled: template execSubCreate(c: Computation; msg: ref nimbus_message) = c.chainTo(msg): - c.gasMeter.returnGas(c.res.gas_left) + c.gasMeter.returnGas(GasInt c.res.gas_left) if c.res.status_code == EVMC_SUCCESS: ? c.stack.top(c.res.create_address) elif c.res.status_code == EVMC_REVERT: diff --git a/nimbus/evm/interpreter/utils/utils_numeric.nim b/nimbus/evm/interpreter/utils/utils_numeric.nim index a24c38c9a..2ad7d06dc 100644 --- a/nimbus/evm/interpreter/utils/utils_numeric.nim +++ b/nimbus/evm/interpreter/utils/utils_numeric.nim @@ -1,5 +1,5 @@ # Nimbus -# Copyright (c) 2018 Status Research & Development GmbH +# 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) @@ -13,7 +13,7 @@ import type # cannot use range for unknown reason # Nim bug? - GasNatural* = int64 # range[0'i64..high(int64)] + GasNatural* = Natural # some methods based on py-evm utils/numeric diff --git a/nimbus/evm/precompiles.nim b/nimbus/evm/precompiles.nim index 5119ad1fe..eac520d09 100644 --- a/nimbus/evm/precompiles.nim +++ b/nimbus/evm/precompiles.nim @@ -336,11 +336,11 @@ func bn256ecMul(c: Computation, fork: EVMFork = FkByzantium): EvmResultVoid = ok() func bn256ecPairing(c: Computation, fork: EVMFork = FkByzantium): EvmResultVoid = - let msglen = len(c.msg.data) + let msglen = c.msg.data.len if msglen mod 192 != 0: return err(prcErr(PrcInvalidParam)) - let numPoints = msglen div 192 + let numPoints = GasInt msglen div 192 let gasFee = if fork < FkIstanbul: GasECPairingBase + numPoints * GasECPairingPerPoint else: @@ -452,7 +452,7 @@ const 179, 179, 178, 177, 176, 176, 175, 174 ] -func calcBlsMultiExpGas(K: int, gasCost: GasInt): GasInt = +func calcBlsMultiExpGas(K: GasInt, gasCost: GasInt): GasInt = # Calculate G1 point, scalar value pair length if K == 0: # Return 0 gas for small input length @@ -460,8 +460,8 @@ func calcBlsMultiExpGas(K: int, gasCost: GasInt): GasInt = const dLen = Bls12381MultiExpDiscountTable.len # Lookup discount value for G1 point, scalar value pair length - let discount = if K < dLen: Bls12381MultiExpDiscountTable[K-1] - else: Bls12381MultiExpDiscountTable[dLen-1] + let discount = if K < dLen: GasInt Bls12381MultiExpDiscountTable[K-1] + else: GasInt Bls12381MultiExpDiscountTable[dLen-1] # Calculate gas and return the result result = (K * gasCost * discount) div 1000 @@ -476,7 +476,7 @@ func blsG1MultiExp*(c: Computation): EvmResultVoid = let K = input.len div L - gas = K.calcBlsMultiExpGas(Bls12381G1MulGas) + gas = calcBlsMultiExpGas(GasInt K, Bls12381G1MulGas) ? c.gasMeter.consumeGas(gas, reason="blsG1MultiExp Precompile") @@ -565,7 +565,7 @@ func blsG2MultiExp*(c: Computation): EvmResultVoid = let K = input.len div L - gas = K.calcBlsMultiExpGas(Bls12381G2MulGas) + gas = calcBlsMultiExpGas(GasInt K, Bls12381G2MulGas) ? c.gasMeter.consumeGas(gas, reason="blsG2MultiExp Precompile") diff --git a/nimbus/evm/state.nim b/nimbus/evm/state.nim index f1f32cd0f..537b19faa 100644 --- a/nimbus/evm/state.nim +++ b/nimbus/evm/state.nim @@ -42,7 +42,7 @@ func blockCtx(com: CommonRef, header: BlockHeader): BlockContext( timestamp : header.timestamp, gasLimit : header.gasLimit, - fee : header.fee, + baseFeePerGas: header.baseFeePerGas, prevRandao : header.prevRandao, difficulty : header.difficulty, coinbase : com.minerAddress(header), @@ -57,7 +57,7 @@ proc `$`*(vmState: BaseVMState): string result = "nil" else: result = &"VMState:"& - &"\n blockNumber: {vmState.parent.blockNumber + 1}" + &"\n blockNumber: {vmState.parent.number + 1}" proc new*( T: type BaseVMState; @@ -216,8 +216,8 @@ proc coinbase*(vmState: BaseVMState): EthAddress = proc blockNumber*(vmState: BaseVMState): BlockNumber = # it should return current block number - # and not head.blockNumber - vmState.parent.blockNumber + 1 + # and not head.number + vmState.parent.number + 1 proc difficultyOrPrevRandao*(vmState: BaseVMState): UInt256 = if vmState.com.consensus == ConsensusType.POS: @@ -226,8 +226,8 @@ proc difficultyOrPrevRandao*(vmState: BaseVMState): UInt256 = else: vmState.blockCtx.difficulty -proc baseFee*(vmState: BaseVMState): UInt256 = - vmState.blockCtx.fee.get(0.u256) +proc baseFeePerGas*(vmState: BaseVMState): UInt256 = + vmState.blockCtx.baseFeePerGas.get(0.u256) method getAncestorHash*( vmState: BaseVMState, blockNumber: BlockNumber): Hash256 {.base.} = diff --git a/nimbus/evm/state_transactions.nim b/nimbus/evm/state_transactions.nim index b1658beaf..93d8135f7 100644 --- a/nimbus/evm/state_transactions.nim +++ b/nimbus/evm/state_transactions.nim @@ -24,7 +24,7 @@ import proc setupTxContext*(vmState: BaseVMState, txCtx: sink TxContext, - forkOverride=none(EVMFork)) = + forkOverride=Opt.none(EVMFork)) = ## this proc will be called each time a new transaction ## is going to be executed vmState.txCtx = system.move(txCtx) diff --git a/nimbus/evm/types.nim b/nimbus/evm/types.nim index b39e2ae67..e6acc5337 100644 --- a/nimbus/evm/types.nim +++ b/nimbus/evm/types.nim @@ -41,7 +41,7 @@ type BlockContext* = object timestamp* : EthTime gasLimit* : GasInt - fee* : Option[UInt256] + baseFeePerGas* : Opt[UInt256] prevRandao* : Hash256 difficulty* : UInt256 coinbase* : EthAddress @@ -95,7 +95,7 @@ type evmcStatus*: evmc_status_code info* : string burnsGas* : bool - + GasMeter* = object gasRefunded*: GasInt gasRemaining*: GasInt diff --git a/nimbus/graphql/ethapi.nim b/nimbus/graphql/ethapi.nim index e4f6948ba..05263cf65 100644 --- a/nimbus/graphql/ethapi.nim +++ b/nimbus/graphql/ethapi.nim @@ -51,11 +51,11 @@ type TxNode = ref object of Node tx: Transaction - index: int + index: uint64 blockNumber: common.BlockNumber receipt: Receipt gasUsed: GasInt - baseFee: Option[UInt256] + baseFee: Opt[UInt256] LogNode = ref object of Node log: Log @@ -85,9 +85,9 @@ proc toHash(n: Node): common.Hash256 {.gcsafe, raises: [ValueError].} = proc toBlockNumber(n: Node): common.BlockNumber {.gcsafe, raises: [ValueError].} = if n.kind == nkInt: - result = parse(n.intVal, UInt256, radix = 10) + result = parse(n.intVal, UInt256, radix = 10).truncate(common.BlockNumber) elif n.kind == nkString: - result = parse(n.stringVal, UInt256, radix = 16) + result = parse(n.stringVal, UInt256, radix = 16).truncate(common.BlockNumber) else: doAssert(false, "unknown node type: " & $n.kind) @@ -109,7 +109,7 @@ proc accountNode(ctx: GraphqlContextRef, acc: Account, address: EthAddress, db: db: db ) -proc txNode(ctx: GraphqlContextRef, tx: Transaction, index: int, blockNumber: common.BlockNumber, baseFee: Option[UInt256]): Node = +proc txNode(ctx: GraphqlContextRef, tx: Transaction, index: uint64, blockNumber: common.BlockNumber, baseFee: Opt[UInt256]): Node = TxNode( kind: nkMap, typeName: ctx.ids[ethTransaction], @@ -281,15 +281,15 @@ proc getTxs(ctx: GraphqlContextRef, header: common.BlockHeader): RespResult = if txCount == 0: return ok(respNull()) var list = respList() - var index = 0 + var index = 0'u64 for n in getBlockTransactionData(ctx.chainDB, header.txRoot): let tx = decodeTx(n) - list.add txNode(ctx, tx, index, header.blockNumber, header.fee) + list.add txNode(ctx, tx, index, header.number, header.baseFeePerGas) inc index - index = 0 + index = 0'u64 var prevUsed = 0.GasInt - for r in getReceipts(ctx.chainDB, header.receiptRoot): + for r in getReceipts(ctx.chainDB, header.receiptsRoot): let tx = TxNode(list.sons[index]) tx.receipt = r tx.gasUsed = r.cumulativeGasUsed - prevUsed @@ -313,15 +313,15 @@ proc getWithdrawals(ctx: GraphqlContextRef, header: common.BlockHeader): RespRes except CatchableError as e: err("can't get transactions: " & e.msg) -proc getTxAt(ctx: GraphqlContextRef, header: common.BlockHeader, index: int): RespResult = +proc getTxAt(ctx: GraphqlContextRef, header: common.BlockHeader, index: uint64): RespResult = try: var tx: Transaction if getTransaction(ctx.chainDB, header.txRoot, index, tx): - let txn = txNode(ctx, tx, index, header.blockNumber, header.fee) + let txn = txNode(ctx, tx, index, header.number, header.baseFeePerGas) - var i = 0 + var i = 0'u64 var prevUsed = 0.GasInt - for r in getReceipts(ctx.chainDB, header.receiptRoot): + for r in getReceipts(ctx.chainDB, header.receiptsRoot): if i == index: let tx = TxNode(txn) tx.receipt = r @@ -619,14 +619,14 @@ proc txNonce(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} proc txIndex(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = let tx = TxNode(parent) - ok(resp(tx.index)) + ok(resp(tx.index.int)) proc txFrom(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = let ctx = GraphqlContextRef(ud) let tx = TxNode(parent) let blockNumber = if params[0].val.kind != nkEmpty: - parseU64(params[0].val).toBlockNumber + parseU64(params[0].val) else: tx.blockNumber @@ -644,7 +644,7 @@ proc txTo(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = let tx = TxNode(parent) let blockNumber = if params[0].val.kind != nkEmpty: - parseU64(params[0].val).toBlockNumber + parseU64(params[0].val) else: tx.blockNumber @@ -662,27 +662,27 @@ proc txValue(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} proc txGasPrice(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = let tx = TxNode(parent) - if tx.tx.txType == TxEip1559: + if tx.tx.txType >= TxEip1559: if tx.baseFee.isNone: return bigIntNode(tx.tx.gasPrice) let baseFee = tx.baseFee.get().truncate(GasInt) - let priorityFee = min(tx.tx.maxPriorityFee, tx.tx.maxFee - baseFee) + let priorityFee = min(tx.tx.maxPriorityFeePerGas, tx.tx.maxFeePerGas - baseFee) bigIntNode(priorityFee + baseFee) else: bigIntNode(tx.tx.gasPrice) proc txMaxFeePerGas(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = let tx = TxNode(parent) - if tx.tx.txType == TxEip1559: - bigIntNode(tx.tx.maxFee) + if tx.tx.txType >= TxEip1559: + bigIntNode(tx.tx.maxFeePerGas) else: ok(respNull()) proc txMaxPriorityFeePerGas(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = let tx = TxNode(parent) - if tx.tx.txType == TxEip1559: - bigIntNode(tx.tx.maxPriorityFee) + if tx.tx.txType >= TxEip1559: + bigIntNode(tx.tx.maxPriorityFeePerGas) else: ok(respNull()) @@ -692,7 +692,7 @@ proc txEffectiveGasPrice(ud: RootRef, params: Args, parent: Node): RespResult {. return bigIntNode(tx.tx.gasPrice) let baseFee = tx.baseFee.get().truncate(GasInt) - let priorityFee = min(tx.tx.maxPriorityFee, tx.tx.maxFee - baseFee) + let priorityFee = min(tx.tx.maxPriorityFeePerGas, tx.tx.maxFeePerGas - baseFee) bigIntNode(priorityFee + baseFee) proc txChainId(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = @@ -885,7 +885,7 @@ const wdProcs = { proc blockNumberImpl(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = let h = HeaderNode(parent) - longNode(h.header.blockNumber) + longNode(h.header.number) proc blockHashImpl(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = let h = HeaderNode(parent) @@ -916,7 +916,7 @@ proc blockStateRoot(ud: RootRef, params: Args, parent: Node): RespResult {.apiPr proc blockReceiptsRoot(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = let h = HeaderNode(parent) - resp(h.header.receiptRoot) + resp(h.header.receiptsRoot) proc blockMiner(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = let ctx = GraphqlContextRef(ud) @@ -941,11 +941,11 @@ proc blockTimestamp(ud: RootRef, params: Args, parent: Node): RespResult {.apiPr proc blockLogsBloom(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = let h = HeaderNode(parent) - resp(h.header.bloom) + resp(h.header.logsBloom) proc blockMixHash(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = let h = HeaderNode(parent) - resp(h.header.mixDigest) + resp(h.header.mixHash) proc blockDifficulty(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = let h = HeaderNode(parent) @@ -989,7 +989,7 @@ proc blockTransactionAt(ud: RootRef, params: Args, parent: Node): RespResult {.a try: let index = parseU64(params[0].val) {.cast(noSideEffect).}: - getTxAt(ctx, h.header, index.int) + getTxAt(ctx, h.header, index) except ValueError as ex: err(ex.msg) @@ -1027,24 +1027,24 @@ template fieldString(n: Node, field: int): string = template optionalAddress(dstField: untyped, n: Node, field: int) = if isSome(n, field): let address = Address.fromHex(fieldString(n, field)) - dstField = some(address) + dstField = Opt.some(address) template optionalGasInt(dstField: untyped, n: Node, field: int) = if isSome(n, field): - dstField = some(parseU64(n[field][1]).Quantity) + dstField = Opt.some(parseU64(n[field][1]).Quantity) template optionalGasHex(dstField: untyped, n: Node, field: int) = if isSome(n, field): let gas = parse(fieldString(n, field), UInt256, radix = 16) - dstField = some(gas.truncate(uint64).Quantity) + dstField = Opt.some(gas.truncate(uint64).Quantity) template optionalHexU256(dstField: untyped, n: Node, field: int) = if isSome(n, field): - dstField = some(parse(fieldString(n, field), UInt256, radix = 16)) + dstField = Opt.some(parse(fieldString(n, field), UInt256, radix = 16)) template optionalBytes(dstField: untyped, n: Node, field: int) = if isSome(n, field): - dstField = some(hexToSeqByte(fieldString(n, field))) + dstField = Opt.some(hexToSeqByte(fieldString(n, field))) proc toTxArgs(n: Node): TransactionArgs {.gcsafe, raises: [ValueError].} = optionalAddress(result.source, n, fFrom) @@ -1093,8 +1093,8 @@ proc blockEstimateGas(ud: RootRef, params: Args, parent: Node): RespResult {.api proc blockBaseFeePerGas(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = let h = HeaderNode(parent) - if h.header.fee.isSome: - bigIntNode(h.header.fee.get) + if h.header.baseFeePerGas.isSome: + bigIntNode(h.header.baseFeePerGas.get) else: ok(respNull()) @@ -1243,7 +1243,7 @@ proc pickBlockNumber(ctx: GraphqlContextRef, number: Node): common.BlockNumber = if number.kind == nkEmpty: ctx.com.syncCurrent else: - parseU64(number).toBlockNumber + parseU64(number) proc queryAccount(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = let ctx = GraphqlContextRef(ud) @@ -1279,17 +1279,17 @@ proc queryBlock(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma proc queryBlocks(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = let ctx = GraphqlContextRef(ud) - let fromNumber = parseU64(params[0].val).toBlockNumber + let fromNumber = parseU64(params[0].val) let to = params[1].val let toNumber = pickBlockNumber(ctx, to) if fromNumber > toNumber: - return err("from(" & fromNumber.toString & - ") is bigger than to(" & toNumber.toString & ")") + return err("from(" & $fromNumber & + ") is bigger than to(" & $toNumber & ")") # TODO: what is the maximum number here? - if toNumber - fromNumber > 32.toBlockNumber: + if toNumber - fromNumber > 32'u64: return err("can't get more than 32 blocks at once") var list = respList() @@ -1300,7 +1300,7 @@ proc queryBlocks(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragm list.add respNull() else: list.add n.get() - number += 1.toBlockNumber + number += 1'u64 ok(list) diff --git a/nimbus/nimbus_import.nim b/nimbus/nimbus_import.nim index 54ae86ff4..c21f03025 100644 --- a/nimbus/nimbus_import.nim +++ b/nimbus/nimbus_import.nim @@ -59,7 +59,7 @@ proc importBlocks*(conf: NimbusConf, com: CommonRef) = setControlCHook(controlCHandler) let - start = com.db.getSavedStateBlockNumber().truncate(uint64) + 1 + start = com.db.getSavedStateBlockNumber() + 1 chain = com.newChain() var diff --git a/nimbus/rpc/debug.nim b/nimbus/rpc/debug.nim index 88b5be30f..ccd9814c9 100644 --- a/nimbus/rpc/debug.nim +++ b/nimbus/rpc/debug.nim @@ -22,18 +22,18 @@ import type TraceOptions = object - disableStorage: Option[bool] - disableMemory: Option[bool] - disableStack: Option[bool] - disableState: Option[bool] - disableStateDiff: Option[bool] + disableStorage: Opt[bool] + disableMemory: Opt[bool] + disableStack: Opt[bool] + disableState: Opt[bool] + disableStateDiff: Opt[bool] TraceOptions.useDefaultSerializationIn JrpcConv -proc isTrue(x: Option[bool]): bool = +proc isTrue(x: Opt[bool]): bool = result = x.isSome and x.get() == true -proc traceOptionsToFlags(options: Option[TraceOptions]): set[TracerFlags] = +proc traceOptionsToFlags(options: Opt[TraceOptions]): set[TracerFlags] = if options.isSome: let opts = options.get if opts.disableStorage.isTrue: result.incl TracerFlags.DisableStorage @@ -45,7 +45,7 @@ proc traceOptionsToFlags(options: Option[TraceOptions]): set[TracerFlags] = proc setupDebugRpc*(com: CommonRef, txPool: TxPoolRef, rpcsrv: RpcServer) = let chainDB = com.db - rpcsrv.rpc("debug_traceTransaction") do(data: Web3Hash, options: Option[TraceOptions]) -> JsonNode: + rpcsrv.rpc("debug_traceTransaction") do(data: Web3Hash, options: Opt[TraceOptions]) -> JsonNode: ## The traceTransaction debugging method will attempt to run the transaction in the exact ## same manner as it was executed on the network. It will replay any transaction that may ## have been executed prior to this one before it will finally attempt to execute the @@ -75,7 +75,7 @@ proc setupDebugRpc*(com: CommonRef, txPool: TxPoolRef, rpcsrv: RpcServer) = ## "latest" or "pending", as in the default block parameter. var header = chainDB.headerFromTag(quantityTag) - blockHash = chainDB.getBlockHash(header.blockNumber) + blockHash = chainDB.getBlockHash(header.number) body = chainDB.getBlockBody(blockHash) dumpBlockState(com, EthBlock.init(move(header), move(body))) @@ -91,7 +91,7 @@ proc setupDebugRpc*(com: CommonRef, txPool: TxPoolRef, rpcsrv: RpcServer) = dumpBlockState(com, blk) - rpcsrv.rpc("debug_traceBlockByNumber") do(quantityTag: BlockTag, options: Option[TraceOptions]) -> JsonNode: + rpcsrv.rpc("debug_traceBlockByNumber") do(quantityTag: BlockTag, options: Opt[TraceOptions]) -> JsonNode: ## The traceBlock method will return a full stack trace of all invoked opcodes of all transaction ## that were included included in this block. ## @@ -100,13 +100,13 @@ proc setupDebugRpc*(com: CommonRef, txPool: TxPoolRef, rpcsrv: RpcServer) = ## options: see debug_traceTransaction var header = chainDB.headerFromTag(quantityTag) - blockHash = chainDB.getBlockHash(header.blockNumber) + blockHash = chainDB.getBlockHash(header.number) body = chainDB.getBlockBody(blockHash) flags = traceOptionsToFlags(options) traceBlock(com, EthBlock.init(move(header), move(body)), flags) - rpcsrv.rpc("debug_traceBlockByHash") do(data: Web3Hash, options: Option[TraceOptions]) -> JsonNode: + rpcsrv.rpc("debug_traceBlockByHash") do(data: Web3Hash, options: Opt[TraceOptions]) -> JsonNode: ## The traceBlock method will return a full stack trace of all invoked opcodes of all transaction ## that were included included in this block. ## @@ -115,7 +115,7 @@ proc setupDebugRpc*(com: CommonRef, txPool: TxPoolRef, rpcsrv: RpcServer) = var h = data.ethHash header = chainDB.getBlockHeader(h) - blockHash = chainDB.getBlockHash(header.blockNumber) + blockHash = chainDB.getBlockHash(header.number) body = chainDB.getBlockBody(blockHash) flags = traceOptionsToFlags(options) @@ -133,7 +133,7 @@ proc setupDebugRpc*(com: CommonRef, txPool: TxPoolRef, rpcsrv: RpcServer) = ## Returns an RLP-encoded block. var header = chainDB.headerFromTag(quantityTag) - blockHash = chainDB.getBlockHash(header.blockNumber) + blockHash = chainDB.getBlockHash(header.number) body = chainDB.getBlockBody(blockHash) rlp.encode(EthBlock.init(move(header), move(body))) @@ -146,7 +146,7 @@ proc setupDebugRpc*(com: CommonRef, txPool: TxPoolRef, rpcsrv: RpcServer) = rpcsrv.rpc("debug_getRawReceipts") do(quantityTag: BlockTag) -> seq[seq[byte]]: ## Returns an array of EIP-2718 binary-encoded receipts. let header = chainDB.headerFromTag(quantityTag) - for receipt in chainDB.getReceipts(header.receiptRoot): + for receipt in chainDB.getReceipts(header.receiptsRoot): result.add rlp.encode(receipt) rpcsrv.rpc("debug_getRawTransaction") do(data: Web3Hash) -> seq[byte]: diff --git a/nimbus/rpc/engine_api.nim b/nimbus/rpc/engine_api.nim index c6a86f973..2ee4954c4 100644 --- a/nimbus/rpc/engine_api.nim +++ b/nimbus/rpc/engine_api.nim @@ -52,13 +52,13 @@ proc setupEngineAPI*(engine: BeaconEngineRef, server: RpcServer) = return engine.newPayload(Version.V2, payload) server.rpc("engine_newPayloadV3") do(payload: ExecutionPayload, - expectedBlobVersionedHashes: Option[seq[Web3Hash]], - parentBeaconBlockRoot: Option[Web3Hash]) -> PayloadStatusV1: + expectedBlobVersionedHashes: Opt[seq[Web3Hash]], + parentBeaconBlockRoot: Opt[Web3Hash]) -> PayloadStatusV1: return engine.newPayload(Version.V3, payload, expectedBlobVersionedHashes, parentBeaconBlockRoot) server.rpc("engine_newPayloadV4") do(payload: ExecutionPayload, - expectedBlobVersionedHashes: Option[seq[Web3Hash]], - parentBeaconBlockRoot: Option[Web3Hash]) -> PayloadStatusV1: + expectedBlobVersionedHashes: Opt[seq[Web3Hash]], + parentBeaconBlockRoot: Opt[Web3Hash]) -> PayloadStatusV1: return engine.newPayload(Version.V4, payload, expectedBlobVersionedHashes, parentBeaconBlockRoot) server.rpc("engine_getPayloadV1") do(payloadId: PayloadID) -> ExecutionPayloadV1: @@ -78,23 +78,23 @@ proc setupEngineAPI*(engine: BeaconEngineRef, server: RpcServer) = return engine.exchangeConf(conf) server.rpc("engine_forkchoiceUpdatedV1") do(update: ForkchoiceStateV1, - attrs: Option[PayloadAttributesV1]) -> ForkchoiceUpdatedResponse: + attrs: Opt[PayloadAttributesV1]) -> ForkchoiceUpdatedResponse: return engine.forkchoiceUpdated(Version.V1, update, attrs.payloadAttributes) server.rpc("engine_forkchoiceUpdatedV2") do(update: ForkchoiceStateV1, - attrs: Option[PayloadAttributes]) -> ForkchoiceUpdatedResponse: + attrs: Opt[PayloadAttributes]) -> ForkchoiceUpdatedResponse: return engine.forkchoiceUpdated(Version.V2, update, attrs) server.rpc("engine_forkchoiceUpdatedV3") do(update: ForkchoiceStateV1, - attrs: Option[PayloadAttributes]) -> ForkchoiceUpdatedResponse: + attrs: Opt[PayloadAttributes]) -> ForkchoiceUpdatedResponse: return engine.forkchoiceUpdated(Version.V3, update, attrs) server.rpc("engine_getPayloadBodiesByHashV1") do(hashes: seq[Web3Hash]) -> - seq[Option[ExecutionPayloadBodyV1]]: + seq[Opt[ExecutionPayloadBodyV1]]: return engine.getPayloadBodiesByHash(hashes) server.rpc("engine_getPayloadBodiesByRangeV1") do( - start: Quantity, count: Quantity) -> seq[Option[ExecutionPayloadBodyV1]]: + start: Quantity, count: Quantity) -> seq[Opt[ExecutionPayloadBodyV1]]: return engine.getPayloadBodiesByRange(start.uint64, count.uint64) server.rpc("engine_getClientVersionV1") do(version: ClientVersionV1) -> diff --git a/nimbus/rpc/experimental.nim b/nimbus/rpc/experimental.nim index b2b497d34..1cfb4fe28 100644 --- a/nimbus/rpc/experimental.nim +++ b/nimbus/rpc/experimental.nim @@ -37,7 +37,7 @@ proc getMultiKeys*( let chainDB = com.db - blk = chainDB.getEthBlock(blockHeader.blockNumber) + blk = chainDB.getEthBlock(blockHeader.number) # Initializing the VM will throw a Defect if the state doesn't exist. # Once we enable pruning we will need to check if the block state has been pruned # before trying to initialize the VM as we do here. diff --git a/nimbus/rpc/filters.nim b/nimbus/rpc/filters.nim index 9c42b968f..10e73b5ee 100644 --- a/nimbus/rpc/filters.nim +++ b/nimbus/rpc/filters.nim @@ -33,7 +33,7 @@ proc deriveLogs*(header: BlockHeader, transactions: seq[Transaction], receipts: doAssert(len(transactions) == len(receipts)) var resLogs: seq[FilterLog] = @[] - var logIndex = 0 + var logIndex = 0'u64 for i, receipt in receipts: for log in receipt.logs: @@ -43,11 +43,11 @@ proc deriveLogs*(header: BlockHeader, transactions: seq[Transaction], receipts: # level, to keep track about potential re-orgs # - in fluffy there is no concept of re-org removed: false, - logIndex: some(w3Qty(logIndex)), - transactionIndex: some(w3Qty(i)), - transactionHash: some(w3Hash transactions[i].rlpHash), - blockHash: some(w3Hash header.blockHash), - blockNumber: some(w3BlockNumber(header.blockNumber)), + logIndex: Opt.some(w3Qty(logIndex)), + transactionIndex: Opt.some(Quantity(i)), + transactionHash: Opt.some(w3Hash transactions[i].rlpHash), + blockHash: Opt.some(w3Hash header.blockHash), + blockNumber: Opt.some(w3BlockNumber(header.number)), address: w3Addr log.address, data: log.data, # TODO topics should probably be kept as Hash256 in receipts @@ -114,7 +114,7 @@ proc headerBloomFilter*( header: BlockHeader, addresses: AddressOrList, topics: seq[TopicOrList]): bool = - return bloomFilter(header.bloom, addresses, topics) + return bloomFilter(header.logsBloom, addresses, topics) proc matchTopics(log: FilterLog, topics: seq[TopicOrList]): bool = for i, sub in topics: diff --git a/nimbus/rpc/oracle.nim b/nimbus/rpc/oracle.nim index 11cd3346c..5c1e3a636 100644 --- a/nimbus/rpc/oracle.nim +++ b/nimbus/rpc/oracle.nim @@ -85,11 +85,11 @@ func toBytes(list: openArray[float64]): seq[byte] = result.add(cast[uint64](x).toBytesLE) func calcBaseFee(com: CommonRef, bc: BlockContent): UInt256 = - if com.isLondon((bc.blockNumber + 1).toBlockNumber): + if com.isLondon(bc.blockNumber + 1): calcEip1599BaseFee( bc.header.gasLimit, bc.header.gasUsed, - bc.header.baseFee) + bc.header.baseFeePerGas.get(0.u256)) else: 0.u256 @@ -98,7 +98,7 @@ func calcBaseFee(com: CommonRef, bc: BlockContent): UInt256 = # fills in the rest of the fields. proc processBlock(oracle: Oracle, bc: BlockContent, percentiles: openArray[float64]): ProcessedFees = result = ProcessedFees( - baseFee: bc.header.baseFee, + baseFee: bc.header.baseFeePerGas.get(0.u256), blobBaseFee: getBlobBaseFee(bc.header.excessBlobGas.get(0'u64)), nextBaseFee: calcBaseFee(oracle.com, bc), nextBlobBaseFee: getBlobBaseFee(calcExcessBlobGas(bc.header)), @@ -125,7 +125,7 @@ proc processBlock(oracle: Oracle, bc: BlockContent, percentiles: openArray[float for i, tx in bc.txs: let - reward = tx.effectiveGasTip(bc.header.fee) + reward = tx.effectiveGasTip(bc.header.baseFeePerGas) gasUsed = bc.receipts[i].cumulativeGasUsed - prevUsed sorter[i] = TxGasAndReward( gasUsed: gasUsed.uint64, @@ -163,7 +163,7 @@ proc resolveBlockRange(oracle: Oracle, blockId: BlockTag, numBlocks: uint64): Re oracle.com.db.getCanonicalHead() except CatchableError as exc: return err(exc.msg) - head = headBlock.blockNumber.truncate(uint64) + head = headBlock.number var reqEnd: uint64 @@ -182,7 +182,7 @@ proc resolveBlockRange(oracle: Oracle, blockId: BlockTag, numBlocks: uint64): Re if tag == "pending": try: resolved = headerFromTag(oracle.com.db, blockId) - pendingBlock = Opt.some(resolved.blockNumber.truncate(uint64)) + pendingBlock = Opt.some(resolved.number) except CatchableError: # Pending block not supported by backend, process only until latest block. resolved = headBlock @@ -195,7 +195,7 @@ proc resolveBlockRange(oracle: Oracle, blockId: BlockTag, numBlocks: uint64): Re return err(exc.msg) # Absolute number resolved. - reqEnd = resolved.blockNumber.truncate(uint64) + reqEnd = resolved.number # If there are no blocks to return, short circuit. if blocks == 0: @@ -221,11 +221,11 @@ proc getBlockContent(oracle: Oracle, let db = oracle.com.db try: - bc.header = db.getBlockHeader(blockNumber.toblockNumber) + bc.header = db.getBlockHeader(blockNumber.BlockNumber) for tx in db.getBlockTransactions(bc.header): bc.txs.add tx - for rc in db.getReceipts(bc.header.receiptRoot): + for rc in db.getReceipts(bc.header.receiptsRoot): bc.receipts.add rc return ok(bc) @@ -357,9 +357,9 @@ proc feeHistory*(oracle: Oracle, if rewardPercentiles.len != 0: res.reward.setLen(res.firstMissing) - historyResult.reward = some(system.move res.reward) + historyResult.reward = Opt.some(system.move res.reward) else: - historyResult.reward = none(seq[FeeHistoryReward]) + historyResult.reward = Opt.none(seq[FeeHistoryReward]) res.baseFee.setLen(res.firstMissing+1) res.gasUsedRatio.setLen(res.firstMissing) diff --git a/nimbus/rpc/p2p.nim b/nimbus/rpc/p2p.nim index 9a7b5cbbc..8636b63f6 100644 --- a/nimbus/rpc/p2p.nim +++ b/nimbus/rpc/p2p.nim @@ -12,7 +12,7 @@ import std/[sequtils, times, tables, typetraits], json_rpc/rpcserver, stint, stew/byteutils, - json_serialization, web3/conversions, json_serialization/std/options, + json_serialization, web3/conversions, json_serialization/stew/results, eth/common/eth_types_json_serialization, eth/[keys, rlp, p2p], ".."/[transaction, vm_state, constants], @@ -66,9 +66,9 @@ proc getProof*( var storage = newSeqOfCap[StorageProof](slots.len) for i, slotKey in slots: - let slotValue = accDB.getStorage(address, u256(slotKey)).valueOr: 0.u256 + let slotValue = accDB.getStorage(address, slotKey).valueOr: 0.u256 storage.add(StorageProof( - key: u256(slotKey), + key: slotKey, value: slotValue, proof: seq[RlpEncodedBytes](slotProofs[i]))) @@ -102,7 +102,7 @@ proc setupEthRpc*( {.gcsafe, raises: [CatchableError].} = result = getStateDB(chainDB.headerFromTag(quantityTag)) - server.rpc("eth_protocolVersion") do() -> Option[string]: + server.rpc("eth_protocolVersion") do() -> Opt[string]: # Old Ethereum wiki documents this as returning a decimal string. # Infura documents this as returning 0x-prefixed hex string. # Geth 1.10.0 has removed this call "as it makes no sense". @@ -111,8 +111,8 @@ proc setupEthRpc*( # - https://blog.ethereum.org/2021/03/03/geth-v1-10-0/#compatibility for n in node.capabilities: if n.name == "eth": - return some($n.version) - return none(string) + return Opt.some($n.version) + return Opt.none(string) server.rpc("eth_chainId") do() -> Web3Quantity: return w3Qty(distinctBase(com.chainId)) @@ -159,7 +159,7 @@ proc setupEthRpc*( server.rpc("eth_blockNumber") do() -> Web3Quantity: ## Returns integer of the current block number the client is on. - result = w3Qty(chainDB.getCanonicalHead().blockNumber) + result = w3Qty(chainDB.getCanonicalHead().number) server.rpc("eth_getBalance") do(data: Web3Address, quantityTag: BlockTag) -> UInt256: ## Returns the balance of the account of given address. @@ -205,7 +205,7 @@ proc setupEthRpc*( blockHash = data.ethHash header = chainDB.getBlockHeader(blockHash) txCount = chainDB.getTransactionCount(header.txRoot) - result = w3Qty(txCount) + result = Web3Quantity(txCount) server.rpc("eth_getBlockTransactionCountByNumber") do(quantityTag: BlockTag) -> Web3Quantity: ## Returns the number of transactions in a block matching the given block number. @@ -215,7 +215,7 @@ proc setupEthRpc*( let header = chainDB.headerFromTag(quantityTag) txCount = chainDB.getTransactionCount(header.txRoot) - result = w3Qty(txCount) + result = Web3Quantity(txCount) server.rpc("eth_getUncleCountByBlockHash") do(data: Web3Hash) -> Web3Quantity: ## Returns the number of uncles in a block from a block matching the given block hash. @@ -226,7 +226,7 @@ proc setupEthRpc*( blockHash = data.ethHash header = chainDB.getBlockHeader(blockHash) unclesCount = chainDB.getUnclesCount(header.ommersHash) - result = w3Qty(unclesCount) + result = Web3Quantity(unclesCount) server.rpc("eth_getUncleCountByBlockNumber") do(quantityTag: BlockTag) -> Web3Quantity: ## Returns the number of uncles in a block from a block matching the given block number. @@ -236,7 +236,7 @@ proc setupEthRpc*( let header = chainDB.headerFromTag(quantityTag) unclesCount = chainDB.getUnclesCount(header.ommersHash) - result = w3Qty(unclesCount.uint) + result = Web3Quantity(unclesCount) server.rpc("eth_getCode") do(data: Web3Address, quantityTag: BlockTag) -> seq[byte]: ## Returns code at a given address. @@ -416,7 +416,7 @@ proc setupEthRpc*( let header = chainDB.getBlockHeader(txDetails.blockNumber) var tx: Transaction if chainDB.getTransaction(header.txRoot, txDetails.index, tx): - result = populateTransactionObject(tx, some(header), some(txDetails.index)) + result = populateTransactionObject(tx, Opt.some(header), Opt.some(txDetails.index)) server.rpc("eth_getTransactionByBlockHashAndIndex") do(data: Web3Hash, quantity: Web3Quantity) -> TransactionObject: ## Returns information about a transaction by block hash and transaction index position. @@ -424,14 +424,14 @@ proc setupEthRpc*( ## data: hash of a block. ## quantity: integer of the transaction index position. ## Returns requested transaction information. - let index = int(quantity) + let index = uint64(quantity) var header: BlockHeader if not chainDB.getBlockHeader(data.ethHash(), header): return nil var tx: Transaction if chainDB.getTransaction(header.txRoot, index, tx): - result = populateTransactionObject(tx, some(header), some(index)) + result = populateTransactionObject(tx, Opt.some(header), Opt.some(index)) else: result = nil @@ -442,11 +442,11 @@ proc setupEthRpc*( ## quantity: the transaction index position. let header = chainDB.headerFromTag(quantityTag) - index = int(quantity) + index = uint64(quantity) var tx: Transaction if chainDB.getTransaction(header.txRoot, index, tx): - result = populateTransactionObject(tx, some(header), some(index)) + result = populateTransactionObject(tx, Opt.some(header), Opt.some(index)) else: result = nil @@ -466,10 +466,10 @@ proc setupEthRpc*( return nil var - idx = 0 + idx = 0'u64 prevGasUsed = GasInt(0) - for receipt in chainDB.getReceipts(header.receiptRoot): + for receipt in chainDB.getReceipts(header.receiptsRoot): let gasUsed = receipt.cumulativeGasUsed - prevGasUsed prevGasUsed = receipt.cumulativeGasUsed if idx == txDetails.index: @@ -482,13 +482,13 @@ proc setupEthRpc*( ## data: hash of block. ## quantity: the uncle's index position. ## Returns BlockObject or nil when no block was found. - let index = int(quantity) + let index = uint64(quantity) var header: BlockHeader if not chainDB.getBlockHeader(data.ethHash(), header): return nil let uncles = chainDB.getUncles(header.ommersHash) - if index < 0 or index >= uncles.len: + if index < 0 or index >= uncles.len.uint64: return nil result = populateBlockObject(uncles[index], chainDB, false, true) @@ -501,11 +501,11 @@ proc setupEthRpc*( ## quantity: the uncle's index position. ## Returns BlockObject or nil when no block was found. let - index = int(quantity) + index = uint64(quantity) header = chainDB.headerFromTag(quantityTag) uncles = chainDB.getUncles(header.ommersHash) - if index < 0 or index >= uncles.len: + if index < 0 or index >= uncles.len.uint64: return nil result = populateBlockObject(uncles[index], chainDB, false, true) @@ -519,7 +519,7 @@ proc setupEthRpc*( {.gcsafe, raises: [RlpError,ValueError].} = if headerBloomFilter(header, opts.address, opts.topics): let blockBody = chain.getBlockBody(hash) - let receipts = chain.getReceipts(header.receiptRoot) + let receipts = chain.getReceipts(header.receiptsRoot) # Note: this will hit assertion error if number of block transactions # do not match block receipts. # Although this is fine as number of receipts should always match number @@ -532,8 +532,8 @@ proc setupEthRpc*( proc getLogsForRange( chain: CoreDbRef, - start: UInt256, - finish: UInt256, + start: common.BlockNumber, + finish: common.BlockNumber, opts: FilterOptions): seq[FilterLog] {.gcsafe, raises: [RlpError,ValueError].} = var logs = newSeq[FilterLog]() @@ -572,11 +572,11 @@ proc setupEthRpc*( let fromHeader = chainDB.headerFromTag(filterOptions.fromBlock) let toHeader = chainDB.headerFromTag(filterOptions.toBlock) - # Note: if fromHeader.blockNumber > toHeader.blockNumber, no logs will be + # Note: if fromHeader.number > toHeader.number, no logs will be # returned. This is consistent with, what other ethereum clients return let logs = chainDB.getLogsForRange( - fromHeader.blockNumber, - toHeader.blockNumber, + fromHeader.number, + toHeader.number, filterOptions ) return logs @@ -606,12 +606,12 @@ proc setupEthRpc*( prevGasUsed = GasInt(0) recs: seq[ReceiptObject] txs: seq[Transaction] - index = 0 + index = 0'u64 for tx in chainDB.getBlockTransactions(header): txs.add tx - for receipt in chainDB.getReceipts(header.receiptRoot): + for receipt in chainDB.getReceipts(header.receiptsRoot): let gasUsed = receipt.cumulativeGasUsed - prevGasUsed prevGasUsed = receipt.cumulativeGasUsed recs.add populateReceipt(receipt, gasUsed, txs[index], index, header) @@ -629,7 +629,7 @@ proc setupEthRpc*( return createAccessList(header, com, args) except CatchableError as exc: return AccessListResult( - error: some("createAccessList error: " & exc.msg), + error: Opt.some("createAccessList error: " & exc.msg), ) server.rpc("eth_blobBaseFee") do() -> Web3Quantity: @@ -646,7 +646,7 @@ proc setupEthRpc*( server.rpc("eth_feeHistory") do(blockCount: Quantity, newestBlock: BlockTag, - rewardPercentiles: Option[seq[float64]]) -> FeeHistoryResult: + rewardPercentiles: Opt[seq[float64]]) -> FeeHistoryResult: let blocks = blockCount.uint64 percentiles = rewardPercentiles.get(newSeq[float64]()) @@ -711,12 +711,12 @@ proc setupEthRpc*( ## DATA, 32 Bytes - the boundary condition ("target"), 2^256 / difficulty. discard - server.rpc("eth_submitWork") do(nonce: int64, powHash: HexDataStr, mixDigest: HexDataStr) -> bool: + server.rpc("eth_submitWork") do(nonce: int64, powHash: HexDataStr, mixHash: HexDataStr) -> bool: ## Used for submitting a proof-of-work solution. ## ## nonce: the nonce found. ## headerPow: the header's pow-hash. - ## mixDigest: the mix digest. + ## mixHash: the mix digest. ## Returns true if the provided solution is valid, otherwise false. discard diff --git a/nimbus/rpc/params.nim b/nimbus/rpc/params.nim index a78b8d398..e4d503c39 100644 --- a/nimbus/rpc/params.nim +++ b/nimbus/rpc/params.nim @@ -32,8 +32,8 @@ func destination*(args: TransactionArgs): EthAddress = ethAddr args.to.get(ZeroAddr) proc toCallParams*(vmState: BaseVMState, args: TransactionArgs, - globalGasCap: GasInt, baseFee: Option[UInt256], - forkOverride = none(EVMFork)): EvmResult[CallParams] = + globalGasCap: GasInt, baseFee: Opt[UInt256], + forkOverride = Opt.none(EVMFork)): EvmResult[CallParams] = # Reject invalid combinations of pre- and post-1559 fee styles if args.gasPrice.isSome and diff --git a/nimbus/rpc/rpc_utils.nim b/nimbus/rpc/rpc_utils.nim index 49b41bb3d..672550923 100644 --- a/nimbus/rpc/rpc_utils.nim +++ b/nimbus/rpc/rpc_utils.nim @@ -10,7 +10,7 @@ {.push raises: [].} import - std/[strutils, algorithm, options], + std/[strutils, algorithm], ./rpc_types, ./params, ../common/common, @@ -55,10 +55,10 @@ proc headerFromTag*(chain: CoreDbRef, blockId: BlockTag): BlockHeader else: raise newException(ValueError, "Unsupported block tag " & tag) else: - let blockNum = blockId.number.uint64.toBlockNumber + let blockNum = blockId.number.uint64 result = chain.getBlockHeader(blockNum) -proc headerFromTag*(chain: CoreDbRef, blockTag: Option[BlockTag]): BlockHeader +proc headerFromTag*(chain: CoreDbRef, blockTag: Opt[BlockTag]): BlockHeader {.gcsafe, raises: [CatchableError].} = let blockId = blockTag.get(defaultTag) chain.headerFromTag(blockId) @@ -94,7 +94,7 @@ proc calculateMedianGasPrice*(chain: CoreDbRef): GasInt proc unsignedTx*(tx: TransactionArgs, chain: CoreDbRef, defaultNonce: AccountNonce): Transaction {.gcsafe, raises: [CatchableError].} = if tx.to.isSome: - result.to = some(ethAddr(tx.to.get)) + result.to = Opt.some(ethAddr(tx.to.get)) if tx.gas.isSome: result.gasLimit = tx.gas.get.GasInt @@ -132,15 +132,15 @@ proc toWdList(list: openArray[Withdrawal]): seq[WithdrawalObject] = result.add toWd(x) proc populateTransactionObject*(tx: Transaction, - optionalHeader: Option[BlockHeader] = none(BlockHeader), - txIndex: Option[int] = none(int)): TransactionObject + optionalHeader: Opt[BlockHeader] = Opt.none(BlockHeader), + txIndex: Opt[uint64] = Opt.none(uint64)): TransactionObject {.gcsafe, raises: [ValidationError].} = result = TransactionObject() - result.`type` = some w3Qty(tx.txType.ord) + result.`type` = Opt.some Quantity(tx.txType) if optionalHeader.isSome: let header = optionalHeader.get - result.blockHash = some(w3Hash header.blockHash) - result.blockNumber = some(w3BlockNumber(header.blockNumber)) + result.blockHash = Opt.some(w3Hash header.blockHash) + result.blockNumber = Opt.some(w3BlockNumber(header.number)) result.`from` = w3Addr tx.getSender() result.gas = w3Qty(tx.gasLimit) @@ -148,99 +148,97 @@ proc populateTransactionObject*(tx: Transaction, result.hash = w3Hash tx.rlpHash result.input = tx.payload result.nonce = w3Qty(tx.nonce) - result.to = some(w3Addr tx.destination) + result.to = Opt.some(w3Addr tx.destination) if txIndex.isSome: - result.transactionIndex = some(w3Qty(txIndex.get)) + result.transactionIndex = Opt.some(Quantity(txIndex.get)) result.value = tx.value result.v = w3Qty(tx.V) - result.r = u256(tx.R) - result.s = u256(tx.S) - result.maxFeePerGas = some w3Qty(tx.maxFee) - result.maxPriorityFeePerGas = some w3Qty(tx.maxPriorityFee) + result.r = tx.R + result.s = tx.S + result.maxFeePerGas = Opt.some w3Qty(tx.maxFeePerGas) + result.maxPriorityFeePerGas = Opt.some w3Qty(tx.maxPriorityFeePerGas) if tx.txType >= TxEip2930: - result.chainId = some(Web3Quantity(tx.chainId)) - result.accessList = some(w3AccessList(tx.accessList)) + result.chainId = Opt.some(Web3Quantity(tx.chainId)) + result.accessList = Opt.some(w3AccessList(tx.accessList)) if tx.txType >= TxEIP4844: - result.maxFeePerBlobGas = some(tx.maxFeePerBlobGas) - result.blobVersionedHashes = some(w3Hashes tx.versionedHashes) + result.maxFeePerBlobGas = Opt.some(tx.maxFeePerBlobGas) + result.blobVersionedHashes = Opt.some(w3Hashes tx.versionedHashes) proc populateBlockObject*(header: BlockHeader, chain: CoreDbRef, fullTx: bool, isUncle = false): BlockObject {.gcsafe, raises: [CatchableError].} = let blockHash = header.blockHash result = BlockObject() - result.number = w3BlockNumber(header.blockNumber) + result.number = w3BlockNumber(header.number) result.hash = w3Hash blockHash result.parentHash = w3Hash header.parentHash - result.nonce = some(FixedBytes[8] header.nonce) + result.nonce = Opt.some(FixedBytes[8] header.nonce) result.sha3Uncles = w3Hash header.ommersHash - result.logsBloom = FixedBytes[256] header.bloom + result.logsBloom = FixedBytes[256] header.logsBloom result.transactionsRoot = w3Hash header.txRoot result.stateRoot = w3Hash header.stateRoot - result.receiptsRoot = w3Hash header.receiptRoot + result.receiptsRoot = w3Hash header.receiptsRoot result.miner = w3Addr header.coinbase result.difficulty = header.difficulty result.extraData = HistoricExtraData header.extraData - result.mixHash = w3Hash header.mixDigest + result.mixHash = w3Hash header.mixHash # discard sizeof(seq[byte]) of extraData and use actual length let size = sizeof(BlockHeader) - sizeof(common.Blob) + header.extraData.len - result.size = w3Qty(size) + result.size = Quantity(size) result.gasLimit = w3Qty(header.gasLimit) result.gasUsed = w3Qty(header.gasUsed) result.timestamp = w3Qty(header.timestamp) - result.baseFeePerGas = if header.fee.isSome: - some(header.baseFee) - else: - none(UInt256) + result.baseFeePerGas = header.baseFeePerGas + if not isUncle: result.totalDifficulty = chain.getScore(blockHash).valueOr(0.u256) result.uncles = w3Hashes chain.getUncleHashes(header) if fullTx: - var i = 0 + var i = 0'u64 for tx in chain.getBlockTransactions(header): - result.transactions.add txOrHash(populateTransactionObject(tx, some(header), some(i))) + result.transactions.add txOrHash(populateTransactionObject(tx, Opt.some(header), Opt.some(i))) inc i else: for x in chain.getBlockTransactionHashes(header): result.transactions.add txOrHash(w3Hash(x)) if header.withdrawalsRoot.isSome: - result.withdrawalsRoot = some(w3Hash header.withdrawalsRoot.get) - result.withdrawals = some(toWdList(chain.getWithdrawals(header.withdrawalsRoot.get))) + result.withdrawalsRoot = Opt.some(w3Hash header.withdrawalsRoot.get) + result.withdrawals = Opt.some(toWdList(chain.getWithdrawals(header.withdrawalsRoot.get))) if header.blobGasUsed.isSome: - result.blobGasUsed = some(w3Qty(header.blobGasUsed.get)) + result.blobGasUsed = Opt.some(w3Qty(header.blobGasUsed.get)) if header.excessBlobGas.isSome: - result.excessBlobGas = some(w3Qty(header.excessBlobGas.get)) + result.excessBlobGas = Opt.some(w3Qty(header.excessBlobGas.get)) if header.parentBeaconBlockRoot.isSome: - result.parentBeaconBlockRoot = some(w3Hash header.parentBeaconBlockRoot.get) + result.parentBeaconBlockRoot = Opt.some(w3Hash header.parentBeaconBlockRoot.get) proc populateReceipt*(receipt: Receipt, gasUsed: GasInt, tx: Transaction, - txIndex: int, header: BlockHeader): ReceiptObject + txIndex: uint64, header: BlockHeader): ReceiptObject {.gcsafe, raises: [ValidationError].} = result = ReceiptObject() result.transactionHash = w3Hash tx.rlpHash result.transactionIndex = w3Qty(txIndex) result.blockHash = w3Hash header.blockHash - result.blockNumber = w3BlockNumber(header.blockNumber) + result.blockNumber = w3BlockNumber(header.number) result.`from` = w3Addr tx.getSender() - result.to = some(w3Addr tx.destination) + result.to = Opt.some(w3Addr tx.destination) result.cumulativeGasUsed = w3Qty(receipt.cumulativeGasUsed) result.gasUsed = w3Qty(gasUsed) - result.`type` = some w3Qty(receipt.receiptType.ord) + result.`type` = Opt.some Quantity(receipt.receiptType) if tx.contractCreation: var sender: EthAddress if tx.getSender(sender): let contractAddress = generateAddress(sender, tx.nonce) - result.contractAddress = some(w3Addr contractAddress) + result.contractAddress = Opt.some(w3Addr contractAddress) for log in receipt.logs: # TODO: Work everywhere with either `Hash256` as topic or `array[32, byte]` @@ -252,13 +250,13 @@ proc populateReceipt*(receipt: Receipt, gasUsed: GasInt, tx: Transaction, removed: false, # TODO: Not sure what is difference between logIndex and TxIndex and how # to calculate it. - logIndex: some(result.transactionIndex), + logIndex: Opt.some(result.transactionIndex), # Note: the next 4 fields cause a lot of duplication of data, but the spec # is what it is. Not sure if other clients actually add this. - transactionIndex: some(result.transactionIndex), - transactionHash: some(result.transactionHash), - blockHash: some(result.blockHash), - blockNumber: some(result.blockNumber), + transactionIndex: Opt.some(result.transactionIndex), + transactionHash: Opt.some(result.transactionHash), + blockHash: Opt.some(result.blockHash), + blockNumber: Opt.some(result.blockNumber), # The actual fields address: w3Addr log.address, data: log.data, @@ -266,21 +264,22 @@ proc populateReceipt*(receipt: Receipt, gasUsed: GasInt, tx: Transaction, ) result.logs.add(logObject) - result.logsBloom = FixedBytes[256] receipt.bloom + result.logsBloom = FixedBytes[256] receipt.logsBloom # post-transaction stateroot (pre Byzantium). if receipt.hasStateRoot: - result.root = some(w3Hash receipt.stateRoot) + result.root = Opt.some(w3Hash receipt.stateRoot) else: # 1 = success, 0 = failure. - result.status = some(w3Qty(receipt.status.uint64)) + result.status = Opt.some(w3Qty(receipt.status.uint64)) - let normTx = eip1559TxNormalization(tx, header.baseFee.truncate(GasInt)) + let baseFeePerGas = header.baseFeePerGas.get(0.u256) + let normTx = eip1559TxNormalization(tx, baseFeePerGas.truncate(GasInt)) result.effectiveGasPrice = w3Qty(normTx.gasPrice) if tx.txType == TxEip4844: - result.blobGasUsed = some(w3Qty(tx.versionedHashes.len.uint64 * GAS_PER_BLOB.uint64)) - result.blobGasPrice = some(getBlobBaseFee(header.excessBlobGas.get(0'u64))) + result.blobGasUsed = Opt.some(w3Qty(tx.versionedHashes.len.uint64 * GAS_PER_BLOB.uint64)) + result.blobGasPrice = Opt.some(getBlobBaseFee(header.excessBlobGas.get(0'u64))) proc createAccessList*(header: BlockHeader, com: CommonRef, @@ -288,19 +287,19 @@ proc createAccessList*(header: BlockHeader, template handleError(msg: string) = return AccessListResult( - error: some(msg), + error: Opt.some(msg), ) var args = args # If the gas amount is not set, default to RPC gas cap. if args.gas.isNone: - args.gas = some(Quantity DEFAULT_RPC_GAS_CAP) + args.gas = Opt.some(Quantity DEFAULT_RPC_GAS_CAP) let vmState = BaseVMState.new(header, com).valueOr: handleError("failed to create vmstate: " & $error.code) - fork = com.toEVMFork(forkDeterminationInfo(header.blockNumber, header.timestamp)) + fork = com.toEVMFork(forkDeterminationInfo(header.number, header.timestamp)) sender = args.sender # TODO: nonce should be retrieved from txPool nonce = vmState.stateDB.getNonce(sender) @@ -321,7 +320,7 @@ proc createAccessList*(header: BlockHeader, # Set the accesslist to the last accessList # generated by prevTracer - args.accessList = some(w3AccessList accessList) + args.accessList = Opt.some(w3AccessList accessList) # Apply the transaction with the access list tracer let diff --git a/nimbus/sync/beacon.nim b/nimbus/sync/beacon.nim index c4aadde2d..e4f062607 100644 --- a/nimbus/sync/beacon.nim +++ b/nimbus/sync/beacon.nim @@ -110,7 +110,7 @@ func updateBeaconHeaderCB(ctx: BeaconSyncRef): SyncReqNewHeadCB = ## for the RPC module. result = proc(h: BlockHeader) {.gcsafe, raises: [].} = try: - debug "REQUEST SYNC", number=h.blockNumber, hash=h.blockHash.short + debug "REQUEST SYNC", number=h.number, hash=h.blockHash.short waitFor ctx.ctx.appendSyncTarget(h) except CatchableError as ex: error "updateBeconHeaderCB error", msg=ex.msg diff --git a/nimbus/sync/beacon/beacon_impl.nim b/nimbus/sync/beacon/beacon_impl.nim index 4fc64d6ba..c02a0e608 100644 --- a/nimbus/sync/beacon/beacon_impl.nim +++ b/nimbus/sync/beacon/beacon_impl.nim @@ -9,7 +9,7 @@ # except according to those terms. import - std/tables, + std/[tables, options], chronicles, chronos, chronos/timer, @@ -52,7 +52,7 @@ func makeGetBlocksJob(number, maxResults: uint64) : BeaconJob = func makeHeaderRequest(number: uint64, maxResults: uint64): BlocksRequest = BlocksRequest( - startBlock: HashOrNum(isHash: false, number: number.u256), + startBlock: HashOrNum(isHash: false, number: number), maxResults: maxResults.uint, skip: 0, reverse: true @@ -283,7 +283,7 @@ proc executeGetBodyJob*(buddy: BeaconBuddyRef, job: BeaconJob): Future[void] {.a if b.isNone: debug "executeGetBodyJob->getBodies none", hash=job.getBodyJob.headerHash.short, - number=job.getBodyJob.header.blockNumber + number=job.getBodyJob.header.number # retry with other peer buddy.requeue job return @@ -292,7 +292,7 @@ proc executeGetBodyJob*(buddy: BeaconBuddyRef, job: BeaconJob): Future[void] {.a if bodies.blocks.len == 0: debug "executeGetBodyJob->getBodies isZero", hash=job.getBodyJob.headerHash.short, - number=job.getBodyJob.header.blockNumber + number=job.getBodyJob.header.number # retry with other peer buddy.requeue job return diff --git a/nimbus/sync/beacon/skeleton_db.nim b/nimbus/sync/beacon/skeleton_db.nim index 248b7050e..0e90d6728 100644 --- a/nimbus/sync/beacon/skeleton_db.nim +++ b/nimbus/sync/beacon/skeleton_db.nim @@ -77,7 +77,7 @@ proc getHeader*(sk: SkeletonRef, onlySkeleton: bool = false): Result[Opt[BlockHeader], string] = ## Gets a block from the skeleton or canonical db by number. try: - let rawHeader = sk.get(skeletonHeaderKey(number.toBlockNumber)) + let rawHeader = sk.get(skeletonHeaderKey(number.BlockNumber)) if rawHeader.len != 0: let output = rlp.decode(rawHeader, BlockHeader) return ok(Opt.some output) @@ -88,7 +88,7 @@ proc getHeader*(sk: SkeletonRef, # As a fallback, try to get the block from the canonical chain # in case it is available there var output: BlockHeader - if sk.db.getBlockHeader(number.toBlockNumber, output): + if sk.db.getBlockHeader(number.BlockNumber, output): return ok(Opt.some output) ok(Opt.none BlockHeader) @@ -124,10 +124,10 @@ proc getHeader*(sk: SkeletonRef, proc putHeader*(sk: SkeletonRef, header: BlockHeader) = ## Writes a skeleton block header to the db by number let encodedHeader = rlp.encode(header) - sk.put(skeletonHeaderKey(header.blockNumber), encodedHeader) + sk.put(skeletonHeaderKey(header.number), encodedHeader) sk.put( skeletonBlockHashToNumberKey(header.blockHash), - rlp.encode(header.blockNumber) + rlp.encode(header.number) ) proc putBody*(sk: SkeletonRef, header: BlockHeader, body: BlockBody): Result[void, string] = @@ -180,7 +180,7 @@ proc readProgress*(sk: SkeletonRef): Result[void, string] = proc deleteHeaderAndBody*(sk: SkeletonRef, header: BlockHeader) = ## Deletes a skeleton block from the db by number - sk.del(skeletonHeaderKey(header.blockNumber)) + sk.del(skeletonHeaderKey(header.number)) sk.del(skeletonBlockHashToNumberKey(header.blockHash)) sk.del(skeletonBodyKey(header.sumHash)) @@ -193,7 +193,7 @@ proc canonicalHead*(sk: SkeletonRef): Result[BlockHeader, string] = proc resetCanonicalHead*(sk: SkeletonRef, newHead, oldHead: uint64) = debug "RESET CANONICAL", newHead, oldHead - sk.chain.com.syncCurrent = newHead.toBlockNumber + sk.chain.com.syncCurrent = newHead.BlockNumber proc insertBlocks*(sk: SkeletonRef, blocks: openArray[EthBlock], diff --git a/nimbus/sync/beacon/skeleton_utils.nim b/nimbus/sync/beacon/skeleton_utils.nim index f36e9dd15..f08361d6d 100644 --- a/nimbus/sync/beacon/skeleton_utils.nim +++ b/nimbus/sync/beacon/skeleton_utils.nim @@ -26,7 +26,7 @@ const # ------------------------------------------------------------------------------ func u64*(h: BlockHeader): uint64 = - h.blockNumber.truncate(uint64) + h.number func blockHash*(x: Opt[BlockHeader]): Hash256 = if x.isSome: x.get.blockHash @@ -79,7 +79,7 @@ func notEmpty*(sk: SkeletonRef): bool = sk.progress.segments.len > 0 func blockHeight*(sk: SkeletonRef): uint64 = - sk.chain.com.syncCurrent.truncate(uint64) + sk.chain.com.syncCurrent func genesisHash*(sk: SkeletonRef): Hash256 = sk.chain.com.genesisHash diff --git a/nimbus/sync/handlers/eth.nim b/nimbus/sync/handlers/eth.nim index 95a1125e6..b7f283211 100644 --- a/nimbus/sync/handlers/eth.nim +++ b/nimbus/sync/handlers/eth.nim @@ -92,17 +92,17 @@ proc successorHeader(db: CoreDbRef, h: BlockHeader, output: var BlockHeader, skip = 0'u): bool {.gcsafe, raises: [RlpError].} = - let offset = 1 + skip.toBlockNumber - if h.blockNumber <= (not 0.toBlockNumber) - offset: - result = db.getBlockHeader(h.blockNumber + offset, output) + let offset = 1 + skip.BlockNumber + if h.number <= (not 0.BlockNumber) - offset: + result = db.getBlockHeader(h.number + offset, output) proc ancestorHeader(db: CoreDbRef, h: BlockHeader, output: var BlockHeader, skip = 0'u): bool {.gcsafe, raises: [RlpError].} = - let offset = 1 + skip.toBlockNumber - if h.blockNumber >= offset: - result = db.getBlockHeader(h.blockNumber - offset, output) + let offset = 1 + skip.BlockNumber + if h.number >= offset: + result = db.getBlockHeader(h.number - offset, output) proc blockHeader(db: CoreDbRef, b: HashOrNum, @@ -399,7 +399,7 @@ method getStatus*(ctx: EthWireRef): Result[EthState, string] db = ctx.db com = ctx.chain.com bestBlock = db.getCanonicalHead() - forkId = com.forkId(bestBlock.blockNumber, bestBlock.timestamp) + forkId = com.forkId(bestBlock.number, bestBlock.timestamp) return ok(EthState( totalDifficulty: db.headTotalDifficulty, @@ -426,7 +426,7 @@ method getReceipts*(ctx: EthWireRef, var list: seq[seq[Receipt]] for blockHash in hashes: if db.getBlockHeader(blockHash, header): - list.add db.getReceipts(header.receiptRoot) + list.add db.getReceipts(header.receiptsRoot) else: list.add @[] trace "handlers.getReceipts: blockHeader not found", blockHash @@ -574,7 +574,7 @@ method handleNewBlock*(ctx: EthWireRef, try: if ctx.chain.com.forkGTE(MergeFork): debug "Dropping peer for sending NewBlock after merge (EIP-3675)", - peer, blockNumber=blk.header.blockNumber, + peer, blockNumber=blk.header.number, blockHash=blk.header.blockHash, totalDifficulty asyncSpawn banPeer(ctx.peerPool, peer, PEER_LONG_BANTIME) return ok() diff --git a/nimbus/sync/protocol/eth68.nim b/nimbus/sync/protocol/eth68.nim index 488b55b4f..d348cadc9 100644 --- a/nimbus/sync/protocol/eth68.nim +++ b/nimbus/sync/protocol/eth68.nim @@ -228,7 +228,7 @@ p2pProtocol eth68(version = ethVersion, when trEthTraceGossipOk: trace trEthRecvReceived & "NewBlock (0x07)", peer, totalDifficulty, - blockNumber = blk.header.blockNumber, + blockNumber = blk.header.number, blockDifficulty = blk.header.difficulty let ctx = peer.networkState() diff --git a/nimbus/sync/snap/range_desc.nim b/nimbus/sync/snap/range_desc.nim index 65d5f6452..c76755ab6 100644 --- a/nimbus/sync/snap/range_desc.nim +++ b/nimbus/sync/snap/range_desc.nim @@ -78,12 +78,12 @@ type ## Storage root header accKey*: NodeKey ## Owner account, maybe unnecessary storageRoot*: Hash256 ## Start of storage tree - subRange*: Option[NodeTagRange] ## Sub-range of slot range covered + subRange*: Opt[NodeTagRange] ## Sub-range of slot range covered AccountSlotsChanged* = object ## Variant of `AccountSlotsHeader` representing some transition account*: AccountSlotsHeader ## Account header - newRange*: Option[NodeTagRange] ## New sub-range (if-any) + newRange*: Opt[NodeTagRange] ## New sub-range (if-any) AccountStorageRange* = object ## List of storage descriptors, the last `AccountSlots` storage data might @@ -282,14 +282,14 @@ proc emptyFactor*(lrs: openArray[NodeTagRangeSet]): float = if accu == 0.to(NodeTag): 1.0 else: - ((high(NodeTag) - accu).u256 + 1).to(float) / (2.0^256) + ((high(NodeTag) - accu) + 1).to(float) / (2.0^256) proc fullFactor*(lrs: NodeTagRangeSet): float = ## Relative covered total, i.e. `#points-covered / 2^256` to be used ## in statistics or triggers if 0 < lrs.total: - lrs.total.u256.to(float) / (2.0^256) + lrs.total.to(float) / (2.0^256) elif lrs.chunks == 0: 0.0 # `total` represents the residue class `mod 2^256` from `0`..`(2^256-1)` else: @@ -314,7 +314,7 @@ proc fullFactor*(lrs: openArray[NodeTagRangeSet]): float = proc fullFactor*(iv: NodeTagRange): float = ## Relative covered length of an inetrval, i.e. `#points-covered / 2^256` if 0 < iv.len: - iv.len.u256.to(float) / (2.0^256) + iv.len.to(float) / (2.0^256) else: 1.0 # number of points in `iv` is `2^256 + 1` diff --git a/nimbus/tracer.nim b/nimbus/tracer.nim index 7f0e58ce9..2b83019b6 100644 --- a/nimbus/tracer.nim +++ b/nimbus/tracer.nim @@ -44,7 +44,7 @@ proc toJson(receipt: Receipt): JsonNode = result = newJObject() result["cumulativeGasUsed"] = %receipt.cumulativeGasUsed - result["bloom"] = %receipt.bloom + result["bloom"] = %receipt.logsBloom result["logs"] = %receipt.logs if receipt.hasStateRoot: @@ -54,7 +54,7 @@ proc toJson(receipt: Receipt): JsonNode = proc dumpReceipts*(chainDB: CoreDbRef, header: BlockHeader): JsonNode = result = newJArray() - for receipt in chainDB.getReceipts(header.receiptRoot): + for receipt in chainDB.getReceipts(header.receiptsRoot): result.add receipt.toJson proc toJson*(receipts: seq[Receipt]): JsonNode = @@ -110,7 +110,7 @@ const internalTxName = "internalTx" proc traceTransaction*(com: CommonRef, header: BlockHeader, - transactions: openArray[Transaction], txIndex: int, + transactions: openArray[Transaction], txIndex: uint64, tracerFlags: set[TracerFlags] = {}): JsonNode = let # we add a memory layer between backend/lower layer db @@ -147,7 +147,7 @@ proc traceTransaction*(com: CommonRef, header: BlockHeader, let sender = tx.getSender let recipient = tx.getRecipient(sender) - if idx == txIndex: + if idx.uint64 == txIndex: vmState.tracer = tracerInst # only enable tracer on target tx before.captureAccount(stateDb, sender, senderName) before.captureAccount(stateDb, recipient, recipientName) @@ -160,7 +160,7 @@ proc traceTransaction*(com: CommonRef, header: BlockHeader, let rc = vmState.processTransaction(tx, sender, header) gasUsed = if rc.isOk: rc.value else: 0 - if idx == txIndex: + if idx.uint64 == txIndex: after.captureAccount(stateDb, sender, senderName) after.captureAccount(stateDb, recipient, recipientName) after.captureAccount(stateDb, miner, minerName) @@ -293,14 +293,14 @@ proc traceBlock*(com: CommonRef, blk: EthBlock, tracerFlags: set[TracerFlags] = proc traceTransactions*(com: CommonRef, header: BlockHeader, transactions: openArray[Transaction]): JsonNode = result = newJArray() for i in 0 ..< transactions.len: - result.add traceTransaction(com, header, transactions, i, {DisableState}) + result.add traceTransaction(com, header, transactions, i.uint64, {DisableState}) proc dumpDebuggingMetaData*(vmState: BaseVMState, blk: EthBlock, launchDebugger = true) = template header: BlockHeader = blk.header let com = vmState.com - blockNumber = header.blockNumber + blockNumber = header.number capture = com.db.newCapture.value captureCom = com.clone(capture.recorder) bloom = createBloom(vmState.receipts) @@ -308,7 +308,7 @@ proc dumpDebuggingMetaData*(vmState: BaseVMState, blk: EthBlock, launchDebugger capture.forget() let blockSummary = %{ - "receiptsRoot": %("0x" & toHex(calcReceiptRoot(vmState.receipts).data)), + "receiptsRoot": %("0x" & toHex(calcReceiptsRoot(vmState.receipts).data)), "stateRoot": %("0x" & toHex(vmState.stateDB.rootHash.data)), "logsBloom": %("0x" & toHex(bloom)) } diff --git a/nimbus/transaction.nim b/nimbus/transaction.nim index c57afebcc..44b85d12b 100644 --- a/nimbus/transaction.nim +++ b/nimbus/transaction.nim @@ -38,15 +38,15 @@ proc intrinsicGas*(tx: Transaction, fork: EVMFork): GasInt = result = result + gasFees[fork][GasTXCreate] if fork >= FkShanghai: # cannot use wordCount here, it will raise unlisted exception - let numWords = toWordSize(tx.payload.len) + let numWords = toWordSize(GasInt tx.payload.len) result = result + (gasFees[fork][GasInitcodeWord] * numWords) if tx.txType > TxLegacy: - result = result + tx.accessList.len * ACCESS_LIST_ADDRESS_COST + result = result + GasInt(tx.accessList.len) * ACCESS_LIST_ADDRESS_COST var numKeys = 0 for n in tx.accessList: inc(numKeys, n.storageKeys.len) - result = result + numKeys * ACCESS_LIST_STORAGE_KEY_COST + result = result + GasInt(numKeys) * ACCESS_LIST_STORAGE_KEY_COST proc getSignature*(tx: Transaction, output: var Signature): bool = var bytes: array[65, byte] @@ -98,8 +98,8 @@ proc getRecipient*(tx: Transaction, sender: EthAddress): EthAddress = proc validateTxLegacy(tx: Transaction, fork: EVMFork) = var - vMin = 27'i64 - vMax = 28'i64 + vMin = 27'u64 + vMax = 28'u64 if tx.V >= EIP155_CHAIN_ID_OFFSET: let chainId = (tx.V - EIP155_CHAIN_ID_OFFSET) div 2 @@ -120,7 +120,7 @@ proc validateTxLegacy(tx: Transaction, fork: EVMFork) = raise newException(ValidationError, "Invalid legacy transaction") proc validateTxEip2930(tx: Transaction) = - var isValid = tx.V == 0'i64 or tx.V == 1'i64 + var isValid = tx.V == 0'u64 or tx.V == 1'u64 isValid = isValid and tx.S >= UInt256.one isValid = isValid and tx.S < SECPK1_N isValid = isValid and tx.R < SECPK1_N @@ -173,7 +173,7 @@ proc signTransaction*(tx: Transaction, privateKey: PrivateKey, chainId: ChainId, result = tx if eip155: # trigger rlpEncodeEIP155 in nim-eth - result.V = chainId.int64 * 2'i64 + 35'i64 + result.V = chainId.uint64 * 2'u64 + 35'u64 let rlpTx = rlpEncode(result) @@ -182,17 +182,17 @@ proc signTransaction*(tx: Transaction, privateKey: PrivateKey, chainId: ChainId, case tx.txType of TxLegacy: if eip155: - result.V = sig[64].int64 + result.V + result.V = sig[64].uint64 + result.V else: - result.V = sig[64].int64 + 27'i64 + result.V = sig[64].uint64 + 27'u64 else: - result.V = sig[64].int64 + result.V = sig[64].uint64 result.R = UInt256.fromBytesBE(sig[0..31]) result.S = UInt256.fromBytesBE(sig[32..63]) # deriveChainId derives the chain id from the given v parameter -func deriveChainId*(v: int64, chainId: ChainId): ChainId = +func deriveChainId*(v: uint64, chainId: ChainId): ChainId = if v == 27 or v == 28: chainId else: @@ -205,28 +205,29 @@ func validateChainId*(tx: Transaction, chainId: ChainId): bool = chainId.uint64 == tx.chainId.uint64 func eip1559TxNormalization*(tx: Transaction; - baseFee: GasInt): Transaction = + baseFeePerGas: GasInt): Transaction = ## This function adjusts a legacy transaction to EIP-1559 standard. This ## is needed particularly when using the `validateTransaction()` utility ## with legacy transactions. result = tx if tx.txType < TxEip1559: - result.maxPriorityFee = tx.gasPrice - result.maxFee = tx.gasPrice + result.maxPriorityFeePerGas = tx.gasPrice + result.maxFeePerGas = tx.gasPrice else: - result.gasPrice = baseFee + min(result.maxPriorityFee, result.maxFee - baseFee) + result.gasPrice = baseFeePerGas + + min(result.maxPriorityFeePerGas, result.maxFeePerGas - baseFeePerGas) -func effectiveGasTip*(tx: Transaction; baseFee: Option[UInt256]): GasInt = +func effectiveGasTip*(tx: Transaction; baseFeePerGas: Opt[UInt256]): GasInt = var - maxPriorityFee = tx.maxPriorityFee - maxFee = tx.maxFee - baseFee = baseFee.get(0.u256).truncate(GasInt) + maxPriorityFeePerGas = tx.maxPriorityFeePerGas + maxFeePerGas = tx.maxFeePerGas + baseFeePerGas = baseFeePerGas.get(0.u256).truncate(GasInt) if tx.txType < TxEip1559: - maxPriorityFee = tx.gasPrice - maxFee = tx.gasPrice + maxPriorityFeePerGas = tx.gasPrice + maxFeePerGas = tx.gasPrice - min(maxPriorityFee, maxFee - baseFee) + min(maxPriorityFeePerGas, maxFeePerGas - baseFeePerGas) proc decodeTx*(bytes: openArray[byte]): Transaction = var rlp = rlpFromBytes(bytes) diff --git a/nimbus/transaction/call_common.nim b/nimbus/transaction/call_common.nim index 7208a5db2..81ffd76ec 100644 --- a/nimbus/transaction/call_common.nim +++ b/nimbus/transaction/call_common.nim @@ -9,8 +9,9 @@ {.push raises: [].} import - eth/common/eth_types, stint, options, stew/ptrops, + eth/common/eth_types, stint, stew/ptrops, chronos, + results, ".."/[vm_types, vm_state, vm_computation], ".."/[vm_internals, vm_precompiles, vm_gas_costs], ".."/[db/ledger], @@ -28,8 +29,8 @@ type # Standard call parameters. CallParams* = object vmState*: BaseVMState # Chain, database, state, block, fork. - forkOverride*: Option[EVMFork] # Default fork is usually correct. - origin*: Option[HostAddress] # Default origin is `sender`. + forkOverride*: Opt[EVMFork] # Default fork is usually correct. + origin*: Opt[HostAddress] # Default origin is `sender`. gasPrice*: GasInt # Gas price for this call. gasLimit*: GasInt # Maximum gas available for this call. sender*: HostAddress # Sender account. @@ -63,7 +64,7 @@ proc hostToComputationMessage*(msg: EvmcMessage): Message = Message( kind: CallKind(msg.kind.ord), depth: msg.depth, - gas: msg.gas, + gas: GasInt msg.gas, sender: msg.sender.fromEvmc, contractAddress: msg.recipient.fromEvmc, codeAddress: msg.code_address.fromEvmc, @@ -97,7 +98,7 @@ func intrinsicGas*(call: CallParams, vmState: BaseVMState): GasInt {.inline.} = if fork >= FkBerlin: for account in call.accessList: gas += ACCESS_LIST_ADDRESS_COST - gas += account.storageKeys.len * ACCESS_LIST_STORAGE_KEY_COST + gas += GasInt(account.storageKeys.len) * ACCESS_LIST_STORAGE_KEY_COST return gas @@ -217,7 +218,7 @@ when defined(evmc_enabled): else: c.setError(callResult.status_code, true) - c.gasMeter.gasRemaining = callResult.gas_left + c.gasMeter.gasRemaining = GasInt callResult.gas_left c.msg.contractAddress = callResult.create_address.fromEvmc c.output = if callResult.output_size <= 0: @[] else: @(makeOpenArray(callResult.output_data, @@ -265,7 +266,7 @@ proc calculateAndPossiblyRefundGas(host: TransactionHost, call: CallParams): Gas result = c.gasMeter.gasRemaining elif not c.shouldBurnGas: let maxRefund = (call.gasLimit - c.gasMeter.gasRemaining) div MaxRefundQuotient - let refund = min(c.getGasRefund(), maxRefund) + let refund = min(GasInt c.getGasRefund(), maxRefund) c.gasMeter.returnGas(refund) result = c.gasMeter.gasRemaining @@ -279,7 +280,7 @@ proc finishRunningComputation(host: TransactionHost, call: CallParams): CallResu let gasRemaining = calculateAndPossiblyRefundGas(host, call) # evm gas used without intrinsic gas - let gasUsed = host.msg.gas - gasRemaining + let gasUsed = host.msg.gas.GasInt - gasRemaining host.vmState.captureEnd(c, c.output, gasUsed, c.errorOpt) if c.isError: diff --git a/nimbus/transaction/call_evm.nim b/nimbus/transaction/call_evm.nim index 6c68eb50b..56dc3a58c 100644 --- a/nimbus/transaction/call_evm.nim +++ b/nimbus/transaction/call_evm.nim @@ -9,7 +9,6 @@ {.push raises: [].} import - std/[options], chronicles, chronos, eth/common/eth_types_rlp, @@ -30,10 +29,11 @@ proc rpcCallEvm*(args: TransactionArgs, let topHeader = common.BlockHeader( parentHash: header.blockHash, timestamp: EthTime.now(), - gasLimit: 0.GasInt, ## ??? - fee: UInt256.none()) ## ??? + gasLimit: 0.GasInt, ## ??? + baseFeePerGas: Opt.none UInt256, ## ??? + ) let vmState = ? BaseVMState.new(topHeader, com) - let params = ? toCallParams(vmState, args, globalGasCap, header.fee) + let params = ? toCallParams(vmState, args, globalGasCap, header.baseFeePerGas) var dbTx = com.db.newTransaction() defer: dbTx.dispose() # always dispose state changes @@ -45,7 +45,7 @@ proc rpcCallEvm*(args: TransactionArgs, com: CommonRef, vmState: BaseVMState): EvmResult[CallResult] = const globalGasCap = 0 # TODO: globalGasCap should configurable by user - let params = ? toCallParams(vmState, args, globalGasCap, header.fee) + let params = ? toCallParams(vmState, args, globalGasCap, header.baseFeePerGas) var dbTx = com.db.newTransaction() defer: dbTx.dispose() # always dispose state changes @@ -59,12 +59,13 @@ proc rpcEstimateGas*(args: TransactionArgs, let topHeader = common.BlockHeader( parentHash: header.blockHash, timestamp: EthTime.now(), - gasLimit: 0.GasInt, ## ??? - fee: UInt256.none()) ## ??? + gasLimit: 0.GasInt, ## ??? + baseFeePerGas: Opt.none UInt256, ## ??? + ) let vmState = ? BaseVMState.new(topHeader, com) let fork = vmState.determineFork let txGas = gasFees[fork][GasTransaction] # txGas always 21000, use constants? - var params = ? toCallParams(vmState, args, gasCap, header.fee) + var params = ? toCallParams(vmState, args, gasCap, header.baseFeePerGas) var lo : GasInt = txGas - 1 @@ -151,7 +152,7 @@ proc callParamsForTx(tx: Transaction, sender: EthAddress, vmState: BaseVMState, # just be writing this as a bunch of assignment statements? result = CallParams( vmState: vmState, - forkOverride: some(fork), + forkOverride: Opt.some(fork), gasPrice: tx.gasPrice, gasLimit: tx.gasLimit, sender: sender, @@ -169,7 +170,7 @@ proc callParamsForTx(tx: Transaction, sender: EthAddress, vmState: BaseVMState, proc callParamsForTest(tx: Transaction, sender: EthAddress, vmState: BaseVMState, fork: EVMFork): CallParams = result = CallParams( vmState: vmState, - forkOverride: some(fork), + forkOverride: Opt.some(fork), gasPrice: tx.gasPrice, gasLimit: tx.gasLimit, sender: sender, diff --git a/nimbus/transaction/evmc_host_glue.nim b/nimbus/transaction/evmc_host_glue.nim index 54f6ae2b0..8d6d24fe6 100644 --- a/nimbus/transaction/evmc_host_glue.nim +++ b/nimbus/transaction/evmc_host_glue.nim @@ -65,7 +65,7 @@ proc getBlockHash(p: evmc_host_context, number: int64): evmc_bytes32 {.cdecl.} = # TODO: `HostBlockNumber` is 256-bit unsigned. It should be changed to match # EVMC which is more sensible. - toHost(p).getBlockHash(number.uint64.u256).toEvmc + toHost(p).getBlockHash(number.uint64).toEvmc proc emitLog(p: evmc_host_context, address: var evmc_address, data: ptr byte, data_size: csize_t, diff --git a/nimbus/transaction/host_call_nested.nim b/nimbus/transaction/host_call_nested.nim index d3a893f2a..ad3a61df3 100644 --- a/nimbus/transaction/host_call_nested.nim +++ b/nimbus/transaction/host_call_nested.nim @@ -25,7 +25,7 @@ proc beforeExecCreateEvmcNested(host: TransactionHost, let childMsg = Message( kind: CallKind(m.kind.ord), depth: m.depth, - gas: m.gas, + gas: GasInt m.gas, sender: m.sender.fromEvmc, value: m.value.fromEvmc, data: @(makeOpenArray(m.inputData, m.inputSize.int)) @@ -56,7 +56,7 @@ proc beforeExecCallEvmcNested(host: TransactionHost, let childMsg = Message( kind: CallKind(m.kind.ord), depth: m.depth, - gas: m.gas, + gas: GasInt m.gas, sender: m.sender.fromEvmc, codeAddress: m.code_address.fromEvmc, contractAddress: if m.kind == EVMC_CALL: diff --git a/nimbus/transaction/host_services.nim b/nimbus/transaction/host_services.nim index e77b9c852..8af70d954 100644 --- a/nimbus/transaction/host_services.nim +++ b/nimbus/transaction/host_services.nim @@ -9,11 +9,13 @@ #{.push raises: [].} import + std/typetraits, stint, chronicles, eth/common/eth_types, ../db/ledger, ../common/[evmforks, common], ".."/[vm_state, vm_computation, vm_internals, vm_gas_costs], - ./host_types, ./host_trace, ./host_call_nested + ./host_types, ./host_trace, ./host_call_nested, + stew/saturation_arith proc setupTxContext(host: TransactionHost) = # Conversion issues: @@ -24,9 +26,8 @@ proc setupTxContext(host: TransactionHost) = # anyway. Largest ever so far may be 100,000,000. # https://medium.com/amberdata/most-expensive-transaction-in-ethereum-blockchain-history-99d9a30d8e02 # - # `txContext.block_number` is 64-bit signed. This is actually too small for - # the Nimbus `BlockNumber` type which is 256-bit (for now), so we truncate - # the other way. + # `txContext.block_number` is 64-bit signed. Nimbus `BlockNumber` is + # 64-bit unsigned, so we use int64.saturate to avoid overflow assertion. # # `txContext.chain_id` is 256-bit, but `vmState.chaindb.config.chainId` is # 64-bit or 32-bit depending on the target CPU architecture (Nim `uint`). @@ -37,10 +38,11 @@ proc setupTxContext(host: TransactionHost) = # `txContext.tx_origin` and `txContext.block_coinbase` are 20-byte Ethereum # addresses, no issues with these. # - # `txContext.block_timestamp` is 64-bit signed. `vmState.timestamp.toUnix` - # is from Nim `std/times` and returns `int64` so this matches. (It's - # overkill that we store a full seconds and nanoseconds object in - # `vmState.timestamp` though.) + # `txContext.block_timestamp` is 64-bit signed. Nimbus `EthTime` is + # `distinct uint64`, but the wrapped value comes from std/times + # `getTime().utc.toTime.toUnix` when EthTime.now() called. + # So the wrapped value is actually in int64 range. + # Value from other sources e.g. test vectors can overflow this int64. # # `txContext.block_gas_limit` is 64-bit signed (EVMC assumes # [EIP-1985](https://eips.ethereum.org/EIPS/eip-1985) although it's not @@ -54,16 +56,25 @@ proc setupTxContext(host: TransactionHost) = host.txContext.tx_origin = vmState.txCtx.origin.toEvmc # vmState.coinbase now unused host.txContext.block_coinbase = vmState.blockCtx.coinbase.toEvmc - # vmState.blockNumber now unused - host.txContext.block_number = (vmState.blockNumber - .truncate(typeof(host.txContext.block_number))) + # vmState.number now unused + host.txContext.block_number = int64.saturate(vmState.blockNumber) # vmState.timestamp now unused + + # TODO: do not use int64.saturate for timestamp for the moment + # while the choice of using int64 in evmc will not affect the evm/evmc operations + # but some of the tests will fail if the value from test vector overflow + # see getTimestamp of computation.nim too. + # probably block timestamp should be checked before entering EVM + # problematic test vectors: + # - BlockchainTests/GeneralStateTests/Pyspecs/cancun/eip4788_beacon_root/beacon_root_contract_timestamps.json + # - BlockchainTests/GeneralStateTests/Pyspecs/cancun/eip4788_beacon_root/beacon_root_equal_to_timestamp.json host.txContext.block_timestamp = cast[int64](vmState.blockCtx.timestamp) + # vmState.gasLimit now unused host.txContext.block_gas_limit = vmState.blockCtx.gasLimit # vmState.difficulty now unused host.txContext.chain_id = vmState.com.chainId.uint.u256.toEvmc - host.txContext.block_base_fee = vmState.blockCtx.fee.get(0.u256).toEvmc + host.txContext.block_base_fee = vmState.blockCtx.baseFeePerGas.get(0.u256).toEvmc if vmState.txCtx.versionedHashes.len > 0: type @@ -253,7 +264,7 @@ proc getTxContext(host: TransactionHost): EvmcTxContext {.show.} = proc getBlockHash(host: TransactionHost, number: HostBlockNumber): HostHash {.show.} = # TODO: Clean up the different messy block number types. - host.vmState.getAncestorHash(number.toBlockNumber) + host.vmState.getAncestorHash(number.BlockNumber) proc emitLog(host: TransactionHost, address: HostAddress, data: ptr byte, data_size: HostSize, diff --git a/nimbus/utils/debug.nim b/nimbus/utils/debug.nim index 328f81d8a..7c5b6ac10 100644 --- a/nimbus/utils/debug.nim +++ b/nimbus/utils/debug.nim @@ -33,24 +33,24 @@ proc `$`(data: Blob): string = data.toHex proc debug*(h: BlockHeader): string = - result.add "parentHash : " & $h.parentHash & "\n" - result.add "ommersHash : " & $h.ommersHash & "\n" - result.add "coinbase : " & $h.coinbase & "\n" - result.add "stateRoot : " & $h.stateRoot & "\n" - result.add "txRoot : " & $h.txRoot & "\n" - result.add "receiptRoot : " & $h.receiptRoot & "\n" - result.add "bloom : " & $h.bloom & "\n" - result.add "difficulty : " & $h.difficulty & "\n" - result.add "blockNumber : " & $h.blockNumber & "\n" - result.add "gasLimit : " & $h.gasLimit & "\n" - result.add "gasUsed : " & $h.gasUsed & "\n" - result.add "timestamp : " & $h.timestamp & "\n" - result.add "extraData : " & $h.extraData & "\n" - result.add "mixDigest : " & $h.mixDigest & "\n" - result.add "nonce : " & $h.nonce & "\n" - result.add "fee.isSome : " & $h.fee.isSome & "\n" - if h.fee.isSome: - result.add "fee : " & $h.fee.get() & "\n" + result.add "parentHash : " & $h.parentHash & "\n" + result.add "ommersHash : " & $h.ommersHash & "\n" + result.add "coinbase : " & $h.coinbase & "\n" + result.add "stateRoot : " & $h.stateRoot & "\n" + result.add "txRoot : " & $h.txRoot & "\n" + result.add "receiptsRoot : " & $h.receiptsRoot & "\n" + result.add "logsBloom : " & $h.logsBloom & "\n" + result.add "difficulty : " & $h.difficulty & "\n" + result.add "blockNumber : " & $h.number & "\n" + result.add "gasLimit : " & $h.gasLimit & "\n" + result.add "gasUsed : " & $h.gasUsed & "\n" + result.add "timestamp : " & $h.timestamp & "\n" + result.add "extraData : " & $h.extraData & "\n" + result.add "mixHash : " & $h.mixHash & "\n" + result.add "nonce : " & $h.nonce & "\n" + result.add "baseFeePerGas.isSome: " & $h.baseFeePerGas.isSome & "\n" + if h.baseFeePerGas.isSome: + result.add "baseFeePerGas : " & $h.baseFeePerGas.get() & "\n" if h.withdrawalsRoot.isSome: result.add "withdrawalsRoot: " & $h.withdrawalsRoot.get() & "\n" if h.blobGasUsed.isSome: @@ -88,7 +88,7 @@ proc debug*(vms: BaseVMState): string = result.add "parent : " & $vms.parent.blockHash & "\n" result.add "timestamp : " & $vms.blockCtx.timestamp & "\n" result.add "gasLimit : " & $vms.blockCtx.gasLimit & "\n" - result.add "fee : " & $vms.blockCtx.fee & "\n" + result.add "baseFeePerGas : " & $vms.blockCtx.baseFeePerGas & "\n" result.add "prevRandao : " & $vms.blockCtx.prevRandao & "\n" result.add "blockDifficulty : " & $vms.blockCtx.difficulty & "\n" result.add "coinbase : " & $vms.blockCtx.coinbase & "\n" @@ -125,8 +125,8 @@ proc debug*(tx: Transaction): string = result.add "chainId : " & $tx.chainId & "\n" result.add "nonce : " & $tx.nonce & "\n" result.add "gasPrice : " & $tx.gasPrice & "\n" - result.add "maxPriorityFee: " & $tx.maxPriorityFee & "\n" - result.add "maxFee : " & $tx.maxFee & "\n" + result.add "maxPriorityFee: " & $tx.maxPriorityFeePerGas & "\n" + result.add "maxFee : " & $tx.maxFeePerGas & "\n" result.add "gasLimit : " & $tx.gasLimit & "\n" result.add "to : " & $tx.to & "\n" result.add "value : " & $tx.value & "\n" diff --git a/nimbus/utils/utils.nim b/nimbus/utils/utils.nim index 9caf320f3..cf165ebe1 100644 --- a/nimbus/utils/utils.nim +++ b/nimbus/utils/utils.nim @@ -24,7 +24,7 @@ export eth_types_rlp proc calcRootHash[T](items: openArray[T]): Hash256 {.gcsafe.} = let sig = merkleSignBegin() for i, t in items: - sig.merkleSignAdd(rlp.encode(i), rlp.encode(t)) + sig.merkleSignAdd(rlp.encode(i.uint), rlp.encode(t)) sig.merkleSignCommit.value.to(Hash256) template calcTxRoot*(transactions: openArray[Transaction]): Hash256 = @@ -33,7 +33,7 @@ template calcTxRoot*(transactions: openArray[Transaction]): Hash256 = template calcWithdrawalsRoot*(withdrawals: openArray[Withdrawal]): Hash256 = calcRootHash(withdrawals) -template calcReceiptRoot*(receipts: openArray[Receipt]): Hash256 = +template calcReceiptsRoot*(receipts: openArray[Receipt]): Hash256 = calcRootHash(receipts) func sumHash*(hashes: varargs[Hash256]): Hash256 = @@ -135,5 +135,5 @@ func weiAmount*(w: Withdrawal): UInt256 = w.amount.u256 * (10'u64 ^ 9'u64).u256 func isGenesis*(header: BlockHeader): bool = - header.blockNumber == 0.u256 and + header.number == 0'u64 and header.parentHash == GENESIS_PARENT_HASH diff --git a/nimbus/vm_state.nim b/nimbus/vm_state.nim index d729c9fa9..ff51d3c0e 100644 --- a/nimbus/vm_state.nim +++ b/nimbus/vm_state.nim @@ -20,7 +20,7 @@ export vms.coinbase, vms.determineFork, vms.difficultyOrPrevRandao, - vms.baseFee, + vms.baseFeePerGas, vms.forkDeterminationInfoForVMState, vms.collectWitnessData, vms.`collectWitnessData=`, diff --git a/nimbus_verified_proxy/rpc/rpc_eth_api.nim b/nimbus_verified_proxy/rpc/rpc_eth_api.nim index ddf6255fd..83978769f 100644 --- a/nimbus_verified_proxy/rpc/rpc_eth_api.nim +++ b/nimbus_verified_proxy/rpc/rpc_eth_api.nim @@ -220,23 +220,23 @@ proc installEthApiHandlers*(lcProxy: VerifiedRpcProxy) = # nim-web3 side lcProxy.proxy.rpc("eth_getBlockByNumber") do( quantityTag: BlockTag, fullTransactions: bool - ) -> Option[BlockObject]: + ) -> Opt[BlockObject]: let executionPayload = lcProxy.getPayloadByTag(quantityTag) if executionPayload.isErr: - return none(BlockObject) + return Opt.none(BlockObject) - return some(asBlockObject(executionPayload.get())) + return Opt.some(asBlockObject(executionPayload.get())) lcProxy.proxy.rpc("eth_getBlockByHash") do( blockHash: BlockHash, fullTransactions: bool - ) -> Option[BlockObject]: + ) -> Opt[BlockObject]: let executionPayload = lcProxy.blockCache.getPayloadByHash(blockHash) if executionPayload.isErr: - return none(BlockObject) + return Opt.none(BlockObject) - return some(asBlockObject(executionPayload.get())) + return Opt.some(asBlockObject(executionPayload.get())) proc new*( T: type VerifiedRpcProxy, proxy: RpcProxy, blockCache: BlockCache, chainId: Quantity diff --git a/nimbus_verified_proxy/rpc/rpc_utils.nim b/nimbus_verified_proxy/rpc/rpc_utils.nim index 46ea5132f..e03ba9c4b 100644 --- a/nimbus_verified_proxy/rpc/rpc_utils.nim +++ b/nimbus_verified_proxy/rpc/rpc_utils.nim @@ -107,17 +107,17 @@ func blockHeaderSize(payload: ExecutionData, txRoot: etypes.Hash256): uint64 = coinbase: etypes.EthAddress payload.feeRecipient, stateRoot: payload.stateRoot.asEthHash, txRoot: txRoot, - receiptRoot: payload.receiptsRoot.asEthHash, - bloom: distinctBase(payload.logsBloom), + receiptsRoot: payload.receiptsRoot.asEthHash, + logsBloom: distinctBase(payload.logsBloom), difficulty: default(etypes.DifficultyInt), - blockNumber: payload.blockNumber.distinctBase.u256, + number: payload.blockNumber.distinctBase, gasLimit: payload.gasLimit.unsafeQuantityToInt64, gasUsed: payload.gasUsed.unsafeQuantityToInt64, timestamp: payload.timestamp.EthTime, extraData: bytes payload.extraData, - mixDigest: payload.prevRandao.asEthHash, + mixHash: payload.prevRandao.asEthHash, nonce: default(etypes.BlockNonce), - fee: some payload.baseFeePerGas, + baseFeePerGas: Opt.some payload.baseFeePerGas, ) return uint64(len(rlp.encode(bh))) @@ -143,7 +143,7 @@ proc asBlockObject*(p: ExecutionData): BlockObject {.raises: [ValueError].} = gasLimit: p.gasLimit, gasUsed: p.gasUsed, timestamp: p.timestamp, - nonce: some(default(FixedBytes[8])), + nonce: Opt.some(default(FixedBytes[8])), size: Quantity(blockSize), # TODO: It does not matter what we put here after merge blocks. # Other projects like `helios` return `0`, data providers like alchemy return @@ -151,5 +151,5 @@ proc asBlockObject*(p: ExecutionData): BlockObject {.raises: [ValueError].} = totalDifficulty: UInt256.zero, transactions: txHashes, uncles: @[], - baseFeePerGas: some(p.baseFeePerGas), + baseFeePerGas: Opt.some(p.baseFeePerGas), ) diff --git a/premix/configuration.nim b/premix/configuration.nim index f46e295ab..9c852ffa8 100644 --- a/premix/configuration.nim +++ b/premix/configuration.nim @@ -32,7 +32,7 @@ type PremixConfiguration* = ref object dataDir*: string - head*: UInt256 + head*: BlockNumber maxBlocks*: int numCommits*: int netId*: NetworkId @@ -55,7 +55,7 @@ proc initConfiguration(): PremixConfiguration = const dataDir = defaultDataDir() result.dataDir = dataDir - result.head = 0.u256 + result.head = 0'u64 result.maxBlocks = 0 result.numCommits = 128 result.netId = MainNet @@ -65,11 +65,11 @@ proc getConfiguration*(): PremixConfiguration = premixConfig = initConfiguration() result = premixConfig -proc processU256(val: string, o: var UInt256): ConfigStatus = +proc processBlockNumber(val: string, o: var BlockNumber): ConfigStatus = if val.len > 2 and val[0] == '0' and val[1] == 'x': - o = UInt256.fromHex(val) + o = UInt256.fromHex(val).truncate(BlockNumber) else: - o = parse(val, UInt256) + o = parse(val, UInt256).truncate(BlockNumber) result = Success func processNetId(val: string, o: var NetworkId): ConfigStatus = @@ -112,7 +112,7 @@ proc processArguments*(msg: var string): ConfigStatus = of "maxblocks": checkArgument(processInteger, config.maxBlocks, value) of "head": - checkArgument(processU256, config.head, value) + checkArgument(processBlockNumber, config.head, value) of "numcommits": checkArgument(processInteger, config.numCommits, value) config.numCommits = max(config.numCommits, 512) diff --git a/premix/debug.nim b/premix/debug.nim index e54ff4fd5..847015481 100644 --- a/premix/debug.nim +++ b/premix/debug.nim @@ -9,7 +9,7 @@ # according to those terms. import - std/[json, os], + std/[json, os, strutils], stew/byteutils, chronicles, results, @@ -28,7 +28,7 @@ proc prepareBlockEnv(node: JsonNode, memoryDB: CoreDbRef) = kvt.put(key, value).isOkOr: raiseAssert "prepareBlockEnv(): put() (loop) failed " & $$error -proc executeBlock(blockEnv: JsonNode, memoryDB: CoreDbRef, blockNumber: UInt256) = +proc executeBlock(blockEnv: JsonNode, memoryDB: CoreDbRef, blockNumber: BlockNumber) = var parentNumber = blockNumber - 1 com = CommonRef.new(memoryDB) @@ -70,7 +70,8 @@ proc main() = let blockEnv = json.parseFile(paramStr(1)) memoryDB = newCoreDbRef(DefaultDbMemory) - blockNumber = UInt256.fromHex(blockEnv["blockNumber"].getStr()) + blockNumberHex = blockEnv["blockNumber"].getStr() + blockNumber = parseHexInt(blockNumberHex).uint64 prepareBlockEnv(blockEnv, memoryDB) executeBlock(blockEnv, memoryDB, blockNumber) diff --git a/premix/downloader.nim b/premix/downloader.nim index 515a2da7d..86bca1ce5 100644 --- a/premix/downloader.nim +++ b/premix/downloader.nim @@ -122,10 +122,10 @@ proc requestBlock*( result.receipts = requestReceipts(header, client) if DownloadAndValidate in flags: let - receiptRoot = calcReceiptRoot(result.receipts).prefixHex - receiptRootOK = result.header.receiptRoot.prefixHex - if receiptRoot != receiptRootOK: - debug "wrong receipt root", receiptRoot, receiptRootOK, blockNumber + receiptsRoot = calcReceiptsRoot(result.receipts).prefixHex + receiptsRootOK = result.header.receiptsRoot.prefixHex + if receiptsRoot != receiptsRootOK: + debug "wrong receipt root", receiptsRoot, receiptsRootOK, blockNumber raise newException(ValueError, "Error when validating receipt root") if DownloadAndValidate in flags: diff --git a/premix/dumper.nim b/premix/dumper.nim index 6f2d1804a..b46c6333d 100644 --- a/premix/dumper.nim +++ b/premix/dumper.nim @@ -14,7 +14,6 @@ # import - stint, results, ../nimbus/common/common, ../nimbus/db/opts, @@ -24,7 +23,7 @@ import ../nimbus/tracer, ./configuration # must be late (compilation annoyance) -proc dumpDebug(com: CommonRef, blockNumber: UInt256) = +proc dumpDebug(com: CommonRef, blockNumber: BlockNumber) = var capture = com.db.newCapture.value captureCom = com.clone(capture.recorder) @@ -50,7 +49,7 @@ proc main() {.used.} = let com = CommonRef.new( newCoreDbRef(DefaultDbPersistent, conf.dataDir, DbOptions.init())) - if conf.head != 0.u256: + if conf.head != 0'u64: dumpDebug(com, conf.head) when isMainModule: diff --git a/premix/no-hunter.nim b/premix/no-hunter.nim index 7610ac878..67373fb41 100644 --- a/premix/no-hunter.nim +++ b/premix/no-hunter.nim @@ -40,10 +40,10 @@ proc prepareBlockEnv(parent: BlockHeader, thisBlock: Block): CoreDbRef = accounts = requestPostState(thisBlock) memoryDB = newCoreDbRef DefaultDbMemory accountDB = newAccountStateDB(memoryDB, parent.stateRoot) - parentNumber = %(parent.blockNumber.prefixHex) + parentNumber = %(parent.number.prefixHex) for address, account in accounts: - updateAccount(address, account, parent.blockNumber) + updateAccount(address, account, parent.number) let accountProof = account["accountProof"] storageProof = account["storageProof"] diff --git a/premix/parser.nim b/premix/parser.nim index c58bdba00..0a5a3a89d 100644 --- a/premix/parser.nim +++ b/premix/parser.nim @@ -9,7 +9,7 @@ # according to those terms. import - json, strutils, options, os, + json, strutils, os, eth/common, httputils, nimcrypto/utils, stint, stew/byteutils @@ -100,11 +100,11 @@ proc fromJson*(n: JsonNode, name: string, x: var EthTime) = x = EthTime(hexToInt(n[name].getStr(), uint64)) doAssert(x.uint64.prefixHex == toLowerAscii(n[name].getStr()), name) -proc fromJson*[T](n: JsonNode, name: string, x: var Option[T]) = +proc fromJson*[T](n: JsonNode, name: string, x: var Opt[T]) = if name in n: var val: T n.fromJson(name, val) - x = some(val) + x = Opt.some(val) proc fromJson*(n: JsonNode, name: string, x: var TxType) = let node = n[name] @@ -127,25 +127,25 @@ proc parseBlockHeader*(n: JsonNode): BlockHeader = n.fromJson "miner", result.coinbase n.fromJson "stateRoot", result.stateRoot n.fromJson "transactionsRoot", result.txRoot - n.fromJson "receiptsRoot", result.receiptRoot - n.fromJson "logsBloom", result.bloom + n.fromJson "receiptsRoot", result.receiptsRoot + n.fromJson "logsBloom", result.logsBloom n.fromJson "difficulty", result.difficulty - n.fromJson "number", result.blockNumber + n.fromJson "number", result.number n.fromJson "gasLimit", result.gasLimit n.fromJson "gasUsed", result.gasUsed n.fromJson "timestamp", result.timestamp n.fromJson "extraData", result.extraData - n.fromJson "mixHash", result.mixDigest + n.fromJson "mixHash", result.mixHash n.fromJson "nonce", result.nonce - n.fromJson "baseFeePerGas", result.fee + n.fromJson "baseFeePerGas", result.baseFeePerGas n.fromJson "withdrawalsRoot", result.withdrawalsRoot n.fromJson "blobGasUsed", result.blobGasUsed n.fromJson "excessBlobGas", result.excessBlobGas n.fromJson "parentBeaconBlockRoot", result.parentBeaconBlockRoot - if result.baseFee == 0.u256: + if result.baseFeePerGas.get(0.u256) == 0.u256: # probably geth bug - result.fee = none(UInt256) + result.baseFeePerGas = Opt.none(UInt256) proc parseAccessPair(n: JsonNode): AccessPair = n.fromJson "address", result.address @@ -162,7 +162,7 @@ proc parseTransaction*(n: JsonNode): Transaction = if n["to"].kind != JNull: var to: EthAddress n.fromJson "to", to - tx.to = some(to) + tx.to = Opt.some(to) n.fromJson "value", tx.value n.fromJson "input", tx.payload @@ -174,8 +174,8 @@ proc parseTransaction*(n: JsonNode): Transaction = n.fromJson "type", tx.txType if tx.txType >= TxEip1559: - n.fromJson "maxPriorityFeePerGas", tx.maxPriorityFee - n.fromJson "maxFeePerGas", tx.maxFee + n.fromJson "maxPriorityFeePerGas", tx.maxPriorityFeePerGas + n.fromJson "maxFeePerGas", tx.maxFeePerGas if tx.txType >= TxEip2930: if n.hasKey("chainId"): @@ -248,7 +248,7 @@ proc parseReceipt*(n: JsonNode): Receipt = rec.status = status == 1 n.fromJson "cumulativeGasUsed", rec.cumulativeGasUsed - n.fromJson "logsBloom", rec.bloom + n.fromJson "logsBloom", rec.logsBloom rec.logs = parseLogs(n["logs"]) rec diff --git a/premix/persist.nim b/premix/persist.nim index 943b7db88..2bd597fe7 100644 --- a/premix/persist.nim +++ b/premix/persist.nim @@ -62,7 +62,7 @@ proc main() {.used.} = conf.netId, networkParams(conf.netId)) # move head to block number ... - if conf.head != 0.u256: + if conf.head != 0'u64: var parentBlock = requestBlock(conf.head, { DownloadAndValidate }) discard com.db.setHead(parentBlock.header) @@ -73,13 +73,13 @@ proc main() {.used.} = doAssert(canonicalHeadHashKey().toOpenArray in kvt) var head = com.db.getCanonicalHead() - var blockNumber = head.blockNumber + 1 + var blockNumber = head.number + 1 var chain = newChain(com) let numBlocksToCommit = conf.numCommits var blocks = newSeqOfCap[EthBlock](numBlocksToCommit) - var one = 1.u256 + var one = 1'u64 var numBlocks = 0 var counter = 0 diff --git a/premix/premix.nim b/premix/premix.nim index 2fdb78b7c..efe5d4ce2 100644 --- a/premix/premix.nim +++ b/premix/premix.nim @@ -10,11 +10,11 @@ import std/[json, strutils, os], - downloader, stint, + downloader, ../nimbus/tracer, prestate, eth/common, premixcore -proc generateGethData(thisBlock: Block, blockNumber: UInt256, accounts: JsonNode): JsonNode = +proc generateGethData(thisBlock: Block, blockNumber: BlockNumber, accounts: JsonNode): JsonNode = let receipts = toJson(thisBlock.receipts) @@ -28,7 +28,7 @@ proc generateGethData(thisBlock: Block, blockNumber: UInt256, accounts: JsonNode result = geth -proc printDebugInstruction(blockNumber: UInt256) = +proc printDebugInstruction(blockNumber: BlockNumber) = var text = """ Successfully created debugging environment for block $1. @@ -48,11 +48,12 @@ proc main() = try: let nimbus = json.parseFile(paramStr(1)) - blockNumber = UInt256.fromHex(nimbus["blockNumber"].getStr()) + blockNumberHex = nimbus["blockNumber"].getStr() + blockNumber = parseHexInt(blockNumberHex).uint64 thisBlock = requestBlock(blockNumber, {DownloadReceipts, DownloadTxTrace}) accounts = requestPostState(thisBlock) geth = generateGethData(thisBlock, blockNumber, accounts) - parentNumber = blockNumber - 1.u256 + parentNumber = blockNumber - 1 parentBlock = requestBlock(parentNumber) processNimbusData(nimbus) diff --git a/premix/premixcore.nim b/premix/premixcore.nim index 828224d3b..1ac9b14e1 100644 --- a/premix/premixcore.nim +++ b/premix/premixcore.nim @@ -1,5 +1,5 @@ # Nimbus -# Copyright (c) 2020-2023 Status Research & Development GmbH +# Copyright (c) 2020-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) @@ -10,7 +10,7 @@ import json, strutils, os, - stint, chronicles, eth/common, + chronicles, eth/common, ../nimbus/transaction, ../nimbus/launcher, ./js_tracer, ./parser, ./downloader @@ -78,7 +78,7 @@ proc generatePremixData*(nimbus, geth: JsonNode) = var data = "var premixData = " & premixData.pretty & "\n" writeFile(getFileDir("index.html") / "premixData.js", data) -proc hasInternalTx(tx: Transaction, blockNumber: UInt256, sender: EthAddress): bool = +proc hasInternalTx(tx: Transaction, blockNumber: BlockNumber, sender: EthAddress): bool = let number = %(blockNumber.prefixHex) recipient = tx.getRecipient(sender) @@ -100,7 +100,7 @@ proc requestInternalTx(txHash, tracer: JsonNode): JsonNode = raise newException(ValueError, "Error when retrieving transaction postState") result = txTrace -proc requestAccount*(premix: JsonNode, blockNumber: UInt256, address: EthAddress) = +proc requestAccount*(premix: JsonNode, blockNumber: BlockNumber, address: EthAddress) = let number = %(blockNumber.prefixHex) address = address.prefixHex @@ -124,7 +124,7 @@ proc padding(x: string): JsonNode = let pad = repeat('0', 64 - val.len) result = newJString("0x" & pad & val) -proc updateAccount*(address: string, account: JsonNode, blockNumber: UInt256) = +proc updateAccount*(address: string, account: JsonNode, blockNumber: BlockNumber) = let number = %(blockNumber.prefixHex) var storage = newJArray() @@ -143,7 +143,7 @@ proc updateAccount*(address: string, account: JsonNode, blockNumber: UInt256) = x["value"] = padding(x["value"].getStr()) account["storage"][x["key"].getStr] = x["value"] -proc requestPostState*(premix, n: JsonNode, blockNumber: UInt256) = +proc requestPostState*(premix, n: JsonNode, blockNumber: BlockNumber) = type TxKind {.pure.} = enum Regular @@ -172,7 +172,7 @@ proc requestPostState*(premix, n: JsonNode, blockNumber: UInt256) = t["txKind"] = %($txKind) proc requestPostState*(thisBlock: Block): JsonNode = - let blockNumber = thisBlock.header.blockNumber + let blockNumber = thisBlock.header.number var premix = newJArray() premix.requestPostState(thisBlock.jsonData, blockNumber) diff --git a/premix/prestate.nim b/premix/prestate.nim index 61eeba7bd..5b70e6d77 100644 --- a/premix/prestate.nim +++ b/premix/prestate.nim @@ -9,12 +9,13 @@ # according to those terms. import - json, stint, stew/byteutils, + std/strutils, + json, stew/byteutils, results, ../nimbus/db/[core_db, storage_types], eth/[rlp, common], ../nimbus/tracer -proc generatePrestate*(nimbus, geth: JsonNode, blockNumber: UInt256, parent: BlockHeader, blk: EthBlock) = +proc generatePrestate*(nimbus, geth: JsonNode, blockNumber: BlockNumber, parent: BlockHeader, blk: EthBlock) = template header: BlockHeader = blk.header let state = nimbus["state"] @@ -28,7 +29,7 @@ proc generatePrestate*(nimbus, geth: JsonNode, blockNumber: UInt256, parent: Blo kvt.put(genericHashKey(headerHash).toOpenArray, rlp.encode(header)).isOkOr: raiseAssert "generatePrestate(): put() failed " & $$error - chainDB.addBlockNumberToHashLookup(header.blockNumber, headerHash) + chainDB.addBlockNumberToHashLookup(header.number, headerHash) for k, v in state: let key = hexToSeqByte(k) diff --git a/premix/regress.nim b/premix/regress.nim index 175fb595d..471c893f2 100644 --- a/premix/regress.nim +++ b/premix/regress.nim @@ -27,13 +27,13 @@ proc validateBlock(com: CommonRef, blockNumber: BlockNumber): BlockNumber = blocks = newSeq[EthBlock](numBlocks) for i in 0 ..< numBlocks: - blocks[i] = com.db.getEthBlock(blockNumber + i.u256) + blocks[i] = com.db.getEthBlock(blockNumber + i.BlockNumber) let transaction = com.db.newTransaction() defer: transaction.dispose() for i in 0 ..< numBlocks: - stdout.write blockNumber + i.u256 + stdout.write blockNumber + i.BlockNumber stdout.write "\r" let @@ -42,12 +42,12 @@ proc validateBlock(com: CommonRef, blockNumber: BlockNumber): BlockNumber = if validationResult.isErr: error "block validation error", - err = validationResult.error(), blockNumber = blockNumber + i.u256 + err = validationResult.error(), blockNumber = blockNumber + i.BlockNumber parent = blocks[i].header transaction.rollback() - result = blockNumber + numBlocks.u256 + result = blockNumber + numBlocks.BlockNumber proc main() {.used.} = let @@ -56,7 +56,7 @@ proc main() {.used.} = DefaultDbPersistent, conf.dataDir, DbOptions.init())) # move head to block number ... - if conf.head == 0.u256: + if conf.head == 0'u64: raise newException(ValueError, "please set block number with --head: blockNumber") var counter = 0 diff --git a/tests/fixtures/TracerTests/block46147.json b/tests/fixtures/TracerTests/block46147.json index 7002ed3c6..0728ef6a0 100644 --- a/tests/fixtures/TracerTests/block46147.json +++ b/tests/fixtures/TracerTests/block46147.json @@ -168,7 +168,7 @@ "4513310FCB9F6F616972A3B948DC5D547F280849A87EBB5AF0191F98B87BE598": "F86E822080B869F86780862D79883D2000825208945DF9B87991262F6BA471F09758CDE1C0FC1DE734827A69801CA088FF6CF0FEFD94DB46111149AE4BFC179E9B94721FFFD821D38D16464B3F71D0A045E0AFF800961CFCE805DAEF7016B9B675C137A6A41A548F7B60A3484C06A33A", "004E3A3754410177E6937EF1F84BBA68EA139E8D1A2258C5F85DB9F1CD715A1BDD": "F90208A05A41D0E66B4120775176C09FCF39E7C0520517A13D2B57B18D33D342DF038BFCA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794E6A7A1D47FF21B6321162AEA7C6CB457D5476BCAA00E0DF2706B0A4FB8BD08C9246D472ABBE850AF446405D9EBA1DB41DB18B4A169A04513310FCB9F6F616972A3B948DC5D547F280849A87EBB5AF0191F98B87BE598A0FE2BF2A941ABF41D72637E5B91750332A30283EFD40C424DC522B77E6F0ED8C4B9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000860153886C1BBD82B44382520B8252088455C426598B657468706F6F6C2E6F7267A0B48C515A9DDE8D346C3337EA520AA995A4738BB595495506125449C1149D6CF488BA4F8ECD18AAB215", "56E81F171BCC55A6FF8345E692C0F86E5B48E01B996CADC001622FB5E363B421": "80", - "0143B4000000000000000000000000000000000000000000000000000000000000": "A04E3A3754410177E6937EF1F84BBA68EA139E8D1A2258C5F85DB9F1CD715A1BDD", + "0143B4000000000000": "A04E3A3754410177E6937EF1F84BBA68EA139E8D1A2258C5F85DB9F1CD715A1BDD", "FE2BF2A941ABF41D72637E5B91750332A30283EFD40C424DC522B77E6F0ED8C4": "F90131822080B9012BF90128A096A8E009D2B88B1483E6941E6812E32263B05683FAC202ABC622A3E31AED1957825208B9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000C0", "5BA4F56BA77B4D796A6901126E6EA7632A99E8437C62242B0182EDE6E7A3CB59": "F90211A0FD8B8ED81CE9C92162A37456BBC65EB09C59A59159FEA166AEF8D70E0560C697A0A9F3F642CD4621068258A1BC8098C467B3E617DDF480610B8D971F9B86F21C42A0941B16643A3F3A50687108CC498CAA2CEFACD7EC53756B8E6A8A2A9485DBF5FFA0F25EBB37FB04D725BCFBD38A7DBF260A4003C6149F6DA3E5105FAB580C7DB8FAA09B12DEE4DE8754528FFE313CA135149001394A72D7637C1B401F09E6F36DF3ECA0A39723C4F872A2596154BC430093799B5CC630B003F4F227B34B390AEB7E39FDA0FDC112AA83DACBEF35165F40D7E0EC7BCEC10E4176597FE524F172B9E31FFC57A0EC11A92536F952138379A77EDF5F6453F52FCC8DDAA48E2796EF38933FB87DE3A0AC9E27F43F4965F73F11289B0D1FCA7C212F977F41DE8662F75ADEF09E47D135A0163B88927480AAD3B83498C08AEBF181ABBBAC93F4F4675EE58120664F2382A3A0C077CE8064CB20C31118AF3B99CB4AC77A371A12B44058B44A25E7FBF8AB4288A059872941F5434694B9E22253251166F797B83691BCAB723005692287A36CFF95A0E1888DFF1A3E4FD453FBCF657D55CAAE2F64D6EEB3A9B072C7CB15A3738C1488A0D7F40FEEC87A940C994E4200F68CE5CC0FDB527FCA1741AC4C4D212AFDCB4AAAA0A8440EF6E36D273B58C65344EDAB0583A03F09912D22E723DAE51CC1D716D786A080931062CF57B118E1E88A9508B2DCE6E2A6E4E73F388CC23AAE90DB1F53B3A880", "691FC4F4D21D10787902E8F3266711F1D640E75FEDBEB406DC0B8D3096128436": "F90211A0DC089BF98B185C858EC4B865117FF57AE79656A627437848E1C6D61E64DC8040A0614A746937F7FAE4206B30E9C513E3224A5E0862A53EFCBD50DDC23907A810D9A0220E8A43118054330D08E22AF1BE29B7C8EEAD661EC8F73A1DE50741019EBA76A05D4FCE5D8DF4B4DDE9640219F0CA4104A229E1053FF7ED15FDF85208890CF203A0F95407904CB0E7910A7CDE600CAA0F8C32D997480C99D44347936BD7C638DC9EA0F1EA4A2BE43078928EC8BED825293778121173755A146C2A44627923F7CC67FEA07C868FBC08F09FE674B381F467D43F3D5B1AA86DAC98FCA1E0EA6CC7C1BB715EA0932107FC43830D02D9C20A142653D91A738ECDCB51D03EF36E016EAEAB49323BA0014996DE5CC0B2EE1AAA1FF209870A808D4C407F0EE4143F6E50FA7129466847A0FEB4F03FD566F8EF81B82C633D3E9C1784F159E86613487C607BA2403B1088EBA05BA4F56BA77B4D796A6901126E6EA7632A99E8437C62242B0182EDE6E7A3CB59A017AAF2F4CB447BB9B776EFD70A723AD6D801A93469B52170E49835DE2EF38CA2A0F46BED067E2729A639BA465DD6BDA652813F63D17C54B30D1EDCE879C4331902A0D8B23924722A6C570FF99DFE4215852EAA932F9237517C2C19E0A72B965CC66BA02967BDF8160FDFF829F298FC127749A9342D839272B51C88A97C85AC4A10DA02A02F679EFC42E7F825F27AE68F5876BD506D0DBDD5BAC1343FADFF3630920F741480", diff --git a/tests/fixtures/TracerTests/block46400.json b/tests/fixtures/TracerTests/block46400.json index b4c53685f..ca7678942 100644 --- a/tests/fixtures/TracerTests/block46400.json +++ b/tests/fixtures/TracerTests/block46400.json @@ -168,7 +168,7 @@ "27054556A1FFE03835448641692D5FA0752EC1E44C197E8A1710A9EB1165871B": "F8709E3761C9C0BD5CB39E03D3C68C3F356B45C45ED51CB9D42C91AD869529DC39B84FF84D0189023BAAA0ACF79020E0A056E81F171BCC55A6FF8345E692C0F86E5B48E01B996CADC001622FB5E363B421A0C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", "5CB2E10967B7F6E99EF27131296B1A437A93F906B547A9D8F1613DFD0D05E39E": "F901F1A09CAB3DEECB3FA76CC3CEED9A9C6B376A8340B9F53E0225C327900F8634FBA00F80A0EACD1C5BC03B56A682C55A3B5F1BA2C55E5E0DCFD4534EFCAE1CFFE45038890BA0E24BE25ECB914AD7B73928054F5F781C702A46BD555D2A09E3AB88870D7827E9A04AD8CF4799D432AB62A749D4C92CFDA9CA43EB7D7072176473DF48552B64105EA08C35A03B8583DA7DD9010DD7FA0EBA29C8F2EC05F45D0A859762B196206C0D0BA08E72A76EB0DAB09FF4FDCEB37149175CD66975DFD0863948AD5D0CEF47426449A0C8562CEC73340A655559E0DDF8ED7808C702C2462E6F1A5FDFA552606EF8B7B1A054FFD758CD9859F3EAA8CAB0B17D682ABD863D94E35705FC262E2FC2D4E8DC6EA0CC63F87033310932F5C17F6C222A3FAC3D48C1551FC8D895464B9CD30172FA26A0C98460DA75E60E035F5B26075FE1FC2F2174C952A02C234E43D7BEE61280A860A03932FAF9691CD061D83F2C9AAAEDAE67204093702F0A259729FFEA69BCCC8DDDA062D87B452726077D12494335E8594F0FCD0E936719CF67EE96DD7508386E4A92A0361CC2E0E99B1CD3AB6A489AAD302409ACA0D958AED5D47D31DD50123A2241E6A08D04043C602DC1A519BFF28B17E4B3089579B6B8DD77BFB7F62F8CCA187653D1A0D0D7579A2AD173C20D565EA489439971E4F67A728A6885E2101053C3DB7A98B480", "56E81F171BCC55A6FF8345E692C0F86E5B48E01B996CADC001622FB5E363B421": "80", - "0140B5000000000000000000000000000000000000000000000000000000000000": "A09B430B5151969097FD7E5C29726A3AFE680AB56F0F14A49A8F045B66392ADD15", + "0140B5000000000000": "A09B430B5151969097FD7E5C29726A3AFE680AB56F0F14A49A8F045B66392ADD15", "007428907E594ABB3E850E07AA5DAA7161E4C35E95E2A17A4664E5516CA304624D": "F9021DA066B948E173404273B343FDCDE1F07B21615061BEF65E494197C77DAEF5B7C4E9A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D493479488D74A59454F6CF3B51EF6B9136AFB6B9D405A88A07224FBEAD7F295EDFAD8E3798A17B9AD16324DB12655BE09BA6973C17E2EF6AFA0B9ED4837D90935F63FEEBD006F130DC69CB00249B646E50287AA82B90ED62AA9A0A6E753EDC1A92FAFC1355C2DD450F8D6CC285BF455ACCF9B7202847272EE2FF5B9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000860155849719A982B53F825F2E8252088455C436EEA0476574682F76312E302E302D66633739643332642F6C696E75782F676F312E34A074EB70001E83F0C74852704FFE3BBAABA812AAC96940BC9608B89C888E38322288AA79D8EA2F3EC35A", "397B9E46D7E8678516C8820E610F5825A42C5FDA6D9C89FA3263D9802F144A7A": "F86F9F201ACF57F99D21DD086E2C1516595BF3190F4925D4A416F0D675F615CE0E35B84DF84B8087B1A2BC2EC50000A056E81F171BCC55A6FF8345E692C0F86E5B48E01B996CADC001622FB5E363B421A0C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", "6DDBD0DC5643168D9CC99EBA533E0E231E9F2E07A550D27E2BA94CC79A2FB1AF": "F851A027054556A1FFE03835448641692D5FA0752EC1E44C197E8A1710A9EB1165871B8080808080808080A01FE898C16A3E5B21746823E564D2115FCF2F648732D9941CDB11290D06DF431980808080808080", diff --git a/tests/fixtures/TracerTests/block46402.json b/tests/fixtures/TracerTests/block46402.json index 6adac872d..4cacbc554 100644 --- a/tests/fixtures/TracerTests/block46402.json +++ b/tests/fixtures/TracerTests/block46402.json @@ -731,7 +731,7 @@ "56E81F171BCC55A6FF8345E692C0F86E5B48E01B996CADC001622FB5E363B421": "80", "5708F26C9EBC6D645B41A8F695E6CC0AA503FC49E2D4FCFDA7FF9C1FFE505808": "F90211A028BAA23D3062382310899793A9FDB01534B820FEA601272FC713C4D8A3440203A055C03D814060FFB4923CF2D7FB5E9E3C8256F5759BEDAAD0BBE811EA848E3251A0BEF8A03D28E3D6074A1754891FD5B19CECBE34E5CA22775D9F991CFB0329BDA1A0766C61F38ECF6F10320DD6D0440C9E804E3425D19F4DECE5FAEF4C5A70BB54E1A00DA11923EB659D0972DA9F45C7D7C51FEADAF0F6D8964545C4647A1DDBE507E5A05C6FCAE1770CBEFBA440A5986677FC3E1302AD21CE92BCC85B8F30A5ACD468BDA074C16CD0A82A53953FB26422FED0F80F4C98EDF567EC209F4BBD678B67FFAE06A0E317F138C0A697D83207BD102A73505FDEAD9999A6F2C9889E11520A0B1D72A8A008BCF12CC8584E9ECD38141B62968A1FB50954D4E34DC3022CEA5BFC50C8FF8BA0F63D306B35EA9B9F6ABA22719B97B15E12EB0BBCC6157A2FD2319B427977B034A0AC3EEEF7D89C662707CDAAD6C4A25EE7AAEA65CA11966325F2287EE055705ABFA0048BF63BFB97D83B3740B53F66BED6C9BD4081469A41F78156373552C2025708A091DA6A990F5C6224FAA732379F1EE1728D8DAAB8366FEC9A80568B55B510E86BA0BB45BF2253F9B2054B1927D49802A635C1A49A1AF7478CE16BA67F540D10DAC2A085ADF2EEE152FDDDA16A42E4880451669A78FEFE71E6CC8C07D65B0C7CA28A56A059CF4B462F305BDED1CB911C484B386AF0658539D00BD29F2317CCFB7AF7765F80", "72C02C0BCE7FF357E228773C7129B0E57DD1F7F8C5025341B93C8634DD11A7DA": "F8719F20BC78D73B85DC7C81AF5CDE0D18A7A6F26A6ECB3B74C5892E8DC052E84D77B84FF84D03896C3ED29108159090C5A056E81F171BCC55A6FF8345E692C0F86E5B48E01B996CADC001622FB5E363B421A0C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - "0142B5000000000000000000000000000000000000000000000000000000000000": "A0249EA54EADA07708B29D7C424B8466DEC9F1D98067B0BE1B89C7EE660CCA858D", + "0142B5000000000000": "A0249EA54EADA07708B29D7C424B8466DEC9F1D98067B0BE1B89C7EE660CCA858D", "EBB4F31EF3E0DFF0174E82D159D9E6112699FDFB878D280465CE92EBB73B0742": "F89180A09B9F85631EB59095CDC5BDF03F3556B7D9933BF2EAB9EA3720ABA22E73023FF1808080A02B83B1BA2674A6AB622282AF7A3E56AED6DC0E427EAEF14A1711612CD86FDD42A08DAED4D73CA8D6A29A96EC92C0C788F41C16AABC72CFD368D1AD818875C683EF80808080808080A072C02C0BCE7FF357E228773C7129B0E57DD1F7F8C5025341B93C8634DD11A7DA8080", "1CF10BA2B41800CC55E1A380ACC3BAD7F86C7BA8A7BC3D1B1759858B6FF5EA11": "F881822080B87CF87A038609184E72A000825DC08080A9606060405260008054600160A060020A0319163317905560068060236000396000F3006060604052001CA0589B4531C6D66F6850277AF29E06E60B28A280916CCBB38595BF3347ACA65C2CA040B1A3D6E47A04C0CD78506AA7D3AA0AEEF734D7942424ABDB64C88C2BA5F536", "41BED9733EB03A087FC69E8DD0D80B546647276D1921FE6BDBAD06DABABF54EE": "F8719F397B0E43D0507C3DC69B82B3B19194D28155268EC637FF005973E8521B9181B84FF84D808910CE1D3D8CB3180000A056E81F171BCC55A6FF8345E692C0F86E5B48E01B996CADC001622FB5E363B421A0C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", diff --git a/tests/fixtures/TracerTests/block47205.json b/tests/fixtures/TracerTests/block47205.json index 965c0c60e..2d2516f32 100644 --- a/tests/fixtures/TracerTests/block47205.json +++ b/tests/fixtures/TracerTests/block47205.json @@ -161,7 +161,7 @@ "30AB21F33FB9BFF8DF3F6CF65380589A96CFC224943EC1CE3B2CBB7FAB5E6463": "F90211A078DDA26A52B7ACA39EE745884A94426F3FAE59C8A530C9FFFF9572900D098988A0E1873CA348667FB981A9D7BCF3A2D59713E244268C168F4F1B31E8E75433A906A0FE0B9CA8B8F12DD1D1D7F5B0D4CD0E2942F4F688AF48EDBE1787371261706544A046F5B76154B3F73E6EAD8CC34DC12E4A464D95FFFFA14391794185A7E13D1D95A02142EC0C48669316796487F7D960E0C01D429913C34EABDB0D6473CE71CA80A5A045B887F6B950FEBE82BEE928D5FC97146C1C0040D04FC7A6FEF1A1C1832FA6CDA05B29E4B97303A5665247525A0C6420BEA3033D43CFB05AE141EF4CE32E930AD9A02E5EB5029E05BEB7E3E1D060A8530037796A5DE53D620BEB9539F3E9A6D3DD15A015C38E1E2E074377E2F91136CFA0FCF6DD4A71F8F7BBE94E6AAD85512089837CA03EA4FD917D9AF7F9E236E6C8F348662EBF6C7698D43A0C6405025B11CFC688F8A0F42B081F158CB649DFDEC4A6DD91C571FC9FFD95F1858C8C6EFE96E115380460A08584296339BB2A100045EF00E681DF7BB01ED0FD4E3A18AB3B2E1C725FC10EDEA03D0B9885370FCCAE0EB00C3C30B4B3620439E531E058582964614F24F42E31BAA015D24D88EE32423B54B4BA9D74E008F5063A0043D417E9B576F7BC77A393D7A0A02FD0DE7934B8F56D343D4B98137DA1364F35FE03DE7F100B66A6551EB25E03B4A0D94A49F5B0AB6B6FE4FDCFFF6454E1627C2CCEAAABCAE17B153D457731652CC580", "00A85842A20755232169DB76C5BD4AD4672C1551FCA4B07D0BD139CD0E6FEF684D": "F90216A0C751D07FCA9FF9BF7B1BEE2625DC028608EC20BAB292A8E52D3247785FAD3CDDA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794C0EDE9A639D107851462C15F2FB729C7C61BBF62A05EEA610130E3A2368C6FD102E9A7E4D0BCAAF5152DD18DCE60D74E1C46219A94A0D709B472238C8B12B0B66ACD2DC3302BFCC5FE30FF1669865E4887F717597075A0FDBC75CBD98E50C3D4CAD07B9C2D0EA604318FAB47D686CB5D4DE622B58C2057B901000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000086015451E9450582B86482A2718252088455C46BB399476574682F76312E302E312F6C696E75782F676F312E342E32A09DFFD5055C23D0FCF7695A877CA56CEE801230BA43B7597DF0F76AFA7949762288169B5BC47FDAC77F", "008CC34CFE4E1C5CC49EB8F7D6242F5F7A84DA3539B5AB68FAEDEE634776EE5B47": "F9021BA0A85842A20755232169DB76C5BD4AD4672C1551FCA4B07D0BD139CD0E6FEF684DA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794BB7B8287F3F0A933474A79EAE42CBCA977791171A0D1F9DD04F17019A7A08D7F8641601C36F293C301FE0AF8E0823F2480784315C6A0C864072AF2EC7514CA19131D4007AAE00D429452E5E2059E02C84BD5676C5C1CA0A7DF100062910A5F3425D5FFC97F92463BD677B05B88FDB1521CD451DC4E049DB90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008601547C73822D82B86582A2988252088455C46BBA9E476574682F4C5649562F76312E302E312F6C696E75782F676F312E342E32A0FBF2DBBB310A4E45DB26492A432900A4BFBD90031DD3704D77CD27FBF83C38FE884C7FC9AE12C9677A", - "0165B8000000000000000000000000000000000000000000000000000000000000": "A08CC34CFE4E1C5CC49EB8F7D6242F5F7A84DA3539B5AB68FAEDEE634776EE5B47", + "0165B8000000000000": "A08CC34CFE4E1C5CC49EB8F7D6242F5F7A84DA3539B5AB68FAEDEE634776EE5B47", "CEFD3B0B7336ED9F68447A4A3E2545C4B1A93B2777F152198D03331E0F4AC640": "F901B1A084957E0882A83E8A2B4B4D53478DE1AC7259A556CA0432BC93A8101D02ECF16BA019D297F57CF479FC7E2D774B7FECB2C323E7CC23C0865B4F39843D8D755EB3E8A09812B2E76D9DE7E16251436641DF5E3D5FF1973ADA13187414D665F42C2EB0F680A087E1E054DC75D06145BF158B7C746D35586EA0EA64B4943B092C7657F268A110A049B3E569F9D418875FD44D4229CF721B7279E987ADDBD33CCD400CA5ED5FA615A0DBE00D606478B8E631B340E94A0CE269F784CC8EB28A404324EBF9FDFB4DF96480A087952CE54F47F497AA3A92BECE385FD7A99C730ACDAF9C806B8EC8BF935A41B5A0CD3F06248B9F8B5144E2A3E4D00BCD716F912DBBA8CC2DF0192D424682892951A063C3B649EF9F70CB8BC3E17A9C97BEBDCA7C6D278F0E91B8860D6D4AE4996D51A0E5682CC25C3BDD35C5E00A39A2293FAC682567F3E09C6305AAE49150605032D280A07DA50003001A681080D1857E5BB585522C7869AA1AC71F1D8625A6220FF9B0BEA03877E05A14C10B7692F087F6B48B9DE74A5875549D867AC5601E5579249F0B3EA07F64010B162255F7B3CB0A3C58691FC4DE275BF09D43ED597A983FF5DDAF153480", "56E81F171BCC55A6FF8345E692C0F86E5B48E01B996CADC001622FB5E363B421": "80", "5EEA610130E3A2368C6FD102E9A7E4D0BCAAF5152DD18DCE60D74E1C46219A94": "F90211A0D2E8DBA0642753922F398B07096F611A20263D9F9E585FB66AE0780D5370A36DA0F27488264A4FFE3526608DECFFC2ED1092E40D626A46A6F876C06BA8831F42CFA01C1471B7C5CD4FB822AF83115A666C36370CD60628BF25631E2040DBC4A45274A0017D63205C1546279F96C7AA67766C2F1EE332ECC0C8A1504438F12CD2C3A247A090FC1BB8EFB80653679D0C86AAECE868FF59F9BB466BEF7D7A47CBACAB9A7592A043A0F22C40B2576CE1077A60B77E83CA4CF21C4FDAC07B74E1EC7AE4782877D6A07A48B72AB4CD323303FDC75E194264D6C63CEDBEA72A461FE22E31BB64220411A06A5FCA8D789C4D864D054E10CEEC042FB075DAA3CA6DEE3605269743A21CBE9EA0AF6F533CBADCEC117C729772DF8AD184A68EA066F96037CC817C741A8370F07AA03A97BA115E7C117E5F7FDFBDDC1C6E83A8DAF45C7E6EA384B4AE13EE1B4AEBDAA0919A81EBF1D48403F242864BB4BED15A0C8D3EF61BC7EA6EDB8173E555F189FCA07674E887298ABE5D32ABB42A5C10565CF7CEF3D747AA0355570AC0CC4CCB7CADA030AB21F33FB9BFF8DF3F6CF65380589A96CFC224943EC1CE3B2CBB7FAB5E6463A0477EC8D35720FFF05BF627560C62ED9E60E99A9A9720DACE70CE6569127E9FBDA0F6AEEA1C1EE6453077B346361B29345EF0AB1397B9C3C501575796D8E8D0B64FA0E81D29B9625B71E8C68921119BBB5C416CFB52E4146D79A71C0E3BF78893FE0280", diff --git a/tests/fixtures/TracerTests/block48712.json b/tests/fixtures/TracerTests/block48712.json index 9de31a9be..9be0322ce 100644 --- a/tests/fixtures/TracerTests/block48712.json +++ b/tests/fixtures/TracerTests/block48712.json @@ -639,7 +639,7 @@ "state": { "904F4F5D5514916FEBD06A71B00B0DF1DB12FFBCA8B7CAE02EAB6FFCE7E67B29": "F901B1A0565859C900551C172AF58D72008634D8DA4F5CC630C1310794C4D6B17654190EA0BB5F36F58539BE753C1857F786CD5C317608E7CA1760BD17FC10BDC7B6450FD9A0E93E98C69B399A7AC12DFFFDA8D608DE02332AF07E06938F944E1DC3EE04FCAAA0E36E3E7FD628A10D1C879179337E861C289F9B3C477166AA1FC4CEF38201DA05A0F0D3C7B7457BDB9F9E65465021CBBC3E1DDC862BF8CC70825C558D54866C2D0BA0498680F1CF3804C1E9AF01CC76F5974484247BD941154DAA9B190075DD732AEEA071D94047E43593785F8DD4EAD2C9F849F8060715A2AA04DE0939ABFB18DA8BC880A07DEDD548975A4D9FA6CFEE54470EB93A974FDB6F905FD9710DC123C74A2145ACA0BA108165C5C101085663C7A7A44E80947BC93B15AB972AE6D050425E09FD88FB80A0C11A8B8995590E42586C767DD916EB84E90509BE61D1E03D1099E7EE13BDB9D7A00C747E7FDDB2729A0836AA853FD3567257EF02AD59A50C881C25D41597492F67A06F6E81875C2151F35697EB50762BDE8ED48354086E4CBAE5069A9CFC47633511A0E6066D206427CE40B90488891273C04816D89DA3421F6976A85AE9D6051228938080", "7F05D940C9A3C2F9A135A3FAB68739B7B4C2EA8C10B9D633ACF23676B78DFB19": "F90211A03A313493633D08B3DE8A9C3CD2B207F6FEDBE1420F4D0E00F17717D652DD1BFAA06060A15766E6E43215C42436FCE4017FDBA34F4CDD53C5D8BCB29204E3226F17A04D21029238729E23AD9B4414D2FC9752B5A4BB77B5D8989A7882EB2F1F13B1D4A02B82DA70991E126E0E1F294E9D69FC1938F764EEC3AD8DF79B028587B259C2DDA0D793413F5E367B9208E5E9CF7DC5D34EE3470D6B7E20A3C49F9D5250A4806D36A021FCE5FC8CE71DBF7E0476324D3147366A3D7F3B6DC1215A1B962151AA694183A0CEFB748CE0891576A8407FA0AE54BC08117424BDD6542758554B331F6FC69E93A0096AA475BA7F6322DB1E4993F86577E794C060FF9F27A376CE4A969B9BCCA28FA09726EE13DE390179B833CEE8A01D76EA9ABF034CFA1A7478482FF74F7BB08F9DA01B6673FFA58EE9845F2581249DD7F358E054207D79AC5F749FB5143A766D9C6EA0C119EBCADDB0D0D56379932A0254FF34FF0657B46844BE7E967AE077F302E10DA0C88EA67867E94993C35E183918E5EED5B250E0221539E7EDCCC0AB6407AEFD63A05BBFC8E1CCF7EA9E78203EEC4368E3FF1F7C2FE727DB68D2AFD5BFAF1C9A8238A04182884BAE14D1400D6E67962D6E016484D8308A78B4A27B16381717321B448CA062A177EF0981BF5FA190D7CDD1232F18894FD8B4F13701AF4090D40CDDD0B686A0FBD8F2760CC206D7343785E4E4605B7A52FE5A743075FCDCCAA4FF64F953586480", - "0148BE000000000000000000000000000000000000000000000000000000000000": "A01AB5368FF651A64EA9B58360B76663F425C843E1DCFF333EA6A6D319EDDEFA57", + "0148BE000000000000": "A01AB5368FF651A64EA9B58360B76663F425C843E1DCFF333EA6A6D319EDDEFA57", "5D57B9C1348A24638D6DFB13E49AB9FE1A41D12FD5C9FA4F48152C4AF6FA2D0D": "F87180A07632B992A9ACCA942E4D5C07AD1B1B4FE22FB788F30162F87EFD5EE5E9F28A6A808080808080A081DCF323A9BD8198B4EDDA489804DECB6580EFF6FDABB04FA283793A952A291280808080A098D6F9AD70C794C3009FFD508676D4C57015D387419B74E7E0572B9D28E3C916808080", "520E699FA8218A3A8A7D0C07AA2C0BE66D2A00901708C2BF7305142AFECB63FA": "F901D1A0FAB82D3458E0FEDDED3162B364A88935ABD00D171B1C626E55EAEF1D5B9D2E5CA04B9D57B508ECBC99DEF1BA60B750DAE48AEF48F82281C66A7FC095F0BA9BA7B480A0A6CCF2CD4991E32353AAC08913AA4AD049A256D61A78C40511A0F330651D6259A090B0897D4A7C190A48EEB9AAA54782A99839C6BD1A1339E456D332BC24A86DAAA065185F6AD66AA460F26D50004373F5939C9EC45094E6E1A9A66D79FA666BABC8A0D4DB7198A99FC70E5FF537F06D1990F4195AF4E4AFAD99E5F1338A5EC49F8F0DA0541D47C96C6A4F939D241F364F525F6CC630E298C70587E814A4B37B4CD86CEDA08BD0BDBE5F0C7DC89C60A82F26EE86E0230E9F3CA90C7B865ABBE928F5FD28AFA00975793F1C54224099EA045A8F298084D22AA210BB463FBB310C0B47C9E08FAE80A06EAA957D326471F24DCA76363FF448CF2CE18985BB485EEC8870411C1AA51393A05F2A4E4061D5570E5285D09BF72F1A0D9C6677D3C415DBF39FE59BE2E2CC0E90A0B6F0C1C4B83D43AD7860E59B5B139884F76C43CD053EBFAC9F386505141EBC1CA080618739B3AA903570C0CFD798047661DB729D578B9C4D483ADAAEF5F51E57F8A0E98032BD670EF43A700F2E1E876B2E7ECB32F2BD2B5DF9D016ADBD1F341345C480", "112907318E93F02013543B6FD2B9901D614EB373BAB73A623729F8707B4A566B": "F901D1A0387A8387D9587CADF195DD49CF3104D46375DA853B3B3CD07DD62FB41470F1DFA08779A215C51EAC5D2FC48ED5CCA207E7431C418001A9E4E324A7076A3671CED7A0FD8C82E97E3A206EAA86EDE0054F5EE3EEE3180638EF8440500CA255253FA1ABA02DAA0C5ED685F5AA5BAFF026607233A09C27D326E6D0E1305CC6EA74CAE818B7A08EECB423CE2A9872686362CD5225E25C721FFC224B0CD3BF71F6C4C46260B4B7A0B598BD70853D49194B37560E8A3962BE141576B67E21C87A37C4471CE5D2782980A075FE120D9F9382A431AA17CE1CA81EDC40B7CABE725EA296CB750D0AA6022D6980A03CFF7CA8B42E7C76F46A6D4C231556F0B14D2EAEA4012E778063EE9FD28C8C8CA0AECCFCCEEEBAEC87D3FD049B5E7E2CA36A0AB043520FFEA95DE9B8544C20D412A0B73C4EFE365852AFDB4C23FF98F9B1DC99A37F27DD3936C4E388220C284BF4F1A01BA3FD959ABF6D8005CA1814FCCF700ACD941E14B02549E8CAB18D43EA1D462DA0C4432032458F908E2F9F0169F47D1CF2F6EC8C5CA653222FB5F5B927906B77B1A0E3A2C997B48222A985B3FFC3F4DD329D461053E118D0AD736083AA288359DA91A025536F30CB2CA396CE386D6841ECBDB039A3699F6FEAE3C934FCE66152FD055580", diff --git a/tests/fixtures/TracerTests/block48915.json b/tests/fixtures/TracerTests/block48915.json index a9b2d8d89..30e56099f 100644 --- a/tests/fixtures/TracerTests/block48915.json +++ b/tests/fixtures/TracerTests/block48915.json @@ -473,7 +473,7 @@ } ], "state": { - "0113BF000000000000000000000000000000000000000000000000000000000000": "A02F58A1FA8B4C9A945BA6CD9BEB98F0298A71D507693A4F7C8778571B4B9A0040", + "0113BF000000000000": "A02F58A1FA8B4C9A945BA6CD9BEB98F0298A71D507693A4F7C8778571B4B9A0040", "9C14B628EAB51B7B5B1624BCCA150CAD37F679BE839E7CBD6FD5A23F6113CC53": "F901F1A088E83CF830375E1B5C4CD389E2C803F5B8E80E69A1869A198DCDD9759483CA9E80A0926C37EBDA308455D98F08EFFCC18DFE2A524469441E7D1719583489181D7151A072A403F9B5ADA10A53743CBD93AD31D21BB094E5AE4DC451935B9AAA39EB2F4EA0C7F29424051A57CA2F7C89D23734470FB6EF3D745991228963DED696664666C4A066DAD1C949E69EE8AC95ABED09F24A934D2056D51AEBF1C5B933EBF7BC9E7503A05D1D93F9EA366249216471E7576C1FDBE6510E8511369B58E875161C775E0060A000EB16FD161F6630D76DE59075FD720C4D4257758B8A44B2162B2FEE7D841F29A07E263A893FD1F4CD633A042A4602CCC26710A2FAEF57E3B5AF647E640A89215FA0AA7F022D4C024EDB4EE72EF2F0BA8B02E38F1E44EC5FFCBCD5FD378B04DEA3A5A0559520C332549E394CF61E754E6467965E64774EE089430185A87FDAED26ACC7A0DB0CD95A34F14D6FD37B9F0EA261B2611BE650A511CA6B1BCB78525E691B5EAAA0616ACC17D09C0A11EF790979E13CCC1741A4AB1704B0487A65DF5749DA209086A024B228AE92FF13CEF6D05356D640F8BBACFC200F9226BECBB1293E07E73FF284A06902E5D975054D9B347BC80D8F5F9A7B405A027DE3250E9AF69FCF843905A3A0A0250DA64C1476B73C3726970004D417A339DF041EA44DB1CB0B9CF54F0AEE27FD80", "A32F0BB3FFAA9AEF98D7FF8E26F117AE446A72F2FB17A66CD58F454577EC713B": "F90211A0A2F0DCFC61934BF48DA584E6892FBC2E0608663F45788ECDD3FA89308B3D6BE3A0C2E14D9412AA3303CBF34415FC15FE10EE9AA177227A001C3F805C07D4554FB8A0F3F8E2D490F4420DA631F57482AE74A6AAF61E135E5FD6664188C5070EACA544A017D4CC47A783DB73953ACE2767C8556E12358A734D543D028D7DA54BC8E95BB0A0BAE9C2F34C637C05979D677427A4EB638999E7C0584023B88E6D66CFCB41C0ACA04CFC9E4F7CB640362E763F14C48B20024887BE74FC6D970CC9BDB399BF2C1D1DA0E6CCA36112D80E7A000DFB2FA8EA93569D1C96B76BCCC5D36D6269E6ECC1708DA03552B48ECCE21BC63DE42E8420BFB483635382D4261E02F8765C1D3C45D2EF92A0A95340AD4C6A22B2F4D1E4F2BB169C567E37E21224FB67613B10806EC30CF127A0D9CFBA2BA169C9394C23E49319866EC07BFFAAA7CC1E8047CBB6DEE3AB7F3923A09C8040D944ABF7BFF15F9D29AACC17FA8595C18F823A63E85CBB9941F6E16886A04DC81B6F8E8CCE066D5483D140D0FC251D5C6F38619D9143B051030C01FE716EA09AC5FF42A36523B5493FB4FFC3F46340BC5EBF35EBEF50B4D5B2DF4BA86F881CA038517D527084889E2C197552304FE68CF0D7E10B10CF9D20858CD297545D3392A00C3AE2FFA68BF62ECBEBC2C343D008D857130E1505AEFDEB7DC192A35C81B98CA0404F4EEDB718D4BE0252A20DE242AB7C98F6C8BA73EE37EE0DA3C49A3145C44A80", "EC4E983A62E4607D9B77634035680E19E0660CC3D928773945C4A86C44E2BBFE": "F8719F205983F8AD36BB34D77730505275FB403A91FAF89DFCBF84A482276CAE3B3FB84FF84D808901159AB5726495D700A056E81F171BCC55A6FF8345E692C0F86E5B48E01B996CADC001622FB5E363B421A0C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", diff --git a/tests/fixtures/TracerTests/block49018.json b/tests/fixtures/TracerTests/block49018.json index 59fd5048d..e336388f6 100644 --- a/tests/fixtures/TracerTests/block49018.json +++ b/tests/fixtures/TracerTests/block49018.json @@ -7519,7 +7519,7 @@ "399167AA45E4F3D5B5D3C8ADACE294DC6EF820D43134230DA258324886A76F4A": "F901F1A07E3841A449BD5A6DF6ACEACCE40C5B64DA60027FA5100AE010CCB96966FA40A3A021B066C4E81C1FE54C8034493A4F97104721FF18B19D41CF6E4180D031FCBF48A0D2F5F41F4D99634813BBB72C6598AFCC6FEAE74D56C5A7E965E4F84C61DE88F7A01DC1363756D994C0DED724EEB3B962044517EE8CCB2D819EF806CCC22D6B19BCA0881D03A502FB8B7AE1EA1AC001BC18B5D16AE2352B759753ECA8DBCD1929A4C9A08F9FF6D4A46141C987260931A6B2D47B19575519270B36DA3C64EA612F0BAB4FA0ECFD6C4C8066F5BA5D3E5799BB791E9027389448120B9B85D2F225F7AF95B81BA038C0BE1A498CC8A81B3823420F588262BA547123CBBE5496ED9C9BBE8746E2EEA0FB973E874FEFB1A847154BA6711CCA33610C2916B37E5853A8DB434D63DE56D0A014E1434148BAE838820BF07E69756B5A23497BBA247E466E9A9C82FAAC33E41AA0737A835A03BB4D86E72CCB72C5A19A4FB5D527D7574DF7E707CC2D2E968C6B91A02B33586FFFEE450DF84D574BD66E98DB9F5059DDBC111984B38EBFD941E278F3A0D92E5C7BA701F75F742D824235AFB2FF5F228FAD3ACA6A30EDED0336D648F214A0B41EFE936355F7EA256D1FB5212563F6C36611CAE557A70917B26AB69ABB6BCD80A071BE33594382CD7FB42D039800CA2026FF2FC1FF4BC06963F3B4DA16E90577C180", "EBA0C52143F7C3D0E2233F5B108742E1FB389ADBD21173E61DEE030A80EDDE83": "F8709F20D0A5C62D3EFEFC550F065DAB36BFA72FB40B9884AB62FC447B7BA18B52C1B84EF84C0A8843F0CF1107E922CEA056E81F171BCC55A6FF8345E692C0F86E5B48E01B996CADC001622FB5E363B421A0C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", "18C452B86564EA5D94076CA7F5D509EA92DC98A904ACC9E3C549145E386F56A4": "F8729F20E342BBA2807022514C2D522E22BA66F911653D1ABCC74BD0A7868AD3CB36B850F84E038A047D269FC4069450D050A056E81F171BCC55A6FF8345E692C0F86E5B48E01B996CADC001622FB5E363B421A0C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - "017ABF000000000000000000000000000000000000000000000000000000000000": "A071508D8B2FDFC3BDE1992FE79AB9D51999B7F14342252D160CC5B5100CDC42A0", + "017ABF000000000000": "A071508D8B2FDFC3BDE1992FE79AB9D51999B7F14342252D160CC5B5100CDC42A0", "A00A394AF5C46BACF7BB36C6B2E771A61199696386A46E6FFF0B84094451346F": "F90370822080B9036AF903670A850DB5AAA975830236858080B9031460606040526040516102B43803806102B48339016040526060805160600190602001505B5B33600060006101000A81548173FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF021916908302179055505B806001600050908051906020019082805482825590600052602060002090601F01602090048101928215609E579182015B82811115609D5782518260005055916020019190600101906081565B5B50905060C5919060A9565B8082111560C1576000818150600090555060010160A9565B5090565B50505B506101DC806100D86000396000F30060606040526000357C01000000000000000000000000000000000000000000000000000000009004806341C0E1B514610044578063CFAE32171461005157610042565B005B61004F6004506100CA565B005B61005C60045061015E565B60405180806020018281038252838181518152602001915080519060200190808383829060006004602084601F0104600302600F01F150905090810190601F1680156100BC5780820380516001836020036101000A031916815260200191505B509250505060405180910390F35B600060009054906101000A900473FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF1673FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF163373FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF16141561015B57600060009054906101000A900473FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF1673FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF16FF5B5B565B60206040519081016040528060008152602001506001600050805480601F016020809104026020016040519081016040528092919081815260200182805480156101CD57820191906000526020600020905B8154815290600101906020018083116101B057829003601F168201915B505050505090506101D9565B90560000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000C48656C6C6F20576F726C642100000000000000000000000000000000000000001BA078142D902B12A160B4235A49395555CC19EB2C94623365D5E2F9E6441D0CCE4DA07363727E891A7FD5561F7A2438300F6733A8E950BF5EFC1123D8B90158B0BBD0", "1168295A0DB6416DEFF90413F9F8E0142A0213B3F70BB8F908B6C3AE49BD3715": "F90211A0EE1A65A7A01AD9CFCFC643FEA7D6B39822BAFD83E8246FDB404A42D68B2E054FA04BFB1455DE928467A8C439F4ACCAA470A5670686A77F74A10D10B90EB3DE7D12A08A839C0C6FF77A30BAE2D3D9F2634260F8F2102D42107C9587D686DAF68B129CA0673E513A520FF78A84F8058FE1E45616BB6FEDA4B21D5752A8C945CF88608BDBA0425BD5D1FE18AB465960205B59A9CB0F3467370BFCD63C3F2F419C54B8688129A0101FC418C3604CE0D7415639E7FD45FA943FE191C2C2340959AB32F829BCE529A0575F1C82211778B83481E8407E3907D12879B37DF1506E736C4CE375902B2A94A02551ACE861E655CAB8B1B317B01C22BCBB43C3237793FC582688B79AD9F0C258A088F21F90B6EEEBB758EFDA6430C77196866A83F5199F50ADCAACF866F33C4FE3A001E8B23AA610FC81B30301ADEC4CB29499E1695CBD7937FD4B41155A503DFFA0A0AA59E33777C9C214561A8A4FA3287D6E4270A862A5E757E25C3C59090A3BD7BBA0A8D9F8B9EAE907C72614339243EE6634C333462E55D753D02B54972693F4C877A092B0CAD04C1409B6840481A9DAF9398B4C75617BB4B625E490B48B9D7E7F9571A0BE2F9F7B4016FF7F9D3C227BE36D4F2289808C6E76A920B42288DF7482FE0802A07DC24FA128A2E5C864AAD6EA36E1ACA7DE7A9768DF701B770C96E9F065277307A0FBF8C18397F377857F31DFF97ECE10A6214446C841F693A4ECBA85DD6F78D03880", "88F21F90B6EEEBB758EFDA6430C77196866A83F5199F50ADCAACF866F33C4FE3": "F90211A0E12DEBA6D77E29D5D79E2A19AE902F86A8DFC64D43038250AAA83119E9FBA7FFA0FAE5FF63D50B6EB3FEA8F9FCD501309FCDC72B1776C9525604D44D31249C76C1A0AC35F435450CF5FC8FC85F56963A9E47E72E961E59EA6DB8DDF0295772D74B2DA08FEAF622870EA8FDF6CC204E4E96E554F6D166981401AACF4BEFB491E57A0551A05EF3B232C163DC2BED7FBFA1420668A7C377D7C1877E9F9E743615A249195E56A01400F1CAE63720ABB34845A6F7C3CD8894F9EDF81369C3AD50119E89DE7103D5A00BC3185B259201DD77263E42D2AEB2B6068004DD9ACC63616C4D37BFAF91E92CA02DDF9D6DD400A0D264444B52FC01FECF2CAA350F5DFD13154068341EE4BC4640A009CAECDA3F3567DA968374A3FFA8AC82A420495714F2AE99C4B101DCAAC4EAE3A03CAA050A10785316FB6BFC1A073706FBFFD1CD18808F6527E410BDE2D0E12D79A0A9D78E9B0321CD33EC91842CBDBD6C466C8F7B81A2C6C5919E570D2E763BE4A4A0AEEBFC200B3259A37118B43B8D9C624F9C5B5E5D04D20E53D02A82808F2B7EF9A0014F5A9EA1A7EBE36D64CD24172FF7FF315A8D60CDB82CFEC9444B6B744FDB9AA04E41FD640897693ED2AE2F88E8A71FF8C2F36499710AAF1A486B45EFDF12ABF7A0B4DEED89648E46C7AF572ECDBEFB8ED9AAAAD10E9C3208999946FC34D704BF52A006F41A5BCC06DB92A00CD61355E2240F3F33F30E99E239CA60F3C4E3A033E5CF80" diff --git a/tests/fixtures/TracerTests/block97.json b/tests/fixtures/TracerTests/block97.json index 9d7565f47..b6b211187 100644 --- a/tests/fixtures/TracerTests/block97.json +++ b/tests/fixtures/TracerTests/block97.json @@ -83,7 +83,7 @@ "5BABE001FD5C118558E7B131ADBC41D9131F51A5A94E875FBA41D070B72C7809": "F871808080808080A0582A075603FD332B47322AF21B0358619BD1865CA6402DF0D6888005EDBCE16480A07DD486BA8BC217016258648DAB25924EB47588642FA0F9BE579867256E798517808080A0D07D20A429C8A0CD30B5C30FD6E72E6D5404795A9B10ED31FDA1422014036E8380808080", "56E81F171BCC55A6FF8345E692C0F86E5B48E01B996CADC001622FB5E363B421": "80", "803B0C8EC037D493EBF19CDFFD202A826C82A3F7CBE55495FC53E4092432693B": "F8719F205CFF8BE348CB55792F52966BBC619F0BC63DDAB2BF660D6F8A8E452CF27EB84FF84D808901F090894C3D722000A056E81F171BCC55A6FF8345E692C0F86E5B48E01B996CADC001622FB5E363B421A0C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - "016100000000000000000000000000000000000000000000000000000000000000": "A0E9FB121A7EE5CB03B33ADBF59E95321A2453F09DB98068E1F31F0DA79860C50C", + "016100000000000000": "A0E9FB121A7EE5CB03B33ADBF59E95321A2453F09DB98068E1F31F0DA79860C50C", "00E9FB121A7EE5CB03B33ADBF59E95321A2453F09DB98068E1F31F0DA79860C50C": "F90216A0350565A8DA416084AF658287442EEF4F651BF944C6D804B5C3BDEE5D7D951F80A027E6B6AD4E6D50EF76EC5C1A8B09A6F852EF5D589FE8D87873F5935A9FEF1BBA94BB7B8287F3F0A933474A79EAE42CBCA977791171A092AE5D0DCC3E4329063C0D80FF5745E16C23EB23D187AD89F9AD0FD5105508CAA056E81F171BCC55A6FF8345E692C0F86E5B48E01B996CADC001622FB5E363B421A056E81F171BCC55A6FF8345E692C0F86E5B48E01B996CADC001622FB5E363B421B901000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000085042A57101361821388808455BA43E69E476574682F4C5649562F76312E302E302F6C696E75782F676F312E342E32A0FA49E533FBF3C65EC8F3C3D23FC5F74C47C41DFE952ED3B756A5B4EA2A7ACFFD883688FCDCA62E5DF3", "D07D20A429C8A0CD30B5C30FD6E72E6D5404795A9B10ED31FDA1422014036E83": "F8719F201318F1145B0B422363876E3BCDAD686EF7B177708C4616E795A67CA42BC1B84FF84D8089045CBA6DC885B6E000A056E81F171BCC55A6FF8345E692C0F86E5B48E01B996CADC001622FB5E363B421A0C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", "563401469B5C16712B251E6042620838DCF4B88B6C59969A86FAA94C7B4402D8": "F90211A0C637B5994860158E4EFC9ABACA8B16FD7D690896FF610F3F40EBFCED8A80FB8EA0BABE369F6B12092F49181AE04CA173FB68D1A5456F18D20FA32CBA73954052BDA0302EB94C0B18C718D1D7465DD0E0E090B57114CAA335A187ABC90B1AF6E8286AA06152AF848978F926680FD694B2EEB6DB839BB30EBAB8E3EF8E8765B3D61081A4A0FCB892B735626A4B290598396D07818BE4DC4EA54B79704D23AACE3283EF1788A03D666815D326EA39BB152FD7A94305180D243D6AB090BD85B2079FC3EF288804A09C8A14529A6EB5508F695352706A8BFADB3044BDC70FE71DDB0B0FB31C868664A0F7A00CBE7D4B30B11FAEA3AE61B7F1F2B315B61D9F6BD68BFE587AD0EECEB721A087D97DC44C15FFDCC44AC0A08EB4C696193AEE5CE0AFE2DADBF372FE76F0A6F4A0F30E9A00AC1D8B2033452A21A03FDCC06D93A004463B52A165F67D1E0EB2847EA0203D26456312BBC4DA5CD293B75B840FC5045E493D6F904D180823EC22BFED8EA04933DCD3876194414121888105975C1D2D3E6F2058F76B54A7E7078F93F2CEB5A0857866471DC094921E22545450C5B800ED1142C848B94C48EB406277128BF87BA08E438497094BF3918FBF639F70E88E47F18BD864DBE4BC79C9B40C990B653462A051F9DD3739A927C89E357580A4C97B40234AA01ED3D5E0390DC982A7975880A0A0E49D17F8244F436A0BE2E72109684E38FEABC82C9D03CDD6C389621BE4123A1980", diff --git a/tests/macro_assembler.nim b/tests/macro_assembler.nim index 1ffd76cc7..62b9fed6d 100644 --- a/tests/macro_assembler.nim +++ b/tests/macro_assembler.nim @@ -46,8 +46,7 @@ type code* : seq[byte] logs* : seq[Log] success* : bool - gasLimit*: GasInt - gasUsed* : GasInt + gasUsed* : Opt[GasInt] data* : seq[byte] output* : seq[byte] @@ -195,14 +194,14 @@ proc parseFork(fork: NimNode): string = fork[0].expectKind({nnkIdent, nnkStrLit}) fork[0].strVal -proc parseGasUsed(gas: NimNode): GasInt = +proc parseGasUsed(gas: NimNode): Opt[GasInt] = gas[0].expectKind(nnkIntLit) - result = gas[0].intVal + result = Opt.some(GasInt gas[0].intVal) proc parseAssembler(list: NimNode): MacroAssembler = result.forkStr = "Frontier" result.asmBlock.success = true - result.asmBlock.gasUsed = -1 + result.asmBlock.gasUsed = Opt.none(GasInt) list.expectKind nnkStmtList for callSection in list: callSection.expectKind(nnkCall) @@ -272,7 +271,7 @@ proc initVMEnv*(network: string): BaseVMState = parent = BlockHeader(stateRoot: EMPTY_ROOT_HASH) parentHash = rlpHash(parent) header = BlockHeader( - blockNumber: 1.u256, + number: 1'u64, stateRoot: EMPTY_ROOT_HASH, parentHash: parentHash, coinbase: coinbase, @@ -295,9 +294,9 @@ proc verifyAsmResult(vmState: BaseVMState, boa: Assembler, asmResult: CallResult error "different success value", expected=boa.success, actual=false return false - if boa.gasUsed != -1: - if boa.gasUsed != asmResult.gasUsed: - error "different gasUsed", expected=boa.gasUsed, actual=asmResult.gasUsed + if boa.gasUsed.isSome: + if boa.gasUsed.get != asmResult.gasUsed: + error "different gasUsed", expected=boa.gasUsed.get, actual=asmResult.gasUsed return false if boa.stack.len != asmResult.stack.len: @@ -387,7 +386,7 @@ proc createSignedTx(payload: Blob, chainId: ChainId): Transaction = nonce: 0, gasPrice: 1.GasInt, gasLimit: 500_000_000.GasInt, - to: codeAddress.some, + to: Opt.some codeAddress, value: 500.u256, payload: payload, versionedHashes: @[EMPTY_UNCLE_HASH, EMPTY_SHA3] diff --git a/tests/persistBlockTestGen.nim b/tests/persistBlockTestGen.nim index f9076414d..f18cbbdbf 100644 --- a/tests/persistBlockTestGen.nim +++ b/tests/persistBlockTestGen.nim @@ -9,7 +9,7 @@ # according to those terms. import - json, stint, + std/[json, strutils], results, ../nimbus/[tracer, config], ../nimbus/core/chain, @@ -17,9 +17,8 @@ import ../nimbus/db/opts, ../nimbus/db/core_db/persistent -proc dumpTest(com: CommonRef, blockNumber: int) = +proc dumpTest(com: CommonRef, blockNumber: BlockNumber) = let - blockNumber = blockNumber.u256 parentNumber = blockNumber - 1 var diff --git a/tests/replay/pp.nim b/tests/replay/pp.nim index 4df3bd03f..4e7fedc7f 100644 --- a/tests/replay/pp.nim +++ b/tests/replay/pp.nim @@ -31,7 +31,7 @@ func pp*(b: Blob): string = func pp*(a: EthAddress): string = a.toHex[32 .. 39] -func pp*(a: Option[EthAddress]): string = +func pp*(a: Opt[EthAddress]): string = if a.isSome: a.unsafeGet.pp else: "n/a" func pp*(a: openArray[EthAddress]): string = @@ -51,7 +51,7 @@ func pp*(a: NetworkPayload): string = func pp*(h: BlockHeader; sep = " "): string = "" & &"hash={h.blockHash.pp}{sep}" & - &"blockNumber={h.blockNumber}{sep}" & + &"blockNumber={h.number}{sep}" & &"parentHash={h.parentHash.pp}{sep}" & &"coinbase={h.coinbase.pp}{sep}" & &"gasLimit={h.gasLimit}{sep}" & @@ -59,13 +59,13 @@ func pp*(h: BlockHeader; sep = " "): string = &"timestamp={h.timestamp}{sep}" & &"extraData={h.extraData.pp}{sep}" & &"difficulty={h.difficulty}{sep}" & - &"mixDigest={h.mixDigest.pp}{sep}" & + &"mixHash={h.mixHash.pp}{sep}" & &"nonce={h.nonce.pp}{sep}" & &"ommersHash={h.ommersHash.pp}{sep}" & &"txRoot={h.txRoot.pp}{sep}" & - &"receiptRoot={h.receiptRoot.pp}{sep}" & + &"receiptsRoot={h.receiptsRoot.pp}{sep}" & &"stateRoot={h.stateRoot.pp}{sep}" & - &"baseFee={h.baseFee}{sep}" & + &"baseFee={h.baseFeePerGas}{sep}" & &"withdrawalsRoot={h.withdrawalsRoot.get(EMPTY_ROOT_HASH)}{sep}" & &"blobGasUsed={h.blobGasUsed.get(0'u64)}{sep}" & &"excessBlobGas={h.excessBlobGas.get(0'u64)}" @@ -91,8 +91,8 @@ func pp*(t: Transaction; sep = " "): string = &"chainId={t.chainId.distinctBase}{sep}" & &"nonce={t.nonce}{sep}" & &"gasPrice={t.gasPrice}{sep}" & - &"maxPriorityFee={t.maxPriorityFee}{sep}" & - &"maxFee={t.maxFee}{sep}" & + &"maxPriorityFee={t.maxPriorityFeePerGas}{sep}" & + &"maxFee={t.maxFeePerGas}{sep}" & &"gasLimit={t.gasLimit}{sep}" & &"to={t.to.pp}{sep}" & &"value={t.value}{sep}" & diff --git a/tests/replay/undump_blocks_era1.nim b/tests/replay/undump_blocks_era1.nim index 45ea3840e..4cd64dc2c 100644 --- a/tests/replay/undump_blocks_era1.nim +++ b/tests/replay/undump_blocks_era1.nim @@ -41,7 +41,7 @@ iterator undumpBlocksEra1*( # Genesis block requires a chunk of its own, for compatibility with current # test setup (a bit weird, that...) - if tmp.len mod blocksPerYield == 0 or tmp[0].header.blockNumber == 0: + if tmp.len mod blocksPerYield == 0 or tmp[0].header.number == 0: yield tmp tmp.setLen(0) diff --git a/tests/replay/undump_blocks_gz.nim b/tests/replay/undump_blocks_gz.nim index c3f2d50a4..7f1e08bf7 100644 --- a/tests/replay/undump_blocks_gz.nim +++ b/tests/replay/undump_blocks_gz.nim @@ -28,7 +28,7 @@ template say(args: varargs[untyped]) = # ------------------------------------------------------------------------------ proc dumpBlocksBegin*(headers: openArray[BlockHeader]): string = - & "transaction #{headers[0].blockNumber} {headers.len}" + & "transaction #{headers[0].number} {headers.len}" proc dumpBlocksList*(header: BlockHeader; body: BlockBody): string = & "block {rlp.encode(header).toHex} {rlp.encode(body).toHex}" @@ -45,9 +45,9 @@ proc dumpBlocksListNl*(header: BlockHeader; body: BlockBody): string = proc dumpBlocksBeginNl*(db: CoreDbRef; headers: openArray[BlockHeader]): string = - if headers[0].blockNumber == 1.u256: + if headers[0].number == 1'u64: let - h0 = db.getBlockHeader(0.u256) + h0 = db.getBlockHeader(0'u64) b0 = db.getBlockBody(h0.blockHash) result = "" & dumpBlocksBegin(@[h0]) & "\n" & diff --git a/tests/replay/undump_helpers.nim b/tests/replay/undump_helpers.nim index 051753c99..2a93a8263 100644 --- a/tests/replay/undump_helpers.nim +++ b/tests/replay/undump_helpers.nim @@ -21,12 +21,12 @@ proc startAt*( start: uint64; ): seq[EthBlock] = ## Filter out blocks with smaller `blockNumber` - if start.toBlockNumber <= h[0].header.blockNumber: + if start.BlockNumber <= h[0].header.number: return h.toSeq() - if start.toBlockNumber <= h[^1].header.blockNumber: + if start.BlockNumber <= h[^1].header.number: # There are at least two headers, find the least acceptable one var n = 1 - while h[n].header.blockNumber < start.toBlockNumber: + while h[n].header.number < start.BlockNumber: n.inc return h[n ..< h.len] @@ -35,12 +35,12 @@ proc stopAfter*( last: uint64; ): seq[EthBlock] = ## Filter out blocks with larger `blockNumber` - if h[^1].header.blockNumber <= last.toBlockNumber: + if h[^1].header.number <= last.BlockNumber: return h.toSeq() - if h[0].header.blockNumber <= last.toBlockNumber: + if h[0].header.number <= last.BlockNumber: # There are at least two headers, find the last acceptable one var n = 1 - while h[n].header.blockNumber <= last.toBlockNumber: + while h[n].header.number <= last.BlockNumber: n.inc return h[0 ..< n] diff --git a/tests/test_accounts_cache.nim b/tests/test_accounts_cache.nim index dac3c86f5..92154c4ad 100644 --- a/tests/test_accounts_cache.nim +++ b/tests/test_accounts_cache.nim @@ -295,8 +295,8 @@ proc runner(noisy = true; capture = goerliCapture) = test &"Import from {fileInfo}": # Import minimum amount of blocks, then collect transactions for chain in filePath.undumpBlocks: - let leadBlkNum = chain[0].header.blockNumber - topNumber = chain[^1].header.blockNumber + let leadBlkNum = chain[0].header.number + topNumber = chain[^1].header.number if loadTxs <= txs.len: break @@ -325,7 +325,7 @@ proc runner(noisy = true; capture = goerliCapture) = test &"Collect unique sender addresses from {txs.len} txs," & - &" head=#{xdb.getCanonicalHead.blockNumber}, top=#{topNumber}": + &" head=#{xdb.getCanonicalHead.number}, top=#{topNumber}": var seen: Table[EthAddress,bool] for n,tx in txs: let a = tx.getSender @@ -337,14 +337,14 @@ proc runner(noisy = true; capture = goerliCapture) = let dbTx = xdb.beginTransaction() defer: dbTx.dispose() for n in txi: - let vmState = com.getVmState(xdb.getCanonicalHead.blockNumber) + let vmState = com.getVmState(xdb.getCanonicalHead.number) vmState.runTrial2ok(n) test &"Run {txi.len} three-step trials with rollback": let dbTx = xdb.beginTransaction() defer: dbTx.dispose() for n in txi: - let vmState = com.getVmState(xdb.getCanonicalHead.blockNumber) + let vmState = com.getVmState(xdb.getCanonicalHead.number) vmState.runTrial3(n, rollback = true) test &"Run {txi.len} three-step trials with extra db frame rollback" & @@ -352,7 +352,7 @@ proc runner(noisy = true; capture = goerliCapture) = let dbTx = xdb.beginTransaction() defer: dbTx.dispose() for n in txi: - let vmState = com.getVmState(xdb.getCanonicalHead.blockNumber) + let vmState = com.getVmState(xdb.getCanonicalHead.number) expect AssertionDefect: vmState.runTrial3crash(n, noisy) @@ -360,14 +360,14 @@ proc runner(noisy = true; capture = goerliCapture) = let dbTx = xdb.beginTransaction() defer: dbTx.dispose() for n in txi: - let vmState = com.getVmState(xdb.getCanonicalHead.blockNumber) + let vmState = com.getVmState(xdb.getCanonicalHead.number) vmState.runTrial3(n, rollback = false) test &"Run {txi.len} four-step trials with rollback and db frames": let dbTx = xdb.beginTransaction() defer: dbTx.dispose() for n in txi: - let vmState = com.getVmState(xdb.getCanonicalHead.blockNumber) + let vmState = com.getVmState(xdb.getCanonicalHead.number) vmState.runTrial4(n, rollback = true) # ------------------------------------------------------------------------------ diff --git a/tests/test_beacon/setup_env.nim b/tests/test_beacon/setup_env.nim index 6b2799680..09982f356 100644 --- a/tests/test_beacon/setup_env.nim +++ b/tests/test_beacon/setup_env.nim @@ -32,23 +32,23 @@ type let block49* = BlockHeader( - blockNumber: 49.toBlockNumber + number: 49.BlockNumber ) block49B* = BlockHeader( - blockNumber: 49.toBlockNumber, + number: 49.BlockNumber, extraData: @['B'.byte] ) block50* = BlockHeader( - blockNumber: 50.toBlockNumber, + number: 50.BlockNumber, parentHash: block49.blockHash ) block50B* = BlockHeader( - blockNumber: 50.toBlockNumber, + number: 50.BlockNumber, parentHash: block49.blockHash, gasLimit: 999.GasInt, ) block51* = BlockHeader( - blockNumber: 51.toBlockNumber, + number: 51.BlockNumber, parentHash: block50.blockHash ) @@ -80,19 +80,19 @@ func subchain*(head, tail: uint64): Subchain = func header*(bn: uint64, temp, parent: BlockHeader, diff: uint64): BlockHeader = BlockHeader( - blockNumber: bn.toBlockNumber, + number: bn.BlockNumber, parentHash : parent.blockHash, difficulty : diff.u256, timestamp : parent.timestamp + 1, gasLimit : temp.gasLimit, stateRoot : temp.stateRoot, txRoot : temp.txRoot, - fee : temp.fee, - receiptRoot: temp.receiptRoot, - ommersHash : temp.ommersHash, + baseFeePerGas : temp.baseFeePerGas, + receiptsRoot : temp.receiptsRoot, + ommersHash : temp.ommersHash, withdrawalsRoot: temp.withdrawalsRoot, - blobGasUsed: temp.blobGasUsed, - excessBlobGas: temp.excessBlobGas, + blobGasUsed : temp.blobGasUsed, + excessBlobGas : temp.excessBlobGas, parentBeaconBlockRoot: temp.parentBeaconBlockRoot, ) @@ -114,7 +114,7 @@ func emptyBody*(): BlockBody = BlockBody( transactions: @[], uncles: @[], - withdrawals: none(seq[Withdrawal]), + withdrawals: Opt.none(seq[Withdrawal]), ) template fillCanonical(skel, z, stat) = diff --git a/tests/test_beacon/test_6_abort_filling.nim b/tests/test_beacon/test_6_abort_filling.nim index 7402c9d49..359cede38 100644 --- a/tests/test_beacon/test_6_abort_filling.nim +++ b/tests/test_beacon/test_6_abort_filling.nim @@ -1,5 +1,5 @@ # Nimbus -# Copyright (c) 2023 Status Research & Development GmbH +# Copyright (c) 2023-2024 Status Research & Development GmbH # Licensed and distributed under either of # * MIT license (license terms in the root directory or at # https://opensource.org/licenses/MIT). @@ -18,7 +18,7 @@ import ../../nimbus/sync/beacon/skeleton_db proc ccm(cc: NetworkParams) = - cc.config.terminalTotalDifficulty = some(262000.u256) + cc.config.terminalTotalDifficulty = Opt.some(262000.u256) cc.genesis.extraData = hexToSeqByte("0x000000000000000000") cc.genesis.difficulty = 1.u256 diff --git a/tests/test_beacon/test_7_abort_and_backstep.nim b/tests/test_beacon/test_7_abort_and_backstep.nim index 92b4062b2..df6d66c9e 100644 --- a/tests/test_beacon/test_7_abort_and_backstep.nim +++ b/tests/test_beacon/test_7_abort_and_backstep.nim @@ -1,5 +1,5 @@ # Nimbus -# Copyright (c) 2023 Status Research & Development GmbH +# Copyright (c) 2023-2024 Status Research & Development GmbH # Licensed and distributed under either of # * MIT license (license terms in the root directory or at # https://opensource.org/licenses/MIT). @@ -17,7 +17,7 @@ import ../../nimbus/sync/beacon/skeleton_db proc ccm(cc: NetworkParams) = - cc.config.terminalTotalDifficulty = some(262000.u256) + cc.config.terminalTotalDifficulty = Opt.some(262000.u256) cc.genesis.extraData = hexToSeqByte("0x000000000000000000") cc.genesis.difficulty = 1.u256 diff --git a/tests/test_beacon/test_8_pos_too_early.nim b/tests/test_beacon/test_8_pos_too_early.nim index 44eda5cd1..3e7d70031 100644 --- a/tests/test_beacon/test_8_pos_too_early.nim +++ b/tests/test_beacon/test_8_pos_too_early.nim @@ -1,5 +1,5 @@ # Nimbus -# Copyright (c) 2023 Status Research & Development GmbH +# Copyright (c) 2023-2024 Status Research & Development GmbH # Licensed and distributed under either of # * MIT license (license terms in the root directory or at # https://opensource.org/licenses/MIT). @@ -17,7 +17,7 @@ import ../../nimbus/sync/beacon/skeleton_db proc ccm(cc: NetworkParams) = - cc.config.terminalTotalDifficulty = some(262000.u256) + cc.config.terminalTotalDifficulty = Opt.some(262000.u256) cc.genesis.extraData = hexToSeqByte("0x000000000000000000") cc.genesis.difficulty = 1.u256 diff --git a/tests/test_beacon/test_skeleton.nim b/tests/test_beacon/test_skeleton.nim index 16c557026..b5cfb8a69 100644 --- a/tests/test_beacon/test_skeleton.nim +++ b/tests/test_beacon/test_skeleton.nim @@ -1,5 +1,5 @@ # Nimbus -# Copyright (c) 2023 Status Research & Development GmbH +# Copyright (c) 2023-2024 Status Research & Development GmbH # Licensed and distributed under either of # * MIT license (license terms in the root directory or at # https://opensource.org/licenses/MIT). @@ -22,28 +22,28 @@ import ./setup_env proc noTtdAndNoTtdPassed(cc: NetworkParams) = - cc.config.terminalTotalDifficultyPassed = none(bool) - cc.config.terminalTotalDifficulty = none(UInt256) + cc.config.terminalTotalDifficultyPassed = Opt.none(bool) + cc.config.terminalTotalDifficulty = Opt.none(UInt256) cc.genesis.difficulty = 1.u256 proc ttdPassedNoTtd(cc: NetworkParams) = - cc.config.terminalTotalDifficultyPassed = some(true) - cc.config.terminalTotalDifficulty = none(UInt256) + cc.config.terminalTotalDifficultyPassed = Opt.some(true) + cc.config.terminalTotalDifficulty = Opt.none(UInt256) cc.genesis.difficulty = 1.u256 proc ttdNoTtdPassed(cc: NetworkParams) = - cc.config.terminalTotalDifficultyPassed = none(bool) - cc.config.terminalTotalDifficulty = some(0.u256) + cc.config.terminalTotalDifficultyPassed = Opt.none(bool) + cc.config.terminalTotalDifficulty = Opt.some(0.u256) cc.genesis.difficulty = 1.u256 proc ttdAndTtdPassed(cc: NetworkParams) = - cc.config.terminalTotalDifficultyPassed = some(true) - cc.config.terminalTotalDifficulty = some(0.u256) + cc.config.terminalTotalDifficultyPassed = Opt.some(true) + cc.config.terminalTotalDifficulty = Opt.some(0.u256) cc.genesis.difficulty = 1.u256 proc ttdPassedFalseNoTtd(cc: NetworkParams) = - cc.config.terminalTotalDifficultyPassed = some(false) - cc.config.terminalTotalDifficulty = none(UInt256) + cc.config.terminalTotalDifficultyPassed = Opt.some(false) + cc.config.terminalTotalDifficulty = Opt.none(UInt256) cc.genesis.difficulty = 1.u256 proc skeletonMain*() = diff --git a/tests/test_config.nim b/tests/test_config.nim index 1051d4ff5..2bfa46f79 100644 --- a/tests/test_config.nim +++ b/tests/test_config.nim @@ -1,5 +1,5 @@ # Nimbus -# Copyright (c) 2019-2023 Status Research & Development GmbH +# Copyright (c) 2019-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) @@ -9,7 +9,8 @@ # according to those terms. import - std/[parseopt, strutils, options] + std/[parseopt, strutils], + results type ConfigStatus* = enum @@ -24,7 +25,7 @@ type Configuration = ref object testSubject*: string fork*: string - index*: Option[int] + index*: Opt[int] trace*: bool legacy*: bool pruning*: bool @@ -55,7 +56,7 @@ proc processArguments*(msg: var string): ConfigStatus = of cmdLongOption, cmdShortOption: case key.toLowerAscii() of "fork": config.fork = value - of "index": config.index = some(parseInt(value)) + of "index": config.index = Opt.some(parseInt(value)) of "trace": config.trace = parseBool(value) of "legacy": config.legacy = parseBool(value) of "pruning": config.pruning = parseBool(value) diff --git a/tests/test_coredb/test_chainsync.nim b/tests/test_coredb/test_chainsync.nim index 014c80dff..43b95a660 100644 --- a/tests/test_coredb/test_chainsync.nim +++ b/tests/test_coredb/test_chainsync.nim @@ -155,10 +155,10 @@ proc test_chainSync*( ): bool = ## Store persistent blocks from dump into chain DB let - sayBlocks = 900 + sayBlocks = 900'u64 chain = com.newChain blockOnDb = com.db.getSavedStateBlockNumber() - lastBlock = max(1, numBlocks).toBlockNumber + lastBlock = max(1, numBlocks).BlockNumber noisy.initLogging com defer: com.finishLogging() @@ -178,7 +178,7 @@ proc test_chainSync*( 0u64 elif blockOnDb < lastBlock: noisy.say "***", "resuming at #", blockOnDb+1 - blockOnDb.truncate(uint64) + 1 + blockOnDb + 1 else: noisy.say "***", "stop: sample exhausted" return true @@ -213,15 +213,15 @@ proc test_chainSync*( sample = done for w in files.undumpBlocks(least = start): - let (fromBlock, toBlock) = (w[0].header.blockNumber, w[^1].header.blockNumber) - if fromBlock == 0.u256: - xCheck w[0].header == com.db.getBlockHeader(0.u256) + let (fromBlock, toBlock) = (w[0].header.number, w[^1].header.number) + if fromBlock == 0'u64: + xCheck w[0].header == com.db.getBlockHeader(0'u64) continue # Process groups of blocks ... if toBlock < lastBlock: # Message if `[fromBlock,toBlock]` contains a multiple of `sayBlocks` - if fromBlock + (toBlock mod sayBlocks.u256) <= toBlock: + if fromBlock + (toBlock mod sayBlocks) <= toBlock: if oldLogAlign: noisy.whisper "***", &"processing ...[#{fromBlock},#{toBlock}]...\n" @@ -230,7 +230,7 @@ proc test_chainSync*( noisy.whisper "***", &"processing ...[#{fromBlock:>8},#{toBlock:>8}]..." if enaLogging: - noisy.startLogging(w[0].header.blockNumber) + noisy.startLogging(w[0].header.number) noisy.stopLoggingAfter(): let runPersistBlocksRc = chain.persistBlocks(w) @@ -251,9 +251,9 @@ proc test_chainSync*( # So It might be necessary to Split off all blocks smaller than `lastBlock` # and execute them first. Then the next batch starts with the `lastBlock`. let - pivot = (lastBlock - fromBlock).truncate(uint) + pivot = lastBlock - fromBlock blocks9 = w[pivot .. ^1] - doAssert lastBlock == blocks9[0].header.blockNumber + doAssert lastBlock == blocks9[0].header.number # Process leading batch before `lastBlock` (if any) var dotsOrSpace = "..." @@ -270,7 +270,7 @@ proc test_chainSync*( xCheck runPersistBlocks1Rc.isOk() dotsOrSpace = " " - noisy.startLogging(blocks9[0].header.blockNumber) + noisy.startLogging(blocks9[0].header.number) if lastOneExtra: let blocks0 = blocks9[0..0] diff --git a/tests/test_difficulty.nim b/tests/test_difficulty.nim index ad7793b1e..5dfdd4a7f 100644 --- a/tests/test_difficulty.nim +++ b/tests/test_difficulty.nim @@ -23,7 +23,7 @@ type parentDifficulty: Uint256 parentUncles: Hash256 currentTimestamp: int64 - currentBlockNumber: Uint256 + currentBlockNumber: uint64 currentDifficulty: Uint256 Tests = Table[string, Tester] @@ -63,7 +63,7 @@ proc parseTests(testData: JSonNode): Tests = else: t.parentUncles = parseHash(pu.getStr) t.currentTimestamp = hexOrInt64(data, "currentTimestamp", hex) - t.currentBlockNumber = hexOrInt256(data, "currentBlockNumber", hex) + t.currentBlockNumber = uint64 hexOrInt64(data, "currentBlockNumber", hex) t.currentDifficulty = hexOrInt256(data, "currentDifficulty", hex) result[title] = t @@ -95,7 +95,7 @@ proc testFixture(fixtures: JsonNode, testStatusIMPL: var TestStatus) = let p = BlockHeader( difficulty : t.parentDifficulty, timestamp : EthTime(t.parentTimestamp), - blockNumber: t.currentBlockNumber - 1, + number : t.currentBlockNumber - 1, ommersHash : t.parentUncles ) diff --git a/tests/test_eip4844.nim b/tests/test_eip4844.nim index d1c4b5849..be46fb46b 100644 --- a/tests/test_eip4844.nim +++ b/tests/test_eip4844.nim @@ -27,7 +27,7 @@ proc tx0(i: int): Transaction = Transaction( txType: TxLegacy, nonce: i.AccountNonce, - to: recipient.some, + to: Opt.some recipient, gasLimit: 1.GasInt, gasPrice: 2.GasInt, payload: abcdef) @@ -47,7 +47,7 @@ proc tx2(i: int): Transaction = txType: TxEip2930, chainId: 1.ChainId, nonce: i.AccountNonce, - to: recipient.some, + to: Opt.some recipient, gasLimit: 123457.GasInt, gasPrice: 10.GasInt, accessList: accesses, @@ -59,7 +59,7 @@ proc tx3(i: int): Transaction = txType: TxEip2930, chainId: 1.ChainId, nonce: i.AccountNonce, - to: recipient.some, + to: Opt.some recipient, gasLimit: 123457.GasInt, gasPrice: 10.GasInt, payload: abcdef) @@ -80,8 +80,8 @@ proc tx5(i: int): Transaction = chainId: 1.ChainId, nonce: i.AccountNonce, gasLimit: 123457.GasInt, - maxPriorityFee: 42.GasInt, - maxFee: 10.GasInt, + maxPriorityFeePerGas: 42.GasInt, + maxFeePerGas: 10.GasInt, accessList: accesses) proc tx6(i: int): Transaction = @@ -93,8 +93,8 @@ proc tx6(i: int): Transaction = chainId: 1.ChainId, nonce: i.AccountNonce, gasLimit: 123457.GasInt, - maxPriorityFee: 42.GasInt, - maxFee: 10.GasInt, + maxPriorityFeePerGas:42.GasInt, + maxFeePerGas: 10.GasInt, accessList: accesses, versionedHashes: @[digest] ) @@ -108,8 +108,8 @@ proc tx7(i: int): Transaction = chainID: 1.ChainId, nonce: i.AccountNonce, gasLimit: 123457.GasInt, - maxPriorityFee: 42.GasInt, - maxFee: 10.GasInt, + maxPriorityFeePerGas:42.GasInt, + maxFeePerGas: 10.GasInt, accessList: accesses, versionedHashes: @[digest], maxFeePerBlobGas: 10000000.u256, @@ -123,10 +123,10 @@ proc tx8(i: int): Transaction = txType: TxEip4844, chainID: 1.ChainId, nonce: i.AccountNonce, - to: some(recipient), + to: Opt.some recipient, gasLimit: 123457.GasInt, - maxPriorityFee: 42.GasInt, - maxFee: 10.GasInt, + maxPriorityFeePerGas:42.GasInt, + maxFeePerGas: 10.GasInt, accessList: accesses, versionedHashes: @[digest], maxFeePerBlobGas: 10000000.u256, diff --git a/tests/test_forkid.nim b/tests/test_forkid.nim index 22e3228b8..5b0ae4017 100644 --- a/tests/test_forkid.nim +++ b/tests/test_forkid.nim @@ -82,24 +82,24 @@ template runTest(network: untyped, name: string) = func config(shanghai, cancun: uint64): ChainConfig = ChainConfig( chainID: ChainId(1337), - homesteadBlock: some(0.u256), - dAOForkBlock: none(BlockNumber), + homesteadBlock: Opt.some(0'u64), + dAOForkBlock: Opt.none(BlockNumber), dAOForkSupport: true, - eIP150Block: some(0.u256), - eIP155Block: some(0.u256), - eIP158Block: some(0.u256), - byzantiumBlock: some(0.u256), - constantinopleBlock: some(0.u256), - petersburgBlock: some(0.u256), - istanbulBlock: some(0.u256), - muirGlacierBlock: some(0.u256), - berlinBlock: some(0.u256), - londonBlock: some(0.u256), - terminalTotalDifficulty: some(0.u256), - terminalTotalDifficultyPassed: some(true), - mergeForkBlock: some(0.u256), - shanghaiTime: some(shanghai.EthTime), - cancunTime: some(cancun.EthTime), + eIP150Block: Opt.some(0'u64), + eIP155Block: Opt.some(0'u64), + eIP158Block: Opt.some(0'u64), + byzantiumBlock: Opt.some(0'u64), + constantinopleBlock: Opt.some(0'u64), + petersburgBlock: Opt.some(0'u64), + istanbulBlock: Opt.some(0'u64), + muirGlacierBlock: Opt.some(0'u64), + berlinBlock: Opt.some(0'u64), + londonBlock: Opt.some(0'u64), + terminalTotalDifficulty: Opt.some(0.u256), + terminalTotalDifficultyPassed: Opt.some(true), + mergeForkBlock: Opt.some(0'u64), + shanghaiTime: Opt.some(shanghai.EthTime), + cancunTime: Opt.some(cancun.EthTime), ) func calcID(conf: ChainConfig, crc: uint32, time: uint64): ForkID = diff --git a/tests/test_generalstate_json.nim b/tests/test_generalstate_json.nim index abbefd4c1..b98d7670e 100644 --- a/tests/test_generalstate_json.nim +++ b/tests/test_generalstate_json.nim @@ -6,7 +6,7 @@ # at your option. This file may not be copied, modified, or distributed except according to those terms. import - std/[strutils, tables, json, os, sets, options], + std/[strutils, tables, json, os, sets], ./test_helpers, ./test_allowed_to_fail, ../nimbus/core/executor, test_config, ../nimbus/transaction, diff --git a/tests/test_genesis.nim b/tests/test_genesis.nim index 285597745..612309a39 100644 --- a/tests/test_genesis.nim +++ b/tests/test_genesis.nim @@ -101,7 +101,7 @@ proc customGenesisTest() = check com.ttd.get == ttd check com.consensus == ConsensusType.POW check cg.config.mergeNetsplitBlock.isSome - check cg.config.mergeNetsplitBlock.get == 14660963.toBlockNumber + check cg.config.mergeNetsplitBlock.get == 14660963.BlockNumber check cg.config.mergeNetsplitBlock == cg.config.mergeForkBlock test "Holesky": diff --git a/tests/test_graphql.nim b/tests/test_graphql.nim index 3081f2d33..f1a847ce5 100644 --- a/tests/test_graphql.nim +++ b/tests/test_graphql.nim @@ -35,12 +35,12 @@ proc toBlock(n: JsonNode, key: string): EthBlock = proc setupChain(): CommonRef = let config = ChainConfig( chainId : MainNet.ChainId, - byzantiumBlock : some(0.toBlockNumber), - constantinopleBlock : some(0.toBlockNumber), - petersburgBlock : some(0.toBlockNumber), - istanbulBlock : some(0.toBlockNumber), - muirGlacierBlock : some(0.toBlockNumber), - berlinBlock : some(10.toBlockNumber) + byzantiumBlock : some(0.BlockNumber), + constantinopleBlock : some(0.BlockNumber), + petersburgBlock : some(0.BlockNumber), + istanbulBlock : some(0.BlockNumber), + muirGlacierBlock : some(0.BlockNumber), + berlinBlock : some(10.BlockNumber) ) var jn = json.parseFile(dataFolder & "/oneUncle.json") @@ -55,7 +55,7 @@ proc setupChain(): CommonRef = extraData : gen.header.extraData, gasLimit : gen.header.gasLimit, difficulty: gen.header.difficulty, - mixHash : gen.header.mixDigest, + mixHash : gen.header.mixHash, coinBase : gen.header.coinbase, timestamp : gen.header.timestamp, baseFeePerGas: gen.header.fee diff --git a/tests/test_overflow.nim b/tests/test_overflow.nim index 1fa3ff979..1709a8737 100644 --- a/tests/test_overflow.nim +++ b/tests/test_overflow.nim @@ -39,7 +39,7 @@ proc overflowMain*() = test "GasCall unhandled overflow": let header = BlockHeader( stateRoot: emptyRlpHash, - blockNumber: u256(1150000), + number: 1150000'u64, coinBase: coinbase, gasLimit: 30000000, timeStamp: EthTime(123456), @@ -59,7 +59,7 @@ proc overflowMain*() = chainId: MainNet.ChainId, gasPrice: 0.GasInt, gasLimit: 30000000, - to: codeAddress.some, + to: Opt.some codeAddress, value: 0.u256, payload: @data ) diff --git a/tests/test_pow.nim b/tests/test_pow.nim index e9538c026..088026dd9 100644 --- a/tests/test_pow.nim +++ b/tests/test_pow.nim @@ -62,11 +62,11 @@ proc runPowTests(noisy = true; file = specsDump; test "Loading from capture": for (lno,line) in gunzipLines(filePath): let specs = line.undumpPowSpecs - if 0 < specs.blockNumber: + if 0 < specs.number: specsList.add specs check line == specs.dumpPowSpecs noisy.say "***", " block range #", - specsList[0].blockNumber, " .. #", specsList[^1].blockNumber + specsList[0].number, " .. #", specsList[^1].number # Adjust number of tests let @@ -80,7 +80,7 @@ proc runPowTests(noisy = true; file = specsDump; else: noisy.showElapsed(&"first getPowDigest() instance"): let p = specsList[startVerify] - check pow.getPowDigest(p).mixDigest == p.mixDigest + check pow.getPowDigest(p).mixDigest == p.mixHash test &"Running getPowDigest() on {nDoVerify} specs records": if nVerify <= 0: @@ -89,7 +89,7 @@ proc runPowTests(noisy = true; file = specsDump; noisy.showElapsed(&"all {nDoVerify} getPowDigest() instances"): for n in startVerify ..< specsList.len: let p = specsList[n] - check pow.getPowDigest(p).mixDigest == p.mixDigest + check pow.getPowDigest(p).mixDigest == p.mixHash # ------------------------------------------------------------------------------ # Main function(s) diff --git a/tests/test_precompiles.nim b/tests/test_precompiles.nim index 8a735f1eb..882916dc5 100644 --- a/tests/test_precompiles.nim +++ b/tests/test_precompiles.nim @@ -29,14 +29,17 @@ template doTest(fixture: JsonNode; vmState: BaseVMState; fork: EVMFork, address: expectedErr = test.hasKey("ExpectedError") expected = if test.hasKey("Expected"): hexToSeqByte(test["Expected"].getStr) else: @[] dataStr = test["Input"].getStr - gasExpected = if test.hasKey("Gas"): test["Gas"].getInt else: -1 + gasExpected = if test.hasKey("Gas"): + Opt.some(GasInt test["Gas"].getInt) + else: + Opt.none(GasInt) let unsignedTx = Transaction( txType: TxLegacy, nonce: 0, gasPrice: 1.GasInt, gasLimit: 1_000_000_000.GasInt, - to: initAddress(address.byte).some, + to: Opt.some initAddress(address.byte), value: 0.u256, payload: if dataStr.len > 0: dataStr.hexToSeqByte else: @[] ) @@ -51,10 +54,10 @@ template doTest(fixture: JsonNode; vmState: BaseVMState; fork: EVMFork, address: if not c: echo "Output : " & fixtureResult.output.toHex & "\nExpected: " & expected.toHex check c - if gasExpected >= 0: - if fixtureResult.gasUsed != gasExpected: - debugEcho "GAS: ", fixtureResult.gasUsed, " ", gasExpected - check fixtureResult.gasUsed == gasExpected + if gasExpected.isSome: + if fixtureResult.gasUsed != gasExpected.get: + debugEcho "GAS: ", fixtureResult.gasUsed, " ", gasExpected.get + check fixtureResult.gasUsed == gasExpected.get proc parseFork(x: string): EVMFork = let x = x.toLowerAscii @@ -71,7 +74,7 @@ proc testFixture(fixtures: JsonNode, testStatusIMPL: var TestStatus) = privateKey = PrivateKey.fromHex("7a28b5ba57c53603b0b07b56bba752f7784bf506fa95edc395f5cf6c7514fe9d")[] com = CommonRef.new(newCoreDbRef DefaultDbMemory, config = ChainConfig()) vmState = BaseVMState.new( - BlockHeader(blockNumber: 1.u256, stateRoot: emptyRlpHash), + BlockHeader(number: 1'u64, stateRoot: emptyRlpHash), BlockHeader(), com ) diff --git a/tests/test_rpc.nim b/tests/test_rpc.nim index 12cdfd98c..37c28e033 100644 --- a/tests/test_rpc.nim +++ b/tests/test_rpc.nim @@ -87,14 +87,14 @@ proc persistFixtureBlock(chainDB: CoreDbRef) = # Manually inserting header to avoid any parent checks chainDB.kvt.put(genericHashKey(header.blockHash).toOpenArray, rlp.encode(header)) chainDB.addBlockNumberToHashLookup(header) - chainDB.persistTransactions(header.blockNumber, getBlockBody4514995().transactions) + chainDB.persistTransactions(header.number, getBlockBody4514995().transactions) chainDB.persistReceipts(getReceipts4514995()) proc setupEnv(com: CommonRef, signer, ks2: EthAddress, ctx: EthContext): TestEnv = var parent = com.db.getCanonicalHead() acc = ctx.am.getAccount(signer).tryGet() - blockNumber = 1.toBlockNumber + blockNumber = 1.BlockNumber parentHash = parent.blockHash const code = evmByteCode: @@ -180,7 +180,7 @@ proc setupEnv(com: CommonRef, signer, ks2: EthAddress, ctx: EthContext): TestEnv #coinbase*: EthAddress stateRoot : vmState.stateDB.rootHash, txRoot : txRoot, - receiptRoot : receiptRoot, + receiptsRoot : receiptsRoot, bloom : createBloom(vmState.receipts), difficulty : difficulty, blockNumber : blockNumber, @@ -188,7 +188,7 @@ proc setupEnv(com: CommonRef, signer, ks2: EthAddress, ctx: EthContext): TestEnv gasUsed : vmState.cumulativeGasUsed, timestamp : timeStamp #extraData: Blob - #mixDigest: Hash256 + #mixHash: Hash256 #nonce: BlockNonce ) @@ -346,7 +346,7 @@ proc rpcMain*() = check res == w3Qty(0'u64) test "eth_getBlockTransactionCountByHash": - let hash = com.db.getBlockHash(0.toBlockNumber) + let hash = com.db.getBlockHash(0.BlockNumber) let res = await client.eth_getBlockTransactionCountByHash(w3Hash hash) check res == w3Qty(0'u64) @@ -355,7 +355,7 @@ proc rpcMain*() = check res == w3Qty(0'u64) test "eth_getUncleCountByBlockHash": - let hash = com.db.getBlockHash(0.toBlockNumber) + let hash = com.db.getBlockHash(0.BlockNumber) let res = await client.eth_getUncleCountByBlockHash(w3Hash hash) check res == w3Qty(0'u64) @@ -444,14 +444,14 @@ proc rpcMain*() = test "eth_getTransactionByHash": let res = await client.eth_getTransactionByHash(w3Hash env.txHash) check res.isNil.not - check res.blockNumber.get() == w3BlockNumber(1'u64) + check res.number.get() == w3BlockNumber(1'u64) let res2 = await client.eth_getTransactionByHash(w3Hash env.blockHash) check res2.isNil test "eth_getTransactionByBlockHashAndIndex": let res = await client.eth_getTransactionByBlockHashAndIndex(w3Hash env.blockHash, w3Qty(0'u64)) check res.isNil.not - check res.blockNumber.get() == w3BlockNumber(1'u64) + check res.number.get() == w3BlockNumber(1'u64) let res2 = await client.eth_getTransactionByBlockHashAndIndex(w3Hash env.blockHash, w3Qty(3'u64)) check res2.isNil @@ -462,7 +462,7 @@ proc rpcMain*() = test "eth_getTransactionByBlockNumberAndIndex": let res = await client.eth_getTransactionByBlockNumberAndIndex("latest", w3Qty(1'u64)) check res.isNil.not - check res.blockNumber.get() == w3BlockNumber(1'u64) + check res.number.get() == w3BlockNumber(1'u64) let res2 = await client.eth_getTransactionByBlockNumberAndIndex("latest", w3Qty(3'u64)) check res2.isNil @@ -470,7 +470,7 @@ proc rpcMain*() = test "eth_getTransactionReceipt": let res = await client.eth_getTransactionReceipt(w3Hash env.txHash) check res.isNil.not - check res.blockNumber == w3BlockNumber(1'u64) + check res.number == w3BlockNumber(1'u64) let res2 = await client.eth_getTransactionReceipt(w3Hash env.blockHash) check res2.isNil @@ -517,8 +517,8 @@ proc rpcMain*() = test "eth_getLogs by blockNumber, no filters": let testHeader = getBlockHeader4514995() let testHash = testHeader.blockHash - let fBlock = blockId(testHeader.blockNumber.truncate(uint64)) - let tBlock = blockId(testHeader.blockNumber.truncate(uint64)) + let fBlock = blockId(testHeader.number) + let tBlock = blockId(testHeader.number) let filterOptions = FilterOptions( fromBlock: some(fBlock), toBlock: some(tBlock) diff --git a/tests/test_tracer_json.nim b/tests/test_tracer_json.nim index e41d0943b..22a2a75ac 100644 --- a/tests/test_tracer_json.nim +++ b/tests/test_tracer_json.nim @@ -10,9 +10,9 @@ import std/[json, os, sets, tables, strutils], + stew/byteutils, chronicles, unittest2, - stew/byteutils, results, ./test_helpers, ../nimbus/sync/protocol/snap/snap_types, @@ -51,10 +51,10 @@ proc preLoadAristoDb(cdb: CoreDbRef; jKvp: JsonNode; num: BlockNumber) = try: # Pull our particular header fields (if possible) let header = rlp.decode(val, BlockHeader) - if header.blockNumber == num: + if header.number == num: txRoot = header.txRoot - rcptRoot = header.receiptRoot - elif header.blockNumber == num-1: + rcptRoot = header.receiptsRoot + elif header.number == num-1: predRoot = header.stateRoot except RlpError: discard @@ -80,13 +80,14 @@ proc testFixtureImpl(node: JsonNode, testStatusIMPL: var TestStatus, memoryDB: C setErrorLevel() var - blockNumber = UInt256.fromHex(node["blockNumber"].getStr()) + blockNumberHex = node["blockNumber"].getStr() + blockNumber = parseHexInt(blockNumberHex).uint64 com = CommonRef.new(memoryDB, chainConfigForNetwork(MainNet)) state = node["state"] receipts = node["receipts"] # disable POS/post Merge feature - com.setTTD none(DifficultyInt) + com.setTTD Opt.none(DifficultyInt) # Import raw data into database # Some hack for `Aristo` using the `snap` protocol proof-loader diff --git a/tests/test_txpool.nim b/tests/test_txpool.nim index d34cc6249..f06a3975f 100644 --- a/tests/test_txpool.nim +++ b/tests/test_txpool.nim @@ -185,7 +185,7 @@ proc runTxLoader(noisy = true; capture = loadSpecs) = "Latest item: <", xp.txDB.byItemID.last.value.data.info, ">" # make sure that the block chain was initialised - check capture.numBlocks.u256 <= bcCom.db.getCanonicalHead.blockNumber + check capture.numBlocks.u256 <= bcCom.db.getCanonicalHead.number check xp.nItems.total == foldl(@[0]&statCount.toSeq, a+b) # ^^^ sum up statCount[] values @@ -714,7 +714,7 @@ proc runTxPackerTests(noisy = true) = # at least `nTrgTxs` txs and `nTrgAccounts` known accounts let (backHeader,backTxs,accLst) = xq.getBackHeader(nTrgTxs,nTrgAccounts) - nBackBlocks = xq.head.blockNumber - backHeader.blockNumber + nBackBlocks = xq.head.number - backHeader.number stats = xq.nItems # verify that the test would not degenerate diff --git a/tests/test_txpool/helpers.nim b/tests/test_txpool/helpers.nim index c9c6f28d4..60ea8cf8a 100644 --- a/tests/test_txpool/helpers.nim +++ b/tests/test_txpool/helpers.nim @@ -104,7 +104,7 @@ proc toXX(a: EthAddress): string = proc toXX(h: Hash256): string = h.data.mapIt(it.toHex2).joinXX -proc toXX(v: int64; r,s: UInt256): string = +proc toXX(v: uint64; r,s: UInt256): string = v.toXX & ":" & ($r).joinXX & ":" & ($s).joinXX # ------------------------------------------------------------------------------ @@ -127,10 +127,10 @@ proc pp*(tx: Transaction): string = result &= ",nonce=" & tx.nonce.toXX if tx.gasPrice != 0: result &= ",gasPrice=" & tx.gasPrice.toKMG - if tx.maxPriorityFee != 0: - result &= ",maxPrioFee=" & tx.maxPriorityFee.toKMG - if tx.maxFee != 0: - result &= ",maxFee=" & tx.maxFee.toKMG + if tx.maxPriorityFeePerGas != 0: + result &= ",maxPrioFee=" & tx.maxPriorityFeePerGas.toKMG + if tx.maxFeePerGas != 0: + result &= ",maxFee=" & tx.maxFeePerGas.toKMG if tx.gasLimit != 0: result &= ",gasLimit=" & tx.gasLimit.toKMG if tx.to.isSome: diff --git a/tests/test_txpool2.nim b/tests/test_txpool2.nim index 8690cd959..a3c88a7ce 100644 --- a/tests/test_txpool2.nim +++ b/tests/test_txpool2.nim @@ -70,7 +70,7 @@ func makeTx( nonce : AccountNonce(t.nonce), gasPrice: gasPrice, gasLimit: gasLimit, - to : some(recipient), + to : Opt.some(recipient), value : amount, payload : @payload ) @@ -95,13 +95,13 @@ proc initEnv(envFork: HardFork): TestEnv = ) if envFork >= MergeFork: - conf.networkParams.config.terminalTotalDifficulty = some(100.u256) + conf.networkParams.config.terminalTotalDifficulty = Opt.some(100.u256) if envFork >= Shanghai: - conf.networkParams.config.shanghaiTime = some(0.EthTime) + conf.networkParams.config.shanghaiTime = Opt.some(0.EthTime) if envFork >= Cancun: - conf.networkParams.config.cancunTime = some(0.EthTime) + conf.networkParams.config.cancunTime = Opt.some(0.EthTime) let com = CommonRef.new( @@ -230,7 +230,7 @@ proc runTxPoolBlobhashTest() = body = BlockBody( transactions: blk.txs, uncles: blk.uncles, - withdrawals: some[seq[Withdrawal]](@[]) + withdrawals: Opt.some(newSeq[Withdrawal]()) ) check blk.txs.len == 2 @@ -330,7 +330,7 @@ proc runTxHeadDelta(noisy = true) = setErrorLevel() # in case we set trace level - check com.syncCurrent == 10.toBlockNumber + check com.syncCurrent == 10.BlockNumber head = com.db.getBlockHeader(com.syncCurrent) let sdb = LedgerRef.init(com.db, head.stateRoot) diff --git a/tests/tracerTestGen.nim b/tests/tracerTestGen.nim index 3967a7505..799ef6eb2 100644 --- a/tests/tracerTestGen.nim +++ b/tests/tracerTestGen.nim @@ -9,17 +9,14 @@ # according to those terms. import - json, + std/[json, strutils], results, ../nimbus/common/common, # must be early (compilation annoyance) ../nimbus/db/opts, ../nimbus/db/core_db/persistent, ../nimbus/[config, tracer, vm_types] -proc dumpTest(com: CommonRef, blockNumber: int) = - let - blockNumber = blockNumber.u256 - +proc dumpTest(com: CommonRef, blockNumber: BlockNumber) = var capture = com.db.newCapture.value captureCom = com.clone(capture.recorder) diff --git a/tools/common/helpers.nim b/tools/common/helpers.nim index 761f62f8d..7b7455762 100644 --- a/tools/common/helpers.nim +++ b/tools/common/helpers.nim @@ -16,49 +16,54 @@ export types const - BlockNumberZero: BlockNumber = 0.toBlockNumber - BlockNumberFive: BlockNumber = 5.toBlockNumber + BlockNumberZero = 0.BlockNumber + BlockNumberFive = 5.BlockNumber TimeZero = EthTime(0) -proc createForkTransitionTable(transitionFork: HardFork, b: Option[BlockNumber], t: Option[EthTime], ttd: Option[DifficultyInt]): ForkTransitionTable = +proc createForkTransitionTable(transitionFork: HardFork, + b: Opt[BlockNumber], + t: Opt[EthTime], + ttd: Opt[DifficultyInt]): ForkTransitionTable = - proc blockNumberToUse(f: HardFork): Option[BlockNumber] = + proc blockNumberToUse(f: HardFork): Opt[BlockNumber] = if f < transitionFork: - some(BlockNumberZero) + Opt.some(BlockNumberZero) elif f == transitionFork: b else: - none(BlockNumber) + Opt.none(BlockNumber) - proc timeToUse(f: HardFork): Option[EthTime] = + proc timeToUse(f: HardFork): Opt[EthTime] = if f < transitionFork: - some(TimeZero) + Opt.some(TimeZero) elif f == transitionFork: t else: - none(EthTime) + Opt.none(EthTime) for f in low(HardFork) .. lastPurelyBlockNumberBasedFork: result.blockNumberThresholds[f] = blockNumberToUse(f) - result.mergeForkTransitionThreshold.blockNumber = blockNumberToUse(HardFork.MergeFork) + result.mergeForkTransitionThreshold.number = blockNumberToUse(HardFork.MergeFork) result.mergeForkTransitionThreshold.ttd = ttd for f in firstTimeBasedFork .. high(HardFork): result.timeThresholds[f] = timeToUse(f) proc assignNumber(c: ChainConfig, transitionFork: HardFork, n: BlockNumber) = - let table = createForkTransitionTable(transitionFork, some(n), none(EthTime), none(DifficultyInt)) + let table = createForkTransitionTable(transitionFork, + Opt.some(n), Opt.none(EthTime), Opt.none(DifficultyInt)) c.populateFromForkTransitionTable(table) proc assignTime(c: ChainConfig, transitionFork: HardFork, t: EthTime) = - let table = createForkTransitionTable(transitionFork, none(BlockNumber), some(t), none(DifficultyInt)) + let table = createForkTransitionTable(transitionFork, + Opt.none(BlockNumber), Opt.some(t), Opt.none(DifficultyInt)) c.populateFromForkTransitionTable(table) func getChainConfig*(network: string, c: ChainConfig) = c.daoForkSupport = false c.chainId = 1.ChainId - c.terminalTotalDifficulty = none(UInt256) + c.terminalTotalDifficulty = Opt.none(UInt256) case network of $TestFork.Frontier: @@ -90,7 +95,7 @@ func getChainConfig*(network: string, c: ChainConfig) = c.assignNumber(HardFork.Constantinople, BlockNumberFive) of $TestFork.ByzantiumToConstantinopleFixAt5: c.assignNumber(HardFork.Petersburg, BlockNumberFive) - c.constantinopleBlock = some(BlockNumberFive) + c.constantinopleBlock = Opt.some(BlockNumberFive) of $TestFork.ConstantinopleFixToIstanbulAt5: c.assignNumber(HardFork.Istanbul, BlockNumberFive) of $TestFork.Berlin: @@ -107,7 +112,7 @@ func getChainConfig*(network: string, c: ChainConfig) = c.assignNumber(HardFork.MergeFork, BlockNumberZero) of $TestFork.ArrowGlacierToParisAtDiffC0000: c.assignNumber(HardFork.GrayGlacier, BlockNumberZero) - c.terminalTotalDifficulty = some(0xC0000.u256) + c.terminalTotalDifficulty = Opt.some(0xC0000.u256) of $TestFork.Shanghai: c.assignTime(HardFork.Shanghai, TimeZero) of $TestFork.ParisToShanghaiAtTime15k: diff --git a/tools/evmstate/helpers.nim b/tools/evmstate/helpers.nim index 52dd10687..b892d7130 100644 --- a/tools/evmstate/helpers.nim +++ b/tools/evmstate/helpers.nim @@ -9,7 +9,7 @@ # according to those terms. import - std/[options, json, strutils], + std/[json, strutils], eth/[common, keys], eth/trie/trie_defs, stint, @@ -91,9 +91,9 @@ template omitZero(T: type, nField: string, index: int): auto = template optional(T: type, nField: string): auto = if n.hasKey(nField): - some(T.fromJson(n[nField])) + Opt.some(T.fromJson(n[nField])) else: - none(T) + Opt.none(T) proc txType(n: JsonNode): TxType = if "blobVersionedHashes" in n: @@ -108,14 +108,14 @@ proc parseHeader*(n: JsonNode): BlockHeader = BlockHeader( coinbase : required(EthAddress, "currentCoinbase"), difficulty : required(DifficultyInt, "currentDifficulty"), - blockNumber: required(BlockNumber, "currentNumber"), + number : required(BlockNumber, "currentNumber"), gasLimit : required(GasInt, "currentGasLimit"), timestamp : required(EthTime, "currentTimestamp"), stateRoot : emptyRlpHash, - mixDigest : omitZero(Hash256, "currentRandom"), - fee : optional(UInt256, "currentBaseFee"), + mixHash : omitZero(Hash256, "currentRandom"), + baseFeePerGas : optional(UInt256, "currentBaseFee"), withdrawalsRoot: optional(Hash256, "currentWithdrawalsRoot"), - excessBlobGas: optional(uint64, "currentExcessBlobGas"), + excessBlobGas : optional(uint64, "currentExcessBlobGas"), parentBeaconBlockRoot: optional(Hash256, "currentBeaconRoot"), ) @@ -135,16 +135,16 @@ proc parseTx*(n: JsonNode, dataIndex, gasIndex, valueIndex: int): Transaction = payload : required(Blob, "data", dataIndex), chainId : ChainId(1), gasPrice: omitZero(GasInt, "gasPrice"), - maxFee : omitZero(GasInt, "maxFeePerGas"), - accessList: omitZero(AccessList, "accessLists", dataIndex), - maxPriorityFee: omitZero(GasInt, "maxPriorityFeePerGas"), - maxFeePerBlobGas: omitZero(UInt256, "maxFeePerBlobGas"), - versionedHashes: omitZero(VersionedHashes, "blobVersionedHashes") + maxFeePerGas : omitZero(GasInt, "maxFeePerGas"), + accessList : omitZero(AccessList, "accessLists", dataIndex), + maxPriorityFeePerGas: omitZero(GasInt, "maxPriorityFeePerGas"), + maxFeePerBlobGas : omitZero(UInt256, "maxFeePerBlobGas"), + versionedHashes : omitZero(VersionedHashes, "blobVersionedHashes") ) let rawTo = n["to"].getStr if rawTo != "": - tx.to = some(hexToByteArray(rawTo, 20)) + tx.to = Opt.some(hexToByteArray(rawTo, 20)) let secretKey = required(PrivateKey, "secretKey") signTransaction(tx, secretKey, tx.chainId, false) diff --git a/tools/t8n/helpers.nim b/tools/t8n/helpers.nim index c971a5990..87adf8e08 100644 --- a/tools/t8n/helpers.nim +++ b/tools/t8n/helpers.nim @@ -113,7 +113,7 @@ template `gas=`(tx: var Transaction, x: GasInt) = template `input=`(tx: var Transaction, x: Blob) = tx.payload = x -template `v=`(tx: var Transaction, x: int64) = +template `v=`(tx: var Transaction, x: uint64) = tx.V = x template `r=`(tx: var Transaction, x: UInt256) = @@ -122,12 +122,6 @@ template `r=`(tx: var Transaction, x: UInt256) = template `s=`(tx: var Transaction, x: UInt256) = tx.S = x -template `maxPriorityFeePerGas=`(tx: var Transaction, x: GasInt) = - tx.maxPriorityFee = x - -template `maxFeePerGas=`(tx: var Transaction, x: GasInt) = - tx.maxFee = x - template `blobVersionedHashes=`(tx: var Transaction, x: VersionedHashes) = tx.versionedHashes = x @@ -145,7 +139,7 @@ template omitZero(o: untyped, T: type, oField: untyped) = template optional(o: untyped, T: type, oField: untyped) = const fName = astToStr(oField) if n.hasKey(fName) and n[fName].kind != JNull: - o.oField = some(T.fromJson(n, fName)) + o.oField = Opt.some(T.fromJson(n, fName)) proc parseAlloc*(ctx: var TransContext, n: JsonNode) = for accAddr, acc in n: @@ -200,14 +194,14 @@ proc parseEnv*(ctx: var TransContext, n: JsonNode) = var withdrawals: seq[Withdrawal] for v in w: withdrawals.add Withdrawal.fromJson(v) - ctx.env.withdrawals = some(withdrawals) + ctx.env.withdrawals = Opt.some(withdrawals) proc parseTx(n: JsonNode, chainId: ChainID): Transaction = var tx: Transaction if not n.hasKey("type"): tx.txType = TxLegacy else: - tx.txType = int64.fromJson(n, "type").TxType + tx.txType = uint64.fromJson(n, "type").TxType required(tx, AccountNonce, nonce) required(tx, GasInt, gas) @@ -215,7 +209,7 @@ proc parseTx(n: JsonNode, chainId: ChainID): Transaction = required(tx, Blob, input) if n.hasKey("to"): - tx.to = some(EthAddress.fromJson(n, "to")) + tx.to = Opt.some(EthAddress.fromJson(n, "to")) case tx.txType of TxLegacy: @@ -246,7 +240,7 @@ proc parseTx(n: JsonNode, chainId: ChainID): Transaction = let secretKey = PrivateKey.fromRaw(data).tryGet signTransaction(tx, secretKey, chainId, eip155) else: - required(tx, int64, v) + required(tx, uint64, v) required(tx, UInt256, r) required(tx, UInt256, s) tx @@ -420,7 +414,7 @@ proc `@@`[T](x: seq[T]): JsonNode = for c in x: result.add @@(c) -proc `@@`[T](x: Option[T]): JsonNode = +proc `@@`[T](x: Opt[T]): JsonNode = if x.isNone: newJNull() else: @@ -432,7 +426,7 @@ proc `@@`*(x: ExecutionResult): JsonNode = "txRoot" : @@(x.txRoot), "receiptsRoot": @@(x.receiptsRoot), "logsHash" : @@(x.logsHash), - "logsBloom" : @@(x.bloom), + "logsBloom" : @@(x.logsBloom), "receipts" : @@(x.receipts), "currentDifficulty": @@(x.currentDifficulty), "gasUsed" : @@(x.gasUsed) diff --git a/tools/t8n/transition.nim b/tools/t8n/transition.nim index 2a03773b3..52ff96e1e 100644 --- a/tools/t8n/transition.nim +++ b/tools/t8n/transition.nim @@ -83,24 +83,24 @@ proc dispatchOutput(ctx: var TransContext, conf: T8NConf, res: ExecOutput) = stderr.write(dis.stderr.pretty) stderr.write("\n") -proc calcWithdrawalsRoot(w: Option[seq[Withdrawal]]): Option[Hash256] = +proc calcWithdrawalsRoot(w: Opt[seq[Withdrawal]]): Opt[Hash256] = if w.isNone: - return none(Hash256) - calcWithdrawalsRoot(w.get).some() + return Opt.none(Hash256) + Opt.some calcWithdrawalsRoot(w.get) proc envToHeader(env: EnvStruct): BlockHeader = BlockHeader( coinbase : env.currentCoinbase, difficulty : env.currentDifficulty.get(0.u256), - mixDigest : env.currentRandom.get(Hash256()), - blockNumber: env.currentNumber, + mixHash : env.currentRandom.get(Hash256()), + number : env.currentNumber, gasLimit : env.currentGasLimit, timestamp : env.currentTimestamp, stateRoot : emptyRlpHash, - fee : env.currentBaseFee, + baseFeePerGas : env.currentBaseFee, withdrawalsRoot: env.withdrawals.calcWithdrawalsRoot(), - blobGasUsed: env.currentBlobGasUsed, - excessBlobGas: env.currentExcessBlobGas, + blobGasUsed : env.currentBlobGasUsed, + excessBlobGas : env.currentExcessBlobGas, ) proc postState(db: LedgerRef, alloc: var GenesisAlloc) = @@ -131,7 +131,7 @@ proc toTxReceipt(rec: Receipt, root: if rec.isHash: rec.hash else: Hash256(), status: rec.status, cumulativeGasUsed: rec.cumulativeGasUsed, - logsBloom: rec.bloom, + logsBloom: rec.logsBloom, logs: rec.logs, transactionHash: rlpHash(tx), contractAddress: contractAddress, @@ -292,25 +292,25 @@ proc exec(ctx: var TransContext, result.result = ExecutionResult( stateRoot : stateDB.rootHash, txRoot : includedTx.calcTxRoot, - receiptsRoot: calcReceiptRoot(vmState.receipts), + receiptsRoot: calcReceiptsRoot(vmState.receipts), logsHash : calcLogsHash(vmState.receipts), - bloom : createBloom(vmState.receipts), + logsBloom : createBloom(vmState.receipts), receipts : system.move(receipts), rejected : system.move(rejected), # geth using both vmContext.Difficulty and vmContext.Random # therefore we cannot use vmState.difficulty currentDifficulty: ctx.env.currentDifficulty, - gasUsed : vmState.cumulativeGasUsed, - currentBaseFee: ctx.env.currentBaseFee, - withdrawalsRoot: header.withdrawalsRoot + gasUsed : vmState.cumulativeGasUsed, + currentBaseFee : ctx.env.currentBaseFee, + withdrawalsRoot : header.withdrawalsRoot ) if fork >= FkCancun: - result.result.blobGasUsed = some blobGasUsed + result.result.blobGasUsed = Opt.some blobGasUsed if ctx.env.currentExcessBlobGas.isSome: result.result.currentExcessBlobGas = ctx.env.currentExcessBlobGas elif ctx.env.parentExcessBlobGas.isSome and ctx.env.parentBlobGasUsed.isSome: - result.result.currentExcessBlobGas = some calcExcessBlobGas(vmState.parent) + result.result.currentExcessBlobGas = Opt.some calcExcessBlobGas(vmState.parent) template wrapException(body: untyped) = when wrapExceptionEnabled: @@ -337,18 +337,17 @@ proc setupAlloc(stateDB: LedgerRef, alloc: GenesisAlloc) = method getAncestorHash(vmState: TestVMState; blockNumber: BlockNumber): Hash256 = # we can't raise exception here, it'll mess with EVM exception handler. # so, store the exception for later using `hashError` - let num = blockNumber.truncate(uint64) var h = Hash256() if vmState.blockHashes.len == 0: vmState.hashError = "getAncestorHash(" & - $num & ") invoked, no blockhashes provided" + $blockNumber & ") invoked, no blockhashes provided" return h - vmState.blockHashes.withValue(num, val) do: + vmState.blockHashes.withValue(blockNumber, val) do: h = val[] do: vmState.hashError = "getAncestorHash(" & - $num & ") invoked, blockhash for that block not provided" + $blockNumber & ") invoked, blockhash for that block not provided" return h @@ -416,7 +415,7 @@ proc transitionAction*(ctx: var TransContext, conf: T8NConf) = timestamp: ctx.env.parentTimestamp, difficulty: ctx.env.parentDifficulty.get(0.u256), ommersHash: uncleHash, - blockNumber: ctx.env.currentNumber - 1.toBlockNumber, + number: ctx.env.currentNumber - 1'u64, blobGasUsed: ctx.env.parentBlobGasUsed, excessBlobGas: ctx.env.parentExcessBlobGas, ) @@ -427,7 +426,7 @@ proc transitionAction*(ctx: var TransContext, conf: T8NConf) = # Already set, currentBaseFee has precedent over parentBaseFee. discard elif ctx.env.parentBaseFee.isSome: - ctx.env.currentBaseFee = some(calcBaseFee(ctx.env)) + ctx.env.currentBaseFee = Opt.some(calcBaseFee(ctx.env)) else: raise newError(ErrorConfig, "EIP-1559 config but missing 'currentBaseFee' in env section") @@ -443,7 +442,7 @@ proc transitionAction*(ctx: var TransContext, conf: T8NConf) = raise newError(ErrorConfig, res.error) else: # un-set it if it has been set too early - ctx.env.parentBeaconBlockRoot = none(Hash256) + ctx.env.parentBeaconBlockRoot = Opt.none(Hash256) if com.forkGTE(MergeFork): if ctx.env.currentRandom.isNone: @@ -451,13 +450,13 @@ proc transitionAction*(ctx: var TransContext, conf: T8NConf) = if ctx.env.currentDifficulty.isSome and ctx.env.currentDifficulty.get() != 0: raise newError(ErrorConfig, "post-merge difficulty must be zero (or omitted) in env") - ctx.env.currentDifficulty = none(DifficultyInt) + ctx.env.currentDifficulty = Opt.none(DifficultyInt) elif ctx.env.currentDifficulty.isNone: if ctx.env.parentDifficulty.isNone: raise newError(ErrorConfig, "currentDifficulty was not provided, and cannot be calculated due to missing parentDifficulty") - if ctx.env.currentNumber == 0.toBlockNumber: + if ctx.env.currentNumber == 0.BlockNumber: raise newError(ErrorConfig, "currentDifficulty needs to be provided for block number 0") if ctx.env.currentTimestamp <= ctx.env.parentTimestamp: @@ -465,7 +464,7 @@ proc transitionAction*(ctx: var TransContext, conf: T8NConf) = "currentDifficulty cannot be calculated -- currentTime ($1) needs to be after parent time ($2)" % [$ctx.env.currentTimestamp, $ctx.env.parentTimestamp]) - ctx.env.currentDifficulty = some(calcDifficulty(com, + ctx.env.currentDifficulty = Opt.some(calcDifficulty(com, ctx.env.currentTimestamp, parent)) let header = envToHeader(ctx.env) diff --git a/tools/t8n/types.nim b/tools/t8n/types.nim index c0087b744..02e41fdac 100644 --- a/tools/t8n/types.nim +++ b/tools/t8n/types.nim @@ -1,5 +1,5 @@ # Nimbus -# Copyright (c) 2022 Status Research & Development GmbH +# Copyright (c) 2022-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) @@ -29,26 +29,26 @@ type EnvStruct* = object currentCoinbase*: EthAddress - currentDifficulty*: Option[DifficultyInt] - currentRandom*: Option[Hash256] - parentDifficulty*: Option[DifficultyInt] + currentDifficulty*: Opt[DifficultyInt] + currentRandom*: Opt[Hash256] + parentDifficulty*: Opt[DifficultyInt] currentGasLimit*: GasInt currentNumber*: BlockNumber currentTimestamp*: EthTime parentTimestamp*: EthTime blockHashes*: Table[uint64, Hash256] ommers*: seq[Ommer] - currentBaseFee*: Option[UInt256] + currentBaseFee*: Opt[UInt256] parentUncleHash*: Hash256 - parentBaseFee*: Option[UInt256] - parentGasUsed*: Option[GasInt] - parentGasLimit*: Option[GasInt] - withdrawals*: Option[seq[Withdrawal]] - currentBlobGasUsed*: Option[uint64] - currentExcessBlobGas*: Option[uint64] - parentBlobGasUsed*: Option[uint64] - parentExcessBlobGas*: Option[uint64] - parentBeaconBlockRoot*: Option[Hash256] + parentBaseFee*: Opt[UInt256] + parentGasUsed*: Opt[GasInt] + parentGasLimit*: Opt[GasInt] + withdrawals*: Opt[seq[Withdrawal]] + currentBlobGasUsed*: Opt[uint64] + currentExcessBlobGas*: Opt[uint64] + parentBlobGasUsed*: Opt[uint64] + parentExcessBlobGas*: Opt[uint64] + parentBeaconBlockRoot*: Opt[Hash256] TxsType* = enum TxsNone @@ -90,15 +90,15 @@ type txRoot*: Hash256 receiptsRoot*: Hash256 logsHash*: Hash256 - bloom*: BloomFilter + logsBloom*: BloomFilter receipts*: seq[TxReceipt] rejected*: seq[RejectedTx] - currentDifficulty*: Option[DifficultyInt] + currentDifficulty*: Opt[DifficultyInt] gasUsed*: GasInt - currentBaseFee*: Option[UInt256] - withdrawalsRoot*: Option[Hash256] - blobGasUsed*: Option[uint64] - currentExcessBlobGas*: Option[uint64] + currentBaseFee*: Opt[UInt256] + withdrawalsRoot*: Opt[Hash256] + blobGasUsed*: Opt[uint64] + currentExcessBlobGas*: Opt[uint64] const ErrorEVM* = 2.T8NExitCode diff --git a/vendor/nim-eth b/vendor/nim-eth index c9b545b6c..f169068df 160000 --- a/vendor/nim-eth +++ b/vendor/nim-eth @@ -1 +1 @@ -Subproject commit c9b545b6c4c6c441e1a2105e539f506390ffe3b9 +Subproject commit f169068df6c11a2aeba27584c60e354e19c42e94 diff --git a/vendor/nim-web3 b/vendor/nim-web3 index ac93b9a99..b705f8164 160000 --- a/vendor/nim-web3 +++ b/vendor/nim-web3 @@ -1 +1 @@ -Subproject commit ac93b9a99310fd9f1a63255cfde9df47bd63263f +Subproject commit b705f816439f0068ece8c234336bc7093222d00f diff --git a/vendor/nimbus-eth2 b/vendor/nimbus-eth2 index dc6951eee..fb0494e73 160000 --- a/vendor/nimbus-eth2 +++ b/vendor/nimbus-eth2 @@ -1 +1 @@ -Subproject commit dc6951eee951282e47b773ab780170cdccb328e2 +Subproject commit fb0494e7399b62d7120a8c0b06a854a9a52b8eec