Skip to content

Commit

Permalink
init style for Hash256 (#2661)
Browse files Browse the repository at this point in the history
* init style for Hash256

status-im/nim-eth#733 updates `Hash256` to
become an array instead of an object - unfortunately, nim does not allow
constructing arrays with `name()`, so this PR changes it to `default`
which works with both.

* lint
  • Loading branch information
arnetheduck authored Sep 26, 2024
1 parent b0a4a9e commit f3e3c6b
Show file tree
Hide file tree
Showing 22 changed files with 59 additions and 59 deletions.
12 changes: 6 additions & 6 deletions hive_integration/nodocker/engine/cancun_tests.nim
Original file line number Diff line number Diff line change
Expand Up @@ -527,7 +527,7 @@ let cancunTestListA* = [
testSequence: @[
NewPayloads(
fcUOnPayloadRequest: UpgradeForkchoiceUpdatedVersion(
beaconRoot: Opt.some(common.Hash256()),
beaconRoot: Opt.some(default(common.Hash256)),
expectedError: engineApiUnsupportedFork,
),
expectationDescription: """
Expand Down Expand Up @@ -555,7 +555,7 @@ let cancunTestListA* = [
testSequence: @[
NewPayloads(
fcUOnPayloadRequest: BaseForkchoiceUpdatedCustomizer(
beaconRoot: Opt.some(common.Hash256()),
beaconRoot: Opt.some(default(common.Hash256)),
expectedError: engineApiInvalidPayloadAttributes,
),
expectationDescription: """
Expand Down Expand Up @@ -583,7 +583,7 @@ let cancunTestListA* = [
testSequence: @[
NewPayloads(
fcUOnPayloadRequest: DowngradeForkchoiceUpdatedVersion(
beaconRoot: Opt.some(common.Hash256()),
beaconRoot: Opt.some(default(common.Hash256)),
expectedError: engineApiInvalidPayloadAttributes,
),
expectationDescription: """
Expand Down Expand Up @@ -641,7 +641,7 @@ let cancunTestListA* = [
NewPayloads(
expectedIncludedBlobCount: MAX_BLOBS_PER_BLOCK,
fcUOnPayloadRequest: BaseForkchoiceUpdatedCustomizer(
beaconRoot: Opt.some(common.Hash256()),
beaconRoot: Opt.some(default(common.Hash256)),
),
),
SendBlobTransactions(
Expand Down Expand Up @@ -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.Hash256)),
versionedHashesCustomizer: VersionedHashesCustomizer(
blobs: Opt.some(newSeq[BlobID]()),
),
Expand Down Expand Up @@ -1673,7 +1673,7 @@ let cancunTestListA* = [
NewPayloads(
newPayloadCustomizer: UpgradeNewPayloadVersion(
payloadCustomizer: CustomPayloadData(
parentBeaconRoot: some(common.Hash256()),
parentBeaconRoot: some(default(common.Hash256)),
),
expectedError: engineApiInvalidParams,
),
Expand Down
2 changes: 1 addition & 1 deletion hive_integration/nodocker/engine/clmock.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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.Hash256)
let latestValidHash = s.latestValidHash.get(nullHash)
if s.latestValidHash.isSome and latestValidHash != nullHash:
error "CLMocker: NewPayload returned ACCEPTED status with incorrect LatestValidHash",
Expand Down
4 changes: 2 additions & 2 deletions hive_integration/nodocker/engine/engine/invalid_payload.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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.Hash256)),
suggestedFeerecipient: Opt.some(ZeroAddr),
)
payloadAttributes = customizer.getPayloadAttributes(env.clMock.latestPayloadAttributes)
Expand All @@ -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.Hash256))
src.versionedHashes = Opt.some(collectBlobHashes(basePayload.transactions))

inv_p = env.generateInvalidPayload(src, InvalidStateRoot)
Expand Down
4 changes: 2 additions & 2 deletions hive_integration/nodocker/pyspec/pyspec_sim.nim
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ proc runTest(node: JsonNode, network: string): TestStatus =

let blks = node["blocks"]
var
latestValidHash = common.Hash256()
latestValidHash = default(common.Hash256)
latestVersion: Version

result = TestStatus.OK
Expand Down Expand Up @@ -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.Hash256):
# update with latest valid response
let fcState = ForkchoiceStateV1(headBlockHash: BlockHash latestValidHash.data)
let res = env.rpcClient.forkchoiceUpdated(latestVersion, fcState)
Expand Down
4 changes: 2 additions & 2 deletions nimbus/beacon/api_handler/api_exchangeconf.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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.Hash256):
var headerHash: common.Hash256

if not db.getBlockHash(terminalBlockNumber, headerHash):
Expand All @@ -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.Hash256):
raise newException(ValueError, "invalid terminal block hash, no terminal header set")

TransitionConfigurationV1(terminalTotalDifficulty: ttd.get)
6 changes: 3 additions & 3 deletions nimbus/beacon/api_handler/api_forkchoice.nim
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ proc forkchoiceUpdated*(ben: BeaconEngineRef,
chain = ben.chain
blockHash = ethHash update.headBlockHash

if blockHash == common.Hash256():
if blockHash == default(common.Hash256):
warn "Forkchoice requested update to zero hash"
return simpleFCU(PayloadExecutionStatus.invalid)

Expand Down Expand Up @@ -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.Hash256):
if not ben.posFinalized:
ben.finalizePoS()

Expand All @@ -175,7 +175,7 @@ proc forkchoiceUpdated*(ben: BeaconEngineRef,
db.finalizedHeaderHash(finalizedBlockHash)

let safeBlockHash = ethHash update.safeBlockHash
if safeBlockHash != common.Hash256():
if safeBlockHash != default(common.Hash256):
if not ben.chain.isCanonical(safeBlockHash):
warn "Safe block not in canonical chain",
hash=safeBlockHash.short
Expand Down
8 changes: 4 additions & 4 deletions nimbus/beacon/api_handler/api_utils.nim
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ proc simpleFCU*(status: PayloadExecutionStatus,

proc invalidFCU*(
validationError: string,
hash = common.Hash256()): ForkchoiceUpdatedResponse =
hash = default(common.Hash256)): ForkchoiceUpdatedResponse =
ForkchoiceUpdatedResponse(payloadStatus:
PayloadStatusV1(
status: PayloadExecutionStatus.invalid,
Expand All @@ -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.Hash256)): PayloadStatusV1 =
PayloadStatusV1(
status: PayloadExecutionStatus.invalid,
latestValidHash: toValidHash(validHash)
Expand Down Expand Up @@ -176,14 +176,14 @@ proc latestValidHash*(db: CoreDbRef,
parent: common.BlockHeader,
ttd: DifficultyInt): common.Hash256 =
if parent.isGenesis:
return common.Hash256()
return default(common.Hash256)
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.Hash256)

proc invalidFCU*(validationError: string,
com: CommonRef,
Expand Down
2 changes: 1 addition & 1 deletion nimbus/beacon/beacon_engine.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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.Hash256)

return Opt.some invalidStatus(lastValid, "links to previously rejected block")

Expand Down
2 changes: 1 addition & 1 deletion nimbus/common/genesis.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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(Hash256))

proc toGenesisHeader*(
genesis: Genesis;
Expand Down
2 changes: 1 addition & 1 deletion nimbus/constants.nim
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const
ZERO_ADDRESS* = default(EthAddress)

# ZERO_HASH256 is the parent hash of genesis blocks.
ZERO_HASH256* = Hash256()
ZERO_HASH256* = default(Hash256)

GAS_LIMIT_ADJUSTMENT_FACTOR* = 1_024

Expand Down
2 changes: 1 addition & 1 deletion nimbus/core/chain/persist_blocks.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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(Hash256):
if not c.db.setHead(header):
return err("setHead failed")
return ok()
Expand Down
8 changes: 4 additions & 4 deletions nimbus/db/aristo/aristo_debug.nim
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ proc ppVids(vids: HashSet[RootedVertexID]): string =

func ppCodeHash(h: Hash256): string =
result = "¢"
if h == Hash256():
if h == default(Hash256):
result &= "©"
elif h == EMPTY_CODE_HASH:
result &= "ø"
Expand All @@ -143,7 +143,7 @@ proc ppVidList(vLst: openArray[VertexID]): string =
proc ppKey(key: HashKey; db: AristoDbRef; pfx = true): string =
if pfx:
result = "£"
if key.to(Hash256) == Hash256():
if key.to(Hash256) == default(Hash256):
result &= "©"
elif not key.isValid:
result &= "ø"
Expand Down Expand Up @@ -499,8 +499,8 @@ proc pp*(w: Hash256; codeHashOk: bool): string =
w.ppCodeHash
elif w == EMPTY_ROOT_HASH:
"EMPTY_ROOT_HASH"
elif w == Hash256():
"Hash256()"
elif w == default(Hash256):
"default(Hash256)"
else:
w.data.toHex.squeeze(hex=true,ignLen=true)

Expand Down
16 changes: 8 additions & 8 deletions nimbus/db/core_db/core_apps.nim
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ proc setAsCanonicalChainHead(
# TODO This code handles reorgs - this should be moved elsewhere because we'll
# be handling reorgs mainly in-memory
if header.number == 0 or
db.getCanonicalHeaderHash().valueOr(Hash256()) != header.parentHash:
db.getCanonicalHeaderHash().valueOr(default(Hash256)) != header.parentHash:
var newCanonicalHeaders = sequtils.toSeq(db.findNewAncestors(header))
reverse(newCanonicalHeaders)
for h in newCanonicalHeaders:
Expand Down Expand Up @@ -255,7 +255,7 @@ proc markCanonicalChain(
return false

# it is a genesis block, done
if currHeader.parentHash == Hash256():
if currHeader.parentHash == default(Hash256):
return true

# mark ancestor blocks as canonical too
Expand All @@ -268,9 +268,9 @@ proc markCanonicalChain(
rlp.decode(data, Hash256)
except RlpError as exc:
warn info, key, error=exc.msg
Hash256()
default(Hash256)

while currHash != Hash256():
while currHash != default(Hash256):
let key = blockNumberToHashKey(currHeader.number)
let data = kvt.getOrEmpty(key.toOpenArray).valueOr:
warn info, key, error=($$error)
Expand All @@ -287,7 +287,7 @@ proc markCanonicalChain(
# forking point, done
break

if currHeader.parentHash == Hash256():
if currHeader.parentHash == default(Hash256):
break

currHash = currHeader.parentHash
Expand Down Expand Up @@ -391,7 +391,7 @@ proc getBlockHash*(
raise newException(BlockNotFound, "No block hash for number " & $n)

proc getHeadBlockHash*(db: CoreDbRef): Hash256 =
db.getHash(canonicalHeadHashKey()).valueOr(Hash256())
db.getHash(canonicalHeadHashKey()).valueOr(default(Hash256))

proc getBlockHeader*(
db: CoreDbRef;
Expand Down Expand Up @@ -904,7 +904,7 @@ proc persistUncles*(db: CoreDbRef, uncles: openArray[BlockHeader]): Hash256 =


proc safeHeaderHash*(db: CoreDbRef): Hash256 =
db.getHash(safeHashKey()).valueOr(Hash256())
db.getHash(safeHashKey()).valueOr(default(Hash256))

proc safeHeaderHash*(db: CoreDbRef, headerHash: Hash256) =
let safeHashKey = safeHashKey()
Expand All @@ -915,7 +915,7 @@ proc safeHeaderHash*(db: CoreDbRef, headerHash: Hash256) =
proc finalizedHeaderHash*(
db: CoreDbRef;
): Hash256 =
db.getHash(finalizedHashKey()).valueOr(Hash256())
db.getHash(finalizedHashKey()).valueOr(default(Hash256))

proc finalizedHeaderHash*(db: CoreDbRef, headerHash: Hash256) =
let finalizedHashKey = finalizedHashKey()
Expand Down
8 changes: 4 additions & 4 deletions nimbus/evm/computation.nim
Original file line number Diff line number Diff line change
Expand Up @@ -146,18 +146,18 @@ proc getBlockHash*(c: Computation, number: BlockNumber): Hash256 =
blockNumber = BlockNumber c.host.getTxContext().block_number
ancestorDepth = blockNumber - number - 1
if ancestorDepth >= constants.MAX_PREV_HEADER_DEPTH:
return Hash256()
return default(Hash256)
if number >= blockNumber:
return Hash256()
return default(Hash256)
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(Hash256)
if number >= blockNumber:
return Hash256()
return default(Hash256)
c.vmState.getAncestorHash(number)

template accountExists*(c: Computation, address: EthAddress): bool =
Expand Down
4 changes: 2 additions & 2 deletions nimbus/evm/state.nim
Original file line number Diff line number Diff line change
Expand Up @@ -259,9 +259,9 @@ method getAncestorHash*(
if db.getBlockHash(blockNumber, blockHash):
blockHash
else:
Hash256()
default(Hash256)
except RlpError:
Hash256()
default(Hash256)

proc readOnlyStateDB*(vmState: BaseVMState): ReadOnlyStateDB {.inline.} =
ReadOnlyStateDB(vmState.stateDB)
Expand Down
2 changes: 1 addition & 1 deletion nimbus/sync/beacon/skeleton_utils.nim
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ logScope:
const
# How often to log sync status (in ms)
STATUS_LOG_INTERVAL* = initDuration(microseconds = 8000)
zeroBlockHash* = Hash256()
zeroBlockHash* = default(Hash256)

# ------------------------------------------------------------------------------
# Misc helpers
Expand Down
2 changes: 1 addition & 1 deletion nimbus/sync/types.nim
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ type
# ------------------------------------------------------------------------------

proc new*(T: type BlockHash): T =
Hash256().T
default(Hash256).T

# ------------------------------------------------------------------------------
# Public (probably non-trivial) type conversions
Expand Down
6 changes: 3 additions & 3 deletions tests/test_aristo/test_helpers.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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(Hash256), VertexID(0))
for w in ua:
let thisRoot = w.root
if rootKey != thisRoot:
Expand All @@ -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(Hash256), VertexID(0))
for n,s in us:
for w in s.data.storages:
let thisRoot = w.account.storageRoot
Expand Down Expand Up @@ -216,7 +216,7 @@ proc schedStow*(
db.stow()

# ------------------

proc mergeGenericData*(
db: AristoDbRef; # Database, top layer
leaf: LeafTiePayload; # Leaf item to add to the database
Expand Down
Loading

0 comments on commit f3e3c6b

Please sign in to comment.