Skip to content

Commit

Permalink
fix most ConvFromXtoItselfNotNeeded hints and unhide remaining ones (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
tersec authored May 22, 2024
1 parent e0f8ea7 commit b56a671
Show file tree
Hide file tree
Showing 21 changed files with 64 additions and 75 deletions.
6 changes: 1 addition & 5 deletions beacon_chain/consensus_object_pools/block_dag.nim
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,8 @@

import
chronicles,
../spec/datatypes/[phase0, altair, bellatrix],
../spec/forks

from ../spec/datatypes/capella import SomeBeaconBlock, TrustedBeaconBlock
from ../spec/datatypes/deneb import SomeBeaconBlock, TrustedBeaconBlock

export chronicles, forks

type
Expand Down Expand Up @@ -76,7 +72,7 @@ func init*(
deneb.SomeBeaconBlock | deneb.TrustedBeaconBlock |
electra.SomeBeaconBlock | electra.TrustedBeaconBlock): BlockRef =
BlockRef.init(
root, Opt.some Eth2Digest(blck.body.execution_payload.block_hash),
root, Opt.some blck.body.execution_payload.block_hash,
executionValid =
executionValid or blck.body.execution_payload.block_hash == ZERO_HASH,
blck.slot)
Expand Down
4 changes: 2 additions & 2 deletions beacon_chain/el/deposit_contract.nim
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ proc sendEth(web3: Web3, to: Eth1Address, valueEth: int): Future[TxHash] =
# TODO: Force json-rpc to generate 'data' field
# should not be needed anymore, new execution-api schema
# is using `input` field
data: some(newSeq[byte]()),
data: some(newSeq[byte]()),
gas: Quantity(3000000).some,
gasPrice: Quantity(1).some,
value: some(valueEth.u256 * 1000000000000000000.u256),
Expand Down Expand Up @@ -273,7 +273,7 @@ proc main() {.async.} =
error "Failed to read an Eth1 private key from standard input"

if privateKey.len > 0:
conf.privateKey = privateKey.string
conf.privateKey = privateKey

let web3 = await initWeb3(conf.web3Url, conf.privateKey)

Expand Down
4 changes: 2 additions & 2 deletions beacon_chain/networking/eth2_discovery.nim
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ type

func parseBootstrapAddress*(address: string):
Result[enr.Record, cstring] =
let lowerCaseAddress = toLowerAscii(string address)
let lowerCaseAddress = toLowerAscii(address)
if lowerCaseAddress.startsWith("enr:"):
var enrRec: enr.Record
if enrRec.fromURI(string address):
if enrRec.fromURI(address):
return ok enrRec
return err "Invalid ENR bootstrap record"
elif lowerCaseAddress.startsWith("enode:"):
Expand Down
3 changes: 1 addition & 2 deletions beacon_chain/nim.cfg
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# beacon_chain
# Copyright (c) 2021-2023 Status Research & Development GmbH
# Copyright (c) 2021-2024 Status Research & Development GmbH
# Licensed and distributed under either of
# * MIT license (license terms in the root directory or at https://opensource.org/licenses/MIT).
# * Apache v2 license (license terms in the root directory or at https://www.apache.org/licenses/LICENSE-2.0).
Expand All @@ -10,5 +10,4 @@

--styleCheck:usages
--styleCheck:hint
--hint[ConvFromXtoItselfNotNeeded]:off
--hint[Processing]:off
2 changes: 1 addition & 1 deletion beacon_chain/rpc/rest_key_management_api.nim
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ proc listRemoteValidators*(
if item.kind == ValidatorKind.Remote and item.data.remotes.len == 1:
validators.add RemoteKeystoreInfo(
pubkey: item.pubkey,
url: HttpHostUri(item.data.remotes[0].url)
url: item.data.remotes[0].url
)
validators

Expand Down
8 changes: 4 additions & 4 deletions beacon_chain/rpc/rest_validator_api.nim
Original file line number Diff line number Diff line change
Expand Up @@ -688,8 +688,8 @@ proc installValidatorApiHandlers*(router: var RestRouter, node: BeaconNode) =
message = (await PayloadType.makeBeaconBlockForHeadAndSlot(
node, qrandao, proposer, qgraffiti, qhead, qslot)).valueOr:
return RestApiResponse.jsonError(Http500, error)
executionValue = Opt.some(UInt256(message.executionPayloadValue))
consensusValue = Opt.some(UInt256(message.consensusBlockValue))
executionValue = Opt.some(message.executionPayloadValue)
consensusValue = Opt.some(message.consensusBlockValue)
headers = consensusFork.getMaybeBlindedHeaders(
isBlinded = false, executionValue, consensusValue)

Expand Down Expand Up @@ -914,7 +914,7 @@ proc installValidatorApiHandlers*(router: var RestRouter, node: BeaconNode) =
request.validator_index).pubkey

node.validatorMonitor[].addAutoMonitor(
validator_pubkey, ValidatorIndex(request.validator_index))
validator_pubkey, request.validator_index)

RestApiResponse.jsonMsgResponse(BeaconCommitteeSubscriptionSuccess)

Expand Down Expand Up @@ -955,7 +955,7 @@ proc installValidatorApiHandlers*(router: var RestRouter, node: BeaconNode) =
validator_pubkey, item.until_epoch)

node.validatorMonitor[].addAutoMonitor(
validator_pubkey, ValidatorIndex(item.validator_index))
validator_pubkey, item.validator_index)

RestApiResponse.jsonMsgResponse(SyncCommitteeSubscriptionSuccess)

Expand Down
2 changes: 1 addition & 1 deletion beacon_chain/spec/beaconstate.nim
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ func initiate_validator_exit*(
# Set validator exit epoch and withdrawable epoch
validator.exit_epoch = exit_queue_epoch
validator.withdrawable_epoch =
Epoch(validator.exit_epoch + cfg.MIN_VALIDATOR_WITHDRAWABILITY_DELAY)
validator.exit_epoch + cfg.MIN_VALIDATOR_WITHDRAWABILITY_DELAY
if validator.withdrawable_epoch < validator.exit_epoch:
return err("Invalid large withdrawable epoch")
state.validators.mitem(index) = validator
Expand Down
6 changes: 3 additions & 3 deletions beacon_chain/spec/eth2_apis/rest_light_client_calls.nim
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ proc getLightClientBootstrap*(
let consensusForkRes = ConsensusFork.decodeString(
resp.headers.getString("eth-consensus-version"))
if consensusForkRes.isErr:
raiseRestDecodingBytesError(cstring(consensusForkRes.error))
raiseRestDecodingBytesError(consensusForkRes.error)
ForkedLightClientBootstrap.decodeHttpLightClientObject(
data, resp.contentType, consensusForkRes.get, cfg)
of 404:
Expand Down Expand Up @@ -294,7 +294,7 @@ proc getLightClientFinalityUpdate*(
let consensusForkRes = ConsensusFork.decodeString(
resp.headers.getString("eth-consensus-version"))
if consensusForkRes.isErr:
raiseRestDecodingBytesError(cstring(consensusForkRes.error))
raiseRestDecodingBytesError(consensusForkRes.error)
ForkedLightClientFinalityUpdate.decodeHttpLightClientObject(
data, resp.contentType, consensusForkRes.get, cfg)
of 404:
Expand Down Expand Up @@ -336,7 +336,7 @@ proc getLightClientOptimisticUpdate*(
let consensusForkRes = ConsensusFork.decodeString(
resp.headers.getString("eth-consensus-version"))
if consensusForkRes.isErr:
raiseRestDecodingBytesError(cstring(consensusForkRes.error))
raiseRestDecodingBytesError(consensusForkRes.error)
ForkedLightClientOptimisticUpdate.decodeHttpLightClientObject(
data, resp.contentType, consensusForkRes.get, cfg)
of 404:
Expand Down
62 changes: 31 additions & 31 deletions beacon_chain/spec/keystore.nim
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ template `$`*(x: WalletName): string =
# TODO: `burnMem` in nimcrypto could use distinctBase
# to make its usage less error-prone.
template burnMem*(m: var (Mnemonic|string)) =
ncrutils.burnMem(string m)
ncrutils.burnMem(distinctBase m)

template burnMem*(m: var KeySeed) =
ncrutils.burnMem(distinctBase m)
Expand Down Expand Up @@ -324,7 +324,7 @@ const
englishWordsDigest =
"AD90BF3BEB7B0EB7E5ACD74727DC0DA96E0A280A258354E7293FB7E211AC03DB".toDigest

proc checkEnglishWords(): bool =
func checkEnglishWords(): bool =
if len(englishWords) != wordListLen:
false
else:
Expand All @@ -341,7 +341,7 @@ func validateKeyPath*(path: string): Result[KeyPath, cstring] =
var digitCount: int
var number: BiggestUInt
try:
for elem in path.string.split("/"):
for elem in path.split("/"):
# TODO: doesn't "m" have to be the first character and is it the only
# place where it is valid?
if elem == "m":
Expand Down Expand Up @@ -382,7 +382,7 @@ func isControlRune(r: Rune): bool =
let r = int r
(r >= 0 and r < 0x20) or (r >= 0x7F and r < 0xA0)

proc init*(T: type KeystorePass, input: string): T =
func init*(T: type KeystorePass, input: string): T =
for rune in toNFKD(input):
if not isControlRune(rune):
result.str.add rune
Expand All @@ -395,7 +395,7 @@ func getSeed*(mnemonic: Mnemonic, password: KeystorePass): KeySeed =
template add(m: var Mnemonic, s: cstring) =
m.string.add s

proc generateMnemonic*(
func generateMnemonic*(
rng: var HmacDrbgContext,
words: openArray[cstring] = englishWords,
entropyParam: openArray[byte] = @[]): Mnemonic =
Expand Down Expand Up @@ -429,12 +429,12 @@ proc generateMnemonic*(
result.add " "
result.add words[entropy.getBitsBE(firstBit..lastBit)]

proc cmpIgnoreCase(lhs: cstring, rhs: string): int =
func cmpIgnoreCase(lhs: cstring, rhs: string): int =
# TODO: This is a bit silly.
# Nim should have a `cmp` function for C strings.
cmpIgnoreCase($lhs, rhs)

proc validateMnemonic*(inputWords: string,
func validateMnemonic*(inputWords: string,
outputMnemonic: var Mnemonic): bool =
## Accept a case-insensitive input string and returns `true`
## if it represents a valid mnenomic. The `outputMnemonic`
Expand Down Expand Up @@ -465,7 +465,7 @@ proc validateMnemonic*(inputWords: string,

return true

proc deriveChildKey*(parentKey: ValidatorPrivKey,
func deriveChildKey*(parentKey: ValidatorPrivKey,
index: Natural): ValidatorPrivKey =
let success = derive_child_secretKey(SecretKey result,
SecretKey parentKey,
Expand All @@ -475,25 +475,25 @@ proc deriveChildKey*(parentKey: ValidatorPrivKey,
# into asserts inside the function.
doAssert success

proc deriveMasterKey*(seed: KeySeed): ValidatorPrivKey =
func deriveMasterKey*(seed: KeySeed): ValidatorPrivKey =
let success = derive_master_secretKey(SecretKey result,
seq[byte] seed)
# TODO `derive_master_secretKey` is reporting pre-condition
# failures with return values. We should turn the checks
# into asserts inside the function.
doAssert success

proc deriveMasterKey*(mnemonic: Mnemonic,
func deriveMasterKey*(mnemonic: Mnemonic,
password: KeystorePass): ValidatorPrivKey =
deriveMasterKey(getSeed(mnemonic, password))

proc deriveChildKey*(masterKey: ValidatorPrivKey,
func deriveChildKey*(masterKey: ValidatorPrivKey,
path: KeyPath): ValidatorPrivKey =
result = masterKey
for idx in pathNodes(path):
result = deriveChildKey(result, idx)

proc deriveChildKey*(masterKey: ValidatorPrivKey,
func deriveChildKey*(masterKey: ValidatorPrivKey,
path: openArray[Natural]): ValidatorPrivKey =
result = masterKey
for idx in path:
Expand All @@ -503,12 +503,12 @@ proc deriveChildKey*(masterKey: ValidatorPrivKey,
# if we fail we want to scrub secrets from memory
result = deriveChildKey(result, idx)

proc keyFromPath*(mnemonic: Mnemonic,
func keyFromPath*(mnemonic: Mnemonic,
password: KeystorePass,
path: KeyPath): ValidatorPrivKey =
deriveChildKey(deriveMasterKey(mnemonic, password), path)

proc shaChecksum(key, cipher: openArray[byte]): Sha256Digest =
func shaChecksum(key, cipher: openArray[byte]): Sha256Digest =
var ctx: sha256
ctx.init()
ctx.update(key)
Expand Down Expand Up @@ -681,7 +681,7 @@ proc readValue*(r: var JsonReader[DefaultFlavor], value: var Kdf)
readValueImpl(r, value)
{.pop.}

proc readValue*(r: var JsonReader, value: var (Checksum|Cipher|Kdf)) =
func readValue*(r: var JsonReader, value: var (Checksum|Cipher|Kdf)) =
static: raiseAssert "Unknown flavor `JsonReader[" & $typeof(r).Flavor &
"]` for `readValue` of `" & $typeof(value) & "`"

Expand Down Expand Up @@ -951,7 +951,7 @@ func areValid(params: ScryptParams): bool =
params.p == scryptParams.p and
params.salt.bytes.len > 0

proc decryptCryptoField*(crypto: Crypto, decKey: openArray[byte],
func decryptCryptoField*(crypto: Crypto, decKey: openArray[byte],
outSecret: var seq[byte]): DecryptionStatus =
if crypto.cipher.message.bytes.len == 0:
return DecryptionStatus.InvalidKeystore
Expand All @@ -977,7 +977,7 @@ proc decryptCryptoField*(crypto: Crypto, decKey: openArray[byte],
aesCipher.clear()
DecryptionStatus.Success

proc getDecryptionKey*(crypto: Crypto, password: KeystorePass,
func getDecryptionKey*(crypto: Crypto, password: KeystorePass,
decKey: var seq[byte]): DecryptionStatus =
let res =
case crypto.kdf.function
Expand All @@ -996,7 +996,7 @@ proc getDecryptionKey*(crypto: Crypto, password: KeystorePass,
decKey = res
DecryptionStatus.Success

proc decryptCryptoField*(crypto: Crypto,
func decryptCryptoField*(crypto: Crypto,
password: KeystorePass,
outSecret: var seq[byte]): DecryptionStatus =
# https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition
Expand Down Expand Up @@ -1027,7 +1027,7 @@ template parseRemoteKeystore*(jsonContent: string): RemoteKeystore =
requireAllFields = false,
allowUnknownFields = true)

proc getSaltKey(keystore: Keystore, password: KeystorePass): KdfSaltKey =
func getSaltKey(keystore: Keystore, password: KeystorePass): KdfSaltKey =
let digest =
case keystore.crypto.kdf.function
of kdfPbkdf2:
Expand All @@ -1050,8 +1050,8 @@ proc getSaltKey(keystore: Keystore, password: KeystorePass): KdfSaltKey =
h.update(toBytesLE(uint64(params.r)))
KdfSaltKey(digest.data)

proc `==`*(a, b: KdfSaltKey): bool {.borrow.}
proc hash*(salt: KdfSaltKey): Hash {.borrow.}
func `==`*(a, b: KdfSaltKey): bool {.borrow.}
func hash*(salt: KdfSaltKey): Hash {.borrow.}

{.push warning[ProveField]:off.}
func `==`*(a, b: Kdf): bool =
Expand Down Expand Up @@ -1089,7 +1089,7 @@ func init*(t: typedesc[KeystoreCacheRef],
expireTime: expireTime
)

proc clear*(cache: KeystoreCacheRef) =
func clear*(cache: KeystoreCacheRef) =
cache.table.clear()

proc pruneExpiredKeys*(cache: KeystoreCacheRef) =
Expand All @@ -1110,7 +1110,7 @@ proc init*(t: typedesc[KeystoreCacheItem], keystore: Keystore,
cipher: keystore.crypto.cipher, decryptionKey: @key,
timestamp: Moment.now())

proc getCachedKey*(cache: KeystoreCacheRef,
func getCachedKey*(cache: KeystoreCacheRef,
keystore: Keystore, password: KeystorePass): Opt[seq[byte]] =
if isNil(cache): return Opt.none(seq[byte])
let
Expand All @@ -1132,7 +1132,7 @@ proc setCachedKey*(cache: KeystoreCacheRef, keystore: Keystore,
let saltKey = keystore.getSaltKey(password)
cache.table[saltKey] = KeystoreCacheItem.init(keystore, key)

proc destroyCacheKey*(cache: KeystoreCacheRef,
func destroyCacheKey*(cache: KeystoreCacheRef,
keystore: Keystore, password: KeystorePass) =
if isNil(cache): return
let saltKey = keystore.getSaltKey(password)
Expand Down Expand Up @@ -1206,7 +1206,7 @@ proc readValue*(reader: var JsonReader, value: var lcrypto.PublicKey) {.
# TODO: Can we provide better diagnostic?
raiseUnexpectedValue(reader, "Valid hex-encoded public key expected")

proc decryptNetKeystore*(nkeystore: NetKeystore,
func decryptNetKeystore*(nkeystore: NetKeystore,
password: KeystorePass): KsResult[lcrypto.PrivateKey] =
var secret: seq[byte]
defer: burnMem(secret)
Expand All @@ -1221,18 +1221,18 @@ proc decryptNetKeystore*(nkeystore: NetKeystore,
else:
err $status

proc decryptNetKeystore*(nkeystore: JsonString,
func decryptNetKeystore*(nkeystore: JsonString,
password: KeystorePass): KsResult[lcrypto.PrivateKey] =
try:
let keystore = parseNetKeystore(string nkeystore)
return decryptNetKeystore(keystore, password)
except SerializationError as exc:
return err(exc.formatMsg("<keystore>"))

proc generateKeystoreSalt*(rng: var HmacDrbgContext): seq[byte] =
func generateKeystoreSalt*(rng: var HmacDrbgContext): seq[byte] =
rng.generateBytes(keyLen)

proc createCryptoField(kdfKind: KdfKind,
func createCryptoField(kdfKind: KdfKind,
rng: var HmacDrbgContext,
secret: openArray[byte],
password = KeystorePass.init "",
Expand Down Expand Up @@ -1339,7 +1339,7 @@ proc createKeystore*(kdfKind: KdfKind,
uuid: $uuid,
version: 4)

proc createRemoteKeystore*(pubKey: ValidatorPubKey, remoteUri: HttpHostUri,
func createRemoteKeystore*(pubKey: ValidatorPubKey, remoteUri: HttpHostUri,
version = 1'u64, description = "",
remoteType = RemoteSignerType.Web3Signer,
flags: set[RemoteKeystoreFlag] = {}): RemoteKeystore =
Expand Down Expand Up @@ -1387,10 +1387,10 @@ func makeWithdrawalCredentials*(k: ValidatorPubKey): Eth2Digest =
bytes

# https://github.com/ethereum/consensus-specs/blob/v1.5.0-alpha.2/specs/phase0/deposit-contract.md#withdrawal-credentials
proc makeWithdrawalCredentials*(k: CookedPubKey): Eth2Digest =
func makeWithdrawalCredentials*(k: CookedPubKey): Eth2Digest =
makeWithdrawalCredentials(k.toPubKey())

proc prepareDeposit*(cfg: RuntimeConfig,
func prepareDeposit*(cfg: RuntimeConfig,
withdrawalPubKey: CookedPubKey,
signingKey: ValidatorPrivKey, signingPubKey: CookedPubKey,
amount = MAX_EFFECTIVE_BALANCE.Gwei): DepositData =
Expand Down
2 changes: 1 addition & 1 deletion beacon_chain/spec/state_transition_block.nim
Original file line number Diff line number Diff line change
Expand Up @@ -579,7 +579,7 @@ func process_execution_layer_withdrawal_request*(
exit_queue_epoch =
compute_exit_epoch_and_update_churn(cfg, state, to_withdraw, cache)
withdrawable_epoch =
Epoch(exit_queue_epoch + cfg.MIN_VALIDATOR_WITHDRAWABILITY_DELAY)
exit_queue_epoch + cfg.MIN_VALIDATOR_WITHDRAWABILITY_DELAY

# In theory can fail, but failing/early returning here is indistinguishable
discard state.pending_partial_withdrawals.add(PendingPartialWithdrawal(
Expand Down
Loading

0 comments on commit b56a671

Please sign in to comment.