diff --git a/fluffy/eth_data/era1.nim b/fluffy/eth_data/era1.nim index e66f2757c3..0f13e27a30 100644 --- a/fluffy/eth_data/era1.nim +++ b/fluffy/eth_data/era1.nim @@ -450,7 +450,10 @@ proc buildAccumulator*(f: Era1File): Result[EpochRecordCached, string] = totalDifficulty = ?f.getTotalDifficulty(blockNumber) headerRecords.add( - HeaderRecord(blockHash: blockHeader.blockHash(), totalDifficulty: totalDifficulty) + HeaderRecord( + blockHash: BlockHash(data: blockHeader.blockHash().data), + totalDifficulty: totalDifficulty, + ) ) ok(EpochRecordCached.init(headerRecords)) @@ -479,7 +482,10 @@ proc verify*(f: Era1File): Result[Digest, string] = return err("Invalid receipts root") headerRecords.add( - HeaderRecord(blockHash: blockHeader.blockHash(), totalDifficulty: totalDifficulty) + HeaderRecord( + blockHash: BlockHash(data: blockHeader.blockHash().data), + totalDifficulty: totalDifficulty, + ) ) let expectedRoot = ?f.getAccumulatorRoot() diff --git a/fluffy/eth_data/history_data_json_store.nim b/fluffy/eth_data/history_data_json_store.nim index e04fa835ae..d2fde83e21 100644 --- a/fluffy/eth_data/history_data_json_store.nim +++ b/fluffy/eth_data/history_data_json_store.nim @@ -63,7 +63,7 @@ func readBlockData*( try: # If wanted the hash for the corresponding header can be verified if verify: - if keccakHash(blockData.header.hexToSeqByte()) != blockHash: + if keccak256(blockData.header.hexToSeqByte()) != blockHash: return err("Data is not matching hash, number " & $blockData.number) block: @@ -135,7 +135,7 @@ func readHeaderData*( try: # If wanted the hash for the corresponding header can be verified if verify: - if keccakHash(blockData.header.hexToSeqByte()) != blockHash: + if keccak256(blockData.header.hexToSeqByte()) != blockHash: return err("Data is not matching hash, number " & $blockData.number) let contentKey = diff --git a/fluffy/network/history/history_network.nim b/fluffy/network/history/history_network.nim index a7f83dd7e3..f6675fd7b9 100644 --- a/fluffy/network/history/history_network.nim +++ b/fluffy/network/history/history_network.nim @@ -217,7 +217,7 @@ proc validateBlockBody*( body: PortalBlockBodyLegacy, header: BlockHeader ): Result[void, string] = ## Validate the block body against the txRoot and ommersHash from the header. - let calculatedOmmersHash = keccakHash(body.uncles.asSeq()) + let calculatedOmmersHash = keccak256(body.uncles.asSeq()) if calculatedOmmersHash != header.ommersHash: return err("Invalid ommers hash") diff --git a/fluffy/network/history/validation/historical_hashes_accumulator.nim b/fluffy/network/history/validation/historical_hashes_accumulator.nim index 1dd39cf147..477585ffe3 100644 --- a/fluffy/network/history/validation/historical_hashes_accumulator.nim +++ b/fluffy/network/history/validation/historical_hashes_accumulator.nim @@ -15,7 +15,7 @@ import ../../../common/common_types, ../history_content -export ssz_serialization, merkleization, proofs, eth_types_rlp +export ssz_serialization, merkleization, proofs, eth_types_rlp, BlockHash # Header Accumulator, as per specification: # https://github.com/ethereum/portal-network-specs/blob/master/history-network.md#the-header-accumulator @@ -62,12 +62,12 @@ type # HistoricalHashesAccumulator Accumulator* = object - historicalEpochs*: List[Bytes32, int(MAX_HISTORICAL_EPOCHS)] + historicalEpochs*: List[common_types.Bytes32, int(MAX_HISTORICAL_EPOCHS)] currentEpoch*: EpochRecord # HistoricalHashesAccumulator in its final state FinishedAccumulator* = object - historicalEpochs*: List[Bytes32, int(MAX_HISTORICAL_EPOCHS)] + historicalEpochs*: List[common_types.Bytes32, int(MAX_HISTORICAL_EPOCHS)] currentEpoch*: EpochRecord func init*(T: type Accumulator): T = @@ -103,7 +103,7 @@ func updateAccumulator*(a: var Accumulator, header: BlockHeader) = a.currentEpoch = EpochRecord.init(@[]) let headerRecord = HeaderRecord( - blockHash: header.blockHash(), + blockHash: BlockHash(data: header.blockHash().data), totalDifficulty: lastTotalDifficulty + header.difficulty, ) @@ -150,7 +150,7 @@ func verifyProof( epochIndex = getEpochIndex(header) epochRecordHash = Digest(data: a.historicalEpochs[epochIndex]) - leave = hash_tree_root(header.blockHash()) + leave = hash_tree_root(BlockHash(data: header.blockHash().data)) headerRecordIndex = getHeaderRecordIndex(header, epochIndex) # TODO: Implement more generalized `get_generalized_index` diff --git a/fluffy/network/state/state_endpoints.nim b/fluffy/network/state/state_endpoints.nim index c312daf9da..a458c0c68b 100644 --- a/fluffy/network/state/state_endpoints.nim +++ b/fluffy/network/state/state_endpoints.nim @@ -107,7 +107,7 @@ proc getStorageProof( let nibbles = slotKey.toPath().unpackNibbles() var - addressHash = keccakHash(address) + addressHash = keccak256(address) nibblesIdx = 0 key = ContractTrieNodeKey.init(addressHash, Nibbles.empty(), storageRoot) proof = TrieProof.empty() @@ -203,7 +203,7 @@ proc getCodeByStateRoot*( return Opt.some(Bytecode.empty()) let - contractCodeKey = ContractCodeKey.init(keccakHash(address), account.codeHash) + contractCodeKey = ContractCodeKey.init(keccak256(address), account.codeHash) contractCodeRetrieval = (await n.getContractCode(contractCodeKey)).valueOr: warn "Failed to get contract code" return Opt.none(Bytecode) diff --git a/fluffy/network/state/state_gossip.nim b/fluffy/network/state/state_gossip.nim index ec5194e4dc..b18a86d8f8 100644 --- a/fluffy/network/state/state_gossip.nim +++ b/fluffy/network/state/state_gossip.nim @@ -71,7 +71,7 @@ func getParent*(offerWithKey: AccountTrieOfferWithKey): AccountTrieOfferWithKey (key, offer) = offerWithKey parent = offer.proof.withPath(key.path).getParent() parentKey = - AccountTrieNodeKey.init(parent.path, keccakHash(parent.proof[^1].asSeq())) + AccountTrieNodeKey.init(parent.path, keccak256(parent.proof[^1].asSeq())) parentOffer = AccountTrieNodeOffer.init(parent.proof, offer.blockHash) parentOffer.withKey(parentKey) @@ -81,7 +81,7 @@ func getParent*(offerWithKey: ContractTrieOfferWithKey): ContractTrieOfferWithKe (key, offer) = offerWithKey parent = offer.storageProof.withPath(key.path).getParent() parentKey = ContractTrieNodeKey.init( - key.addressHash, parent.path, keccakHash(parent.proof[^1].asSeq()) + key.addressHash, parent.path, keccak256(parent.proof[^1].asSeq()) ) parentOffer = ContractTrieNodeOffer.init(parent.proof, offer.accountProof, offer.blockHash) diff --git a/fluffy/network/state/state_utils.nim b/fluffy/network/state/state_utils.nim index a5d66c0447..809bb3de11 100644 --- a/fluffy/network/state/state_utils.nim +++ b/fluffy/network/state/state_utils.nim @@ -88,7 +88,7 @@ func toPath*(hash: KeccakHash): Nibbles {.inline.} = Nibbles.init(hash.data, isEven = true) func toPath*(address: EthAddress): Nibbles {.inline.} = - keccakHash(address).toPath() + keccak256(address).toPath() func toPath*(slotKey: UInt256): Nibbles {.inline.} = - keccakHash(toBytesBE(slotKey)).toPath() + keccak256(toBytesBE(slotKey)).toPath() diff --git a/fluffy/network/state/state_validation.nim b/fluffy/network/state/state_validation.nim index c28fa7e478..703f181eed 100644 --- a/fluffy/network/state/state_validation.nim +++ b/fluffy/network/state/state_validation.nim @@ -12,7 +12,7 @@ import results, eth/common, ../../common/common_utils, ./state_content, ./state_ export results, state_content proc hashEquals(value: TrieNode | Bytecode, expectedHash: KeccakHash): bool {.inline.} = - keccakHash(value.asSeq()) == expectedHash + keccak256(value.asSeq()) == expectedHash proc isValidNextNode( thisNodeRlp: Rlp, rlpIdx: int, nextNode: TrieNode diff --git a/fluffy/tests/state_network_tests/state_test_helpers.nim b/fluffy/tests/state_network_tests/state_test_helpers.nim index 94fd2d9072..a2a62e45ec 100644 --- a/fluffy/tests/state_network_tests/state_test_helpers.nim +++ b/fluffy/tests/state_network_tests/state_test_helpers.nim @@ -59,13 +59,13 @@ proc getTrieProof*( proc generateAccountProof*( state: HexaryTrie, address: EthAddress ): TrieProof {.raises: [RlpError].} = - let key = keccakHash(address).data + let key = keccak256(address).data state.getTrieProof(key) proc generateStorageProof*( state: HexaryTrie, slotKey: UInt256 ): TrieProof {.raises: [RlpError].} = - let key = keccakHash(toBytesBE(slotKey)).data + let key = keccak256(toBytesBE(slotKey)).data state.getTrieProof(key) proc getGenesisAlloc*(filePath: string): GenesisAlloc = @@ -89,12 +89,12 @@ proc toState*( if genAccount.code.len() > 0: var storageTrie = initHexaryTrie(newMemoryDB()) for slotKey, slotValue in genAccount.storage: - let key = keccakHash(toBytesBE(slotKey)).data + let key = keccak256(toBytesBE(slotKey)).data storageTrie.put(key, rlp.encode(slotValue)) storageStates[address] = storageTrie storageRoot = storageTrie.rootHash() - codeHash = keccakHash(genAccount.code) + codeHash = keccak256(genAccount.code) let account = Account( nonce: genAccount.nonce, @@ -102,7 +102,7 @@ proc toState*( storageRoot: storageRoot, codeHash: codeHash, ) - accountTrie.put(keccakHash(address).data, rlp.encode(account)) + accountTrie.put(keccak256(address).data, rlp.encode(account)) (accountTrie, storageStates) diff --git a/fluffy/tests/state_network_tests/test_state_content_keys_vectors.nim b/fluffy/tests/state_network_tests/test_state_content_keys_vectors.nim index 76a44a536c..600a76e6ec 100644 --- a/fluffy/tests/state_network_tests/test_state_content_keys_vectors.nim +++ b/fluffy/tests/state_network_tests/test_state_content_keys_vectors.nim @@ -59,7 +59,7 @@ suite "State Content Keys": raiseAssert "Cannot read test vector: " & error packedNibbles = packNibbles(testCase.path) - addressHash = EthAddress.fromHex(testCase.address).keccakHash() + addressHash = EthAddress.fromHex(testCase.address).keccak256() nodeHash = NodeHash.fromHex(testCase.node_hash) contentKey = ContractTrieNodeKey.init(addressHash, packedNibbles, nodeHash).toContentKey() @@ -91,7 +91,7 @@ suite "State Content Keys": testCase = YamlContractBytecodeKey.loadFromYaml(file).valueOr: raiseAssert "Cannot read test vector: " & error - addressHash = EthAddress.fromHex(testCase.address).keccakHash() + addressHash = EthAddress.fromHex(testCase.address).keccak256() codeHash = CodeHash.fromHex(testCase.code_hash) contentKey = ContractCodeKey.init(addressHash, codeHash).toContentKey() encoded = contentKey.encode() diff --git a/fluffy/tests/state_network_tests/test_state_endpoints_genesis.nim b/fluffy/tests/state_network_tests/test_state_endpoints_genesis.nim index 7cfb02cce5..21633f584e 100644 --- a/fluffy/tests/state_network_tests/test_state_endpoints_genesis.nim +++ b/fluffy/tests/state_network_tests/test_state_endpoints_genesis.nim @@ -33,9 +33,9 @@ suite "State Endpoints - Genesis JSON Files": let proof = accountState.generateAccountProof(address) leafNode = proof[^1] - addressHash = keccakHash(address) + addressHash = keccak256(address) path = removeLeafKeyEndNibbles(Nibbles.init(addressHash.data, true), leafNode) - key = AccountTrieNodeKey.init(path, keccakHash(leafNode.asSeq())) + key = AccountTrieNodeKey.init(path, keccak256(leafNode.asSeq())) offer = AccountTrieNodeOffer(proof: proof) # store the account leaf node @@ -68,7 +68,7 @@ suite "State Endpoints - Genesis JSON Files": proc setupCodeInDb(stateNode: StateNode, address: EthAddress, code: seq[byte]) = let key = - ContractCodeKey(addressHash: keccakHash(address), codeHash: keccakHash(code)) + ContractCodeKey(addressHash: keccak256(address), codeHash: keccak256(code)) value = ContractCodeRetrieval(code: Bytecode.init(code)) let contentKey = key.toContentKey().encode() @@ -84,15 +84,15 @@ suite "State Endpoints - Genesis JSON Files": slot: UInt256, ) = let - addressHash = keccakHash(address) + addressHash = keccak256(address) proof = accountState.generateAccountProof(address) storageProof = storageState.generateStorageProof(slot) leafNode = storageProof[^1] path = removeLeafKeyEndNibbles( - Nibbles.init(keccakHash(toBytesBE(slot)).data, true), leafNode + Nibbles.init(keccak256(toBytesBE(slot)).data, true), leafNode ) key = ContractTrieNodeKey( - addressHash: addressHash, path: path, nodeHash: keccakHash(leafNode.asSeq()) + addressHash: addressHash, path: path, nodeHash: keccak256(leafNode.asSeq()) ) offer = ContractTrieNodeOffer(storageProof: storageProof, accountProof: proof) @@ -233,7 +233,7 @@ suite "State Endpoints - Genesis JSON Files": proofs.account.balance == account.balance proofs.account.nonce == account.nonce proofs.account.storageRoot == storageState.rootHash() - proofs.account.codeHash == keccakHash(account.code) + proofs.account.codeHash == keccak256(account.code) proofs.accountProof.len() > 0 proofs.accountProof == accountState.generateAccountProof(address) proofs.slots.len() == 0 @@ -253,7 +253,7 @@ suite "State Endpoints - Genesis JSON Files": proofs.account.balance == account.balance proofs.account.nonce == account.nonce proofs.account.storageRoot == storageState.rootHash() - proofs.account.codeHash == keccakHash(account.code) + proofs.account.codeHash == keccak256(account.code) proofs.accountProof.len() > 0 proofs.accountProof == accountState.generateAccountProof(address) proofs.slots == @[(slotKey, slotValue)] diff --git a/fluffy/tests/state_network_tests/test_state_gossip_getparent_genesis.nim b/fluffy/tests/state_network_tests/test_state_gossip_getparent_genesis.nim index 29860743d0..8c77c50e58 100644 --- a/fluffy/tests/state_network_tests/test_state_gossip_getparent_genesis.nim +++ b/fluffy/tests/state_network_tests/test_state_gossip_getparent_genesis.nim @@ -32,9 +32,9 @@ suite "State Gossip getParent - Genesis JSON Files": let proof = accountState.generateAccountProof(address) leafNode = proof[^1] - addressHash = keccakHash(address).data + addressHash = keccak256(address).data path = removeLeafKeyEndNibbles(Nibbles.init(addressHash, true), leafNode) - key = AccountTrieNodeKey.init(path, keccakHash(leafNode.asSeq())) + key = AccountTrieNodeKey.init(path, keccak256(leafNode.asSeq())) offer = AccountTrieNodeOffer(proof: proof) var db = newMemoryDB() @@ -69,7 +69,7 @@ suite "State Gossip getParent - Genesis JSON Files": for address, account in accounts: let - addressHash = address.keccakHash() + addressHash = address.keccak256() accountProof = accountState.generateAccountProof(address) if account.code.len() > 0: @@ -79,14 +79,14 @@ suite "State Gossip getParent - Genesis JSON Files": let storageProof = storageState.generateStorageProof(slotKey) leafNode = storageProof[^1] - slotKeyHash = keccakHash(toBytesBE(slotKey)).data + slotKeyHash = keccak256(toBytesBE(slotKey)).data path = removeLeafKeyEndNibbles( - Nibbles.init(keccakHash(toBytesBE(slotKey)).data, true), leafNode + Nibbles.init(keccak256(toBytesBE(slotKey)).data, true), leafNode ) key = ContractTrieNodeKey( addressHash: addressHash, path: path, - nodeHash: keccakHash(leafNode.asSeq()), + nodeHash: keccak256(leafNode.asSeq()), ) offer = ContractTrieNodeOffer( storageProof: storageProof, accountProof: accountProof diff --git a/fluffy/tests/state_network_tests/test_state_validation_genesis.nim b/fluffy/tests/state_network_tests/test_state_validation_genesis.nim index be9863a123..7a0018e0fb 100644 --- a/fluffy/tests/state_network_tests/test_state_validation_genesis.nim +++ b/fluffy/tests/state_network_tests/test_state_validation_genesis.nim @@ -23,15 +23,15 @@ template checkValidProofsForExistingLeafs( ) = for address, account in genAccounts: var acc = newAccount(account.nonce, account.balance) - acc.codeHash = keccakHash(account.code) + acc.codeHash = keccak256(account.code) let - addressHash = address.keccakHash() + addressHash = address.keccak256() accountProof = accountState.generateAccountProof(address) accountPath = removeLeafKeyEndNibbles(Nibbles.init(addressHash.data, true), accountProof[^1]) accountTrieNodeKey = AccountTrieNodeKey( - path: accountPath, nodeHash: keccakHash(accountProof[^1].asSeq()) + path: accountPath, nodeHash: keccak256(accountProof[^1].asSeq()) ) accountTrieOffer = AccountTrieNodeOffer(proof: accountProof) proofResult = validateOffer( @@ -56,12 +56,12 @@ template checkValidProofsForExistingLeafs( let storageProof = storageState.generateStorageProof(slotKey) slotPath = removeLeafKeyEndNibbles( - Nibbles.init(keccakHash(toBytesBE(slotKey)).data, true), storageProof[^1] + Nibbles.init(keccak256(toBytesBE(slotKey)).data, true), storageProof[^1] ) contractTrieNodeKey = ContractTrieNodeKey( addressHash: addressHash, path: slotPath, - nodeHash: keccakHash(storageProof[^1].asSeq()), + nodeHash: keccak256(storageProof[^1].asSeq()), ) contractTrieOffer = ContractTrieNodeOffer( storageProof: storageProof, accountProof: accountProof @@ -78,15 +78,15 @@ template checkInvalidProofsWithBadValue( ) = for address, account in genAccounts: var acc = newAccount(account.nonce, account.balance) - acc.codeHash = keccakHash(account.code) + acc.codeHash = keccak256(account.code) var - addressHash = address.keccakHash() + addressHash = address.keccak256() accountProof = accountState.generateAccountProof(address) accountPath = removeLeafKeyEndNibbles(Nibbles.init(addressHash.data, true), accountProof[^1]) accountTrieNodeKey = AccountTrieNodeKey( - path: accountPath, nodeHash: keccakHash(accountProof[^1].asSeq()) + path: accountPath, nodeHash: keccak256(accountProof[^1].asSeq()) ) accountProof[^1][^1] += 1 # bad account leaf value let @@ -115,12 +115,12 @@ template checkInvalidProofsWithBadValue( var storageProof = storageState.generateStorageProof(slotKey) slotPath = removeLeafKeyEndNibbles( - Nibbles.init(keccakHash(toBytesBE(slotKey)).data, true), storageProof[^1] + Nibbles.init(keccak256(toBytesBE(slotKey)).data, true), storageProof[^1] ) contractTrieNodeKey = ContractTrieNodeKey( addressHash: addressHash, path: slotPath, - nodeHash: keccakHash(storageProof[^1].asSeq()), + nodeHash: keccak256(storageProof[^1].asSeq()), ) storageProof[^1][^1] += 1 # bad storage leaf value let diff --git a/fluffy/tests/state_network_tests/test_state_validation_trieproof.nim b/fluffy/tests/state_network_tests/test_state_validation_trieproof.nim index 55bc611387..786c3bd70a 100644 --- a/fluffy/tests/state_network_tests/test_state_validation_trieproof.nim +++ b/fluffy/tests/state_network_tests/test_state_validation_trieproof.nim @@ -20,7 +20,7 @@ import ./state_test_helpers proc getKeyBytes(i: int): seq[byte] = - let hash = keccakHash(u256(i).toBytesBE()) + let hash = keccak256(u256(i).toBytesBE()) return toSeq(hash.data) suite "State Validation - validateTrieProof": diff --git a/fluffy/tools/beacon_lc_bridge/beacon_lc_bridge.nim b/fluffy/tools/beacon_lc_bridge/beacon_lc_bridge.nim index 61eb4ddf6a..d12cddc1f6 100644 --- a/fluffy/tools/beacon_lc_bridge/beacon_lc_bridge.nim +++ b/fluffy/tools/beacon_lc_bridge/beacon_lc_bridge.nim @@ -70,7 +70,7 @@ from beacon_chain/gossip_processing/eth2_processor import toValidationResult type Hash256 = etypes.Hash256 template asEthHash(hash: web3types.BlockHash): Hash256 = - Hash256(data: distinctBase(hash)) + Hash32(distinctBase(hash)) proc calculateTransactionData( items: openArray[TypedTransaction] diff --git a/fluffy/tools/portal_bridge/portal_bridge_history.nim b/fluffy/tools/portal_bridge/portal_bridge_history.nim index 3249b764d2..1107479865 100644 --- a/fluffy/tools/portal_bridge/portal_bridge_history.nim +++ b/fluffy/tools/portal_bridge/portal_bridge_history.nim @@ -440,7 +440,7 @@ proc runBackfillLoopAuditMode( error "Failed to decode block header content", error break headerBlock - if keccakHash(headerWithProof.header.asSeq()) != blockHash: + if keccak256(headerWithProof.header.asSeq()) != blockHash: error "Block hash mismatch", blockNumber break headerBlock diff --git a/fluffy/tools/portal_bridge/state_bridge/offers_builder.nim b/fluffy/tools/portal_bridge/state_bridge/offers_builder.nim index 3fa0bfcc0c..b2e1946214 100644 --- a/fluffy/tools/portal_bridge/state_bridge/offers_builder.nim +++ b/fluffy/tools/portal_bridge/state_bridge/offers_builder.nim @@ -34,7 +34,7 @@ proc buildAccountTrieNodeOffer( path = removeLeafKeyEndNibbles( Nibbles.init(addressHash.data, isEven = true), proof[^1] ) - offerKey = AccountTrieNodeKey.init(path, keccakHash(proof[^1].asSeq())) + offerKey = AccountTrieNodeKey.init(path, keccak256(proof[^1].asSeq())) offerValue = AccountTrieNodeOffer.init(proof, builder.blockHash) builder.accountTrieOffers.add(offerValue.withKey(offerKey)) @@ -54,7 +54,7 @@ proc buildContractTrieNodeOffer( Nibbles.init(slotHash.data, isEven = true), storageProof[^1] ) offerKey = ContractTrieNodeKey.init( - addressHash, path, keccakHash(storageProof[^1].asSeq()) + addressHash, path, keccak256(storageProof[^1].asSeq()) ) offerValue = ContractTrieNodeOffer.init(storageProof, accountProof, builder.blockHash) @@ -72,7 +72,7 @@ proc buildContractCodeOffer( let #bytecode = Bytelist.init(code) # This fails to compile for some reason bytecode = Bytecode(code) - offerKey = ContractCodeKey.init(addressHash, keccakHash(code)) + offerKey = ContractCodeKey.init(addressHash, keccak256(code)) offerValue = ContractCodeOffer.init(bytecode, accountProof, builder.blockHash) builder.contractCodeOffers.add(offerValue.withKey(offerKey)) diff --git a/fluffy/tools/portal_bridge/state_bridge/world_state.nim b/fluffy/tools/portal_bridge/state_bridge/world_state.nim index 38aed481ea..d08f2fd1c0 100644 --- a/fluffy/tools/portal_bridge/state_bridge/world_state.nim +++ b/fluffy/tools/portal_bridge/state_bridge/world_state.nim @@ -87,10 +87,10 @@ proc stateRoot*(state: WorldStateRef): KeccakHash {.inline.} = state.accountsTrie.rootHash() proc toAccountKey*(address: EthAddress): AddressHash {.inline.} = - keccakHash(address) + keccak256(address) proc toStorageKey*(slotKey: UInt256): SlotKeyHash {.inline.} = - keccakHash(toBytesBE(slotKey)) + keccak256(toBytesBE(slotKey)) proc getAccountPreimage(state: WorldStateRef, accountKey: AddressHash): EthAddress = doAssert( @@ -150,7 +150,7 @@ proc setAccount*(state: WorldStateRef, address: EthAddress, accState: AccountSta if accState.codeUpdated: state.bytecodeDb.put(accountKey.data, accState.code) - accountToSave.codeHash = keccakHash(accState.code) + accountToSave.codeHash = keccak256(accState.code) state.accountsTrie.put(accountKey.data, rlp.encode(accountToSave)) except RlpError as e: @@ -223,7 +223,7 @@ proc verifyProofs*( rlpFromBytes(proof[^1]).listElem(1).toBytes(), # pull the value out of the proof ) for p in proof: - memDb.put(keccakHash(p).data, p) + memDb.put(keccak256(p).data, p) let memTrie = initHexaryTrie(memDb, expectedStateRoot, isPruning = false) doAssert(memTrie.rootHash() == expectedStateRoot) @@ -247,6 +247,6 @@ proc verifyProofs*( let updatedCode = state.getUpdatedBytecode(accountKey) if updatedCode.len() > 0: - doAssert(account.codeHash == keccakHash(updatedCode)) + doAssert(account.codeHash == keccak256(updatedCode)) except RlpError as e: raiseAssert(e.msg) # Should never happen diff --git a/hive_integration/nodocker/engine/cancun_tests.nim b/hive_integration/nodocker/engine/cancun_tests.nim index 1ef2a2b3b2..3f9c223d47 100644 --- a/hive_integration/nodocker/engine/cancun_tests.nim +++ b/hive_integration/nodocker/engine/cancun_tests.nim @@ -527,7 +527,7 @@ let cancunTestListA* = [ testSequence: @[ NewPayloads( fcUOnPayloadRequest: UpgradeForkchoiceUpdatedVersion( - beaconRoot: Opt.some(common.Hash256()), + beaconRoot: Opt.some(default(common.Hash32)), expectedError: engineApiUnsupportedFork, ), expectationDescription: """ @@ -555,7 +555,7 @@ let cancunTestListA* = [ testSequence: @[ NewPayloads( fcUOnPayloadRequest: BaseForkchoiceUpdatedCustomizer( - beaconRoot: Opt.some(common.Hash256()), + beaconRoot: Opt.some(default(common.Hash32)), expectedError: engineApiInvalidPayloadAttributes, ), expectationDescription: """ @@ -583,7 +583,7 @@ let cancunTestListA* = [ testSequence: @[ NewPayloads( fcUOnPayloadRequest: DowngradeForkchoiceUpdatedVersion( - beaconRoot: Opt.some(common.Hash256()), + beaconRoot: Opt.some(default(common.Hash32)), expectedError: engineApiInvalidPayloadAttributes, ), expectationDescription: """ @@ -641,7 +641,7 @@ let cancunTestListA* = [ NewPayloads( expectedIncludedBlobCount: MAX_BLOBS_PER_BLOCK, fcUOnPayloadRequest: BaseForkchoiceUpdatedCustomizer( - beaconRoot: Opt.some(common.Hash256()), + beaconRoot: Opt.some(default(common.Hash32)), ), ), SendBlobTransactions( @@ -818,7 +818,7 @@ let cancunTestListA* = [ payloadCustomizer: CustomPayloadData( excessBlobGas: Opt.some(0'u64), blobGasUsed: Opt.some(0'u64), - parentBeaconRoot: Opt.some(common.Hash256()), + parentBeaconRoot: Opt.some(default(common.Hash32)), versionedHashesCustomizer: VersionedHashesCustomizer( blobs: Opt.some(newSeq[BlobID]()), ), @@ -1673,7 +1673,7 @@ let cancunTestListA* = [ NewPayloads( newPayloadCustomizer: UpgradeNewPayloadVersion( payloadCustomizer: CustomPayloadData( - parentBeaconRoot: some(common.Hash256()), + parentBeaconRoot: some(default(common.Hash32)), ), expectedError: engineApiInvalidParams, ), diff --git a/hive_integration/nodocker/engine/clmock.nim b/hive_integration/nodocker/engine/clmock.nim index 5cd0f68a58..c4a9318b99 100644 --- a/hive_integration/nodocker/engine/clmock.nim +++ b/hive_integration/nodocker/engine/clmock.nim @@ -432,7 +432,7 @@ proc broadcastNextNewPayload(cl: CLMocker): bool = # the blockHash of the payload is valid # the payload doesn't extend the canonical chain # the payload hasn't been fully validated. - let nullHash = w3Hash common.Hash256() + let nullHash = w3Hash default(common.Hash32) let latestValidHash = s.latestValidHash.get(nullHash) if s.latestValidHash.isSome and latestValidHash != nullHash: error "CLMocker: NewPayload returned ACCEPTED status with incorrect LatestValidHash", diff --git a/hive_integration/nodocker/engine/engine/invalid_payload.nim b/hive_integration/nodocker/engine/engine/invalid_payload.nim index 5e8d1b9575..bf8cddd254 100644 --- a/hive_integration/nodocker/engine/engine/invalid_payload.nim +++ b/hive_integration/nodocker/engine/engine/invalid_payload.nim @@ -332,7 +332,7 @@ method execute(cs: PayloadBuildAfterInvalidPayloadTest, env: TestEnv): bool = # Get a payload from the invalid payload producer and invalidate it let customizer = BasePayloadAttributesCustomizer( - prevRandao: Opt.some(common.Hash256()), + prevRandao: Opt.some(default(common.Hash32)), suggestedFeerecipient: Opt.some(ZeroAddr), ) payloadAttributes = customizer.getPayloadAttributes(env.clMock.latestPayloadAttributes) @@ -352,7 +352,7 @@ method execute(cs: PayloadBuildAfterInvalidPayloadTest, env: TestEnv): bool = let basePayload = s.get.executionPayload var src = ExecutableData(basePayload: basePayload) if versione == Version.V3: - src.beaconRoot = Opt.some(common.Hash256()) + src.beaconRoot = Opt.some(default(common.Hash32)) src.versionedHashes = Opt.some(collectBlobHashes(basePayload.transactions)) inv_p = env.generateInvalidPayload(src, InvalidStateRoot) diff --git a/hive_integration/nodocker/engine/engine_client.nim b/hive_integration/nodocker/engine/engine_client.nim index 5c5e35f988..dab2e12966 100644 --- a/hive_integration/nodocker/engine/engine_client.nim +++ b/hive_integration/nodocker/engine/engine_client.nim @@ -652,7 +652,7 @@ proc debugPrevRandaoTransaction*( if stack.len < 1: return err("Invalid stack after PREVRANDAO operation") - let stackHash = Hash256(data: hextoByteArray[32](stack[0].getStr)) + let stackHash = Hash32(hextoByteArray[32](stack[0].getStr)) if stackHash != expectedPrevRandao: return err("Invalid stack after PREVRANDAO operation $1 != $2" % [stackHash.data.toHex, expectedPrevRandao.data.toHex]) diff --git a/hive_integration/nodocker/engine/types.nim b/hive_integration/nodocker/engine/types.nim index 7d80da374e..c72a297b14 100644 --- a/hive_integration/nodocker/engine/types.nim +++ b/hive_integration/nodocker/engine/types.nim @@ -83,7 +83,7 @@ const ZeroAddr* = toAddress(0.u256) func toHash*(x: UInt256): common.Hash256 = - common.Hash256(data: x.toByteArrayBE) + common.Hash32(x.toByteArrayBE) func timestampToBeaconRoot*(timestamp: Quantity): FixedBytes[32] = # Generates a deterministic hash from the timestamp diff --git a/hive_integration/nodocker/pyspec/pyspec_sim.nim b/hive_integration/nodocker/pyspec/pyspec_sim.nim index 60d7383b8c..514d36e0a9 100644 --- a/hive_integration/nodocker/pyspec/pyspec_sim.nim +++ b/hive_integration/nodocker/pyspec/pyspec_sim.nim @@ -119,7 +119,7 @@ proc runTest(node: JsonNode, network: string): TestStatus = let blks = node["blocks"] var - latestValidHash = common.Hash256() + latestValidHash = default(common.Hash32) latestVersion: Version result = TestStatus.OK @@ -164,7 +164,7 @@ proc runTest(node: JsonNode, network: string): TestStatus = block blockOne: # only update head of beacon chain if valid response occurred - if latestValidHash != common.Hash256(): + if latestValidHash != default(common.Hash32): # update with latest valid response let fcState = ForkchoiceStateV1(headBlockHash: BlockHash latestValidHash.data) let res = env.rpcClient.forkchoiceUpdated(latestVersion, fcState) diff --git a/hive_integration/nodocker/rpc/client.nim b/hive_integration/nodocker/rpc/client.nim index 4109714907..abf07f69ac 100644 --- a/hive_integration/nodocker/rpc/client.nim +++ b/hive_integration/nodocker/rpc/client.nim @@ -21,7 +21,7 @@ export eth_api proc sendTransaction*( client: RpcClient, tx: PooledTransaction): Future[bool] {.async.} = let data = rlp.encode(tx) - let txHash = keccakHash(data) + let txHash = keccak256(data) let hex = await client.eth_sendRawTransaction(data) let decodedHash = ethHash(hex) result = decodedHash == txHash diff --git a/hive_integration/nodocker/rpc/vault.nim b/hive_integration/nodocker/rpc/vault.nim index aa82924115..9517a260de 100644 --- a/hive_integration/nodocker/rpc/vault.nim +++ b/hive_integration/nodocker/rpc/vault.nim @@ -72,7 +72,7 @@ proc sendSome(address: EthAddress, amount: UInt256): seq[byte] = const padding = repeat('\0', 12).toBytes # makeshift contract ABI construction # https://docs.soliditylang.org/en/develop/abi-spec.html - let h = keccakHash("sendSome(address,uint256)".toBytes) + let h = keccak256("sendSome(address,uint256)".toBytes) result.add h.data[0..3] # first 4 bytes of hash result.add padding # left pad address result.add address diff --git a/nimbus/beacon/api_handler/api_exchangeconf.nim b/nimbus/beacon/api_handler/api_exchangeconf.nim index 06d4e838b3..1fb9f572b8 100644 --- a/nimbus/beacon/api_handler/api_exchangeconf.nim +++ b/nimbus/beacon/api_handler/api_exchangeconf.nim @@ -43,7 +43,7 @@ proc exchangeConf*(ben: BeaconEngineRef, terminalBlockNumber = common.BlockNumber conf.terminalBlockNumber terminalBlockHash = ethHash conf.terminalBlockHash - if terminalBlockHash != common.Hash256(): + if terminalBlockHash != default(common.Hash32): var headerHash: common.Hash256 if not db.getBlockHash(terminalBlockNumber, headerHash): @@ -69,7 +69,7 @@ proc exchangeConf*(ben: BeaconEngineRef, raise newException(ValueError, "invalid terminal block number: $1" % [ $terminalBlockNumber]) - if terminalBlockHash != common.Hash256(): + if terminalBlockHash != default(common.Hash32): raise newException(ValueError, "invalid terminal block hash, no terminal header set") TransitionConfigurationV1(terminalTotalDifficulty: ttd.get) diff --git a/nimbus/beacon/api_handler/api_forkchoice.nim b/nimbus/beacon/api_handler/api_forkchoice.nim index aab5df8784..25320bf9bf 100644 --- a/nimbus/beacon/api_handler/api_forkchoice.nim +++ b/nimbus/beacon/api_handler/api_forkchoice.nim @@ -80,7 +80,7 @@ proc forkchoiceUpdated*(ben: BeaconEngineRef, chain = ben.chain blockHash = ethHash update.headBlockHash - if blockHash == common.Hash256(): + if blockHash == default(common.Hash32): warn "Forkchoice requested update to zero hash" return simpleFCU(PayloadExecutionStatus.invalid) @@ -164,7 +164,7 @@ proc forkchoiceUpdated*(ben: BeaconEngineRef, # If the beacon client also advertised a finalized block, mark the local # chain final and completely in PoS mode. let finalizedBlockHash = ethHash update.finalizedBlockHash - if finalizedBlockHash != common.Hash256(): + if finalizedBlockHash != default(common.Hash32): if not ben.posFinalized: ben.finalizePoS() @@ -175,7 +175,7 @@ proc forkchoiceUpdated*(ben: BeaconEngineRef, db.finalizedHeaderHash(finalizedBlockHash) let safeBlockHash = ethHash update.safeBlockHash - if safeBlockHash != common.Hash256(): + if safeBlockHash != default(common.Hash32): if not ben.chain.isCanonical(safeBlockHash): warn "Safe block not in canonical chain", hash=safeBlockHash.short diff --git a/nimbus/beacon/api_handler/api_newpayload.nim b/nimbus/beacon/api_handler/api_newpayload.nim index a649152716..828eefa3c3 100644 --- a/nimbus/beacon/api_handler/api_newpayload.nim +++ b/nimbus/beacon/api_handler/api_newpayload.nim @@ -21,7 +21,7 @@ import func validateVersionedHashed(payload: ExecutionPayload, expected: openArray[Web3Hash]): bool = - var versionedHashes: seq[common.Hash256] + var versionedHashes: seq[common.Bytes32] for x in payload.transactions: let tx = rlp.decode(distinctBase(x), Transaction) versionedHashes.add tx.versionedHashes diff --git a/nimbus/beacon/api_handler/api_utils.nim b/nimbus/beacon/api_handler/api_utils.nim index d9d3ebbd90..c20ce6974b 100644 --- a/nimbus/beacon/api_handler/api_utils.nim +++ b/nimbus/beacon/api_handler/api_utils.nim @@ -87,7 +87,7 @@ proc simpleFCU*(status: PayloadExecutionStatus, proc invalidFCU*( validationError: string, - hash = common.Hash256()): ForkchoiceUpdatedResponse = + hash = default(common.Hash32)): ForkchoiceUpdatedResponse = ForkchoiceUpdatedResponse(payloadStatus: PayloadStatusV1( status: PayloadExecutionStatus.invalid, @@ -113,7 +113,7 @@ proc invalidStatus*(validHash: common.Hash256, msg: string): PayloadStatusV1 = validationError: Opt.some(msg) ) -proc invalidStatus*(validHash = common.Hash256()): PayloadStatusV1 = +proc invalidStatus*(validHash = default(common.Hash32)): PayloadStatusV1 = PayloadStatusV1( status: PayloadExecutionStatus.invalid, latestValidHash: toValidHash(validHash) @@ -176,14 +176,14 @@ proc latestValidHash*(db: CoreDbRef, parent: common.BlockHeader, ttd: DifficultyInt): common.Hash256 = if parent.isGenesis: - return common.Hash256() + return default(common.Hash32) let ptd = db.getScore(parent.parentHash).valueOr(0.u256) if ptd >= ttd: parent.blockHash else: # If the most recent valid ancestor is a PoW block, # latestValidHash MUST be set to ZERO - common.Hash256() + default(common.Hash32) proc invalidFCU*(validationError: string, com: CommonRef, diff --git a/nimbus/beacon/beacon_engine.nim b/nimbus/beacon/beacon_engine.nim index 841094ac7d..88e549f9f8 100644 --- a/nimbus/beacon/beacon_engine.nim +++ b/nimbus/beacon/beacon_engine.nim @@ -305,7 +305,7 @@ proc checkInvalidAncestor*(ben: BeaconEngineRef, var header: common.BlockHeader if ben.com.db.getBlockHeader(invalid.parentHash, header): if header.difficulty != 0.u256: - lastValid = common.Hash256() + lastValid = default(common.Hash32) return Opt.some invalidStatus(lastValid, "links to previously rejected block") diff --git a/nimbus/beacon/payload_conv.nim b/nimbus/beacon/payload_conv.nim index 2c2c1a5a7e..76d199c1e0 100644 --- a/nimbus/beacon/payload_conv.nim +++ b/nimbus/beacon/payload_conv.nim @@ -99,7 +99,7 @@ func blockHeader*(p: ExecutionPayload, ommersHash : EMPTY_UNCLE_HASH, coinbase : ethAddr p.feeRecipient, stateRoot : ethHash p.stateRoot, - txRoot : txRoot p.transactions, + transactionsRoot: txRoot p.transactions, receiptsRoot : ethHash p.receiptsRoot, logsBloom : ethBloom p.logsBloom, difficulty : 0.u256, diff --git a/nimbus/beacon/web3_eth_conv.nim b/nimbus/beacon/web3_eth_conv.nim index 573286c6ea..ebd7313d37 100644 --- a/nimbus/beacon/web3_eth_conv.nim +++ b/nimbus/beacon/web3_eth_conv.nim @@ -23,6 +23,7 @@ export primitives type + Web3FixedBytes*[N: static int] = web3Types.FixedBytes[N] Web3Hash* = web3types.Hash256 Web3Address* = web3types.Address Web3Bloom* = web3types.FixedBytes[256] @@ -58,7 +59,7 @@ proc `$`*(x: Web3Quantity): string = $distinctBase(x) proc short*(x: Web3Hash): string = - let z = common.Hash256(data: distinctBase x) + let z = common.Hash32(distinctBase x) short(z) # ------------------------------------------------------------------------------ @@ -91,14 +92,17 @@ func u256*(x: Web3Quantity): UInt256 = func u256*(x: Web3BlockNumber): UInt256 = u256(x.uint64) -func u256*(x: FixedBytes[32]): UInt256 = +func u256*(x: Web3FixedBytes[32]): UInt256 = UInt256.fromBytesBE(x.bytes) func ethTime*(x: Web3Quantity): common.EthTime = common.EthTime(x) func ethHash*(x: Web3PrevRandao): common.Hash256 = - common.Hash256(data: distinctBase x) + common.Hash32(distinctBase x) + +func ethVersionedHash*(x: Web3PrevRandao): common.VersionedHash = + common.VersionedHash(distinctBase x) func ethHash*(x: Opt[Web3Hash]): Opt[common.Hash256] = if x.isNone: Opt.none(common.Hash256) @@ -112,6 +116,10 @@ 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 ethVersionedHashes*(list: openArray[Web3Hash]): seq[common.VersionedHash] = + for x in list: + result.add ethVersionedHash(x) + func ethAddr*(x: Web3Address): common.EthAddress = EthAddress x @@ -158,7 +166,7 @@ func ethTxs*(list: openArray[Web3Tx]): for x in list: result.add ethTx(x) -func storageKeys(list: seq[FixedBytes[32]]): seq[StorageKey] = +func storageKeys(list: seq[Web3FixedBytes[32]]): seq[StorageKey] = for x in list: result.add StorageKey(x) @@ -180,11 +188,11 @@ func ethAccessList*(x: Opt[seq[AccessTuple]]): common.AccessList = func w3Hash*(x: common.Hash256): Web3Hash = Web3Hash x.data -func w3Hashes*(list: openArray[common.Hash256]): seq[Web3Hash] = +func w3Hashes*[T: common.Hash256 | common.VersionedHash](list: openArray[T]): seq[Web3Hash] = for x in list: result.add Web3Hash x.data -func w3Hashes*(z: Opt[seq[common.Hash256]]): Opt[seq[Web3Hash]] = +func w3Hashes*[T: common.Hash256 | common.VersionedHash](z: Opt[seq[T]]): Opt[seq[Web3Hash]] = if z.isNone: Opt.none(seq[Web3Hash]) else: let list = z.get @@ -252,8 +260,8 @@ func w3BlockNumber*(x: uint64): Web3BlockNumber = func w3BlockNumber*(x: UInt256): Web3BlockNumber = Web3BlockNumber x.truncate(uint64) -func w3FixedBytes*(x: UInt256): FixedBytes[32] = - FixedBytes[32](x.toBytesBE) +func w3FixedBytes*(x: UInt256): Web3FixedBytes[32] = + Web3FixedBytes[32](x.toBytesBE) func w3ExtraData*(x: common.Blob): Web3ExtraData = Web3ExtraData x @@ -355,10 +363,10 @@ func ethRequest*(x: DepositRequestV1): Request = Request( requestType: DepositRequestType, deposit: DepositRequest( - pubkey: x.pubkey.bytes, - withdrawalCredentials: x.withdrawalCredentials.bytes, + pubkey: Bytes48 x.pubkey.bytes, + withdrawalCredentials: Bytes32 x.withdrawalCredentials.bytes, amount: uint64 x.amount, - signature: x.signature.bytes, + signature: Bytes96 x.signature.bytes, index: uint64 x.index, ) ) @@ -368,7 +376,7 @@ func ethRequest*(x: WithdrawalRequestV1): Request = requestType: WithdrawalRequestType, withdrawal: WithDrawalRequest( sourceAddress: ethAddr x.sourceAddress, - validatorPubkey: x.validatorPubkey.bytes, + validatorPubkey: Bytes48 x.validatorPubkey.bytes, amount: uint64 x.amount, ) ) @@ -378,8 +386,8 @@ func ethRequest*(x: ConsolidationRequestV1): Request = requestType: ConsolidationRequestType, consolidation: ConsolidationRequest( sourceAddress: ethAddr x.sourceAddress, - sourcePubkey: x.sourcePubkey.bytes, - targetPubkey: x.targetPubkey.bytes, + sourcePubkey: Bytes48 x.sourcePubkey.bytes, + targetPubkey: Bytes48 x.targetPubkey.bytes, ) ) diff --git a/nimbus/common/chain_config.nim b/nimbus/common/chain_config.nim index 6953ea67a8..41f75e700b 100644 --- a/nimbus/common/chain_config.nim +++ b/nimbus/common/chain_config.nim @@ -50,6 +50,8 @@ type config* : ChainConfig genesis*: Genesis + Address = addresses.Address + const CustomNet* = 0.NetworkId # these are public network id @@ -103,8 +105,8 @@ type proc read*(rlp: var Rlp, T: type AddressBalance): T {.gcsafe, raises: [RlpError].}= let listLen = rlp.listLen rlp.tryEnterList() - let val = rlp.read(UInt256).toBytesBE() - result.address[0..^1] = val.toOpenArray(12, val.high) + let abytes = rlp.read(Bytes32) + result.address = abytes.to(Address) result.account.balance = rlp.read(UInt256) if listLen == 3: var misc = rlp.read(Misc) @@ -121,10 +123,7 @@ proc append*(w: var RlpWriter, ab: AddressBalance) = inc listLen w.startList(listLen) - var tmp: array[32, byte] - tmp[12..^1] = ab.address[0..^1] - var val = UInt256.fromBytesBE(tmp) - w.append(val) + w.append(ab.address.to(Bytes32)) w.append(ab.account.balance) if listLen == 3: var misc: Misc @@ -210,7 +209,8 @@ proc readValue(reader: var JsonReader[JGenesis], value: var ChainId) proc readValue(reader: var JsonReader[JGenesis], value: var Hash256) {.gcsafe, raises: [SerializationError, IOError].} = - value = Hash256.fromHex(reader.readValue(string)) + wrapError: + value = Hash256.fromHex(reader.readValue(string)) proc readValue(reader: var JsonReader[JGenesis], value: var BlockNonce) {.gcsafe, raises: [SerializationError, IOError].} = @@ -248,7 +248,7 @@ proc readValue(reader: var JsonReader[JGenesis], value: var seq[byte]) proc readValue(reader: var JsonReader[JGenesis], value: var EthAddress) {.gcsafe, raises: [SerializationError, IOError].} = wrapError: - value = parseAddress(reader.readValue(string)) + value = Address.fromHex(reader.readValue(string)) proc readValue(reader: var JsonReader[JGenesis], value: var uint64) {.gcsafe, raises: [SerializationError, IOError].} = @@ -273,7 +273,7 @@ proc readValue(reader: var JsonReader[JGenesis], value: var GenesisAlloc) {.gcsafe, raises: [SerializationError, IOError].} = wrapError: for key in reader.readObjectFields: - value[parseAddress(key)] = reader.readValue(GenesisAccount) + value[Address.fromHex(key)] = reader.readValue(GenesisAccount) macro fillArrayOfBlockNumberBasedForkOptionals(conf, tmp: typed): untyped = result = newStmtList() @@ -456,7 +456,7 @@ func chainConfigForNetwork*(id: NetworkId): ChainConfig = daoForkBlock: Opt.some(1_920_000.BlockNumber), # 2016-07-20 13:20:40 UTC daoForkSupport: true, eip150Block: Opt.some(2_463_000.BlockNumber), # 2016-10-18 13:19:31 UTC - eip150Hash: toDigest("2086799aeebeae135c246c65021c82b4e15a2c451340993aacfd2751886514f0"), + eip150Hash: hash32"2086799aeebeae135c246c65021c82b4e15a2c451340993aacfd2751886514f0", 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 @@ -480,7 +480,7 @@ func chainConfigForNetwork*(id: NetworkId): ChainConfig = homesteadBlock: Opt.some(0.BlockNumber), daoForkSupport: false, eip150Block: Opt.some(0.BlockNumber), - eip150Hash: toDigest("0000000000000000000000000000000000000000000000000000000000000000"), + eip150Hash: hash32"0000000000000000000000000000000000000000000000000000000000000000", eip155Block: Opt.some(0.BlockNumber), eip158Block: Opt.some(0.BlockNumber), byzantiumBlock: Opt.some(0.BlockNumber), diff --git a/nimbus/common/genesis.nim b/nimbus/common/genesis.nim index 728fa45924..6f0d20d25c 100644 --- a/nimbus/common/genesis.nim +++ b/nimbus/common/genesis.nim @@ -115,7 +115,7 @@ proc toGenesisHeader*( coinbase: g.coinbase, stateRoot: sdb.rootHash(), parentHash: GENESIS_PARENT_HASH, - txRoot: EMPTY_ROOT_HASH, + transactionsRoot: EMPTY_ROOT_HASH, receiptsRoot: EMPTY_ROOT_HASH, ommersHash: EMPTY_UNCLE_HASH ) @@ -137,7 +137,7 @@ proc toGenesisHeader*( if fork >= Cancun: 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()) + result.parentBeaconBlockRoot = Opt.some g.parentBeaconBlockRoot.get(default(Hash32)) proc toGenesisHeader*( genesis: Genesis; diff --git a/nimbus/common/manager.nim b/nimbus/common/manager.nim index dc0ab826a2..1608914355 100644 --- a/nimbus/common/manager.nim +++ b/nimbus/common/manager.nim @@ -36,7 +36,7 @@ proc loadKeystores*(am: var AccountsManager, path: string): createDir(path) for filename in walkDirRec(path): var data = Json.loadFile(filename, JsonNode) - let address: EthAddress = hexToByteArray[20](data["address"].getStr()) + let address = EthAddress.fromHex(data["address"].getStr()) am.accounts[address] = NimbusAccount(keystore: data, unlocked: false) except CatchableError as exc: return err("loadKeystrores: " & exc.msg) diff --git a/nimbus/config.nim b/nimbus/config.nim index 1760cf35d9..5e49ddd5b2 100644 --- a/nimbus/config.nim +++ b/nimbus/config.nim @@ -728,7 +728,7 @@ func fromEnr*(T: type ENode, r: enr.Record): ENodeResult[ENode] = ok(ENode( pubkey: pk, - address: Address( + address: enode.Address( ip: utils.ipv4(tr.ip.get()), udpPort: Port(tr.udp.get()), tcpPort: Port(tr.tcp.get()) diff --git a/nimbus/constants.nim b/nimbus/constants.nim index c8064fe111..95a231ea35 100644 --- a/nimbus/constants.nim +++ b/nimbus/constants.nim @@ -28,7 +28,7 @@ const ZERO_ADDRESS* = default(EthAddress) # ZERO_HASH256 is the parent hash of genesis blocks. - ZERO_HASH256* = Hash256() + ZERO_HASH256* = default(Hash32) GAS_LIMIT_ADJUSTMENT_FACTOR* = 1_024 @@ -51,7 +51,7 @@ const GAS_LIMIT_MAXIMUM* = int64.high.GasInt # Maximum the gas limit (2^63-1). DEFAULT_GAS_LIMIT* = 8_000_000 - EMPTY_SHA3* = "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470".toDigest + EMPTY_SHA3* = hash32"c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470" GAS_MOD_EXP_QUADRATIC_DENOMINATOR* = 20.u256 @@ -98,17 +98,17 @@ const # EIP-4788 addresses # BEACON_ROOTS_ADDRESS is the address where historical beacon roots are stored as per EIP-4788 - BEACON_ROOTS_ADDRESS* = hexToByteArray[20]("0x000F3df6D732807Ef1319fB7B8bB8522d0Beac02") + BEACON_ROOTS_ADDRESS* = address"0x000F3df6D732807Ef1319fB7B8bB8522d0Beac02" # SYSTEM_ADDRESS is where the system-transaction is sent from as per EIP-4788 - SYSTEM_ADDRESS* = hexToByteArray[20]("0xfffffffffffffffffffffffffffffffffffffffe") + SYSTEM_ADDRESS* = address"0xfffffffffffffffffffffffffffffffffffffffe" RIPEMD_ADDR* = block: proc initAddress(x: int): EthAddress {.compileTime.} = - result[19] = x.byte + result.data[19] = x.byte initAddress(3) - HISTORY_STORAGE_ADDRESS* = hexToByteArray[20]("0x0aae40965e6800cd9b1f4b05ff21581047e3f91e") - DEPOSIT_CONTRACT_ADDRESS* = hexToByteArray[20]("0x00000000219ab540356cbb839cbe05303d7705fa") - WITHDRAWAL_REQUEST_ADDRESS* = hexToByteArray[20]("0x00A3ca265EBcb825B45F985A16CEFB49958cE017") - CONSOLIDATION_REQUEST_ADDRESS* = hexToByteArray[20]("0x00b42dbF2194e931E80326D950320f7d9Dbeac02") + HISTORY_STORAGE_ADDRESS* = address"0x0aae40965e6800cd9b1f4b05ff21581047e3f91e" + DEPOSIT_CONTRACT_ADDRESS* = address"0x00000000219ab540356cbb839cbe05303d7705fa" + WITHDRAWAL_REQUEST_ADDRESS* = address"0x00A3ca265EBcb825B45F985A16CEFB49958cE017" + CONSOLIDATION_REQUEST_ADDRESS* = address"0x00b42dbF2194e931E80326D950320f7d9Dbeac02" # End diff --git a/nimbus/core/chain/persist_blocks.nim b/nimbus/core/chain/persist_blocks.nim index 7ba8d0209c..416746015c 100644 --- a/nimbus/core/chain/persist_blocks.nim +++ b/nimbus/core/chain/persist_blocks.nim @@ -222,7 +222,7 @@ proc insertBlockWithoutSetHead*(c: ChainRef, blk: EthBlock): Result[void, string ok() proc setCanonical*(c: ChainRef, header: BlockHeader): Result[void, string] = - if header.parentHash == Hash256(): + if header.parentHash == default(Hash32): if not c.db.setHead(header): return err("setHead failed") return ok() diff --git a/nimbus/core/dao.nim b/nimbus/core/dao.nim index 0bf9298a9b..8b23474b3a 100644 --- a/nimbus/core/dao.nim +++ b/nimbus/core/dao.nim @@ -8,7 +8,7 @@ # at your option. This file may not be copied, modified, or distributed except # according to those terms. -import eth/common, stew/byteutils, ../db/ledger +import eth/common, ../db/ledger const # DAOForkBlockExtra is the block header extra-data field to set for the DAO fork @@ -21,125 +21,125 @@ const DAOForkExtraRange* = 10 # DAORefundContract is the address of the refund contract to send DAO balances to. - DAORefundContract: EthAddress = hexToByteArray[20]("0xbf4ed7b27f1d666546e30d74d50d173d20bca754") + DAORefundContract: EthAddress = address"0xbf4ed7b27f1d666546e30d74d50d173d20bca754" DAODrainList = [ - hexToByteArray[20]("0xd4fe7bc31cedb7bfb8a345f31e668033056b2728"), - hexToByteArray[20]("0xb3fb0e5aba0e20e5c49d252dfd30e102b171a425"), - hexToByteArray[20]("0x2c19c7f9ae8b751e37aeb2d93a699722395ae18f"), - hexToByteArray[20]("0xecd135fa4f61a655311e86238c92adcd779555d2"), - hexToByteArray[20]("0x1975bd06d486162d5dc297798dfc41edd5d160a7"), - hexToByteArray[20]("0xa3acf3a1e16b1d7c315e23510fdd7847b48234f6"), - hexToByteArray[20]("0x319f70bab6845585f412ec7724b744fec6095c85"), - hexToByteArray[20]("0x06706dd3f2c9abf0a21ddcc6941d9b86f0596936"), - hexToByteArray[20]("0x5c8536898fbb74fc7445814902fd08422eac56d0"), - hexToByteArray[20]("0x6966ab0d485353095148a2155858910e0965b6f9"), - hexToByteArray[20]("0x779543a0491a837ca36ce8c635d6154e3c4911a6"), - hexToByteArray[20]("0x2a5ed960395e2a49b1c758cef4aa15213cfd874c"), - hexToByteArray[20]("0x5c6e67ccd5849c0d29219c4f95f1a7a93b3f5dc5"), - hexToByteArray[20]("0x9c50426be05db97f5d64fc54bf89eff947f0a321"), - hexToByteArray[20]("0x200450f06520bdd6c527622a273333384d870efb"), - hexToByteArray[20]("0xbe8539bfe837b67d1282b2b1d61c3f723966f049"), - hexToByteArray[20]("0x6b0c4d41ba9ab8d8cfb5d379c69a612f2ced8ecb"), - hexToByteArray[20]("0xf1385fb24aad0cd7432824085e42aff90886fef5"), - hexToByteArray[20]("0xd1ac8b1ef1b69ff51d1d401a476e7e612414f091"), - hexToByteArray[20]("0x8163e7fb499e90f8544ea62bbf80d21cd26d9efd"), - hexToByteArray[20]("0x51e0ddd9998364a2eb38588679f0d2c42653e4a6"), - hexToByteArray[20]("0x627a0a960c079c21c34f7612d5d230e01b4ad4c7"), - hexToByteArray[20]("0xf0b1aa0eb660754448a7937c022e30aa692fe0c5"), - hexToByteArray[20]("0x24c4d950dfd4dd1902bbed3508144a54542bba94"), - hexToByteArray[20]("0x9f27daea7aca0aa0446220b98d028715e3bc803d"), - hexToByteArray[20]("0xa5dc5acd6a7968a4554d89d65e59b7fd3bff0f90"), - hexToByteArray[20]("0xd9aef3a1e38a39c16b31d1ace71bca8ef58d315b"), - hexToByteArray[20]("0x63ed5a272de2f6d968408b4acb9024f4cc208ebf"), - hexToByteArray[20]("0x6f6704e5a10332af6672e50b3d9754dc460dfa4d"), - hexToByteArray[20]("0x77ca7b50b6cd7e2f3fa008e24ab793fd56cb15f6"), - hexToByteArray[20]("0x492ea3bb0f3315521c31f273e565b868fc090f17"), - hexToByteArray[20]("0x0ff30d6de14a8224aa97b78aea5388d1c51c1f00"), - hexToByteArray[20]("0x9ea779f907f0b315b364b0cfc39a0fde5b02a416"), - hexToByteArray[20]("0xceaeb481747ca6c540a000c1f3641f8cef161fa7"), - hexToByteArray[20]("0xcc34673c6c40e791051898567a1222daf90be287"), - hexToByteArray[20]("0x579a80d909f346fbfb1189493f521d7f48d52238"), - hexToByteArray[20]("0xe308bd1ac5fda103967359b2712dd89deffb7973"), - hexToByteArray[20]("0x4cb31628079fb14e4bc3cd5e30c2f7489b00960c"), - hexToByteArray[20]("0xac1ecab32727358dba8962a0f3b261731aad9723"), - hexToByteArray[20]("0x4fd6ace747f06ece9c49699c7cabc62d02211f75"), - hexToByteArray[20]("0x440c59b325d2997a134c2c7c60a8c61611212bad"), - hexToByteArray[20]("0x4486a3d68fac6967006d7a517b889fd3f98c102b"), - hexToByteArray[20]("0x9c15b54878ba618f494b38f0ae7443db6af648ba"), - hexToByteArray[20]("0x27b137a85656544b1ccb5a0f2e561a5703c6a68f"), - hexToByteArray[20]("0x21c7fdb9ed8d291d79ffd82eb2c4356ec0d81241"), - hexToByteArray[20]("0x23b75c2f6791eef49c69684db4c6c1f93bf49a50"), - hexToByteArray[20]("0x1ca6abd14d30affe533b24d7a21bff4c2d5e1f3b"), - hexToByteArray[20]("0xb9637156d330c0d605a791f1c31ba5890582fe1c"), - hexToByteArray[20]("0x6131c42fa982e56929107413a9d526fd99405560"), - hexToByteArray[20]("0x1591fc0f688c81fbeb17f5426a162a7024d430c2"), - hexToByteArray[20]("0x542a9515200d14b68e934e9830d91645a980dd7a"), - hexToByteArray[20]("0xc4bbd073882dd2add2424cf47d35213405b01324"), - hexToByteArray[20]("0x782495b7b3355efb2833d56ecb34dc22ad7dfcc4"), - hexToByteArray[20]("0x58b95c9a9d5d26825e70a82b6adb139d3fd829eb"), - hexToByteArray[20]("0x3ba4d81db016dc2890c81f3acec2454bff5aada5"), - hexToByteArray[20]("0xb52042c8ca3f8aa246fa79c3feaa3d959347c0ab"), - hexToByteArray[20]("0xe4ae1efdfc53b73893af49113d8694a057b9c0d1"), - hexToByteArray[20]("0x3c02a7bc0391e86d91b7d144e61c2c01a25a79c5"), - hexToByteArray[20]("0x0737a6b837f97f46ebade41b9bc3e1c509c85c53"), - hexToByteArray[20]("0x97f43a37f595ab5dd318fb46e7a155eae057317a"), - hexToByteArray[20]("0x52c5317c848ba20c7504cb2c8052abd1fde29d03"), - hexToByteArray[20]("0x4863226780fe7c0356454236d3b1c8792785748d"), - hexToByteArray[20]("0x5d2b2e6fcbe3b11d26b525e085ff818dae332479"), - hexToByteArray[20]("0x5f9f3392e9f62f63b8eac0beb55541fc8627f42c"), - hexToByteArray[20]("0x057b56736d32b86616a10f619859c6cd6f59092a"), - hexToByteArray[20]("0x9aa008f65de0b923a2a4f02012ad034a5e2e2192"), - hexToByteArray[20]("0x304a554a310c7e546dfe434669c62820b7d83490"), - hexToByteArray[20]("0x914d1b8b43e92723e64fd0a06f5bdb8dd9b10c79"), - hexToByteArray[20]("0x4deb0033bb26bc534b197e61d19e0733e5679784"), - hexToByteArray[20]("0x07f5c1e1bc2c93e0402f23341973a0e043f7bf8a"), - hexToByteArray[20]("0x35a051a0010aba705c9008d7a7eff6fb88f6ea7b"), - hexToByteArray[20]("0x4fa802324e929786dbda3b8820dc7834e9134a2a"), - hexToByteArray[20]("0x9da397b9e80755301a3b32173283a91c0ef6c87e"), - hexToByteArray[20]("0x8d9edb3054ce5c5774a420ac37ebae0ac02343c6"), - hexToByteArray[20]("0x0101f3be8ebb4bbd39a2e3b9a3639d4259832fd9"), - hexToByteArray[20]("0x5dc28b15dffed94048d73806ce4b7a4612a1d48f"), - hexToByteArray[20]("0xbcf899e6c7d9d5a215ab1e3444c86806fa854c76"), - hexToByteArray[20]("0x12e626b0eebfe86a56d633b9864e389b45dcb260"), - hexToByteArray[20]("0xa2f1ccba9395d7fcb155bba8bc92db9bafaeade7"), - hexToByteArray[20]("0xec8e57756626fdc07c63ad2eafbd28d08e7b0ca5"), - hexToByteArray[20]("0xd164b088bd9108b60d0ca3751da4bceb207b0782"), - hexToByteArray[20]("0x6231b6d0d5e77fe001c2a460bd9584fee60d409b"), - hexToByteArray[20]("0x1cba23d343a983e9b5cfd19496b9a9701ada385f"), - hexToByteArray[20]("0xa82f360a8d3455c5c41366975bde739c37bfeb8a"), - hexToByteArray[20]("0x9fcd2deaff372a39cc679d5c5e4de7bafb0b1339"), - hexToByteArray[20]("0x005f5cee7a43331d5a3d3eec71305925a62f34b6"), - hexToByteArray[20]("0x0e0da70933f4c7849fc0d203f5d1d43b9ae4532d"), - hexToByteArray[20]("0xd131637d5275fd1a68a3200f4ad25c71a2a9522e"), - hexToByteArray[20]("0xbc07118b9ac290e4622f5e77a0853539789effbe"), - hexToByteArray[20]("0x47e7aa56d6bdf3f36be34619660de61275420af8"), - hexToByteArray[20]("0xacd87e28b0c9d1254e868b81cba4cc20d9a32225"), - hexToByteArray[20]("0xadf80daec7ba8dcf15392f1ac611fff65d94f880"), - hexToByteArray[20]("0x5524c55fb03cf21f549444ccbecb664d0acad706"), - hexToByteArray[20]("0x40b803a9abce16f50f36a77ba41180eb90023925"), - hexToByteArray[20]("0xfe24cdd8648121a43a7c86d289be4dd2951ed49f"), - hexToByteArray[20]("0x17802f43a0137c506ba92291391a8a8f207f487d"), - hexToByteArray[20]("0x253488078a4edf4d6f42f113d1e62836a942cf1a"), - hexToByteArray[20]("0x86af3e9626fce1957c82e88cbf04ddf3a2ed7915"), - hexToByteArray[20]("0xb136707642a4ea12fb4bae820f03d2562ebff487"), - hexToByteArray[20]("0xdbe9b615a3ae8709af8b93336ce9b477e4ac0940"), - hexToByteArray[20]("0xf14c14075d6c4ed84b86798af0956deef67365b5"), - hexToByteArray[20]("0xca544e5c4687d109611d0f8f928b53a25af72448"), - hexToByteArray[20]("0xaeeb8ff27288bdabc0fa5ebb731b6f409507516c"), - hexToByteArray[20]("0xcbb9d3703e651b0d496cdefb8b92c25aeb2171f7"), - hexToByteArray[20]("0x6d87578288b6cb5549d5076a207456a1f6a63dc0"), - hexToByteArray[20]("0xb2c6f0dfbb716ac562e2d85d6cb2f8d5ee87603e"), - hexToByteArray[20]("0xaccc230e8a6e5be9160b8cdf2864dd2a001c28b6"), - hexToByteArray[20]("0x2b3455ec7fedf16e646268bf88846bd7a2319bb2"), - hexToByteArray[20]("0x4613f3bca5c44ea06337a9e439fbc6d42e501d0a"), - hexToByteArray[20]("0xd343b217de44030afaa275f54d31a9317c7f441e"), - hexToByteArray[20]("0x84ef4b2357079cd7a7c69fd7a37cd0609a679106"), - hexToByteArray[20]("0xda2fef9e4a3230988ff17df2165440f37e8b1708"), - hexToByteArray[20]("0xf4c64518ea10f995918a454158c6b61407ea345c"), - hexToByteArray[20]("0x7602b46df5390e432ef1c307d4f2c9ff6d65cc97"), - hexToByteArray[20]("0xbb9bc244d798123fde783fcc1c72d3bb8c189413"), - hexToByteArray[20]("0x807640a13483f8ac783c557fcdf27be11ea4ac7a") + address"0xd4fe7bc31cedb7bfb8a345f31e668033056b2728", + address"0xb3fb0e5aba0e20e5c49d252dfd30e102b171a425", + address"0x2c19c7f9ae8b751e37aeb2d93a699722395ae18f", + address"0xecd135fa4f61a655311e86238c92adcd779555d2", + address"0x1975bd06d486162d5dc297798dfc41edd5d160a7", + address"0xa3acf3a1e16b1d7c315e23510fdd7847b48234f6", + address"0x319f70bab6845585f412ec7724b744fec6095c85", + address"0x06706dd3f2c9abf0a21ddcc6941d9b86f0596936", + address"0x5c8536898fbb74fc7445814902fd08422eac56d0", + address"0x6966ab0d485353095148a2155858910e0965b6f9", + address"0x779543a0491a837ca36ce8c635d6154e3c4911a6", + address"0x2a5ed960395e2a49b1c758cef4aa15213cfd874c", + address"0x5c6e67ccd5849c0d29219c4f95f1a7a93b3f5dc5", + address"0x9c50426be05db97f5d64fc54bf89eff947f0a321", + address"0x200450f06520bdd6c527622a273333384d870efb", + address"0xbe8539bfe837b67d1282b2b1d61c3f723966f049", + address"0x6b0c4d41ba9ab8d8cfb5d379c69a612f2ced8ecb", + address"0xf1385fb24aad0cd7432824085e42aff90886fef5", + address"0xd1ac8b1ef1b69ff51d1d401a476e7e612414f091", + address"0x8163e7fb499e90f8544ea62bbf80d21cd26d9efd", + address"0x51e0ddd9998364a2eb38588679f0d2c42653e4a6", + address"0x627a0a960c079c21c34f7612d5d230e01b4ad4c7", + address"0xf0b1aa0eb660754448a7937c022e30aa692fe0c5", + address"0x24c4d950dfd4dd1902bbed3508144a54542bba94", + address"0x9f27daea7aca0aa0446220b98d028715e3bc803d", + address"0xa5dc5acd6a7968a4554d89d65e59b7fd3bff0f90", + address"0xd9aef3a1e38a39c16b31d1ace71bca8ef58d315b", + address"0x63ed5a272de2f6d968408b4acb9024f4cc208ebf", + address"0x6f6704e5a10332af6672e50b3d9754dc460dfa4d", + address"0x77ca7b50b6cd7e2f3fa008e24ab793fd56cb15f6", + address"0x492ea3bb0f3315521c31f273e565b868fc090f17", + address"0x0ff30d6de14a8224aa97b78aea5388d1c51c1f00", + address"0x9ea779f907f0b315b364b0cfc39a0fde5b02a416", + address"0xceaeb481747ca6c540a000c1f3641f8cef161fa7", + address"0xcc34673c6c40e791051898567a1222daf90be287", + address"0x579a80d909f346fbfb1189493f521d7f48d52238", + address"0xe308bd1ac5fda103967359b2712dd89deffb7973", + address"0x4cb31628079fb14e4bc3cd5e30c2f7489b00960c", + address"0xac1ecab32727358dba8962a0f3b261731aad9723", + address"0x4fd6ace747f06ece9c49699c7cabc62d02211f75", + address"0x440c59b325d2997a134c2c7c60a8c61611212bad", + address"0x4486a3d68fac6967006d7a517b889fd3f98c102b", + address"0x9c15b54878ba618f494b38f0ae7443db6af648ba", + address"0x27b137a85656544b1ccb5a0f2e561a5703c6a68f", + address"0x21c7fdb9ed8d291d79ffd82eb2c4356ec0d81241", + address"0x23b75c2f6791eef49c69684db4c6c1f93bf49a50", + address"0x1ca6abd14d30affe533b24d7a21bff4c2d5e1f3b", + address"0xb9637156d330c0d605a791f1c31ba5890582fe1c", + address"0x6131c42fa982e56929107413a9d526fd99405560", + address"0x1591fc0f688c81fbeb17f5426a162a7024d430c2", + address"0x542a9515200d14b68e934e9830d91645a980dd7a", + address"0xc4bbd073882dd2add2424cf47d35213405b01324", + address"0x782495b7b3355efb2833d56ecb34dc22ad7dfcc4", + address"0x58b95c9a9d5d26825e70a82b6adb139d3fd829eb", + address"0x3ba4d81db016dc2890c81f3acec2454bff5aada5", + address"0xb52042c8ca3f8aa246fa79c3feaa3d959347c0ab", + address"0xe4ae1efdfc53b73893af49113d8694a057b9c0d1", + address"0x3c02a7bc0391e86d91b7d144e61c2c01a25a79c5", + address"0x0737a6b837f97f46ebade41b9bc3e1c509c85c53", + address"0x97f43a37f595ab5dd318fb46e7a155eae057317a", + address"0x52c5317c848ba20c7504cb2c8052abd1fde29d03", + address"0x4863226780fe7c0356454236d3b1c8792785748d", + address"0x5d2b2e6fcbe3b11d26b525e085ff818dae332479", + address"0x5f9f3392e9f62f63b8eac0beb55541fc8627f42c", + address"0x057b56736d32b86616a10f619859c6cd6f59092a", + address"0x9aa008f65de0b923a2a4f02012ad034a5e2e2192", + address"0x304a554a310c7e546dfe434669c62820b7d83490", + address"0x914d1b8b43e92723e64fd0a06f5bdb8dd9b10c79", + address"0x4deb0033bb26bc534b197e61d19e0733e5679784", + address"0x07f5c1e1bc2c93e0402f23341973a0e043f7bf8a", + address"0x35a051a0010aba705c9008d7a7eff6fb88f6ea7b", + address"0x4fa802324e929786dbda3b8820dc7834e9134a2a", + address"0x9da397b9e80755301a3b32173283a91c0ef6c87e", + address"0x8d9edb3054ce5c5774a420ac37ebae0ac02343c6", + address"0x0101f3be8ebb4bbd39a2e3b9a3639d4259832fd9", + address"0x5dc28b15dffed94048d73806ce4b7a4612a1d48f", + address"0xbcf899e6c7d9d5a215ab1e3444c86806fa854c76", + address"0x12e626b0eebfe86a56d633b9864e389b45dcb260", + address"0xa2f1ccba9395d7fcb155bba8bc92db9bafaeade7", + address"0xec8e57756626fdc07c63ad2eafbd28d08e7b0ca5", + address"0xd164b088bd9108b60d0ca3751da4bceb207b0782", + address"0x6231b6d0d5e77fe001c2a460bd9584fee60d409b", + address"0x1cba23d343a983e9b5cfd19496b9a9701ada385f", + address"0xa82f360a8d3455c5c41366975bde739c37bfeb8a", + address"0x9fcd2deaff372a39cc679d5c5e4de7bafb0b1339", + address"0x005f5cee7a43331d5a3d3eec71305925a62f34b6", + address"0x0e0da70933f4c7849fc0d203f5d1d43b9ae4532d", + address"0xd131637d5275fd1a68a3200f4ad25c71a2a9522e", + address"0xbc07118b9ac290e4622f5e77a0853539789effbe", + address"0x47e7aa56d6bdf3f36be34619660de61275420af8", + address"0xacd87e28b0c9d1254e868b81cba4cc20d9a32225", + address"0xadf80daec7ba8dcf15392f1ac611fff65d94f880", + address"0x5524c55fb03cf21f549444ccbecb664d0acad706", + address"0x40b803a9abce16f50f36a77ba41180eb90023925", + address"0xfe24cdd8648121a43a7c86d289be4dd2951ed49f", + address"0x17802f43a0137c506ba92291391a8a8f207f487d", + address"0x253488078a4edf4d6f42f113d1e62836a942cf1a", + address"0x86af3e9626fce1957c82e88cbf04ddf3a2ed7915", + address"0xb136707642a4ea12fb4bae820f03d2562ebff487", + address"0xdbe9b615a3ae8709af8b93336ce9b477e4ac0940", + address"0xf14c14075d6c4ed84b86798af0956deef67365b5", + address"0xca544e5c4687d109611d0f8f928b53a25af72448", + address"0xaeeb8ff27288bdabc0fa5ebb731b6f409507516c", + address"0xcbb9d3703e651b0d496cdefb8b92c25aeb2171f7", + address"0x6d87578288b6cb5549d5076a207456a1f6a63dc0", + address"0xb2c6f0dfbb716ac562e2d85d6cb2f8d5ee87603e", + address"0xaccc230e8a6e5be9160b8cdf2864dd2a001c28b6", + address"0x2b3455ec7fedf16e646268bf88846bd7a2319bb2", + address"0x4613f3bca5c44ea06337a9e439fbc6d42e501d0a", + address"0xd343b217de44030afaa275f54d31a9317c7f441e", + address"0x84ef4b2357079cd7a7c69fd7a37cd0609a679106", + address"0xda2fef9e4a3230988ff17df2165440f37e8b1708", + address"0xf4c64518ea10f995918a454158c6b61407ea345c", + address"0x7602b46df5390e432ef1c307d4f2c9ff6d65cc97", + address"0xbb9bc244d798123fde783fcc1c72d3bb8c189413", + address"0x807640a13483f8ac783c557fcdf27be11ea4ac7a", ] # ApplyDAOHardFork modifies the state database according to the DAO hard-fork diff --git a/nimbus/core/eip4844.nim b/nimbus/core/eip4844.nim index 9d00b94310..a45eabf33c 100644 --- a/nimbus/core/eip4844.nim +++ b/nimbus/core/eip4844.nim @@ -41,7 +41,7 @@ const # kzgToVersionedHash implements kzg_to_versioned_hash from EIP-4844 proc kzgToVersionedHash*(kzg: kzg.KzgCommitment): VersionedHash = - result = sha256.digest(kzg.bytes) + result = sha256.digest(kzg.bytes).data.to(Bytes32) result.data[0] = VERSIONED_HASH_VERSION_KZG # pointEvaluation implements point_evaluation_precompile from EIP-4844 @@ -183,13 +183,13 @@ proc validateBlobTransactionWrapper*(tx: PooledTransaction): return err("tx wrapper is ill formatted") let commitments = tx.networkPayload.commitments.mapIt( - kzg.KzgCommitment(bytes: it)) + kzg.KzgCommitment(bytes: it.data)) # Verify that commitments match the blobs by checking the KZG proof let res = kzg.verifyBlobKzgProofBatch( tx.networkPayload.blobs.mapIt(kzg.KzgBlob(bytes: it)), commitments, - tx.networkPayload.proofs.mapIt(kzg.KzgProof(bytes: it))) + tx.networkPayload.proofs.mapIt(kzg.KzgProof(bytes: it.data))) if res.isErr: return err(res.error) diff --git a/nimbus/core/eip6110.nim b/nimbus/core/eip6110.nim index e855d3bdcd..58cb9b042a 100644 --- a/nimbus/core/eip6110.nim +++ b/nimbus/core/eip6110.nim @@ -36,27 +36,24 @@ func unpackIntoDeposit(data: openArray[byte]): Result[Request, string] = e = d + 8 + 24 + 32 f = e + 96 + 32 - template copyFrom(T: type, input, a, b): auto = - T.initCopyFrom(input.toOpenArray(a, b)) - let res = Request( requestType: DepositRequestType, deposit: DepositRequest( # PublicKey is the first element. ABI encoding pads values to 32 bytes, # so despite BLS public keys being length 48, the value length # here is 64. Then skip over the next length value. - pubkey: array[48, byte].copyFrom(data, b, b+47), + pubkey: Bytes48.copyFrom(data, b), # WithdrawalCredentials is 32 bytes. Read that value then skip over next # length. - withdrawalCredentials: array[32, byte].copyFrom(data, c, c+31), + withdrawalCredentials: Bytes32.copyFrom(data, c), # Amount is 8 bytes, but it is padded to 32. Skip over it and the next # length. amount: uint64.fromBytesLE(data.toOpenArray(d, d+7)), # Signature is 96 bytes. Skip over it and the next length. - signature: array[96, byte].copyFrom(data, e, e+95), + signature: Bytes96.copyFrom(data, e), # Amount is 8 bytes. index: uint64.fromBytesLE(data.toOpenArray(f, f+7)), diff --git a/nimbus/core/executor/executor_helpers.nim b/nimbus/core/executor/executor_helpers.nim index 1f4aac0ae3..6f8e839736 100644 --- a/nimbus/core/executor/executor_helpers.nim +++ b/nimbus/core/executor/executor_helpers.nim @@ -32,7 +32,7 @@ type func logsBloom(logs: openArray[Log]): LogsBloom = for log in logs: - result.incl log.address + result.incl log.address.to(Bytes32) for topic in log.topics: result.incl topic @@ -44,7 +44,7 @@ func createBloom*(receipts: openArray[Receipt]): Bloom = var bloom: LogsBloom for rec in receipts: bloom.value = bloom.value or logsBloom(rec.logs).value - result = bloom.value.toBytesBE + bloom.value.to(Bloom) proc makeReceipt*(vmState: BaseVMState; txType: TxType): Receipt = @@ -61,7 +61,7 @@ proc makeReceipt*(vmState: BaseVMState; txType: TxType): Receipt = rec.receiptType = txType rec.cumulativeGasUsed = vmState.cumulativeGasUsed rec.logs = vmState.getAndClearLogEntries() - rec.logsBloom = logsBloom(rec.logs).value.toBytesBE + rec.logsBloom = logsBloom(rec.logs).value.to(Bloom) rec # ------------------------------------------------------------------------------ diff --git a/nimbus/core/executor/process_transaction.nim b/nimbus/core/executor/process_transaction.nim index 975a58c806..5bd111da93 100644 --- a/nimbus/core/executor/process_transaction.nim +++ b/nimbus/core/executor/process_transaction.nim @@ -190,11 +190,9 @@ proc processParentBlockHash*(vmState: BaseVMState, prevHash: Hash256): ok() func parseWithdrawalRequest(data: openArray[byte]): WithdrawalRequest = - template copyFrom(T: type, input, a, b): auto = - T.initCopyFrom(input.toOpenArray(a, b)) WithdrawalRequest( - sourceAddress: array[20, byte].copyFrom(data, 0, 19), - validatorPubkey: array[48, byte].copyFrom(data, 20, 20+47), + sourceAddress: Address.copyFrom(data, 0), + validatorPubkey: Bytes48.copyFrom(data, 20), amount: uint64.fromBytesLE(data.toOpenArray(68, 68+7)), ) @@ -223,19 +221,16 @@ proc processDequeueWithdrawalRequests*(vmState: BaseVMState): seq[Request] = statedb.persist(clearEmptyAccount = true) for i in 0..= constants.MAX_PREV_HEADER_DEPTH: - return Hash256() + return default(Hash32) if number >= blockNumber: - return Hash256() + return default(Hash32) c.host.getBlockHash(number) else: let blockNumber = c.vmState.blockNumber ancestorDepth = blockNumber - number - 1 if ancestorDepth >= constants.MAX_PREV_HEADER_DEPTH: - return Hash256() + return default(Hash32) if number >= blockNumber: - return Hash256() + return default(Hash32) c.vmState.getAncestorHash(number) template accountExists*(c: Computation, address: EthAddress): bool = diff --git a/nimbus/evm/interpreter/gas_costs.nim b/nimbus/evm/interpreter/gas_costs.nim index a27fbe27ed..8349c62862 100644 --- a/nimbus/evm/interpreter/gas_costs.nim +++ b/nimbus/evm/interpreter/gas_costs.nim @@ -525,7 +525,7 @@ template gasCosts(fork: EVMFork, prefix, ResultGasCostsName: untyped) = Sha3: memExpansion `prefix gasSha3`, # 30s: Environmental Information - Address: fixed GasBase, + opcodes.Address: fixed GasBase, Balance: fixedOrLater GasBalance, Origin: fixed GasBase, Caller: fixed GasBase, diff --git a/nimbus/evm/interpreter/op_handlers/oph_blockdata.nim b/nimbus/evm/interpreter/op_handlers/oph_blockdata.nim index 91853b8ae7..c52f7db923 100644 --- a/nimbus/evm/interpreter/op_handlers/oph_blockdata.nim +++ b/nimbus/evm/interpreter/op_handlers/oph_blockdata.nim @@ -80,7 +80,7 @@ proc blobHashOp(cpt: VmCpt): EvmResultVoid = len = cpt.getVersionedHashesLen if index < len: - conv(cpt.getVersionedHash(index), top) + conv(cpt.getVersionedHash(index).data, top) else: top = zero(UInt256) diff --git a/nimbus/evm/interpreter/op_handlers/oph_hash.nim b/nimbus/evm/interpreter/op_handlers/oph_hash.nim index 98a84e9be2..c8ca4c9e9b 100644 --- a/nimbus/evm/interpreter/op_handlers/oph_hash.nim +++ b/nimbus/evm/interpreter/op_handlers/oph_hash.nim @@ -50,7 +50,7 @@ proc sha3Op(cpt: VmCpt): EvmResultVoid = if endRange == -1 or pos >= cpt.memory.len: cpt.stack.lsTop(EMPTY_SHA3) else: - cpt.stack.lsTop keccakHash cpt.memory.bytes.toOpenArray(pos, endRange) + cpt.stack.lsTop keccak256 cpt.memory.bytes.toOpenArray(pos, endRange) ok() # ------------------------------------------------------------------------------ diff --git a/nimbus/evm/interpreter/op_handlers/oph_log.nim b/nimbus/evm/interpreter/op_handlers/oph_log.nim index 87b4ad5f3c..d0c8c9f2b0 100644 --- a/nimbus/evm/interpreter/op_handlers/oph_log.nim +++ b/nimbus/evm/interpreter/op_handlers/oph_log.nim @@ -77,7 +77,7 @@ proc logImpl(c: Computation, opcode: Op, topicCount: static int): EvmResultVoid var log: Log log.topics = newSeqOfCap[Topic](topicCount) for i in 0 ..< topicCount: - log.topics.add c.stack.lsPeekTopic(^(i+3)) + log.topics.add Bytes32 c.stack.lsPeekTopic(^(i+3)) assign(log.data, c.memory.read(memPos, len)) log.address = c.msg.contractAddress diff --git a/nimbus/evm/interpreter/utils/utils_numeric.nim b/nimbus/evm/interpreter/utils/utils_numeric.nim index 2ad7d06dc6..499d43747d 100644 --- a/nimbus/evm/interpreter/utils/utils_numeric.nim +++ b/nimbus/evm/interpreter/utils/utils_numeric.nim @@ -96,8 +96,3 @@ func safeInt*(x: UInt256): int {.inline.} = result = x.truncate(int) if x > high(int32).u256 or result < 0: result = high(int32) - -func toInt*(x: EthAddress): int = - type T = uint32 - const len = sizeof(T) - fromBytesBE(T, x.toOpenArray(x.len-len, x.len-1)).int diff --git a/nimbus/evm/precompiles.nim b/nimbus/evm/precompiles.nim index 348f3e23c1..a6e5dd4088 100644 --- a/nimbus/evm/precompiles.nim +++ b/nimbus/evm/precompiles.nim @@ -160,7 +160,7 @@ func ecRecover(c: Computation): EvmResultVoid = return err(prcErr(PrcInvalidSig)) c.output.setLen(32) - assign(c.output.toOpenArray(12, 31), pubkey.toCanonicalAddress()) + assign(c.output.toOpenArray(12, 31), pubkey.toCanonicalAddress().data) ok() func sha256(c: Computation): EvmResultVoid = @@ -714,7 +714,7 @@ iterator activePrecompiles*(fork: EVMFork): EthAddress = let maxPrecompileAddr = getMaxPrecompileAddr(fork) for c in PrecompileAddresses.low..maxPrecompileAddr: if validPrecompileAddr(c.byte, maxPrecompileAddr.byte): - res[^1] = c.byte + res.data[^1] = c.byte yield res func activePrecompilesList*(fork: EVMFork): seq[EthAddress] = @@ -723,10 +723,10 @@ func activePrecompilesList*(fork: EVMFork): seq[EthAddress] = proc execPrecompiles*(c: Computation, fork: EVMFork): bool = for i in 0..18: - if c.msg.codeAddress[i] != 0: + if c.msg.codeAddress.data[i] != 0: return false - let lb = c.msg.codeAddress[19] + let lb = c.msg.codeAddress.data[19] if not validPrecompileAddr(lb, fork): return false diff --git a/nimbus/evm/stack.nim b/nimbus/evm/stack.nim index 76d405d0ee..47f19cb2ce 100644 --- a/nimbus/evm/stack.nim +++ b/nimbus/evm/stack.nim @@ -39,7 +39,7 @@ template toStackElem(v: EvmStackInts, elem: EvmStackElement) = elem = v.u256 template toStackElem(v: EthAddress, elem: EvmStackElement) = - elem.initFromBytesBE(v) + elem.initFromBytesBE(v.data) template toStackElem(v: Hash256, elem: EvmStackElement) = elem.initFromBytesBE(v.data) @@ -52,10 +52,10 @@ template fromStackElem(elem: EvmStackElement, _: type UInt256): UInt256 = elem func fromStackElem(elem: EvmStackElement, _: type EthAddress): EthAddress = - assign(result, elem.toBytesBE().toOpenArray(12, 31)) + elem.to(Bytes32).to(EthAddress) template fromStackElem(elem: EvmStackElement, _: type Hash256): Hash256 = - Hash256(data: elem.toBytesBE()) + Hash32(elem.toBytesBE()) template fromStackElem(elem: EvmStackElement, _: type EvmStackBytes32): EvmStackBytes32 = elem.toBytesBE() diff --git a/nimbus/evm/state.nim b/nimbus/evm/state.nim index 06a6613413..1ff909feb4 100644 --- a/nimbus/evm/state.nim +++ b/nimbus/evm/state.nim @@ -259,9 +259,9 @@ method getAncestorHash*( if db.getBlockHash(blockNumber, blockHash): blockHash else: - Hash256() + default(Hash32) except RlpError: - Hash256() + default(Hash32) proc readOnlyStateDB*(vmState: BaseVMState): ReadOnlyStateDB {.inline.} = ReadOnlyStateDB(vmState.stateDB) diff --git a/nimbus/evm/tracer/access_list_tracer.nim b/nimbus/evm/tracer/access_list_tracer.nim index d7fa0e55d6..42e8328fd8 100644 --- a/nimbus/evm/tracer/access_list_tracer.nim +++ b/nimbus/evm/tracer/access_list_tracer.nim @@ -37,7 +37,7 @@ proc new*(T: type AccessListTracer, if acp.address notin act.excl: act.list.add acp.address for slot in acp.storageKeys: - act.list.add(acp.address, UInt256.fromBytesBE(slot)) + act.list.add(acp.address, slot.to(UInt256)) act diff --git a/nimbus/graphql/ethapi.nim b/nimbus/graphql/ethapi.nim index 533fe3120f..1ab8a6b328 100644 --- a/nimbus/graphql/ethapi.nim +++ b/nimbus/graphql/ethapi.nim @@ -81,7 +81,7 @@ type {.pragma: apiPragma, cdecl, gcsafe, apiRaises.} proc toHash(n: Node): common.Hash256 {.gcsafe, raises: [ValueError].} = - result.data = hexToByteArray[32](n.stringVal) + common.Hash256.fromHex(n.stringVal) proc toBlockNumber(n: Node): common.BlockNumber {.gcsafe, raises: [ValueError].} = if n.kind == nkInt: @@ -529,7 +529,7 @@ proc scalarLong(ctx: GraphqlRef, typeNode, node: Node): NodeResult {.cdecl, gcsa proc accountAddress(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = let acc = AccountNode(parent) - resp(acc.address) + resp(acc.address.data) proc accountBalance(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = let acc = AccountNode(parent) @@ -842,7 +842,7 @@ const txProcs = { proc aclAddress(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = let acl = AclNode(parent) - resp(acl.acl.address) + resp(acl.acl.address.data) proc aclStorageKeys(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = let acl = AclNode(parent) @@ -851,7 +851,7 @@ proc aclStorageKeys(ud: RootRef, params: Args, parent: Node): RespResult {.apiPr else: var list = respList() for n in acl.acl.storageKeys: - list.add resp(n).get() + list.add resp(n.data).get() ok(list) const aclProcs = { @@ -869,7 +869,7 @@ proc wdValidator(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragm proc wdAddress(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = let w = WdNode(parent) - resp(w.wd.address) + resp(w.wd.address.data) proc wdAmount(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = let w = WdNode(parent) @@ -940,7 +940,7 @@ 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.logsBloom) + resp(h.header.logsBloom.data) proc blockMixHash(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = let h = HeaderNode(parent) @@ -1000,7 +1000,7 @@ proc blockAccount(ud: RootRef, params: Args, parent: Node): RespResult {.apiPrag let ctx = GraphqlContextRef(ud) let h = HeaderNode(parent) try: - let address = hexToByteArray[20](params[0].val.stringVal) + let address = EthAddress.fromHex(params[0].val.stringVal) ctx.accountNode(h.header, address) except ValueError as ex: err(ex.msg) @@ -1025,8 +1025,8 @@ 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 = Opt.some(address) + let address = addresses.Address.fromHex(fieldString(n, field)) + dstField = Opt.some(primitives.Address address.data) template optionalGasInt(dstField: untyped, n: Node, field: int) = if isSome(n, field): @@ -1046,7 +1046,7 @@ template optionalBytes(dstField: untyped, n: Node, field: int) = dstField = Opt.some(hexToSeqByte(fieldString(n, field))) proc toTxArgs(n: Node): TransactionArgs {.gcsafe, raises: [ValueError].} = - optionalAddress(result.source, n, fFrom) + optionalAddress(result.`from`, n, fFrom) optionalAddress(result.to, n, fTo) optionalGasInt(result.gas, n, fGasLimit) optionalGasHex(result.gasPrice, n, fGasPrice) @@ -1247,7 +1247,7 @@ proc pickBlockNumber(ctx: GraphqlContextRef, number: Node): common.BlockNumber = proc queryAccount(ud: RootRef, params: Args, parent: Node): RespResult {.apiPragma.} = let ctx = GraphqlContextRef(ud) try: - let address = hexToByteArray[20](params[0].val.stringVal) + let address = EthAddress.fromHex(params[0].val.stringVal) let blockNumber = pickBlockNumber(ctx, params[1].val) let hres = getBlockByNumber(ctx, blockNumber) if hres.isErr: diff --git a/nimbus/nimbus.nim b/nimbus/nimbus.nim index 7f06bef4da..cbc9396a7a 100644 --- a/nimbus/nimbus.nim +++ b/nimbus/nimbus.nim @@ -72,7 +72,7 @@ proc setupP2P(nimbus: NimbusNode, conf: NimbusConf, quit(QuitFailure) let keypair = kpres.get() - var address = Address( + var address = enode.Address( ip: conf.listenAddress, tcpPort: conf.tcpPort, udpPort: conf.udpPort diff --git a/nimbus/rpc/common.nim b/nimbus/rpc/common.nim index 89f4c39d7e..5bfa6caf56 100644 --- a/nimbus/rpc/common.nim +++ b/nimbus/rpc/common.nim @@ -37,7 +37,7 @@ proc setupCommonRpc*(node: EthereumNode, conf: NimbusConf, server: RpcServer) = result = conf.agentString server.rpc("web3_sha3") do(data: seq[byte]) -> Web3Hash: - result = w3Hash(keccakHash(data)) + result = w3Hash(keccak256(data)) server.rpc("net_version") do() -> string: result = $conf.networkId diff --git a/nimbus/rpc/filters.nim b/nimbus/rpc/filters.nim index 10e73b5eeb..43baa8ae3d 100644 --- a/nimbus/rpc/filters.nim +++ b/nimbus/rpc/filters.nim @@ -72,7 +72,7 @@ proc bloomFilter*( addresses: AddressOrList, topics: seq[TopicOrList]): bool = - let bloomFilter = bFilter.BloomFilter(value: StUint[2048].fromBytesBE(bloom)) + let bloomFilter = bFilter.BloomFilter(value: bloom.to(StUint[2048])) if addresses.participateInFilter(): var addrIncluded: bool = false diff --git a/nimbus/rpc/p2p.nim b/nimbus/rpc/p2p.nim index 0873eb6198..a4b020c370 100644 --- a/nimbus/rpc/p2p.nim +++ b/nimbus/rpc/p2p.nim @@ -123,7 +123,7 @@ proc setupEthRpc*( address = data.ethAddr result = accDB.getBalance(address) - server.rpc("eth_getStorageAt") do(data: Web3Address, slot: UInt256, quantityTag: BlockTag) -> FixedBytes[32]: + server.rpc("eth_getStorageAt") do(data: Web3Address, slot: UInt256, quantityTag: BlockTag) -> Web3FixedBytes[32]: ## Returns the value from a storage position at a given address. ## ## data: address of the storage. diff --git a/nimbus/rpc/params.nim b/nimbus/rpc/params.nim index 05142ebcd6..758bc73670 100644 --- a/nimbus/rpc/params.nim +++ b/nimbus/rpc/params.nim @@ -67,7 +67,7 @@ proc toCallParams*(vmState: BaseVMState, args: TransactionArgs, template versionedHashes(args: TransactionArgs): VersionedHashes = if args.blobVersionedHashes.isSome: - ethHashes args.blobVersionedHashes.get + ethVersionedHashes args.blobVersionedHashes.get else: @[] diff --git a/nimbus/rpc/server_api.nim b/nimbus/rpc/server_api.nim index 59f89c1238..b0f9e494fa 100644 --- a/nimbus/rpc/server_api.nim +++ b/nimbus/rpc/server_api.nim @@ -80,7 +80,7 @@ proc setupServerAPI*(api: ServerAPIRef, server: RpcServer) = address = ethAddr data result = ledger.getBalance(address) - server.rpc("eth_getStorageAt") do(data: Web3Address, slot: UInt256, blockTag: BlockTag) -> FixedBytes[32]: + server.rpc("eth_getStorageAt") do(data: Web3Address, slot: UInt256, blockTag: BlockTag) -> Web3FixedBytes[32]: ## Returns the value from a storage position at a given address. let ledger = api.ledgerFromTag(blockTag).valueOr: diff --git a/nimbus/rpc/server_api_helpers.nim b/nimbus/rpc/server_api_helpers.nim index 280c87f89c..f23aea8c54 100644 --- a/nimbus/rpc/server_api_helpers.nim +++ b/nimbus/rpc/server_api_helpers.nim @@ -79,9 +79,9 @@ proc populateBlockObject*(blockHash: eth_types.Hash256, result.number = w3BlockNumber(header.number) result.hash = w3Hash blockHash result.parentHash = w3Hash header.parentHash - result.nonce = Opt.some(FixedBytes[8] header.nonce) + result.nonce = Opt.some(Web3FixedBytes[8] header.nonce) result.sha3Uncles = w3Hash header.ommersHash - result.logsBloom = FixedBytes[256] header.logsBloom + result.logsBloom = Web3FixedBytes[256] header.logsBloom result.transactionsRoot = w3Hash header.txRoot result.stateRoot = w3Hash header.stateRoot result.receiptsRoot = w3Hash header.receiptsRoot diff --git a/nimbus/stateless/multi_keys.nim b/nimbus/stateless/multi_keys.nim index 9cd49f8dfd..a55aeeaac9 100644 --- a/nimbus/stateless/multi_keys.nim +++ b/nimbus/stateless/multi_keys.nim @@ -83,7 +83,7 @@ proc newMultiKeys*(keys: openArray[AccountKey]): MultiKeysRef = for i, a in keys: result.keys[i] = KeyData( storageMode: false, - hash: keccakHash(a.address).data, + hash: keccak256(a.address.data).data, address: a.address, codeTouched: a.codeTouched, storageKeys: a.storageKeys) @@ -93,20 +93,20 @@ proc newMultiKeys*(keys: openArray[StorageSlot]): MultiKeysRef = result = new MultiKeysRef result.keys = newSeq[KeyData](keys.len) for i, a in keys: - result.keys[i] = KeyData(storageMode: true, hash: keccakHash(a).data, storageSlot: a) + result.keys[i] = KeyData(storageMode: true, hash: keccak256(a).data, storageSlot: a) result.keys.sort(cmpHash) # never mix storageMode! proc add*(m: MultiKeysRef, address: EthAddress, codeTouched: bool, storageKeys = MultiKeysRef(nil)) = m.keys.add KeyData( storageMode: false, - hash: keccakHash(address).data, + hash: keccak256(address.data).data, address: address, codeTouched: codeTouched, storageKeys: storageKeys) proc add*(m: MultiKeysRef, slot: StorageSlot) = - m.keys.add KeyData(storageMode: true, hash: keccakHash(slot).data, storageSlot: slot) + m.keys.add KeyData(storageMode: true, hash: keccak256(slot).data, storageSlot: slot) proc sort*(m: MultiKeysRef) = m.keys.sort(cmpHash) diff --git a/nimbus/sync/beacon/beacon_impl.nim b/nimbus/sync/beacon/beacon_impl.nim index 18691d0cf9..d931da9faf 100644 --- a/nimbus/sync/beacon/beacon_impl.nim +++ b/nimbus/sync/beacon/beacon_impl.nim @@ -52,7 +52,7 @@ func makeGetBlocksJob(number, maxResults: uint64) : BeaconJob = func makeHeaderRequest(number: uint64, maxResults: uint64): BlocksRequest = BlocksRequest( - startBlock: HashOrNum(isHash: false, number: number), + startBlock: BlockHashOrNumber(isHash: false, number: number), maxResults: maxResults.uint, skip: 0, reverse: true diff --git a/nimbus/sync/beacon/skeleton_utils.nim b/nimbus/sync/beacon/skeleton_utils.nim index f08361d6d2..9c729f54f2 100644 --- a/nimbus/sync/beacon/skeleton_utils.nim +++ b/nimbus/sync/beacon/skeleton_utils.nim @@ -19,7 +19,7 @@ logScope: const # How often to log sync status (in ms) STATUS_LOG_INTERVAL* = initDuration(microseconds = 8000) - zeroBlockHash* = Hash256() + zeroBlockHash* = default(Hash32) # ------------------------------------------------------------------------------ # Misc helpers diff --git a/nimbus/sync/flare/worker/db.nim b/nimbus/sync/flare/worker/db.nim index 0afad6642c..03592913ef 100644 --- a/nimbus/sync/flare/worker/db.nim +++ b/nimbus/sync/flare/worker/db.nim @@ -99,7 +99,7 @@ proc fetchEra1State(ctx: FlareCtxRef): Opt[SavedDbStateSpecs] = if 0 < val.number: let header = ctx.pool.e1db.getEthBlock(val.number).value.header val.parent = header.parentHash - val.hash = rlp.encode(header).keccakHash + val.hash = rlp.encode(header).keccak256 return ok(val) err() diff --git a/nimbus/sync/flare/worker/staged/headers.nim b/nimbus/sync/flare/worker/staged/headers.nim index a921ab5da8..767c7c6405 100644 --- a/nimbus/sync/flare/worker/staged/headers.nim +++ b/nimbus/sync/flare/worker/staged/headers.nim @@ -81,7 +81,7 @@ proc headersFetchReversed*( maxResults: ivReq.len.uint, skip: 0, reverse: true, - startBlock: HashOrNum( + startBlock: BlockHashOrNumber( isHash: true, hash: topHash)) else: @@ -89,7 +89,7 @@ proc headersFetchReversed*( maxResults: ivReq.len.uint, skip: 0, reverse: true, - startBlock: HashOrNum( + startBlock: BlockHashOrNumber( isHash: false, number: ivReq.maxPt)) start = Moment.now() diff --git a/nimbus/sync/flare/worker/staged/linked_hchain.nim b/nimbus/sync/flare/worker/staged/linked_hchain.nim index ddfb3bf99a..4cbae4e972 100644 --- a/nimbus/sync/flare/worker/staged/linked_hchain.nim +++ b/nimbus/sync/flare/worker/staged/linked_hchain.nim @@ -48,14 +48,14 @@ when verifyDataStructureOk: var topHdr, childHdr: BlockHeader try: - doAssert lhc.revHdrs[0].keccakHash == lhc.hash + doAssert lhc.revHdrs[0].keccak256 == lhc.hash topHdr = rlp.decode(lhc.revHdrs[0], BlockHeader) childHdr = topHdr for n in 1 ..< lhc.revHdrs.len: let header = rlp.decode(lhc.revHdrs[n], BlockHeader) doAssert childHdr.number == header.number + 1 - doAssert lhc.revHdrs[n].keccakHash == childHdr.parentHash + doAssert lhc.revHdrs[n].keccak256 == childHdr.parentHash childHdr = header doAssert childHdr.parentHash == lhc.parentHash @@ -96,7 +96,7 @@ proc extendLinkedHChain*( # Set up header with largest block number let blob0 = rlp.encode(rev[0]) - hash0 = blob0.keccakHash + hash0 = blob0.keccak256 lhc.revHdrs[offset] = blob0 if offset == 0: lhc.hash = hash0 @@ -118,7 +118,7 @@ proc extendLinkedHChain*( return false lhc.revHdrs[offset + n] = rlp.encode(rev[n]) - let hashN = lhc.revHdrs[offset + n].keccakHash + let hashN = lhc.revHdrs[offset + n].keccak256 if rev[n-1].parentHash != hashN: when extraTraceMessages: trace info & ": hash mismatch", peer, n, diff --git a/nimbus/sync/flare/worker/update.nim b/nimbus/sync/flare/worker/update.nim index 5978721dc0..d5f02d18c9 100644 --- a/nimbus/sync/flare/worker/update.nim +++ b/nimbus/sync/flare/worker/update.nim @@ -79,7 +79,7 @@ proc updateBeaconChange(ctx: FlareCtxRef): bool = least: z, leastParent: ctx.lhc.beacon.header.parentHash, final: z, - finalHash: rlpHeader.keccakHash) + finalHash: rlpHeader.keccak256) # Save this header on the database so it needs not be fetched again from # somewhere else. diff --git a/nimbus/sync/handlers/eth.nim b/nimbus/sync/handlers/eth.nim index 4effc1f008..3bf9491c65 100644 --- a/nimbus/sync/handlers/eth.nim +++ b/nimbus/sync/handlers/eth.nim @@ -73,7 +73,7 @@ proc ancestorHeader(db: CoreDbRef, result = db.getBlockHeader(h.number - offset, output) proc blockHeader(db: CoreDbRef, - b: HashOrNum, + b: BlockHashOrNumber, output: var BlockHeader): bool = if b.isHash: db.getBlockHeader(b.hash, output) diff --git a/nimbus/sync/types.nim b/nimbus/sync/types.nim index d8f8aa3d57..2ae2562239 100644 --- a/nimbus/sync/types.nim +++ b/nimbus/sync/types.nim @@ -24,7 +24,7 @@ type ## underlying `Hash256` type which needs to be converted to `BlockHash`. BlocksRequest* = object - startBlock*: HashOrNum + startBlock*: BlockHashOrNumber maxResults*, skip*: uint reverse*: bool @@ -33,7 +33,7 @@ type # ------------------------------------------------------------------------------ proc new*(T: type BlockHash): T = - Hash256().T + default(Hash32).T # ------------------------------------------------------------------------------ # Public (probably non-trivial) type conversions @@ -61,8 +61,8 @@ proc to*(w: seq[BlockHash]; T: type seq[Hash256]): T = ## Ditto cast[seq[Hash256]](w) -proc to*(bh: BlockHash; T: type HashOrNum): T = - ## Convert argument blocj hash `bh` to `HashOrNum` +proc to*(bh: BlockHash; T: type BlockHashOrNumber): T = + ## Convert argument blocj hash `bh` to `BlockHashOrNumber` T(isHash: true, hash: bh.Hash256) # ------------------------------------------------------------------------------ @@ -102,7 +102,7 @@ func `$`*(h: BlockHash): string = func `$`*(blob: Blob): string = blob.toHex -func `$`*(hashOrNum: HashOrNum): string = +func `$`*(hashOrNum: BlockHashOrNumber): string = # It's always obvious which one from the visible length of the string. if hashOrNum.isHash: $hashOrNum.hash else: $hashOrNum.number diff --git a/nimbus/transaction/call_common.nim b/nimbus/transaction/call_common.nim index 5e152e99e5..2b0a9761f4 100644 --- a/nimbus/transaction/call_common.nim +++ b/nimbus/transaction/call_common.nim @@ -130,7 +130,7 @@ proc initialAccessListEIP2929(call: CallParams) = for account in call.accessList: db.accessList(account.address) for key in account.storageKeys: - db.accessList(account.address, UInt256.fromBytesBE(key)) + db.accessList(account.address, key.to(UInt256)) proc setupHost(call: CallParams): TransactionHost = let vmState = call.vmState diff --git a/nimbus/utils/debug.nim b/nimbus/utils/debug.nim index 252ea35149..778e450456 100644 --- a/nimbus/utils/debug.nim +++ b/nimbus/utils/debug.nim @@ -156,7 +156,7 @@ proc debugSum*(h: BlockHeader): string = result.add "sumHash : " & $sumHash(h) & "\n" proc debugSum*(body: BlockBody): string = - let ommersHash = keccakHash(rlp.encode(body.uncles)) + let ommersHash = keccak256(rlp.encode(body.uncles)) let txRoot = calcTxRoot(body.transactions) let wdRoot = if body.withdrawals.isSome: calcWithdrawalsRoot(body.withdrawals.get) diff --git a/nimbus/utils/ec_recover.nim b/nimbus/utils/ec_recover.nim index 1bc57b08d3..3c90c0f17d 100644 --- a/nimbus/utils/ec_recover.nim +++ b/nimbus/utils/ec_recover.nim @@ -79,7 +79,7 @@ proc encodePreSealed(header: BlockHeader): seq[byte] = proc hashPreSealed(header: BlockHeader): Hash256 = ## Returns the hash of a block prior to it being sealed. - keccakHash header.encodePreSealed + keccak256 header.encodePreSealed proc recoverImpl(rawSig: openArray[byte]; msg: Hash256): EcAddrResult = diff --git a/nimbus/utils/era_helpers.nim b/nimbus/utils/era_helpers.nim index 13070268c4..122292a92c 100644 --- a/nimbus/utils/era_helpers.nim +++ b/nimbus/utils/era_helpers.nim @@ -146,17 +146,17 @@ proc getEthBlock(blck: ForkyTrustedBeaconBlock): Opt[EthBlock] = Opt.none(uint64) parentBeaconBlockRoot = when consensusFork >= ConsensusFork.Deneb: - Opt.some(blck.parent_root) + Opt.some(common.Hash32(blck.parent_root.data)) else: - Opt.none(common.Hash256) + Opt.none(common.Hash32) header = BlockHeader( - parentHash: payload.parent_hash, + parentHash: Hash32(payload.parent_hash.data), ommersHash: EMPTY_UNCLE_HASH, coinbase: EthAddress(payload.fee_recipient.data), - stateRoot: payload.state_root, - txRoot: calcTxRoot(txs), - receiptsRoot: payload.receipts_root, + stateRoot: Root(payload.state_root.data), + transactionsRoot: calcTxRoot(txs), + receiptsRoot: Root(payload.receipts_root.data), logsBloom: BloomFilter(payload.logs_bloom.data), difficulty: 0.u256, number: payload.block_number, @@ -164,7 +164,7 @@ proc getEthBlock(blck: ForkyTrustedBeaconBlock): Opt[EthBlock] = gasUsed: GasInt(payload.gas_used), timestamp: EthTime(payload.timestamp), extraData: payload.extra_data.asSeq(), - mixHash: payload.prev_randao, + mixHash: Hash32(payload.prev_randao.data), nonce: default(BlockNonce), baseFeePerGas: Opt.some(payload.base_fee_per_gas), withdrawalsRoot: withdrawalRoot, diff --git a/nimbus/utils/state_dump.nim b/nimbus/utils/state_dump.nim index cd3c085076..0993c4af2f 100644 --- a/nimbus/utils/state_dump.nim +++ b/nimbus/utils/state_dump.nim @@ -76,7 +76,7 @@ proc dumpAccount*(db: LedgerRef, acc: EthAddress): DumpAccount = root : db.getStorageRoot(acc), codeHash: db.getCodeHash(acc), code : db.getCode(acc).bytes(), - key : keccakHash(acc) + key : keccak256(acc) ) for k, v in db.cachedStorage(acc): result.storage[k] = v diff --git a/nimbus/utils/utils.nim b/nimbus/utils/utils.nim index 02dd11558c..53afc9cb37 100644 --- a/nimbus/utils/utils.nim +++ b/nimbus/utils/utils.nim @@ -38,7 +38,7 @@ template calcReceiptsRoot*(receipts: openArray[Receipt]): Hash256 = template calcRequestsRoot*(requests: openArray[Request]): Hash256 = calcRootHash(requests) - + func sumHash*(hashes: varargs[Hash256]): Hash256 = var ctx: sha256 ctx.init() @@ -49,7 +49,7 @@ func sumHash*(hashes: varargs[Hash256]): Hash256 = proc sumHash*(body: BlockBody): Hash256 {.gcsafe, raises: []} = let txRoot = calcTxRoot(body.transactions) - let ommersHash = keccakHash(rlp.encode(body.uncles)) + let ommersHash = keccak256(rlp.encode(body.uncles)) let wdRoot = if body.withdrawals.isSome: calcWithdrawalsRoot(body.withdrawals.get) else: EMPTY_ROOT_HASH @@ -67,7 +67,7 @@ func hasBody*(h: BlockHeader): bool = h.withdrawalsRoot.get(EMPTY_ROOT_HASH) != EMPTY_ROOT_HASH func generateAddress*(address: EthAddress, nonce: AccountNonce): EthAddress = - result[0..19] = keccakHash(rlp.encodeList(address, nonce)).data.toOpenArray(12, 31) + result.data[0..19] = keccak256(rlp.encodeList(address, nonce)).data.toOpenArray(12, 31) type ContractSalt* = object bytes*: array[32, byte] @@ -78,14 +78,14 @@ func generateSafeAddress*(address: EthAddress, salt: ContractSalt, data: openArray[byte]): EthAddress = const prefix = [0xff.byte] let - dataHash = keccakHash(data) - hashResult = withKeccakHash: + dataHash = keccak256(data) + hashResult = withKeccak256: h.update(prefix) - h.update(address) + h.update(address.data) h.update(salt.bytes) h.update(dataHash.data) - result[0..19] = hashResult.data.toOpenArray(12, 31) + hashResult.to(Address) proc crc32*(crc: uint32, buf: openArray[byte]): uint32 = const kcrc32 = [ 0'u32, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, diff --git a/nimbus_verified_proxy/rpc/rpc_utils.nim b/nimbus_verified_proxy/rpc/rpc_utils.nim index 3704dcde6b..2eb8b29bb2 100644 --- a/nimbus_verified_proxy/rpc/rpc_utils.nim +++ b/nimbus_verified_proxy/rpc/rpc_utils.nim @@ -77,7 +77,7 @@ func toFixedBytes(d: MDigest[256]): FixedBytes[32] = FixedBytes[32](d.data) template asEthHash(hash: BlockHash): etypes.Hash256 = - etypes.Hash256(data: distinctBase(hash)) + etypes.Hash32(distinctBase(hash)) proc calculateTransactionData( items: openArray[TypedTransaction] @@ -93,7 +93,7 @@ proc calculateTransactionData( let tx = distinctBase(t) txSize = txSize + uint64(len(tx)) tr.merge(rlp.encode(i), tx).expect "merge data" - txHashes.add(txOrHash toFixedBytes(keccakHash(tx))) + txHashes.add(txOrHash toFixedBytes(keccak256(tx))) let rootHash = tr.state(updateOk = true).expect "hash" (rootHash, txHashes, txSize) diff --git a/nimbus_verified_proxy/validate_proof.nim b/nimbus_verified_proxy/validate_proof.nim index 887c3c6655..f8680866e9 100644 --- a/nimbus_verified_proxy/validate_proof.nim +++ b/nimbus_verified_proxy/validate_proof.nim @@ -60,7 +60,7 @@ proc getAccountFromProof*( codeHash: toMDigest(accountCodeHash), ) accountEncoded = rlp.encode(acc) - accountKey = toSeq(keccakHash(distinctBase(accountAddress)).data) + accountKey = toSeq(keccak256(distinctBase(accountAddress)).data) let proofResult = verifyMptProof(mptNodesBytes, keccakStateRootHash, accountKey, accountEncoded) @@ -78,7 +78,7 @@ proc getStorageData( ): Result[UInt256, string] = let storageMptNodes = storageProof.proof.mapIt(distinctBase(it)) - key = toSeq(keccakHash(toBytesBE(storageProof.key)).data) + key = toSeq(keccak256(toBytesBE(storageProof.key)).data) encodedValue = rlp.encode(storageProof.value) proofResult = verifyMptProof(storageMptNodes, account.storageRoot, key, encodedValue) @@ -119,4 +119,4 @@ proc getStorageData*( return getStorageData(account, sproof) func isValidCode*(account: etypes.Account, code: openArray[byte]): bool = - return account.codeHash == keccakHash(code) + return account.codeHash == keccak256(code) diff --git a/premix/no-hunter.nim b/premix/no-hunter.nim index bc34777681..6a553c4e68 100644 --- a/premix/no-hunter.nim +++ b/premix/no-hunter.nim @@ -26,7 +26,7 @@ const proc store(memoryDB: CoreDbRef, branch: JsonNode) = for p in branch: let rlp = hexToSeqByte(p.getStr) - let hash = keccakHash(rlp) + let hash = keccak256(rlp) memoryDB.kvt.put(hash.data, rlp) proc parseAddress(address: string): EthAddress = diff --git a/tests/macro_assembler.nim b/tests/macro_assembler.nim index b936aac7d8..059f980929 100644 --- a/tests/macro_assembler.nim +++ b/tests/macro_assembler.nim @@ -328,12 +328,12 @@ proc verifyAsmResult(vmState: BaseVMState, boa: Assembler, asmResult: CallResult let al = com.db.ctx.getAccounts() - accPath = codeAddress.keccakHash + accPath = codeAddress.keccak256 for kv in boa.storage: let key = kv[0].toHex() let val = kv[1].toHex() - let slotKey = UInt256.fromBytesBE(kv[0]).toBytesBE.keccakHash + let slotKey = UInt256.fromBytesBE(kv[0]).toBytesBE.keccak256 let data = al.slotFetch(accPath, slotKey).valueOr: default(UInt256) let actual = data.toBytesBE().toHex if val != actual: diff --git a/tests/replay/pp_light.nim b/tests/replay/pp_light.nim index 42d2f15cfa..e958b3ac79 100644 --- a/tests/replay/pp_light.nim +++ b/tests/replay/pp_light.nim @@ -146,7 +146,7 @@ func pp*(q: openArray[byte]; noHash = false): string = if q.len == 32 and not noHash: var a: array[32,byte] for n in 0..31: a[n] = q[n] - Hash256(data: a).pp + Hash32(a).pp else: q.toHex.pp(hex = true) diff --git a/tests/test_aristo/test_helpers.nim b/tests/test_aristo/test_helpers.nim index 3a1b6e039c..0e93ba7499 100644 --- a/tests/test_aristo/test_helpers.nim +++ b/tests/test_aristo/test_helpers.nim @@ -155,7 +155,7 @@ proc to*(sample: AccountsSample; T: type seq[UndumpStorages]): T = result.add w func to*(ua: seq[UndumpAccounts]; T: type seq[ProofTrieData]): T = - var (rootKey, rootVid) = (Hash256(), VertexID(0)) + var (rootKey, rootVid) = (default(Hash32), VertexID(0)) for w in ua: let thisRoot = w.root if rootKey != thisRoot: @@ -171,7 +171,7 @@ func to*(ua: seq[UndumpAccounts]; T: type seq[ProofTrieData]): T = payload: LeafPayload(pType: RawData, rawBlob: it.accBlob)))) func to*(us: seq[UndumpStorages]; T: type seq[ProofTrieData]): T = - var (rootKey, rootVid) = (Hash256(), VertexID(0)) + var (rootKey, rootVid) = (default(Hash32), VertexID(0)) for n,s in us: for w in s.data.storages: let thisRoot = w.account.storageRoot @@ -216,7 +216,7 @@ proc schedStow*( db.stow() # ------------------ - + proc mergeGenericData*( db: AristoDbRef; # Database, top layer leaf: LeafTiePayload; # Leaf item to add to the database diff --git a/tests/test_aristo/test_portal_proof.nim b/tests/test_aristo/test_portal_proof.nim index cf668a8ce3..72860ef9f7 100644 --- a/tests/test_aristo/test_portal_proof.nim +++ b/tests/test_aristo/test_portal_proof.nim @@ -60,7 +60,7 @@ proc preLoadAristoDb(jKvp: JsonNode): PartStateRef = key = hexToSeqByte(k) val = hexToSeqByte(v.getStr()) if key.len == 32: - doAssert key == val.keccakHash.data + doAssert key == val.keccak256.data if val != @[0x80u8]: # Exclude empty item proof.add val @@ -149,7 +149,7 @@ proc testCreatePortalProof(node: JsonNode, testStatusIMPL: var TestStatus) = var sample: Table[Hash256,ProofData] for a in addresses: let - path = a.keccakHash + path = a.keccak256 var hike: Hike let rc = path.hikeUp(VertexID(1), ps.db, Opt.none(VertexRef), hike) sample[path] = ProofData( diff --git a/tests/test_beacon/setup_env.nim b/tests/test_beacon/setup_env.nim index e517d6204b..9d9fb87ba5 100644 --- a/tests/test_beacon/setup_env.nim +++ b/tests/test_beacon/setup_env.nim @@ -102,12 +102,12 @@ func header*(com: CommonRef, bn: uint64, temp, parent: BlockHeader): BlockHeader func header*(bn: uint64, temp, parent: BlockHeader, diff: uint64, stateRoot: string): BlockHeader = result = header(bn, temp, parent, diff) - result.stateRoot = Hash256(data: hextoByteArray[32](stateRoot)) + result.stateRoot = Hash32(hextoByteArray[32](stateRoot)) func header*(com: CommonRef, bn: uint64, temp, parent: BlockHeader, stateRoot: string): BlockHeader = result = com.header(bn, temp, parent) - result.stateRoot = Hash256(data: hextoByteArray[32](stateRoot)) + result.stateRoot = Hash32(hextoByteArray[32](stateRoot)) func emptyBody*(): BlockBody = BlockBody( diff --git a/tests/test_beacon/test_1_initsync.nim b/tests/test_beacon/test_1_initsync.nim index 3c69028fd2..ae6aa4d8eb 100644 --- a/tests/test_beacon/test_1_initsync.nim +++ b/tests/test_beacon/test_1_initsync.nim @@ -185,7 +185,7 @@ proc test1*() = skel.putHeader(header) for x in z.oldState: - skel.push(x.head, x.tail, Hash256()) + skel.push(x.head, x.tail, default(Hash32)) let r = skel.initSync(z.head).valueOr: debugEcho "initSync: ", error diff --git a/tests/test_blockchain_json.nim b/tests/test_blockchain_json.nim index f06dea036f..03df47f521 100644 --- a/tests/test_blockchain_json.nim +++ b/tests/test_blockchain_json.nim @@ -54,7 +54,7 @@ proc parseEnv(node: JsonNode): TestEnv = result.blocks = parseBlocks(node["blocks"]) let genesisRLP = hexToSeqByte(node["genesisRLP"].getStr) result.genesisHeader = rlp.decode(genesisRLP, EthBlock).header - result.lastBlockHash = Hash256(data: hexToByteArray[32](node["lastblockhash"].getStr)) + result.lastBlockHash = Hash32(hexToByteArray[32](node["lastblockhash"].getStr)) result.network = node["network"].getStr result.pre = node["pre"] diff --git a/tests/test_generalstate_json.nim b/tests/test_generalstate_json.nim index 098fe7dd05..b297228b75 100644 --- a/tests/test_generalstate_json.nim +++ b/tests/test_generalstate_json.nim @@ -48,13 +48,13 @@ proc toBytes(x: string): seq[byte] = method getAncestorHash*(vmState: BaseVMState; blockNumber: BlockNumber): Hash256 = if blockNumber >= vmState.blockNumber: - return Hash256() + return default(Hash32) elif blockNumber < 0: - return Hash256() + return default(Hash32) elif blockNumber < vmState.blockNumber - 256: - return Hash256() + return default(Hash32) else: - return keccakHash(toBytes($blockNumber)) + return keccak256(toBytes($blockNumber)) func normalizeFileName(x: string): string = const invalidChars = ['/', '\\', '?', '%', '*', ':', '|', '"', '<', '>', ',', ';', '='] diff --git a/tests/test_getproof_json.nim b/tests/test_getproof_json.nim index db8b5654a8..0a5ffffdc6 100644 --- a/tests/test_getproof_json.nim +++ b/tests/test_getproof_json.nim @@ -30,7 +30,7 @@ template toHash256(hash: untyped): Hash256 = proc verifyAccountProof(trustedStateRoot: Hash256, res: ProofResponse): MptProofVerificationResult = let - key = toSeq(keccakHash(res.address.ethAddr).data) + key = toSeq(keccak256(res.address.ethAddr).data) value = rlp.encode(Account( nonce: res.nonce.uint64, balance: res.balance, @@ -45,7 +45,7 @@ proc verifyAccountProof(trustedStateRoot: Hash256, res: ProofResponse): MptProof proc verifySlotProof(trustedStorageRoot: Hash256, slot: StorageProof): MptProofVerificationResult = let - key = toSeq(keccakHash(toBytesBE(slot.key)).data) + key = toSeq(keccak256(toBytesBE(slot.key)).data) value = rlp.encode(slot.value) verifyMptProof( diff --git a/tests/test_ledger.nim b/tests/test_ledger.nim index d9482e906f..d1520ceefe 100644 --- a/tests/test_ledger.nim +++ b/tests/test_ledger.nim @@ -518,7 +518,7 @@ proc runLedgerBasicOperationsTests() = ac.persist() check ac.getCode(addr2) == code let - key = contractHashKey(keccakHash(code)) + key = contractHashKey(keccak256(code)) val = memDB.ctx.getKvt().get(key.toOpenArray).valueOr: EmptyBlob check val == code diff --git a/tests/test_rpc.nim b/tests/test_rpc.nim index b721fced03..81d784e344 100644 --- a/tests/test_rpc.nim +++ b/tests/test_rpc.nim @@ -58,7 +58,7 @@ func emptyStorageHash(): Web3Hash = proc verifyAccountProof(trustedStateRoot: Web3Hash, res: ProofResponse): MptProofVerificationResult = let - key = toSeq(keccakHash(res.address.ethAddr).data) + key = toSeq(keccak256(res.address.ethAddr).data) value = rlp.encode(Account( nonce: res.nonce.uint64, balance: res.balance, @@ -73,7 +73,7 @@ proc verifyAccountProof(trustedStateRoot: Web3Hash, res: ProofResponse): MptProo proc verifySlotProof(trustedStorageRoot: Web3Hash, slot: StorageProof): MptProofVerificationResult = let - key = toSeq(keccakHash(toBytesBE(slot.key)).data) + key = toSeq(keccak256(toBytesBE(slot.key)).data) value = rlp.encode(slot.value) verifyMptProof( @@ -263,7 +263,7 @@ proc rpcMain*() = test "web3_sha3": let data = @(NimbusName.toOpenArrayByte(0, NimbusName.len-1)) let res = await client.web3_sha3(data) - let hash = keccakHash(data) + let hash = keccak256(data) check hash == ethHash res test "net_version": diff --git a/tests/test_tracer_json.nim b/tests/test_tracer_json.nim index 975d0059e5..4efeaea70c 100644 --- a/tests/test_tracer_json.nim +++ b/tests/test_tracer_json.nim @@ -46,7 +46,7 @@ proc preLoadAristoDb(cdb: CoreDbRef; jKvp: JsonNode; num: BlockNumber) = key = hexToSeqByte(k) val = hexToSeqByte(v.getStr()) if key.len == 32: - doAssert key == val.keccakHash.data + doAssert key == val.keccak256.data if val != @[0x80u8]: # Exclude empty item proof.add val else: diff --git a/tests/test_transaction_json.nim b/tests/test_transaction_json.nim index 49e411ac81..8cb657b04e 100644 --- a/tests/test_transaction_json.nim +++ b/tests/test_transaction_json.nim @@ -29,7 +29,7 @@ when isMainModule: transactionJsonMain() proc txHash(tx: Transaction): string = - toLowerAscii($keccakHash(rlp.encode(tx))) + toLowerAscii($keccak256(rlp.encode(tx))) proc testTxByFork(tx: Transaction, forkData: JsonNode, forkName: string, testStatusIMPL: var TestStatus) = try: diff --git a/tests/test_txpool/sign_helper.nim b/tests/test_txpool/sign_helper.nim index 3b864c33ab..daeda175d0 100644 --- a/tests/test_txpool/sign_helper.nim +++ b/tests/test_txpool/sign_helper.nim @@ -93,7 +93,7 @@ proc signerFunc*(signer: EthAddress, msg: openArray[byte]): Result[array[RawSignatureSize, byte], cstring] {.gcsafe.} = doAssert(signer == testAddress) let - data = keccakHash(msg) + data = keccak256(msg) rawSign = sign(prvTestKey, SkMessage(data.data)).toRaw ok(rawSign) diff --git a/tests/test_txpool2.nim b/tests/test_txpool2.nim index 51473904f2..2e75b8a058 100644 --- a/tests/test_txpool2.nim +++ b/tests/test_txpool2.nim @@ -173,7 +173,7 @@ proc runTxPoolPosTest() = test "validate TxPool prevRandao setter": var sdb = LedgerRef.init(com.db, blk.header.stateRoot) let val = sdb.getStorage(recipient, slot) - let randao = Hash256(data: val.toBytesBE) + let randao = Hash32(val.toBytesBE) check randao == prevRandao test "feeRecipient rewarded": @@ -238,7 +238,7 @@ proc runTxPoolBlobhashTest() = test "validate TxPool prevRandao setter": var sdb = LedgerRef.init(com.db, blk.header.stateRoot) let val = sdb.getStorage(recipient, slot) - let randao = Hash256(data: val.toBytesBE) + let randao = Hash32(val.toBytesBE) check randao == prevRandao test "feeRecipient rewarded": diff --git a/tools/evmstate/evmstate.nim b/tools/evmstate/evmstate.nim index 3428558bbe..b9e6d924c4 100644 --- a/tools/evmstate/evmstate.nim +++ b/tools/evmstate/evmstate.nim @@ -65,10 +65,10 @@ proc toBytes(x: string): seq[byte] = for i in 0..