From 6b9f3c9ac55e3878832d0ad6780004376322ded1 Mon Sep 17 00:00:00 2001 From: Jordan Hrycaj Date: Tue, 31 Jan 2023 01:32:17 +0000 Subject: [PATCH] Silence compiler gossip after nim upgrade cont1 (#1455) * Silence some compiler gossip -- part 5, common details: Mostly removing redundant imports and `Defect` tracer after switch to nim 1.6 * Silence some compiler gossip -- part 6, db, rpc, utils details: Mostly removing redundant imports and `Defect` tracer after switch to nim 1.6 * Silence some compiler gossip -- part 7, randomly collected source files details: Mostly removing redundant imports and `Defect` tracer after switch to nim 1.6 * Silence some compiler gossip -- part 8, assorted tests details: Mostly removing redundant imports and `Defect` tracer after switch to nim 1.6 * Clique update why: More impossible exceptions (undoes temporary fix from previous PR) --- nimbus/common/chain_config.nim | 38 ++++++++--------- nimbus/common/common.nim | 40 ++++++++++++------ nimbus/common/context.nim | 5 ++- nimbus/common/genesis.nim | 34 +++++++++++---- nimbus/common/hardforks.nim | 10 +++-- nimbus/common/manager.nim | 8 ++-- nimbus/config.nim | 2 +- nimbus/constants.nim | 2 +- nimbus/core/clique/clique_cfg.nim | 3 +- nimbus/core/clique/clique_verify.nim | 3 +- nimbus/db/kvstore_rocksdb.nim | 4 +- .../evm/interpreter/op_handlers/oph_log.nim | 1 - nimbus/evm/interpreter_dispatch.nim | 2 +- nimbus/rpc/common.nim | 4 +- nimbus/rpc/cors.nim | 2 + nimbus/rpc/debug.nim | 2 + nimbus/rpc/engine_api.nim | 12 ++++-- nimbus/rpc/filters.nim | 4 +- nimbus/rpc/jwt_auth.nim | 6 +-- nimbus/rpc/p2p.nim | 11 +++-- nimbus/rpc/rpc_types.nim | 16 ++++--- nimbus/rpc/rpc_utils.nim | 40 ++++++++++++------ nimbus/transaction/call_common.nim | 2 +- nimbus/utils/ec_recover.nim | 13 +++--- nimbus/utils/keyed_queue/kq_rlp.nim | 4 +- nimbus/utils/prettify.nim | 2 + nimbus/utils/utils.nim | 5 ++- nimbus/utils/utils_defs.nim | 5 ++- stateless/witness_from_tree.nim | 42 ++++++++++++------- stateless/witness_types.nim | 11 +++-- tests/replay/gunzip.nim | 18 ++++---- tests/test_accounts_cache.nim | 16 ++++++- tests/test_clique/pool.nim | 2 +- tests/test_jwt_auth.nim | 3 +- 34 files changed, 236 insertions(+), 136 deletions(-) diff --git a/nimbus/common/chain_config.nim b/nimbus/common/chain_config.nim index 80f69782c..811bb5a67 100644 --- a/nimbus/common/chain_config.nim +++ b/nimbus/common/chain_config.nim @@ -19,7 +19,7 @@ import export hardforks -{.push raises: [Defect].} +{.push raises: [].} type Genesis* = ref object @@ -82,16 +82,16 @@ const # ------------------------------------------------------------------------------ proc read(rlp: var Rlp, x: var AddressBalance, _: type EthAddress): EthAddress - {.gcsafe, raises: [Defect,RlpError].} = + {.gcsafe, raises: [RlpError].} = let val = rlp.read(UInt256).toByteArrayBE() result[0 .. ^1] = val.toOpenArray(12, val.high) proc read(rlp: var Rlp, x: var AddressBalance, _: type GenesisAccount): GenesisAccount - {.gcsafe, raises: [Defect,RlpError].} = + {.gcsafe, raises: [RlpError].} = GenesisAccount(balance: rlp.read(UInt256)) func decodePrealloc*(data: seq[byte]): GenesisAlloc - {.gcsafe, raises: [Defect,RlpError].} = + {.gcsafe, raises: [RlpError].} = for tup in rlp.decode(data, seq[AddressBalance]): result[tup.address] = tup.account @@ -104,7 +104,7 @@ proc fromHex(c: char): int = else: -1 proc readValue(reader: var JsonReader, value: var UInt256) - {.gcsafe, raises: [Defect,CatchableError].} = + {.gcsafe, raises: [CatchableError].} = ## Mixin for `Json.loadFile()`. Note that this driver applies the same ## to `BlockNumber` fields as well as generic `UInt265` fields like the ## account `balance`. @@ -148,35 +148,35 @@ proc readValue(reader: var JsonReader, value: var UInt256) reader.lexer.next() proc readValue(reader: var JsonReader, value: var ChainId) - {.gcsafe, raises: [Defect,CatchableError].} = + {.gcsafe, raises: [CatchableError].} = value = reader.readValue(int).ChainId proc readValue(reader: var JsonReader, value: var Hash256) - {.gcsafe, raises: [Defect,CatchableError].} = + {.gcsafe, raises: [CatchableError].} = value = Hash256.fromHex(reader.readValue(string)) proc readValue(reader: var JsonReader, value: var BlockNonce) - {.gcsafe, raises: [Defect,CatchableError].} = + {.gcsafe, raises: [CatchableError].} = value = fromHex[uint64](reader.readValue(string)).toBlockNonce proc readValue(reader: var JsonReader, value: var EthTime) - {.gcsafe, raises: [Defect,CatchableError].} = + {.gcsafe, raises: [CatchableError].} = value = fromHex[int64](reader.readValue(string)).fromUnix proc readValue(reader: var JsonReader, value: var seq[byte]) - {.gcsafe, raises: [Defect,CatchableError].} = + {.gcsafe, raises: [CatchableError].} = value = hexToSeqByte(reader.readValue(string)) proc readValue(reader: var JsonReader, value: var GasInt) - {.gcsafe, raises: [Defect,CatchableError].} = + {.gcsafe, raises: [CatchableError].} = value = fromHex[GasInt](reader.readValue(string)) proc readValue(reader: var JsonReader, value: var EthAddress) - {.gcsafe, raises: [Defect,CatchableError].} = + {.gcsafe, raises: [CatchableError].} = value = parseAddress(reader.readValue(string)) proc readValue(reader: var JsonReader, value: var AccountNonce) - {.gcsafe, raises: [Defect,CatchableError].} = + {.gcsafe, raises: [CatchableError].} = value = fromHex[uint64](reader.readValue(string)) template to(a: string, b: type EthAddress): EthAddress = @@ -201,7 +201,7 @@ macro fillToBlockNumberArray(conf, arr: typed): untyped = for fork, forkField in forkBlockNumber: let fieldIdent = newIdentNode(forkField) - forkIdent = newIdentNode($HardFork(fork)) + forkIdent = newIdentNode($HardFork(fork.ord)) result.add quote do: `arr`[`forkIdent`] = `conf`.`fieldIdent` @@ -269,7 +269,7 @@ proc validateNetworkParams*(params: var NetworkParams): bool = validateChainConfig(params.config) proc loadNetworkParams*(fileName: string, params: var NetworkParams): - bool {.raises: [Defect,SerializationError].} = + bool = try: params = Json.loadFile(fileName, NetworkParams, allowUnknownFields = true) except IOError as e: @@ -299,7 +299,7 @@ proc decodeNetworkParams*(jsonString: string, params: var NetworkParams): bool = validateNetworkParams(params) proc parseGenesisAlloc*(data: string, ga: var GenesisAlloc): bool - {.gcsafe, raises: [Defect,CatchableError].} = + {.gcsafe, raises: [CatchableError].} = try: ga = Json.decode(data, GenesisAlloc, allowUnknownFields = true) except JsonReaderError as e: @@ -309,7 +309,7 @@ proc parseGenesisAlloc*(data: string, ga: var GenesisAlloc): bool return true proc parseGenesis*(data: string): Genesis - {.gcsafe, raises: [Defect,CatchableError].} = + {.gcsafe, raises: [CatchableError].} = try: result = Json.decode(data, Genesis, allowUnknownFields = true) except JsonReaderError as e: @@ -428,7 +428,7 @@ proc chainConfigForNetwork*(id: NetworkId): ChainConfig = ChainConfig() proc genesisBlockForNetwork*(id: NetworkId): Genesis - {.gcsafe, raises: [Defect, ValueError, RlpError].} = + {.gcsafe, raises: [ValueError, RlpError].} = result = case id of MainNet: Genesis( @@ -477,7 +477,7 @@ proc genesisBlockForNetwork*(id: NetworkId): Genesis Genesis() proc networkParams*(id: NetworkId): NetworkParams - {.gcsafe, raises: [Defect, ValueError, RlpError].} = + {.gcsafe, raises: [ValueError, RlpError].} = result.genesis = genesisBlockForNetwork(id) result.config = chainConfigForNetwork(id) diff --git a/nimbus/common/common.nim b/nimbus/common/common.nim index 22ee7ddbe..93780ed45 100644 --- a/nimbus/common/common.nim +++ b/nimbus/common/common.nim @@ -28,6 +28,8 @@ export genesis, utils +{.push raises: [].} + type SyncProgress = object start : BlockNumber @@ -85,7 +87,7 @@ type # ------------------------------------------------------------------------------ proc hardForkTransition*(com: CommonRef, - number: BlockNumber, td: Option[DifficultyInt]) {.gcsafe.} + number: BlockNumber, td: Option[DifficultyInt]) {.gcsafe, raises: [CatchableError].} func cliquePeriod*(com: CommonRef): int @@ -95,6 +97,16 @@ func cliqueEpoch*(com: CommonRef): int # Private helper functions # ------------------------------------------------------------------------------ +template noExceptionOops(info: static[string]; code: untyped) = + try: + code + except CatchableError as e: + raiseAssert "Inconveivable (" & info & ": name=" & $e.name & " msg=" & e.msg + #except Defect as e: + # raise e + except Exception as e: + raiseAssert "Ooops " & info & ": name=" & $e.name & " msg=" & e.msg + proc consensusTransition(com: CommonRef, fork: HardFork) = if fork >= MergeFork: com.consensusType = ConsensusType.POS @@ -103,8 +115,7 @@ proc consensusTransition(com: CommonRef, fork: HardFork) = # this could happen during reorg com.consensusType = com.config.consensusType -proc setForkId(com: CommonRef, blockZero: BlockHeader) - {. raises: [Defect,CatchableError].} = +proc setForkId(com: CommonRef, blockZero: BlockHeader) = com.genesisHash = blockZero.blockHash let genesisCRC = crc32(0, com.genesisHash.data) com.forkIds = calculateForkIds(com.config, genesisCRC) @@ -121,7 +132,7 @@ proc init(com : CommonRef, pruneTrie: bool, networkId: NetworkId, config : ChainConfig, - genesis : Genesis) = + genesis : Genesis) {.gcsafe, raises: [CatchableError].} = config.daoCheck() @@ -163,7 +174,8 @@ proc new*(_: type CommonRef, db: TrieDatabaseRef, pruneTrie: bool = true, networkId: NetworkId = MainNet, - params = networkParams(MainNet)): CommonRef = + params = networkParams(MainNet)): CommonRef + {.gcsafe, raises: [CatchableError].} = ## If genesis data is present, the forkIds will be initialized ## empty data base also initialized with genesis block @@ -179,7 +191,8 @@ proc new*(_: type CommonRef, db: TrieDatabaseRef, config: ChainConfig, pruneTrie: bool = true, - networkId: NetworkId = MainNet): CommonRef = + networkId: NetworkId = MainNet): CommonRef + {.gcsafe, raises: [CatchableError].} = ## There is no genesis data present ## Mainly used for testing without genesis @@ -258,7 +271,7 @@ proc hardForkTransition(com: CommonRef, proc hardForkTransition*(com: CommonRef, parentHash: Hash256, number: BlockNumber) - {.gcsafe, raises: [Defect, CatchableError].} = + {.gcsafe, raises: [CatchableError].} = # if mergeForkBlock is present, it has higher # priority than TTD @@ -288,7 +301,7 @@ proc hardForkTransition*(com: CommonRef, parentHash: Hash256, doAssert(false, "unreachable code") proc hardForkTransition*(com: CommonRef, header: BlockHeader) - {.gcsafe, raises: [Defect, CatchableError].} = + {.gcsafe, raises: [CatchableError].} = com.hardForkTransition(header.parentHash, header.blockNumber) @@ -312,7 +325,7 @@ func forkGTE*(com: CommonRef, fork: HardFork): bool = # TODO: move this consensus code to where it belongs proc minerAddress*(com: CommonRef; header: BlockHeader): EthAddress - {.gcsafe, raises: [Defect,CatchableError].} = + {.gcsafe, raises: [CatchableError].} = if com.consensusType != ConsensusType.POA: # POW and POS return header.coinbase return header.coinbase @@ -334,7 +347,7 @@ func isEIP155*(com: CommonRef, number: BlockNumber): bool = com.config.eip155Block.isSome and number >= com.config.eip155Block.get proc isBlockAfterTtd*(com: CommonRef, header: BlockHeader): bool - {.gcsafe, raises: [Defect,CatchableError].} = + {.gcsafe, raises: [CatchableError].} = if com.config.terminalTotalDifficulty.isNone: return false @@ -345,14 +358,14 @@ proc isBlockAfterTtd*(com: CommonRef, header: BlockHeader): bool ptd >= ttd and td >= ttd proc consensus*(com: CommonRef, header: BlockHeader): ConsensusType - {.gcsafe, raises: [Defect,CatchableError].} = + {.gcsafe, raises: [CatchableError].} = if com.isBlockAfterTtd(header): return ConsensusType.POS return com.config.consensusType proc initializeEmptyDb*(com: CommonRef) - {.raises: [Defect, CatchableError].} = + {.raises: [CatchableError].} = let trieDB = com.db.db if canonicalHeadHashKey().toOpenArray notin trieDB: trace "Writing genesis to DB" @@ -365,7 +378,8 @@ proc initializeEmptyDb*(com: CommonRef) proc syncReqNewHead*(com: CommonRef; header: BlockHeader) = ## Used by RPC to update the beacon head for snap sync if not com.syncReqNewHead.isNil: - com.syncReqNewHead(header) + noExceptionOops("syncReqNewHead"): + com.syncReqNewHead(header) # ------------------------------------------------------------------------------ # Getters diff --git a/nimbus/common/context.nim b/nimbus/common/context.nim index 9036cf3a9..8e78c3533 100644 --- a/nimbus/common/context.nim +++ b/nimbus/common/context.nim @@ -15,6 +15,8 @@ import export manager +{.push raises: [].} + type EthContext* = ref object am*: AccountsManager @@ -40,7 +42,8 @@ proc containsOnlyHexDigits(hex: string): bool = return false true -proc getNetKeys*(ctx: EthContext, netKey, dataDir: string): Result[KeyPair, string] = +proc getNetKeys*(ctx: EthContext, netKey, dataDir: string): Result[KeyPair, string] + {.gcsafe, raises: [OSError]} = if netKey.len == 0 or netKey == "random": let privateKey = ctx.randomPrivateKey() return ok(privateKey.toKeyPair()) diff --git a/nimbus/common/genesis.nim b/nimbus/common/genesis.nim index e512b68de..262885bc7 100644 --- a/nimbus/common/genesis.nim +++ b/nimbus/common/genesis.nim @@ -1,21 +1,29 @@ import std/tables, eth/[common, rlp, eip1559], - chronicles, eth/trie/[db, trie_defs], + eth/trie/[db, trie_defs], ../db/state_db, ../constants, ./chain_config -{.push raises: [Defect].} +{.push raises: [].} # ------------------------------------------------------------------------------ # Public functions # ------------------------------------------------------------------------------ -proc newStateDB*(db: TrieDatabaseRef, pruneTrie: bool): AccountStateDB = +proc newStateDB*( + db: TrieDatabaseRef; + pruneTrie: bool; + ): AccountStateDB + {.gcsafe, raises: [].}= newAccountStateDB(db, emptyRlpHash, pruneTrie) -proc toGenesisHeader*(g: Genesis, sdb: AccountStateDB, fork: HardFork): BlockHeader - {.raises: [Defect, RlpError].} = +proc toGenesisHeader*( + g: Genesis; + sdb: AccountStateDB; + fork: HardFork; + ): BlockHeader + {.gcsafe, raises: [RlpError].} = ## Initialise block chain DB accounts derived from the `genesis.alloc` table ## of the `db` descriptor argument. ## @@ -86,21 +94,29 @@ proc toGenesisHeader*(g: Genesis, sdb: AccountStateDB, fork: HardFork): BlockHea if g.difficulty.isZero and fork <= London: result.difficulty = GENESIS_DIFFICULTY -proc toGenesisHeader*(genesis: Genesis, fork: HardFork, db: TrieDatabaseRef = nil): BlockHeader - {.raises: [Defect, RlpError].} = +proc toGenesisHeader*( + genesis: Genesis; + fork: HardFork; + db = TrieDatabaseRef(nil); + ): BlockHeader + {.gcsafe, raises: [RlpError].} = ## Generate the genesis block header from the `genesis` and `config` argument value. let db = if db.isNil: newMemoryDB() else: db sdb = newStateDB(db, pruneTrie = true) toGenesisHeader(genesis, sdb, fork) -proc toGenesisHeader*(params: NetworkParams, db: TrieDatabaseRef = nil): BlockHeader - {.raises: [Defect, RlpError].} = +proc toGenesisHeader*( + params: NetworkParams; + db = TrieDatabaseRef(nil); + ): BlockHeader + {.raises: [RlpError].} = ## Generate the genesis block header from the `genesis` and `config` argument value. let map = toForkToBlockNumber(params.config) let fork = map.toHardFork(0.toBlockNumber) toGenesisHeader(params.genesis, fork, db) +# End diff --git a/nimbus/common/hardforks.nim b/nimbus/common/hardforks.nim index 467b46f10..f2469f043 100644 --- a/nimbus/common/hardforks.nim +++ b/nimbus/common/hardforks.nim @@ -14,6 +14,8 @@ import ../utils/utils, ./evmforks +{.push raises: [].} + type ConsensusType* {.pure.} = enum # Proof of Work @@ -265,22 +267,22 @@ type BlockToForks* = array[HardFork, BlockToFork] func forkTrue(data, number, td: UInt256): bool - {.gcsafe, nimcall, raises: [Defect, CatchableError].} = + {.gcsafe, nimcall, raises: [].} = # frontier always return true true func forkFalse(data, number, td: UInt256): bool - {.gcsafe, nimcall, raises: [Defect, CatchableError].} = + {.gcsafe, nimcall, raises: [].} = # forkBlock.isNone always return false false func forkMaybe(data, number, td: UInt256): bool - {.gcsafe, nimcall, raises: [Defect, CatchableError].} = + {.gcsafe, nimcall, raises: [].} = # data is a blockNumber number >= data func mergeMaybe(data, number, td: UInt256): bool - {.gcsafe, nimcall, raises: [Defect, CatchableError].} = + {.gcsafe, nimcall, raises: [].} = # data is a TTD td >= data diff --git a/nimbus/common/manager.nim b/nimbus/common/manager.nim index a77366875..caef599d6 100644 --- a/nimbus/common/manager.nim +++ b/nimbus/common/manager.nim @@ -10,11 +10,12 @@ import std/[os, json, tables, strutils], stew/[byteutils, results], - eth/[keyfile, common, keys], - chronicles + eth/[keyfile, common, keys] from nimcrypto/utils import burnMem +{.push raises: [].} + type NimbusAccount* = object privateKey*: PrivateKey @@ -27,7 +28,8 @@ type proc init*(_: type AccountsManager): AccountsManager = discard -proc loadKeystores*(am: var AccountsManager, path: string): Result[void, string] = +proc loadKeystores*(am: var AccountsManager, path: string): Result[void, string] + {.gcsafe, raises: [OSError].}= try: createDir(path) except OSError, IOError: diff --git a/nimbus/config.nim b/nimbus/config.nim index bb5c12723..5aaeecd99 100644 --- a/nimbus/config.nim +++ b/nimbus/config.nim @@ -534,7 +534,7 @@ proc parseCmdArg(T: type NetworkParams, p: TaintedString): T = try: if not loadNetworkParams(p.string, result): raise newException(ValueError, "failed to load customNetwork") - except Exception as exc: + except Exception: # as exc: -- notused # on linux/mac, nim compiler refuse to compile # with unlisted exception error raise newException(ValueError, "failed to load customNetwork") diff --git a/nimbus/constants.nim b/nimbus/constants.nim index 6e9e2e10e..e341101b0 100644 --- a/nimbus/constants.nim +++ b/nimbus/constants.nim @@ -3,7 +3,7 @@ import eth/common/eth_types -proc default(t: typedesc): t = discard +# proc default(t: typedesc): t = discard -- notused # constants const diff --git a/nimbus/core/clique/clique_cfg.nim b/nimbus/core/clique/clique_cfg.nim index 8ba85b5cc..4c68d48d5 100644 --- a/nimbus/core/clique/clique_cfg.nim +++ b/nimbus/core/clique/clique_cfg.nim @@ -97,8 +97,7 @@ proc newCliqueCfg*(db: ChainDBRef): CliqueCfg = proc ecRecover*( cfg: CliqueCfg; header: BlockHeader; - ): auto - {.gcsafe, raises: [CatchableError].} = + ): auto = cfg.signatures.ecRecover(header) # ------------------------------------------------------------------------------ diff --git a/nimbus/core/clique/clique_verify.nim b/nimbus/core/clique/clique_verify.nim index 0dea56d32..fcc8d7b68 100644 --- a/nimbus/core/clique/clique_verify.nim +++ b/nimbus/core/clique/clique_verify.nim @@ -94,8 +94,7 @@ proc inTurn*(s: Snapshot; number: BlockNumber, signer: EthAddress): bool = # ------------------------------------------------------------------------------ # clique/clique.go(463): func (c *Clique) verifySeal(chain [..] -proc verifySeal(c: Clique; header: BlockHeader): CliqueOkResult - {.gcsafe, raises: [CatchableError].} = +proc verifySeal(c: Clique; header: BlockHeader): CliqueOkResult = ## Check whether the signature contained in the header satisfies the ## consensus protocol requirements. The method accepts an optional list of ## parent headers that aren't yet part of the local blockchain to generate diff --git a/nimbus/db/kvstore_rocksdb.nim b/nimbus/db/kvstore_rocksdb.nim index 8240874d2..ea5c8f01f 100644 --- a/nimbus/db/kvstore_rocksdb.nim +++ b/nimbus/db/kvstore_rocksdb.nim @@ -1,4 +1,4 @@ -{.push raises: [Defect].} +{.push raises: [].} import std/os, @@ -40,7 +40,7 @@ proc init*( readOnly = false): KvResult[T] = let dataDir = basePath / name / "data" - tmpDir = basePath / name / "tmp" + # tmpDir = basePath / name / "tmp" -- notused backupsDir = basePath / name / "backups" try: diff --git a/nimbus/evm/interpreter/op_handlers/oph_log.nim b/nimbus/evm/interpreter/op_handlers/oph_log.nim index f770ff099..9f215ad91 100644 --- a/nimbus/evm/interpreter/op_handlers/oph_log.nim +++ b/nimbus/evm/interpreter/op_handlers/oph_log.nim @@ -27,7 +27,6 @@ import ./oph_gen_handlers, ./oph_helpers, eth/common, - eth/common, sequtils, stint, strformat diff --git a/nimbus/evm/interpreter_dispatch.nim b/nimbus/evm/interpreter_dispatch.nim index ceefe863a..53b5a6a01 100644 --- a/nimbus/evm/interpreter_dispatch.nim +++ b/nimbus/evm/interpreter_dispatch.nim @@ -144,7 +144,7 @@ proc beforeExecCreate(c: Computation): bool = c.snapshot() if c.vmState.readOnlyStateDB().hasCodeOrNonce(c.msg.contractAddress): - let blurb = c.msg.contractAddress.toHex + # let blurb = c.msg.contractAddress.toHex -- notused c.setError("Address collision when creating contract address={blurb}", true) c.rollback() return true diff --git a/nimbus/rpc/common.nim b/nimbus/rpc/common.nim index b9c536503..a506530f5 100644 --- a/nimbus/rpc/common.nim +++ b/nimbus/rpc/common.nim @@ -8,12 +8,14 @@ # those terms. import - std/[strutils, tables], + std/strutils, nimcrypto/utils, eth/common as eth_common, stint, json_rpc/server, json_rpc/errors, eth/p2p, eth/p2p/enode, ../config, ./hexstrings +{.push raises: [].} + type NodePorts = object discovery: string diff --git a/nimbus/rpc/cors.nim b/nimbus/rpc/cors.nim index bd4c0e13e..8e007d166 100644 --- a/nimbus/rpc/cors.nim +++ b/nimbus/rpc/cors.nim @@ -16,6 +16,8 @@ import httputils, websock/websock as ws +{.push raises: [].} + proc sameOrigin(a, b: Uri): bool = a.hostname == b.hostname and a.scheme == b.scheme and diff --git a/nimbus/rpc/debug.nim b/nimbus/rpc/debug.nim index 3520d1429..71fcd000b 100644 --- a/nimbus/rpc/debug.nim +++ b/nimbus/rpc/debug.nim @@ -13,6 +13,8 @@ import hexstrings, ../tracer, ../vm_types, ../common/common +{.push raises: [].} + type TraceOptions = object disableStorage: Option[bool] diff --git a/nimbus/rpc/engine_api.nim b/nimbus/rpc/engine_api.nim index 87eeac78f..def69e37c 100644 --- a/nimbus/rpc/engine_api.nim +++ b/nimbus/rpc/engine_api.nim @@ -9,8 +9,8 @@ import std/[typetraits, times, strutils], - stew/[objects, results, byteutils], - json_rpc/[rpcserver, errors], + stew/[results, byteutils], + json_rpc/rpcserver, web3/[conversions, engine_api_types], eth/rlp, ../common/common, @@ -24,7 +24,10 @@ import # if chronicles import is in the middle chronicles -proc latestValidHash(db: ChainDBRef, parent: EthBlockHeader, ttd: DifficultyInt): Hash256 = +{.push raises: [].} + +proc latestValidHash(db: ChainDBRef, parent: EthBlockHeader, ttd: DifficultyInt): Hash256 + {.gcsafe, raises: [RlpError].} = let ptd = db.getScore(parent.parentHash) if ptd >= ttd: parent.blockHash @@ -33,7 +36,8 @@ proc latestValidHash(db: ChainDBRef, parent: EthBlockHeader, ttd: DifficultyInt) # latestValidHash MUST be set to ZERO Hash256() -proc invalidFCU(com: CommonRef, header: EthBlockHeader): ForkchoiceUpdatedResponse = +proc invalidFCU(com: CommonRef, header: EthBlockHeader): ForkchoiceUpdatedResponse + {.gcsafe, raises: [RlpError].} = var parent: EthBlockHeader if not com.db.getBlockHeader(header.parentHash, parent): return invalidFCU(Hash256()) diff --git a/nimbus/rpc/filters.nim b/nimbus/rpc/filters.nim index bbf01e309..0a3fdd161 100644 --- a/nimbus/rpc/filters.nim +++ b/nimbus/rpc/filters.nim @@ -5,8 +5,6 @@ # * Apache v2 license (license terms in the root directory or at https://www.apache.org/licenses/LICENSE-2.0). # at your option. This file may not be copied, modified, or distributed except according to those terms. -{.push raises: [Defect].} - import std/options, eth/common/[eth_types, eth_types_rlp], @@ -17,6 +15,8 @@ import export rpc_types +{.push raises: [].} + proc topicToDigest(t: seq[Topic]): seq[Hash256] = var resSeq: seq[Hash256] = @[] for top in t: diff --git a/nimbus/rpc/jwt_auth.nim b/nimbus/rpc/jwt_auth.nim index c0c32f88a..6562256a5 100644 --- a/nimbus/rpc/jwt_auth.nim +++ b/nimbus/rpc/jwt_auth.nim @@ -25,7 +25,7 @@ import stew/[byteutils, objects, results], ../config -{.push raises: [Defect].} +{.push raises: [].} logScope: topics = "Jwt/HS256 auth" @@ -95,7 +95,7 @@ proc base64urlEncode(x: auto): string = base64.encode(x, safe = true).replace("=", "") proc base64urlDecode(data: string): string - {.gcsafe, raises: [Defect, CatchableError].} = + {.gcsafe, raises: [CatchableError].} = ## Decodes a JWT specific base64url, optionally encoding with stripped ## padding. let l = data.len mod 4 @@ -254,7 +254,7 @@ proc jwtSharedSecret*(rndSecret: JwtGenSecret; config: NimbusConf): proc jwtSharedSecret*(rng: ref rand.HmacDrbgContext; config: NimbusConf): Result[JwtSharedKey, JwtError] - {.gcsafe, raises: [Defect,JwtExcept].} = + {.gcsafe, raises: [JwtExcept].} = ## Variant of `jwtSharedSecret()` with explicit random generator argument. safeExecutor("jwtSharedSecret"): result = rng.jwtGenSecret.jwtSharedSecret(config) diff --git a/nimbus/rpc/p2p.nim b/nimbus/rpc/p2p.nim index 7120a08e9..f0fc4141e 100644 --- a/nimbus/rpc/p2p.nim +++ b/nimbus/rpc/p2p.nim @@ -22,6 +22,8 @@ import ../utils/utils, ./filters +{.push raises: [].} + #[ Note: * Hexstring types (HexQuantitySt, HexDataStr, EthAddressStr, EthHashStr) @@ -42,7 +44,8 @@ proc setupEthRpc*( let ac = newAccountStateDB(chainDB.db, header.stateRoot, com.pruneTrie) result = ReadOnlyStateDB(ac) - proc stateDBFromTag(tag: string, readOnly = true): ReadOnlyStateDB = + proc stateDBFromTag(tag: string, readOnly = true): ReadOnlyStateDB + {.gcsafe, raises: [CatchableError].} = result = getStateDB(chainDB.headerFromTag(tag)) server.rpc("eth_protocolVersion") do() -> Option[string]: @@ -440,7 +443,8 @@ proc setupEthRpc*( chain: ChainDBRef, hash: Hash256, header: BlockHeader, - opts: FilterOptions): seq[FilterLog] = + opts: FilterOptions): seq[FilterLog] + {.gcsafe, raises: [RlpError,ValueError].} = if headerBloomFilter(header, opts.address, opts.topics): let blockBody = chain.getBlockBody(hash) let receipts = chain.getReceipts(header.receiptRoot) @@ -458,7 +462,8 @@ proc setupEthRpc*( chain: ChainDBRef, start: UInt256, finish: UInt256, - opts: FilterOptions): seq[FilterLog] = + opts: FilterOptions): seq[FilterLog] + {.gcsafe, raises: [RlpError,ValueError].} = var logs = newSeq[FilterLog]() var i = start while i <= finish: diff --git a/nimbus/rpc/rpc_types.nim b/nimbus/rpc/rpc_types.nim index 0ad464090..7604d7c47 100644 --- a/nimbus/rpc/rpc_types.nim +++ b/nimbus/rpc/rpc_types.nim @@ -1,13 +1,15 @@ import json_rpc/jsonmarshal, stew/byteutils, - hexstrings, options, eth/[common, rlp], json + hexstrings, options, eth/common, json from web3/ethtypes import FixedBytes export FixedBytes, common +{.push raises: [].} + #[ Notes: * Some of the types suppose 'null' when there is no appropriate value. @@ -130,8 +132,10 @@ type topics*: seq[Option[seq[Hash256]]] # (optional) list of DATA topics. Topics are order-dependent. Each topic can also be a list of DATA with "or" options. blockHash*: Option[Hash256] # (optional) hash of the block. If its present, fromBlock and toBlock, should be none. Introduced in EIP234 -proc fromJson*(n: JsonNode, argName: string, result: var FilterOptions) = - proc getOptionString(argName: string): Option[string] = +proc fromJson*(n: JsonNode, argName: string, result: var FilterOptions) + {.gcsafe, raises: [KeyError,ValueError].} = + proc getOptionString(argName: string): Option[string] + {.gcsafe, raises: [KeyError,ValueError].} = let s = n.getOrDefault(argName) if s == nil: return none[string]() @@ -141,7 +145,7 @@ proc fromJson*(n: JsonNode, argName: string, result: var FilterOptions) = s.kind.expect(JString, argName) return some[string](s.getStr()) - proc getAddress(): seq[EthAddress] = + proc getAddress(): seq[EthAddress] {.gcsafe, raises: [ValueError].} = ## Address can by provided in two formats: ## 1. {"address": "hexAddress"} ## 2. {"address": ["hexAddress1", "hexAddress2" ...]} @@ -170,7 +174,7 @@ proc fromJson*(n: JsonNode, argName: string, result: var FilterOptions) = else: raise newException(ValueError, "Parameter 'address` should be either string or of array of strings") - proc getTopics(): seq[Option[seq[Hash256]]] = + proc getTopics(): seq[Option[seq[Hash256]]] {.gcsafe, raises: [ValueError].} = ## Topics can be provided in many forms: ## [] "anything" ## [A] "A in first position (and anything after)" @@ -222,7 +226,7 @@ proc fromJson*(n: JsonNode, argName: string, result: var FilterOptions) = raise newException(ValueError, msg) return filterArr - proc getBlockHash(): Option[Hash256] = + proc getBlockHash(): Option[Hash256] {.gcsafe, raises: [KeyError,ValueError].} = let s = getOptionString("blockHash") if s.isNone(): return none[Hash256]() diff --git a/nimbus/rpc/rpc_utils.nim b/nimbus/rpc/rpc_utils.nim index 3221685df..1cd15a539 100644 --- a/nimbus/rpc/rpc_utils.nim +++ b/nimbus/rpc/rpc_utils.nim @@ -9,22 +9,28 @@ import hexstrings, eth/[common, rlp, keys, trie/db], stew/byteutils, ../db/db_chain, strutils, algorithm, options, times, json, - ../constants, stint, hexstrings, rpc_types, + ../constants, stint, rpc_types, ../utils/utils, ../transaction, ../transaction/call_evm, ../common/evmforks +{.push raises: [].} + const defaultTag = "latest" -func toAddress*(value: EthAddressStr): EthAddress = hexToPaddedByteArray[20](value.string) +func toAddress*(value: EthAddressStr): EthAddress + {.gcsafe, raises: [ValueError].} = + hexToPaddedByteArray[20](value.string) -func toHash*(value: array[32, byte]): Hash256 {.inline.} = +func toHash*(value: array[32, byte]): Hash256 = result.data = value -func toHash*(value: EthHashStr): Hash256 {.inline.} = +func toHash*(value: EthHashStr): Hash256 + {.gcsafe, raises: [ValueError].} = result = hexToPaddedByteArray[32](value.string).toHash -func hexToInt*(s: string, T: typedesc[SomeInteger]): T = +func hexToInt*(s: string, T: typedesc[SomeInteger]): T + {.gcsafe, raises: [ValueError].} = var i = 0 if s[i] == '0' and (s[i+1] in {'x', 'X'}): inc(i, 2) if s.len - i > sizeof(T) * 2: @@ -33,7 +39,8 @@ func hexToInt*(s: string, T: typedesc[SomeInteger]): T = result = result shl 4 or readHexChar(s[i]).T inc(i) -proc headerFromTag*(chain: ChainDBRef, blockTag: string): BlockHeader = +proc headerFromTag*(chain: ChainDBRef, blockTag: string): BlockHeader + {.gcsafe, raises: [CatchableError].} = let tag = blockTag.toLowerAscii case tag of "latest": result = chain.getCanonicalHead() @@ -49,13 +56,15 @@ proc headerFromTag*(chain: ChainDBRef, blockTag: string): BlockHeader = let blockNum = stint.fromHex(UInt256, tag) result = chain.getBlockHeader(blockNum.toBlockNumber) -proc headerFromTag*(chain: ChainDBRef, blockTag: Option[string]): BlockHeader = +proc headerFromTag*(chain: ChainDBRef, blockTag: Option[string]): BlockHeader + {.gcsafe, raises: [CatchableError].} = if blockTag.isSome(): return chain.headerFromTag(blockTag.unsafeGet()) else: return chain.headerFromTag(defaultTag) -proc calculateMedianGasPrice*(chain: ChainDBRef): GasInt = +proc calculateMedianGasPrice*(chain: ChainDBRef): GasInt + {.gcsafe, raises: [CatchableError].} = var prices = newSeqOfCap[GasInt](64) let header = chain.getCanonicalHead() for encodedTx in chain.getBlockTransactionData(header.txRoot): @@ -72,7 +81,8 @@ proc calculateMedianGasPrice*(chain: ChainDBRef): GasInt = else: result = prices[middle] -proc unsignedTx*(tx: TxSend, chain: ChainDBRef, defaultNonce: AccountNonce): Transaction = +proc unsignedTx*(tx: TxSend, chain: ChainDBRef, defaultNonce: AccountNonce): Transaction + {.gcsafe, raises: [CatchableError].} = if tx.to.isSome: result.to = some(toAddress(tx.to.get)) @@ -114,7 +124,8 @@ template optionalBytes(src, dst: untyped) = if src.isSome: dst = hexToSeqByte(src.get.string) -proc callData*(call: EthCall): RpcCallData = +proc callData*(call: EthCall): RpcCallData + {.gcsafe, raises: [ValueError].} = optionalAddress(call.source, result.source) optionalAddress(call.to, result.to) optionalGas(call.gas, result.gasLimit) @@ -124,7 +135,8 @@ proc callData*(call: EthCall): RpcCallData = optionalU256(call.value, result.value) optionalBytes(call.data, result.data) -proc populateTransactionObject*(tx: Transaction, header: BlockHeader, txIndex: int): TransactionObject = +proc populateTransactionObject*(tx: Transaction, header: BlockHeader, txIndex: int): TransactionObject + {.gcsafe, raises: [ValidationError].} = result.blockHash = some(header.hash) result.blockNumber = some(encodeQuantity(header.blockNumber)) result.`from` = tx.getSender() @@ -140,7 +152,8 @@ proc populateTransactionObject*(tx: Transaction, header: BlockHeader, txIndex: i result.r = encodeQuantity(tx.R) result.s = encodeQuantity(tx.S) -proc populateBlockObject*(header: BlockHeader, chain: ChainDBRef, fullTx: bool, isUncle = false): BlockObject = +proc populateBlockObject*(header: BlockHeader, chain: ChainDBRef, fullTx: bool, isUncle = false): BlockObject + {.gcsafe, raises: [CatchableError].} = let blockHash = header.blockHash result.number = some(encodeQuantity(header.blockNumber)) @@ -182,7 +195,8 @@ proc populateBlockObject*(header: BlockHeader, chain: ChainDBRef, fullTx: bool, result.transactions.add %(x) proc populateReceipt*(receipt: Receipt, gasUsed: GasInt, tx: Transaction, - txIndex: int, header: BlockHeader, fork: EVMFork): ReceiptObject = + txIndex: int, header: BlockHeader, fork: EVMFork): ReceiptObject + {.gcsafe, raises: [ValidationError].} = result.transactionHash = tx.rlpHash result.transactionIndex = encodeQuantity(txIndex.uint) result.blockHash = header.hash diff --git a/nimbus/transaction/call_common.nim b/nimbus/transaction/call_common.nim index 230bf74fd..4804c2765 100644 --- a/nimbus/transaction/call_common.nim +++ b/nimbus/transaction/call_common.nim @@ -51,7 +51,7 @@ type proc hostToComputationMessage*(msg: EvmcMessage): Message = Message( - kind: CallKind(msg.kind), + kind: CallKind(msg.kind.ord), depth: msg.depth, gas: msg.gas, sender: msg.sender.fromEvmc, diff --git a/nimbus/utils/ec_recover.nim b/nimbus/utils/ec_recover.nim index 14734ca12..895ce55f2 100644 --- a/nimbus/utils/ec_recover.nim +++ b/nimbus/utils/ec_recover.nim @@ -27,7 +27,7 @@ import export utils_defs, results -{.push raises: [Defect].} +{.push raises: [].} const INMEMORY_SIGNATURES* = ##\ @@ -153,7 +153,7 @@ proc len*(er: var EcRecover): int = # ------------------------------------------------------------------------------ proc ecRecover*(er: var EcRecover; header: var BlockHeader): EcAddrResult - {.gcsafe, raises: [Defect,CatchableError].} = + = ## Extract account address from `extraData` field (last 65 bytes) of the ## argument header. The result is kept in a LRU cache to re-purposed for ## improved result delivery avoiding calculations. @@ -169,13 +169,13 @@ proc ecRecover*(er: var EcRecover; header: var BlockHeader): EcAddrResult err(rc.error) proc ecRecover*(er: var EcRecover; header: BlockHeader): EcAddrResult - {.gcsafe, raises: [Defect,CatchableError].} = + = ## Variant of `ecRecover()` for call-by-value header var hdr = header er.ecRecover(hdr) proc ecRecover*(er: var EcRecover; hash: Hash256): EcAddrResult - {.gcsafe, raises: [Defect,CatchableError].} = + = ## Variant of `ecRecover()` for hash only. Will only succeed it the ## argument hash is uk the LRU queue. let rc = er.q.lruFetch(hash.data) @@ -188,7 +188,7 @@ proc ecRecover*(er: var EcRecover; hash: Hash256): EcAddrResult # ------------------------------------------------------------------------------ proc append*(rw: var RlpWriter; data: EcRecover) - {.raises: [Defect,KeyError].} = + {.raises: [KeyError].} = ## Generic support for `rlp.encode()` rw.append((data.size,data.q)) @@ -202,8 +202,7 @@ proc read*(rlp: var Rlp; Q: type EcRecover): Q # Debugging # ------------------------------------------------------------------------------ -iterator keyItemPairs*(er: var EcRecover): (EcKey,EthAddress) - {.gcsafe, raises: [Defect,CatchableError].} = +iterator keyItemPairs*(er: var EcRecover): (EcKey,EthAddress) = var rc = er.q.first while rc.isOk: yield (rc.value.key, rc.value.data) diff --git a/nimbus/utils/keyed_queue/kq_rlp.nim b/nimbus/utils/keyed_queue/kq_rlp.nim index ed8ebb1a6..04b9f5e8d 100644 --- a/nimbus/utils/keyed_queue/kq_rlp.nim +++ b/nimbus/utils/keyed_queue/kq_rlp.nim @@ -21,12 +21,14 @@ import eth/rlp, stew/keyed_queue +{.push raises: [].} + # ------------------------------------------------------------------------------ # Public functions, RLP support # ------------------------------------------------------------------------------ proc append*[K,V](rw: var RlpWriter; kq: KeyedQueue[K,V]) - {.raises: [Defect,KeyError].} = + {.raises: [KeyError].} = ## Generic support for `rlp.encode(kq)` for serialising a queue. ## ## :CAVEAT: diff --git a/nimbus/utils/prettify.nim b/nimbus/utils/prettify.nim index 2b5a774e2..57be4e8d2 100644 --- a/nimbus/utils/prettify.nim +++ b/nimbus/utils/prettify.nim @@ -14,6 +14,8 @@ import std/[math, strutils] +{.push raises: [].} + proc toSI*(num: SomeUnsignedInt): string = ## Prints `num` argument value greater than 99 as rounded SI unit. const diff --git a/nimbus/utils/utils.nim b/nimbus/utils/utils.nim index ccb1f95af..844acbd30 100644 --- a/nimbus/utils/utils.nim +++ b/nimbus/utils/utils.nim @@ -4,7 +4,10 @@ import export eth_types_rlp -proc calcRootHash[T](items: openArray[T]): Hash256 = +{.push raises: [].} + +proc calcRootHash[T](items: openArray[T]): Hash256 + {.gcsafe, raises: [RlpError]} = var tr = initHexaryTrie(newMemoryDB()) for i, t in items: tr.put(rlp.encode(i), rlp.encode(t)) diff --git a/nimbus/utils/utils_defs.nim b/nimbus/utils/utils_defs.nim index 28310550c..bbc72467e 100644 --- a/nimbus/utils/utils_defs.nim +++ b/nimbus/utils/utils_defs.nim @@ -13,6 +13,8 @@ ## =================================== ## +{.push raises: [].} + type UtilsErrorType* = enum resetUtilsError = ##\ @@ -50,8 +52,7 @@ const ## No-error constant (resetUtilsError, "") - -proc `$`*(e: UtilsError): string {.inline.} = +proc `$`*(e: UtilsError): string = ## Join text fragments result = $e[0] if e[1] != "": diff --git a/stateless/witness_from_tree.nim b/stateless/witness_from_tree.nim index 318e018a4..61c1b488c 100644 --- a/stateless/witness_from_tree.nim +++ b/stateless/witness_from_tree.nim @@ -6,6 +6,8 @@ import ./witness_types, ../nimbus/constants, ../nimbus/db/storage_types, ./multi_keys +{.push raises: [].} + type DB = TrieDatabaseRef @@ -31,7 +33,7 @@ proc initWitnessBuilder*(db: DB, rootHash: KeccakHash, flags: WitnessFlags = {}) template extensionNodeKey(r: Rlp): auto = hexPrefixDecode r.listElem(0).toBytes -proc expectHash(r: Rlp): seq[byte] = +proc expectHash(r: Rlp): seq[byte] {.gcsafe, raises: [RlpError].} = result = r.toBytes if result.len != 32: raise newException(RlpTypeMismatch, @@ -41,7 +43,7 @@ template getNode(elem: untyped): untyped = if elem.isList: @(elem.rawData) else: @(get(wb.db, elem.expectHash)) -proc rlpListToBitmask(r: var Rlp): uint = +proc rlpListToBitmask(r: var Rlp): uint {.gcsafe, raises: [RlpError].} = # only bit 1st to 16th are valid # the 1st bit is the rightmost bit var i = 0 @@ -64,7 +66,8 @@ when defined(debugHash): template writeByte(wb: var WitnessBuilder, x: untyped) = wb.write(byte(x)) -proc writeUVarint(wb: var WitnessBuilder, x: SomeUnsignedInt) = +proc writeUVarint(wb: var WitnessBuilder, x: SomeUnsignedInt) + {.gcsafe, raises: [IOError].} = # LEB128 varint encoding var value = x while true: @@ -78,7 +81,8 @@ proc writeUVarint(wb: var WitnessBuilder, x: SomeUnsignedInt) = template writeUVarint32(wb: var WitnessBuilder, x: untyped) = wb.writeUVarint(uint32(x)) -proc writeUVarint(wb: var WitnessBuilder, x: UInt256) = +proc writeUVarint(wb: var WitnessBuilder, x: UInt256) + {.gcsafe, raises: [IOError].} = # LEB128 varint encoding var value = x while true: @@ -90,7 +94,8 @@ proc writeUVarint(wb: var WitnessBuilder, x: UInt256) = wb.writeByte(b) if value == 0: break -proc writeNibbles(wb: var WitnessBuilder; n: NibblesSeq, withLen: bool = true) = +proc writeNibbles(wb: var WitnessBuilder; n: NibblesSeq, withLen: bool = true) + {.gcsafe, raises: [IOError].} = # convert the NibblesSeq into left aligned byte seq # perhaps we can optimize it if the NibblesSeq already left aligned let nibblesLen = n.len @@ -109,7 +114,8 @@ proc writeNibbles(wb: var WitnessBuilder; n: NibblesSeq, withLen: bool = true) = # write nibbles wb.write(bytes.toOpenArray(0, numBytes-1)) -proc writeExtensionNode(wb: var WitnessBuilder, n: NibblesSeq, depth: int, node: openArray[byte]) = +proc writeExtensionNode(wb: var WitnessBuilder, n: NibblesSeq, depth: int, node: openArray[byte]) + {.gcsafe, raises: [IOError].} = # write type wb.writeByte(ExtensionNodeType) # write nibbles @@ -121,7 +127,8 @@ proc writeExtensionNode(wb: var WitnessBuilder, n: NibblesSeq, depth: int, node: when defined(debugHash): wb.write(keccakHash(node).data) -proc writeBranchNode(wb: var WitnessBuilder, mask: uint, depth: int, node: openArray[byte]) = +proc writeBranchNode(wb: var WitnessBuilder, mask: uint, depth: int, node: openArray[byte]) + {.gcsafe, raises: [IOError].} = # write type # branch node 17th elem should always empty doAssert mask.branchMaskBitIsSet(16) == false @@ -137,7 +144,8 @@ proc writeBranchNode(wb: var WitnessBuilder, mask: uint, depth: int, node: openA when defined(debugHash): wb.write(keccakHash(node).data) -proc writeHashNode(wb: var WitnessBuilder, node: openArray[byte], depth: int, storageMode: bool) = +proc writeHashNode(wb: var WitnessBuilder, node: openArray[byte], depth: int, storageMode: bool) + {.gcsafe, raises: [IOError].} = # usually a hash node means the recursion will not go deeper # and the information can be represented by the hash # for chunked witness, a hash node can be a root to another @@ -147,16 +155,18 @@ proc writeHashNode(wb: var WitnessBuilder, node: openArray[byte], depth: int, st wb.writeByte(ShortRlpPrefix) wb.write(node) -proc writeShortRlp(wb: var WitnessBuilder, node: openArray[byte], depth: int, storageMode: bool) = +proc writeShortRlp(wb: var WitnessBuilder, node: openArray[byte], depth: int, storageMode: bool) + {.gcsafe, raises: [IOError].} = doAssert(node.len < 32 and depth >= 9 and storageMode) wb.writeByte(HashNodeType) wb.writeByte(ShortRlpPrefix) wb.writeByte(node.len) wb.write(node) -proc getBranchRecurse(wb: var WitnessBuilder, z: var StackElem) {.raises: [ContractCodeError, IOError, Defect, CatchableError, Exception].} +proc getBranchRecurse(wb: var WitnessBuilder, z: var StackElem) {.gcsafe, raises: [CatchableError].} -proc writeByteCode(wb: var WitnessBuilder, kd: KeyData, acc: Account, depth: int) = +proc writeByteCode(wb: var WitnessBuilder, kd: KeyData, acc: Account, depth: int) + {.gcsafe, raises: [IOError,ContractCodeError].} = if not kd.codeTouched: # the account have code but not touched by the EVM # in current block execution @@ -182,7 +192,8 @@ proc writeByteCode(wb: var WitnessBuilder, kd: KeyData, acc: Account, depth: int wb.writeUVarint32(code.len) wb.write(code) -proc writeStorage(wb: var WitnessBuilder, kd: KeyData, acc: Account, depth: int) = +proc writeStorage(wb: var WitnessBuilder, kd: KeyData, acc: Account, depth: int) + {.gcsafe, raises: [CatchableError].} = if kd.storageKeys.isNil: # the account have storage but not touched by EVM wb.writeHashNode(acc.storageRoot.data, depth, true) @@ -201,7 +212,7 @@ proc writeStorage(wb: var WitnessBuilder, kd: KeyData, acc: Account, depth: int) wb.writeHashNode(emptyRlpHash.data, depth, true) proc writeAccountNode(wb: var WitnessBuilder, kd: KeyData, acc: Account, - node: openArray[byte], depth: int) {.raises: [ContractCodeError, IOError, Defect, CatchableError, Exception].} = + node: openArray[byte], depth: int) {.raises: [ContractCodeError, IOError, CatchableError].} = # write type wb.writeByte(AccountNodeType) @@ -228,7 +239,8 @@ proc writeAccountNode(wb: var WitnessBuilder, kd: KeyData, acc: Account, #0x00 address:
balance: nonce: #0x01 address:
balance: nonce: bytecode: storage: -proc writeAccountStorageLeafNode(wb: var WitnessBuilder, key: openArray[byte], val: UInt256, node: openArray[byte], depth: int) = +proc writeAccountStorageLeafNode(wb: var WitnessBuilder, key: openArray[byte], val: UInt256, node: openArray[byte], depth: int) + {.gcsafe, raises: [IOError].} = wb.writeByte(StorageLeafNodeType) when defined(debugHash): @@ -324,7 +336,7 @@ proc getBranchRecurse(wb: var WitnessBuilder, z: var StackElem) = "HexaryTrie node with an unexpected number of children") proc buildWitness*(wb: var WitnessBuilder, keys: MultikeysRef): seq[byte] - {.raises: [ContractCodeError, IOError, Defect, CatchableError, Exception].} = + {.raises: [CatchableError].} = # witness version wb.writeByte(BlockWitnessVersion) diff --git a/stateless/witness_types.nim b/stateless/witness_types.nim index ed1033bcf..26fe26b47 100644 --- a/stateless/witness_types.nim +++ b/stateless/witness_types.nim @@ -1,4 +1,6 @@ -import nimcrypto/hash, stew/bitops2 +import stew/bitops2 + +{.push raises: [].} type TrieNodeType* = enum @@ -35,15 +37,16 @@ const BlockWitnessVersion* = 0x01 ShortRlpPrefix* = 0.byte -proc setBranchMaskBit*(x: var uint, i: int) {.inline.} = +proc setBranchMaskBit*(x: var uint, i: int) = assert(i >= 0 and i < 17) x = x or (1 shl i).uint -func branchMaskBitIsSet*(x: uint, i: int): bool {.inline.} = +func branchMaskBitIsSet*(x: uint, i: int): bool = assert(i >= 0 and i < 17) result = ((x shr i.uint) and 1'u) == 1'u -func constructBranchMask*(b1, b2: byte): uint {.inline.} = +func constructBranchMask*(b1, b2: byte): uint + {.gcsafe, raises: [ParsingError].} = result = uint(b1) shl 8 or uint(b2) if countOnes(result) < 2 or ((result and (not 0x1FFFF'u)) != 0): raise newException(ParsingError, "Invalid branch mask pattern " & $result) diff --git a/tests/replay/gunzip.nim b/tests/replay/gunzip.nim index e9e8d2ba9..2fbfca1d5 100644 --- a/tests/replay/gunzip.nim +++ b/tests/replay/gunzip.nim @@ -39,7 +39,7 @@ type lnList: seq[string] lnInx: int -{.push raises: [Defect].} +{.push raises: [].} # ------------------------------------------------------------------------------ # Private deflate helpers: @@ -101,7 +101,7 @@ proc explode(state: var GUnzip; data: openArray[char]; # ------------------------------------------------------------------------------ proc open*(state: var GUnzip; fileName: string): - Result[void,ZError] {.gcsafe, raises: [Defect,IOError].} = + Result[void,ZError] {.gcsafe, raises: [IOError].} = ## Open gzipped file with path `fileName` and prepare for deflating and ## extraction. @@ -142,7 +142,7 @@ proc open*(state: var GUnzip; fileName: string): return ok() -proc close*(state: var GUnzip) {.gcsafe.} = +proc close*(state: var GUnzip) = ## Close any open files and free resources if state.gzOpenOK: state.gzIn.close @@ -150,7 +150,7 @@ proc close*(state: var GUnzip) {.gcsafe.} = proc nextChunk*(state: var GUnzip): - Result[string,ZError] {.gcsafe, raises: [Defect,IOError].} = + Result[string,ZError] {.gcsafe, raises: [IOError].} = ## Fetch next unzipped data chunk, return and empty string if input ## is exhausted. var strBuf = 4096.newString @@ -170,14 +170,14 @@ proc nextChunk*(state: var GUnzip): return -proc nextChunkOk*(state: var GUnzip): bool {.inline,gcsafe.} = +proc nextChunkOk*(state: var GUnzip): bool = ## True if there is another chunk of data so that `nextChunk()` might ## fetch another non-empty unzipped data chunk. state.gzCount < state.gzMax proc nextLine*(state: var GUnzip): - Result[string,ZError] {.gcsafe, raises: [Defect,IOError].} = + Result[string,ZError] {.gcsafe, raises: [IOError].} = ## Assume that the `state` argument descriptor referes to a gzipped text ## file with lines separated by a newline character. Then fetch the next ## unzipped line and return it. @@ -216,13 +216,13 @@ proc nextLine*(state: var GUnzip): state.lnInx = 1 -proc nextLineOk*(state: var GUnzip): bool {.inline,gcsafe.} = +proc nextLineOk*(state: var GUnzip): bool = ## True if there is another unzipped line available with `nextLine()`. state.nextChunkOk or state.lnInx + 1 < state.lnList.len iterator gunzipLines*(state: var GUnzip): - (int,string) {.gcsafe, raises: [Defect,IOError].} = + (int,string) {.gcsafe, raises: [IOError].} = ## Iterate over all lines of gzipped text file `fileName` and return ## the pair `(line-number,line-text)` var lno = 0 @@ -235,7 +235,7 @@ iterator gunzipLines*(state: var GUnzip): iterator gunzipLines*(fileName: string): - (int,string) {.gcsafe, raises: [Defect,IOError].} = + (int,string) {.gcsafe, raises: [IOError].} = ## Open a gzipped text file, iterate over its lines (using the other ## version of `gunzipLines()`) and close it. var state: GUnzip diff --git a/tests/test_accounts_cache.nim b/tests/test_accounts_cache.nim index 5a14e72ed..be8b90a78 100644 --- a/tests/test_accounts_cache.nim +++ b/tests/test_accounts_cache.nim @@ -10,6 +10,7 @@ import std/[os, sequtils, strformat, strutils, tables], + chronicles, ../nimbus/db/accounts_cache, ../nimbus/common/common, ../nimbus/core/chain, @@ -78,6 +79,16 @@ proc pp*(tx: Transaction; vmState: BaseVMState): string = "," & $vmState.readOnlyStateDB.getBalance(address) & ")" +proc setTraceLevel = + discard + when defined(chronicles_runtime_filtering) and loggingEnabled: + setLogLevel(LogLevel.TRACE) + +proc setErrorLevel = + discard + when defined(chronicles_runtime_filtering) and loggingEnabled: + setLogLevel(LogLevel.ERROR) + # ------------------------------------------------------------------------------ # Private functions # ------------------------------------------------------------------------------ @@ -203,7 +214,7 @@ proc runTrial3crash(vmState: BaseVMState; inx: int; noisy = false) = try: vmState.stateDB.persist(clearCache = false) - except AssertionError as e: + except AssertionDefect as e: if noisy: let msg = e.msg.rsplit($DirSep,1)[^1] echo &"*** runVmExec({eAddr.pp}): {e.name}: {msg}" @@ -339,7 +350,7 @@ proc runner(noisy = true; capture = goerliCapture) = defer: dbTx.dispose() for n in txi: let vmState = com.getVmState(xdb.getCanonicalHead.blockNumber) - expect AssertionError: + expect AssertionDefect: vmState.runTrial3crash(n, noisy) test &"Run {txi.len} tree-step trials without rollback": @@ -367,6 +378,7 @@ when isMainModule: var noisy = defined(debug) #noisy = true + setErrorLevel() noisy.runner # mainCapture # noisy.runner goerliCapture2 diff --git a/tests/test_clique/pool.nim b/tests/test_clique/pool.nim index 3bea22d2c..94f17778a 100644 --- a/tests/test_clique/pool.nim +++ b/tests/test_clique/pool.nim @@ -10,7 +10,7 @@ import std/[algorithm, sequtils, strformat, strutils, tables, times], - eth/[keys, rlp], + eth/keys, ethash, secp256k1/abi, stew/objects, diff --git a/tests/test_jwt_auth.nim b/tests/test_jwt_auth.nim index ced3c520c..e79e5691b 100644 --- a/tests/test_jwt_auth.nim +++ b/tests/test_jwt_auth.nim @@ -12,11 +12,10 @@ ## ==================================== import - std/[base64, json, options, os, strutils, tables, times], + std/[base64, json, options, os, strutils, times], ../nimbus/config, ../nimbus/rpc/jwt_auth, ./replay/pp, - confutils/defs, chronicles, chronos/apps/http/httpclient as chronoshttpclient, chronos/apps/http/httptable,