Replace some usage of std/options with results Opt (#2323)

* Replace some usage of std/options with results Opt

* more updates
This commit is contained in:
tersec 2024-06-07 21:39:58 +00:00 committed by GitHub
parent 32c51b14a4
commit fd03038cab
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
21 changed files with 85 additions and 116 deletions

View File

@ -160,8 +160,8 @@ proc init(com : CommonRef,
if genesis.isNil.not: if genesis.isNil.not:
com.hardForkTransition(ForkDeterminationInfo( com.hardForkTransition(ForkDeterminationInfo(
blockNumber: 0.toBlockNumber, blockNumber: 0.toBlockNumber,
td: some(0.u256), td: Opt.some(0.u256),
time: some(genesis.timestamp) time: Opt.some(genesis.timestamp)
)) ))
# Must not overwrite the global state on the single state DB # Must not overwrite the global state on the single state DB
@ -174,30 +174,30 @@ proc init(com : CommonRef,
else: else:
com.hardForkTransition(ForkDeterminationInfo( com.hardForkTransition(ForkDeterminationInfo(
blockNumber: 0.toBlockNumber, blockNumber: 0.toBlockNumber,
td: some(0.u256), td: Opt.some(0.u256),
time: some(TimeZero) time: Opt.some(TimeZero)
)) ))
# By default, history begins at genesis. # By default, history begins at genesis.
com.startOfHistory = GENESIS_PARENT_HASH com.startOfHistory = GENESIS_PARENT_HASH
proc getTd(com: CommonRef, blockHash: Hash256): Option[DifficultyInt] = proc getTd(com: CommonRef, blockHash: Hash256): Opt[DifficultyInt] =
var td: DifficultyInt var td: DifficultyInt
if not com.db.getTd(blockHash, td): if not com.db.getTd(blockHash, td):
# TODO: Is this really ok? # TODO: Is this really ok?
none[DifficultyInt]() Opt.none(DifficultyInt)
else: else:
some(td) Opt.some(td)
func needTdForHardForkDetermination(com: CommonRef): bool = func needTdForHardForkDetermination(com: CommonRef): bool =
let t = com.forkTransitionTable.mergeForkTransitionThreshold let t = com.forkTransitionTable.mergeForkTransitionThreshold
t.ttdPassed.isNone and t.blockNumber.isNone and t.ttd.isSome t.ttdPassed.isNone and t.blockNumber.isNone and t.ttd.isSome
proc getTdIfNecessary(com: CommonRef, blockHash: Hash256): Option[DifficultyInt] = proc getTdIfNecessary(com: CommonRef, blockHash: Hash256): Opt[DifficultyInt] =
if needTdForHardForkDetermination(com): if needTdForHardForkDetermination(com):
getTd(com, blockHash) getTd(com, blockHash)
else: else:
none[DifficultyInt]() Opt.none(DifficultyInt)
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
# Public constructors # Public constructors
@ -285,8 +285,8 @@ func hardForkTransition(
func hardForkTransition*( func hardForkTransition*(
com: CommonRef, com: CommonRef,
number: BlockNumber, number: BlockNumber,
td: Option[DifficultyInt], td: Opt[DifficultyInt],
time: Option[EthTime]) = time: Opt[EthTime]) =
com.hardForkTransition(ForkDeterminationInfo( com.hardForkTransition(ForkDeterminationInfo(
blockNumber: number, time: time, td: td)) blockNumber: number, time: time, td: td))
@ -294,14 +294,14 @@ proc hardForkTransition*(
com: CommonRef, com: CommonRef,
parentHash: Hash256, parentHash: Hash256,
number: BlockNumber, number: BlockNumber,
time: Option[EthTime]) = time: Opt[EthTime]) =
com.hardForkTransition(number, getTdIfNecessary(com, parentHash), time) com.hardForkTransition(number, getTdIfNecessary(com, parentHash), time)
proc hardForkTransition*( proc hardForkTransition*(
com: CommonRef, header: BlockHeader) com: CommonRef, header: BlockHeader)
{.gcsafe, raises: [].} = {.gcsafe, raises: [].} =
com.hardForkTransition( com.hardForkTransition(
header.parentHash, header.blockNumber, some(header.timestamp)) header.parentHash, header.blockNumber, Opt.some(header.timestamp))
func toEVMFork*(com: CommonRef, forkDeterminer: ForkDeterminationInfo): EVMFork = func toEVMFork*(com: CommonRef, forkDeterminer: ForkDeterminationInfo): EVMFork =
## similar to toFork, but produce EVMFork ## similar to toFork, but produce EVMFork

View File

@ -10,6 +10,7 @@
import import
std/[options, strutils], std/[options, strutils],
eth/common, eth/common,
results,
stew/endians2, stew/endians2,
json_serialization, json_serialization,
../utils/utils, ../utils/utils,
@ -80,18 +81,20 @@ type
# comment below on forkDeterminationInfo. # comment below on forkDeterminationInfo.
ForkDeterminationInfo* = object ForkDeterminationInfo* = object
blockNumber*: BlockNumber blockNumber*: BlockNumber
time*: Option[EthTime] time*: Opt[EthTime]
td*: Option[DifficultyInt] td*: Opt[DifficultyInt]
func forkDeterminationInfo*(n: BlockNumber): ForkDeterminationInfo = func forkDeterminationInfo*(n: BlockNumber): ForkDeterminationInfo =
# FIXME: All callers of this function are suspect; I'm guess we should # FIXME: All callers of this function are suspect; I'm guess we should
# always be using both block number and time. But we have a few places, # always be using both block number and time. But we have a few places,
# like various tests, where we only have block number and the tests are # like various tests, where we only have block number and the tests are
# meant for pre-Merge forks, so maybe those are okay. # meant for pre-Merge forks, so maybe those are okay.
ForkDeterminationInfo(blockNumber: n, time: none[EthTime](), td: none[DifficultyInt]()) ForkDeterminationInfo(
blockNumber: n, time: Opt.none(EthTime), td: Opt.none(DifficultyInt))
func forkDeterminationInfo*(n: BlockNumber, t: EthTime): ForkDeterminationInfo = func forkDeterminationInfo*(n: BlockNumber, t: EthTime): ForkDeterminationInfo =
ForkDeterminationInfo(blockNumber: n, time: some(t), td: none[DifficultyInt]()) ForkDeterminationInfo(
blockNumber: n, time: Opt.some(t), td: Opt.none(DifficultyInt))
func forkDeterminationInfo*(header: BlockHeader): ForkDeterminationInfo = func forkDeterminationInfo*(header: BlockHeader): ForkDeterminationInfo =
# FIXME-Adam-mightAlsoNeedTTD? # FIXME-Adam-mightAlsoNeedTTD?

View File

@ -121,13 +121,8 @@ func miningHash(header: BlockHeader): Hash256 =
# --------------- # ---------------
proc init(tm: PowRef; proc init(tm: PowRef; light: Option[PowCacheRef]) =
rng: Option[ref HmacDrbgContext];
light: Option[PowCacheRef]) =
## Constructor ## Constructor
if rng.isSome:
tm.rng = rng.get
else:
tm.rng = newRng() tm.rng = newRng()
if light.isSome: if light.isSome:
@ -142,7 +137,7 @@ proc init(tm: PowRef;
proc new*(T: type PowRef; cache: PowCacheRef): T = proc new*(T: type PowRef; cache: PowCacheRef): T =
## Constructor ## Constructor
new result new result
result.init(none(ref HmacDrbgContext), some(cache)) result.init(some(cache))
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
# Public functions # Public functions

View File

@ -8,11 +8,14 @@
# at your option. This file may not be copied, modified, or distributed except # at your option. This file may not be copied, modified, or distributed except
# according to those terms. # according to those terms.
{.push raises: [].}
## Transaction Pool Block Chain Packer Environment ## Transaction Pool Block Chain Packer Environment
## =============================================== ## ===============================================
## ##
import import
results,
../../common/common, ../../common/common,
../../constants, ../../constants,
../../db/ledger, ../../db/ledger,
@ -30,8 +33,6 @@ export
TxChainGasLimits, TxChainGasLimits,
TxChainGasLimitsPc TxChainGasLimitsPc
{.push raises: [].}
const const
TRG_THRESHOLD_PER_CENT = ##\ TRG_THRESHOLD_PER_CENT = ##\
## VM executor may stop if this per centage of `trgLimit` has ## VM executor may stop if this per centage of `trgLimit` has
@ -92,7 +93,8 @@ proc resetTxEnv(dh: TxChainRef; parent: BlockHeader; fee: Option[UInt256])
# BaseVMState querying any hardfork/consensus from CommonRef # BaseVMState querying any hardfork/consensus from CommonRef
let timestamp = dh.getTimestamp(parent) let timestamp = dh.getTimestamp(parent)
dh.com.hardForkTransition(parent.blockHash, parent.blockNumber+1, some(timestamp)) dh.com.hardForkTransition(
parent.blockHash, parent.blockNumber+1, Opt.some(timestamp))
dh.prepareHeader(parent, timestamp) dh.prepareHeader(parent, timestamp)
# we don't consider PoS difficulty here # we don't consider PoS difficulty here

View File

@ -1,5 +1,5 @@
# nimbus-eth1 # nimbus-eth1
# Copyright (c) 2023=-2024 Status Research & Development GmbH # Copyright (c) 2023-2024 Status Research & Development GmbH
# Licensed under either of # Licensed under either of
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
# http://www.apache.org/licenses/LICENSE-2.0) # http://www.apache.org/licenses/LICENSE-2.0)
@ -46,7 +46,7 @@ type
sTab: Table[VertexID,Blob] ## Structural vertex table making up a trie sTab: Table[VertexID,Blob] ## Structural vertex table making up a trie
kMap: Table[VertexID,HashKey] ## Merkle hash key mapping kMap: Table[VertexID,HashKey] ## Merkle hash key mapping
tUvi: Option[VertexID] ## Top used vertex ID tUvi: Option[VertexID] ## Top used vertex ID
lSst: Option[SavedState] ## Last saved state lSst: Opt[SavedState] ## Last saved state
MemBackendRef* = ref object of TypedBackendRef MemBackendRef* = ref object of TypedBackendRef
## Inheriting table so access can be extended for debugging purposes ## Inheriting table so access can be extended for debugging purposes
@ -56,7 +56,7 @@ type
sTab: Table[VertexID,Blob] sTab: Table[VertexID,Blob]
kMap: Table[VertexID,HashKey] kMap: Table[VertexID,HashKey]
tUvi: Option[VertexID] tUvi: Option[VertexID]
lSst: Option[SavedState] lSst: Opt[SavedState]
when extraTraceMessages: when extraTraceMessages:
import chronicles import chronicles
@ -170,7 +170,7 @@ proc putLstFn(db: MemBackendRef): PutLstFn =
if hdl.error.isNil: if hdl.error.isNil:
let rc = lst.blobify # test let rc = lst.blobify # test
if rc.isOk: if rc.isOk:
hdl.lSst = some(lst) hdl.lSst = Opt.some(lst)
else: else:
hdl.error = TypedPutHdlErrRef( hdl.error = TypedPutHdlErrRef(
pfx: AdmPfx, pfx: AdmPfx,

View File

@ -291,12 +291,12 @@ func evmcStatus*(c: Computation): evmc_status_code =
else: else:
c.error.evmcStatus c.error.evmcStatus
func errorOpt*(c: Computation): Option[string] = func errorOpt*(c: Computation): Opt[string] =
if c.isSuccess: if c.isSuccess:
return none(string) return Opt.none(string)
if c.error.evmcStatus == EVMC_REVERT: if c.error.evmcStatus == EVMC_REVERT:
return none(string) return Opt.none(string)
some(c.error.info) Opt.some(c.error.info)
proc writeContract*(c: Computation) = proc writeContract*(c: Computation) =
template withExtra(tracer: untyped, args: varargs[untyped]) = template withExtra(tracer: untyped, args: varargs[untyped]) =

View File

@ -313,7 +313,7 @@ proc captureStart*(vmState: BaseVMState, comp: Computation,
vmState.tracer.captureStart(comp, sender, to, create, input, gasLimit, value) vmState.tracer.captureStart(comp, sender, to, create, input, gasLimit, value)
proc captureEnd*(vmState: BaseVMState, comp: Computation, output: openArray[byte], proc captureEnd*(vmState: BaseVMState, comp: Computation, output: openArray[byte],
gasUsed: GasInt, error: Option[string]) = gasUsed: GasInt, error: Opt[string]) =
if vmState.tracingEnabled: if vmState.tracingEnabled:
vmState.tracer.captureEnd(comp, output, gasUsed, error) vmState.tracer.captureEnd(comp, output, gasUsed, error)
@ -325,7 +325,7 @@ proc captureEnter*(vmState: BaseVMState, comp: Computation, op: Op,
vmState.tracer.captureEnter(comp, op, sender, to, input, gasLimit, value) vmState.tracer.captureEnter(comp, op, sender, to, input, gasLimit, value)
proc captureExit*(vmState: BaseVMState, comp: Computation, output: openArray[byte], proc captureExit*(vmState: BaseVMState, comp: Computation, output: openArray[byte],
gasUsed: GasInt, error: Option[string]) = gasUsed: GasInt, error: Opt[string]) =
if vmState.tracingEnabled: if vmState.tracingEnabled:
vmState.tracer.captureExit(comp, output, gasUsed, error) vmState.tracer.captureExit(comp, output, gasUsed, error)
@ -355,7 +355,7 @@ proc captureOpEnd*(vmState: BaseVMState, comp: Computation, pc: int,
proc captureFault*(vmState: BaseVMState, comp: Computation, pc: int, proc captureFault*(vmState: BaseVMState, comp: Computation, pc: int,
op: Op, gas: GasInt, refund: GasInt, op: Op, gas: GasInt, refund: GasInt,
rData: openArray[byte], rData: openArray[byte],
depth: int, error: Option[string]) = depth: int, error: Opt[string]) =
if vmState.tracingEnabled: if vmState.tracingEnabled:
let fixed = vmState.gasCosts[op].kind == GckFixed let fixed = vmState.gasCosts[op].kind == GckFixed
vmState.tracer.captureFault(comp, fixed, pc, op, gas, refund, rData, depth, error) vmState.tracer.captureFault(comp, fixed, pc, op, gas, refund, rData, depth, error)

View File

@ -70,7 +70,7 @@ iterator storage(ctx: JsonTracer, compDepth: int): UInt256 =
proc captureOpImpl(ctx: JsonTracer, c: Computation, pc: int, proc captureOpImpl(ctx: JsonTracer, c: Computation, pc: int,
op: Op, gas: GasInt, refund: GasInt, op: Op, gas: GasInt, refund: GasInt,
rData: openArray[byte], depth: int, error: Option[string]) {.gcsafe.} = rData: openArray[byte], depth: int, error: Opt[string]) {.gcsafe.} =
let let
gasCost = ctx.gas - gas gasCost = ctx.gas - gas
@ -142,7 +142,7 @@ method captureStart*(ctx: JsonTracer, comp: Computation,
discard discard
method captureEnd*(ctx: JsonTracer, comp: Computation, output: openArray[byte], method captureEnd*(ctx: JsonTracer, comp: Computation, output: openArray[byte],
gasUsed: GasInt, error: Option[string]) {.gcsafe.} = gasUsed: GasInt, error: Opt[string]) {.gcsafe.} =
var res = %{ var res = %{
"output": %(output), "output": %(output),
"gasUsed": encodeHex(gasUsed) "gasUsed": encodeHex(gasUsed)
@ -172,7 +172,7 @@ method captureOpStart*(ctx: JsonTracer, c: Computation,
error "JsonTracer captureOpStart", msg=ex.msg error "JsonTracer captureOpStart", msg=ex.msg
try: try:
ctx.captureOpImpl(c, pc, op, 0, 0, [], depth, none(string)) ctx.captureOpImpl(c, pc, op, 0, 0, [], depth, Opt.none(string))
except RlpError as ex: except RlpError as ex:
error "JsonTracer captureOpStart", msg=ex.msg error "JsonTracer captureOpStart", msg=ex.msg
@ -213,7 +213,7 @@ method captureOpEnd*(ctx: JsonTracer, comp: Computation,
method captureFault*(ctx: JsonTracer, comp: Computation, method captureFault*(ctx: JsonTracer, comp: Computation,
fixed: bool, pc: int, op: Op, gas: GasInt, refund: GasInt, fixed: bool, pc: int, op: Op, gas: GasInt, refund: GasInt,
rData: openArray[byte], rData: openArray[byte],
depth: int, error: Option[string]) {.gcsafe.} = depth: int, error: Opt[string]) {.gcsafe.} =
if ctx.node.isNil.not: if ctx.node.isNil.not:
let res = ctx.node let res = ctx.node

View File

@ -155,7 +155,7 @@ method captureOpEnd*(ctx: LegacyTracer, c: Computation,
method captureFault*(ctx: LegacyTracer, comp: Computation, method captureFault*(ctx: LegacyTracer, comp: Computation,
fixed: bool, pc: int, op: Op, gas: GasInt, refund: GasInt, fixed: bool, pc: int, op: Op, gas: GasInt, refund: GasInt,
rData: openArray[byte], rData: openArray[byte],
depth: int, error: Option[string]) {.gcsafe.} = depth: int, error: Opt[string]) {.gcsafe.} =
try: try:
if ctx.trace["structLogs"].elems.len > 0: if ctx.trace["structLogs"].elems.len > 0:
let j = ctx.trace["structLogs"].elems[^1] let j = ctx.trace["structLogs"].elems[^1]

View File

@ -158,7 +158,7 @@ method captureStart*(ctx: TracerRef, comp: Computation,
discard discard
method captureEnd*(ctx: TracerRef, comp: Computation, output: openArray[byte], method captureEnd*(ctx: TracerRef, comp: Computation, output: openArray[byte],
gasUsed: GasInt, error: Option[string]) {.base, gcsafe.} = gasUsed: GasInt, error: Opt[string]) {.base, gcsafe.} =
discard discard
# Rest of call frames # Rest of call frames
@ -169,7 +169,7 @@ method captureEnter*(ctx: TracerRef, comp: Computation, op: Op,
discard discard
method captureExit*(ctx: TracerRef, comp: Computation, output: openArray[byte], method captureExit*(ctx: TracerRef, comp: Computation, output: openArray[byte],
gasUsed: GasInt, error: Option[string]) {.base, gcsafe.} = gasUsed: GasInt, error: Opt[string]) {.base, gcsafe.} =
discard discard
# Opcode level # Opcode level
@ -192,7 +192,7 @@ method captureOpEnd*(ctx: TracerRef, comp: Computation,
method captureFault*(ctx: TracerRef, comp: Computation, method captureFault*(ctx: TracerRef, comp: Computation,
fixed: bool, pc: int, op: Op, gas: GasInt, refund: GasInt, fixed: bool, pc: int, op: Op, gas: GasInt, refund: GasInt,
rData: openArray[byte], rData: openArray[byte],
depth: int, error: Option[string]) {.base, gcsafe.} = depth: int, error: Opt[string]) {.base, gcsafe.} =
discard discard
# Called at the start of EVM interpreter loop # Called at the start of EVM interpreter loop

View File

@ -133,8 +133,8 @@ proc setupP2P(nimbus: NimbusNode, conf: NimbusConf,
# Early-initialise "--snap-sync" before starting any network connections. # Early-initialise "--snap-sync" before starting any network connections.
block: block:
let let
exCtrlFile = if conf.syncCtrlFile.isNone: none(string) exCtrlFile = if conf.syncCtrlFile.isNone: Opt.none(string)
else: some(conf.syncCtrlFile.get) else: Opt.some(conf.syncCtrlFile.get)
tickerOK = conf.logLevel in { tickerOK = conf.logLevel in {
LogLevel.INFO, LogLevel.DEBUG, LogLevel.TRACE} LogLevel.INFO, LogLevel.DEBUG, LogLevel.TRACE}
case conf.syncMode: case conf.syncMode:

View File

@ -132,7 +132,7 @@ proc init*(
maxPeers: int; maxPeers: int;
id: int = 0): T = id: int = 0): T =
new result new result
result.initSync(ethNode, chain, maxPeers, none(string)) result.initSync(ethNode, chain, maxPeers, Opt.none(string))
result.ctx.pool.rng = rng result.ctx.pool.rng = rng
result.ctx.pool.id = id result.ctx.pool.id = id

View File

@ -1,5 +1,5 @@
# Nimbus # Nimbus
# Copyright (c) 2021 Status Research & Development GmbH # Copyright (c) 2021-2024 Status Research & Development GmbH
# Licensed under either of # Licensed under either of
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
# http://www.apache.org/licenses/LICENSE-2.0) # http://www.apache.org/licenses/LICENSE-2.0)
@ -112,7 +112,7 @@ proc init*(
rng: ref HmacDrbgContext; rng: ref HmacDrbgContext;
maxPeers: int; maxPeers: int;
enableTicker = false; enableTicker = false;
exCtrlFile = none(string); exCtrlFile = Opt.none(string);
): T = ): T =
new result new result
result.initSync(ethNode, chain, maxPeers, exCtrlFile) result.initSync(ethNode, chain, maxPeers, exCtrlFile)

View File

@ -313,7 +313,7 @@ proc runSingle*(buddy: FullBuddyRef) {.async.} =
let rc = pv.pivotHeader(relaxedMode=true) let rc = pv.pivotHeader(relaxedMode=true)
if rc.isOK: if rc.isOK:
# Update/activate `bestNumber` from the pivot header # Update/activate `bestNumber` from the pivot header
bq.bestNumber = some(rc.value.blockNumber) bq.bestNumber = Opt.some(rc.value.blockNumber)
ctx.pool.pivotState = PivotRunMode ctx.pool.pivotState = PivotRunMode
buddy.ctrl.multiOk = true buddy.ctrl.multiOk = true
trace "Single pivot accepted", peer, pivot=('#' & $bq.bestNumber.get) trace "Single pivot accepted", peer, pivot=('#' & $bq.bestNumber.get)
@ -349,7 +349,7 @@ proc runSingle*(buddy: FullBuddyRef) {.async.} =
# `case()` handler to process and `return`. # `case()` handler to process and `return`.
if await pv.pivotNegotiate(buddy.only.bQueue.bestNumber): if await pv.pivotNegotiate(buddy.only.bQueue.bestNumber):
# Update/activate `bestNumber` from the pivot header # Update/activate `bestNumber` from the pivot header
bq.bestNumber = some(pv.pivotHeader.value.blockNumber) bq.bestNumber = Opt.some(pv.pivotHeader.value.blockNumber)
ctx.pool.pivotState = PivotRunMode ctx.pool.pivotState = PivotRunMode
buddy.ctrl.multiOk = true buddy.ctrl.multiOk = true
trace "Pivot accepted", peer, pivot=('#' & $bq.bestNumber.get) trace "Pivot accepted", peer, pivot=('#' & $bq.bestNumber.get)

View File

@ -1,5 +1,5 @@
# Nimbus # Nimbus
# Copyright (c) 2018-2021 Status Research & Development GmbH # Copyright (c) 2018-2024 Status Research & Development GmbH
# Licensed and distributed under either of # Licensed and distributed under either of
# * MIT license (license terms in the root directory or at # * MIT license (license terms in the root directory or at
# https://opensource.org/licenses/MIT). # https://opensource.org/licenses/MIT).
@ -321,7 +321,7 @@ proc pivotHeader*(
proc pivotNegotiate*( proc pivotNegotiate*(
bp: BestPivotWorkerRef; ## Worker peer bp: BestPivotWorkerRef; ## Worker peer
minBlockNumber: Option[BlockNumber]; ## Minimum block number to expect minBlockNumber: Opt[BlockNumber]; ## Minimum block number to expect
): Future[bool] ): Future[bool]
{.async.} = {.async.} =
## Negotiate best header pivot. This function must be run in *single mode* at ## Negotiate best header pivot. This function must be run in *single mode* at

View File

@ -120,15 +120,15 @@ type
BlockQueueWorkerRef* = ref object BlockQueueWorkerRef* = ref object
## Local descriptor data extension ## Local descriptor data extension
global: BlockQueueCtxRef ## Common data global: BlockQueueCtxRef ## Common data
bestNumber: Option[BlockNumber] ## Largest block number reported bestNumber: Opt[BlockNumber] ## Largest block number reported
ctrl: BuddyCtrlRef ## Control and state settings ctrl: BuddyCtrlRef ## Control and state settings
peer: Peer ## network peer peer: Peer ## network peer
BlockQueueStats* = object BlockQueueStats* = object
## Statistics ## Statistics
topAccepted*: BlockNumber topAccepted*: BlockNumber
nextUnprocessed*: Option[BlockNumber] nextUnprocessed*: Opt[BlockNumber]
nextStaged*: Option[BlockNumber] nextStaged*: Opt[BlockNumber]
nStagedQueue*: int nStagedQueue*: int
reOrg*: bool reOrg*: bool
@ -175,7 +175,7 @@ proc `$`(iv: BlockRange): string =
proc `$`(n: Option[BlockRange]): string = proc `$`(n: Option[BlockRange]): string =
if n.isNone: "n/a" else: $n.get if n.isNone: "n/a" else: $n.get
proc `$`(n: Option[BlockNumber]): string = proc `$`(n: Opt[BlockNumber]): string =
n.toStr n.toStr
proc `$`(brs: BlockRangeSetRef): string = proc `$`(brs: BlockRangeSetRef): string =
@ -185,17 +185,17 @@ proc `$`(brs: BlockRangeSetRef): string =
# Private helpers # Private helpers
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
proc nextUnprocessed(ctx: BlockQueueCtxRef): Option[BlockNumber] = proc nextUnprocessed(ctx: BlockQueueCtxRef): Opt[BlockNumber] =
## Pseudo getter ## Pseudo getter
let rc = ctx.unprocessed.ge() let rc = ctx.unprocessed.ge()
if rc.isOK: if rc.isOK:
result = some(rc.value.minPt) result = Opt.some(rc.value.minPt)
proc nextStaged(ctx: BlockQueueCtxRef): Option[BlockRange] = proc nextStaged(ctx: BlockQueueCtxRef): Opt[BlockRange] =
## Pseudo getter ## Pseudo getter
let rc = ctx.staged.ge(low(BlockNumber)) let rc = ctx.staged.ge(low(BlockNumber))
if rc.isOK: if rc.isOK:
result = some(rc.value.data.blocks) result = Opt.some(rc.value.data.blocks)
template safeTransport( template safeTransport(
qd: BlockQueueWorkerRef; qd: BlockQueueWorkerRef;
@ -474,11 +474,11 @@ proc init*(
# Public functions -- getter/setter # Public functions -- getter/setter
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
proc bestNumber*(qd: BlockQueueWorkerRef): Option[BlockNumber] = proc bestNumber*(qd: BlockQueueWorkerRef): Opt[BlockNumber] =
## Getter ## Getter
qd.bestNumber qd.bestNumber
proc `bestNumber=`*(qd: BlockQueueWorkerRef; val: Option[BlockNumber]) = proc `bestNumber=`*(qd: BlockQueueWorkerRef; val: Opt[BlockNumber]) =
## Setter, needs to be set to something valid so that `blockQueueWorker()` ## Setter, needs to be set to something valid so that `blockQueueWorker()`
## does something useful. ## does something useful.
qd.bestNumber = val qd.bestNumber = val
@ -596,8 +596,8 @@ proc blockQueueStats*(ctx: BlockQueueCtxRef; stats: var BlockQueueStats) =
stats.nStagedQueue = ctx.staged.len stats.nStagedQueue = ctx.staged.len
stats.reOrg = ctx.backtrack.isSome stats.reOrg = ctx.backtrack.isSome
stats.nextStaged = stats.nextStaged =
if ctx.nextStaged.isSome: some(ctx.nextStaged.unsafeGet.minPt) if ctx.nextStaged.isSome: Opt.some(ctx.nextStaged.unsafeGet.minPt)
else: none(BlockNumber) else: Opt.none(BlockNumber)
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
# Public functions -- asynchronous # Public functions -- asynchronous
@ -666,7 +666,7 @@ proc blockQueueWorker*(
let rc = qd.newWorkItem() let rc = qd.newWorkItem()
if rc.isErr: if rc.isErr:
# No way, end of capacity for this peer => re-calibrate # No way, end of capacity for this peer => re-calibrate
qd.bestNumber = none(BlockNumber) qd.bestNumber = Opt.none(BlockNumber)
return err(rc.error) return err(rc.error)
rc.value rc.value

View File

@ -1,5 +1,5 @@
# Nimbus # Nimbus
# Copyright (c) 2021 Status Research & Development GmbH # Copyright (c) 2021-2024 Status Research & Development GmbH
# Licensed under either of # Licensed under either of
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
# http://www.apache.org/licenses/LICENSE-2.0) # http://www.apache.org/licenses/LICENSE-2.0)
@ -38,7 +38,7 @@ proc getDataLine(
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
proc syncCtrlBlockNumberFromFile*( proc syncCtrlBlockNumberFromFile*(
fileName: Option[string]; # Optional file name fileName: Opt[string]; # Optional file name
lineNum = 0; # Read line from file lineNum = 0; # Read line from file
): Result[BlockNumber,void] = ): Result[BlockNumber,void] =
## Returns a block number from the file name argument `fileName`. The first ## Returns a block number from the file name argument `fileName`. The first
@ -57,38 +57,6 @@ proc syncCtrlBlockNumberFromFile*(
debug "Exception while parsing block number", file, name, msg debug "Exception while parsing block number", file, name, msg
err() err()
proc syncCtrlHashOrBlockNumFromFile*(
fileName: Option[string]; # Optional file name
lineNum = 0; # Read line from file
): Result[HashOrNum,void] =
## Returns a block number or a hash from the file name argument `fileName`.
## A block number is decimal encoded and a hash is expexted to be a 66 hex
## digits string startnib wiyh `0x`.
if fileName.isSome:
let file = fileName.get
# Parse value dump and fetch a header from the peer (if any)
try:
let data = file.getDataLine(lineNum)
if 0 < data.len:
if 66 == data.len:
let hash = HashOrNum(
isHash: true,
hash: Hash256(
data: UInt256.fromHex(data).toBytesBE))
return ok(hash)
else:
let num = HashOrNum(
isHash: false,
number: parse(data,UInt256))
return ok(num)
except CatchableError as e:
let
name {.used.} = $e.name
msg {.used.} = e.msg
debug "Exception while parsing hash or block number", file, name, msg
err()
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------
# End # End
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------

View File

@ -45,23 +45,23 @@ type
TickerSnapStats* = object TickerSnapStats* = object
## Snap sync state (see `TickerSnapStatsUpdater`) ## Snap sync state (see `TickerSnapStatsUpdater`)
beaconBlock*: Option[BlockNumber] beaconBlock*: Opt[BlockNumber]
pivotBlock*: Option[BlockNumber] pivotBlock*: Opt[BlockNumber]
nAccounts*: (float,float) ## Mean and standard deviation nAccounts*: (float,float) ## Mean and standard deviation
accountsFill*: (float,float,float) ## Mean, standard deviation, merged total accountsFill*: (float,float,float) ## Mean, standard deviation, merged total
nAccountStats*: int ## #chunks nAccountStats*: int ## #chunks
nSlotLists*: (float,float) ## Mean and standard deviation nSlotLists*: (float,float) ## Mean and standard deviation
nContracts*: (float,float) ## Mean and standard deviation nContracts*: (float,float) ## Mean and standard deviation
nStorageQueue*: Option[int] nStorageQueue*: Opt[int]
nContractQueue*: Option[int] nContractQueue*: Opt[int]
nQueues*: int nQueues*: int
TickerFullStats* = object TickerFullStats* = object
## Full sync state (see `TickerFullStatsUpdater`) ## Full sync state (see `TickerFullStatsUpdater`)
pivotBlock*: Option[BlockNumber] pivotBlock*: Opt[BlockNumber]
topPersistent*: BlockNumber topPersistent*: BlockNumber
nextUnprocessed*: Option[BlockNumber] nextUnprocessed*: Opt[BlockNumber]
nextStaged*: Option[BlockNumber] nextStaged*: Opt[BlockNumber]
nStagedQueue*: int nStagedQueue*: int
suspended*: bool suspended*: bool
reOrg*: bool reOrg*: bool
@ -96,7 +96,7 @@ proc pc99(val: float): string =
elif 0.0 < val and val <= 0.01: "1%" elif 0.0 < val and val <= 0.01: "1%"
else: val.toPC(0) else: val.toPC(0)
proc toStr(a: Option[int]): string = proc toStr(a: Opt[int]): string =
if a.isNone: "n/a" if a.isNone: "n/a"
else: $a.unsafeGet else: $a.unsafeGet

View File

@ -1,5 +1,5 @@
# Nimbus # Nimbus
# Copyright (c) 2021 Status Research & Development GmbH # Copyright (c) 2021-2024 Status Research & Development GmbH
# Licensed under either of # Licensed under either of
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
# http://www.apache.org/licenses/LICENSE-2.0) # http://www.apache.org/licenses/LICENSE-2.0)
@ -49,7 +49,7 @@ type
chain*: ChainRef ## Block chain database (no need for `Peer`) chain*: ChainRef ## Block chain database (no need for `Peer`)
poolMode*: bool ## Activate `runPool()` workers if set `true` poolMode*: bool ## Activate `runPool()` workers if set `true`
daemon*: bool ## Enable global background job daemon*: bool ## Enable global background job
exCtrlFile*: Option[string] ## Extra instructions file (if any) exCtrlFile*: Opt[string] ## Extra instructions file (if any)
pool*: S ## Shared context for all worker peers pool*: S ## Shared context for all worker peers
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------

View File

@ -385,7 +385,7 @@ proc initSync*[S,W](
node: EthereumNode; node: EthereumNode;
chain: ChainRef, chain: ChainRef,
slots: int; slots: int;
exCtrlFile = none(string); exCtrlFile = Opt.none(string);
) = ) =
## Constructor ## Constructor
# Leave one extra slot so that it can holds a *zombie* even if all slots # Leave one extra slot so that it can holds a *zombie* even if all slots

View File

@ -1,5 +1,5 @@
# Nimbus # Nimbus
# Copyright (c) 2018-2021 Status Research & Development GmbH # Copyright (c) 2018-2024 Status Research & Development GmbH
# Licensed under either of # Licensed under either of
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or # * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
# http://www.apache.org/licenses/LICENSE-2.0) # http://www.apache.org/licenses/LICENSE-2.0)
@ -13,6 +13,7 @@
import import
std/[math, hashes], std/[math, hashes],
eth/common/eth_types_rlp, eth/common/eth_types_rlp,
results,
stew/byteutils stew/byteutils
type type
@ -110,7 +111,7 @@ func toStr*(n: BlockNumber): string =
## Pretty print block number, explicitely format with a leading hash `#` ## Pretty print block number, explicitely format with a leading hash `#`
if n == high(BlockNumber): "high" else:"#" & $n if n == high(BlockNumber): "high" else:"#" & $n
func toStr*(n: Option[BlockNumber]): string = func toStr*(n: Opt[BlockNumber]): string =
if n.isNone: "n/a" else: n.get.toStr if n.isNone: "n/a" else: n.get.toStr
# ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------