From 347a485b5be2bfc0e4ad25fcff0a7ab4063d56a1 Mon Sep 17 00:00:00 2001 From: Jacek Sieka Date: Tue, 21 Jun 2022 10:29:16 +0200 Subject: [PATCH] bearssl: split abi (#3755) --- beacon_chain/beacon_node_light_client.nim | 2 +- .../sync_committee_msg_pool.nim | 5 +-- beacon_chain/deposits.nim | 4 +- .../gossip_processing/batch_validation.nim | 2 +- .../gossip_processing/block_processor.nim | 2 +- .../gossip_processing/eth2_processor.nim | 6 +-- beacon_chain/light_client.nim | 6 +-- beacon_chain/networking/eth2_discovery.nim | 4 +- beacon_chain/networking/eth2_network.nim | 14 +++---- beacon_chain/nimbus_beacon_node.nim | 14 +++---- beacon_chain/rpc/rest_key_management_api.nim | 2 +- beacon_chain/spec/crypto.nim | 17 ++++----- beacon_chain/spec/engine_authentication.nim | 10 ++--- beacon_chain/spec/keystore.nim | 38 ++++++++----------- beacon_chain/spec/signatures_batch.nim | 9 ++--- beacon_chain/sync/light_client_manager.nim | 4 +- beacon_chain/validators/action_tracker.nim | 5 +-- .../validators/keystore_management.nim | 30 ++++++++------- beacon_chain/wallets.nim | 3 +- ncli/ncli_split_keystore.nim | 2 +- tests/test_discovery.nim | 4 +- tests/test_key_splitting.nim | 4 +- vendor/nim-bearssl | 2 +- vendor/nim-chronos | 2 +- vendor/nim-eth | 2 +- vendor/nim-libp2p | 2 +- vendor/nim-sqlite3-abi | 2 +- vendor/nim-websock | 2 +- 28 files changed, 93 insertions(+), 106 deletions(-) diff --git a/beacon_chain/beacon_node_light_client.nim b/beacon_chain/beacon_node_light_client.nim index 4d1f415ba..5b4c1a2cc 100644 --- a/beacon_chain/beacon_node_light_client.nim +++ b/beacon_chain/beacon_node_light_client.nim @@ -18,7 +18,7 @@ logScope: topics = "beacnde" proc initLightClient*( node: BeaconNode, - rng: ref BrHmacDrbgContext, + rng: ref HmacDrbgContext, cfg: RuntimeConfig, forkDigests: ref ForkDigests, getBeaconTime: GetBeaconTimeFn, diff --git a/beacon_chain/consensus_object_pools/sync_committee_msg_pool.nim b/beacon_chain/consensus_object_pools/sync_committee_msg_pool.nim index 1c6bf18ef..2c071c0d3 100644 --- a/beacon_chain/consensus_object_pools/sync_committee_msg_pool.nim +++ b/beacon_chain/consensus_object_pools/sync_committee_msg_pool.nim @@ -10,7 +10,6 @@ import std/[sets, tables], stew/shims/hashes, - bearssl, eth/p2p/discoveryv5/random2, chronicles, ../spec/[crypto, digest], @@ -55,14 +54,14 @@ type bestContributions*: Table[Eth2Digest, BestSyncSubcommitteeContributions] onContributionReceived*: OnSyncContributionCallback - rng: ref BrHmacDrbgContext + rng: ref HmacDrbgContext syncCommitteeSubscriptions*: Table[ValidatorPubKey, Epoch] func hash*(x: SyncCommitteeMsgKey): Hash = hashAllFields(x) func init*(T: type SyncCommitteeMsgPool, - rng: ref BrHmacDrbgContext, + rng: ref HmacDrbgContext, onSyncContribution: OnSyncContributionCallback = nil ): SyncCommitteeMsgPool = T(rng: rng, onContributionReceived: onSyncContribution) diff --git a/beacon_chain/deposits.nim b/beacon_chain/deposits.nim index f46067dae..691149d8e 100644 --- a/beacon_chain/deposits.nim +++ b/beacon_chain/deposits.nim @@ -8,7 +8,7 @@ import std/[os, sequtils, times], - bearssl, chronicles, + chronicles, ./spec/eth2_apis/rest_beacon_client, ./spec/signatures, ./validators/keystore_management, @@ -236,7 +236,7 @@ proc restValidatorExit(config: BeaconNodeConf) {.async.} = proc handleValidatorExitCommand(config: BeaconNodeConf) {.async.} = await restValidatorExit(config) -proc doDeposits*(config: BeaconNodeConf, rng: var BrHmacDrbgContext) {. +proc doDeposits*(config: BeaconNodeConf, rng: var HmacDrbgContext) {. raises: [Defect, CatchableError].} = case config.depositsCmd of DepositsCmd.createTestnetDeposits: diff --git a/beacon_chain/gossip_processing/batch_validation.nim b/beacon_chain/gossip_processing/batch_validation.nim index e47701823..9b57dfec5 100644 --- a/beacon_chain/gossip_processing/batch_validation.nim +++ b/beacon_chain/gossip_processing/batch_validation.nim @@ -121,7 +121,7 @@ const BatchedCryptoSize = 72 proc new*( - T: type BatchCrypto, rng: ref BrHmacDrbgContext, + T: type BatchCrypto, rng: ref HmacDrbgContext, eager: Eager, taskpool: TaskPoolPtr): ref BatchCrypto = (ref BatchCrypto)( verifier: BatchVerifier(rng: rng, taskpool: taskpool), diff --git a/beacon_chain/gossip_processing/block_processor.nim b/beacon_chain/gossip_processing/block_processor.nim index 9a5abd8e3..eccf621f6 100644 --- a/beacon_chain/gossip_processing/block_processor.nim +++ b/beacon_chain/gossip_processing/block_processor.nim @@ -89,7 +89,7 @@ proc addBlock*( proc new*(T: type BlockProcessor, dumpEnabled: bool, dumpDirInvalid, dumpDirIncoming: string, - rng: ref BrHmacDrbgContext, taskpool: TaskPoolPtr, + rng: ref HmacDrbgContext, taskpool: TaskPoolPtr, consensusManager: ref ConsensusManager, validatorMonitor: ref ValidatorMonitor, getBeaconTime: GetBeaconTimeFn): ref BlockProcessor = diff --git a/beacon_chain/gossip_processing/eth2_processor.nim b/beacon_chain/gossip_processing/eth2_processor.nim index b4e8e56fa..4bf6ed5df 100644 --- a/beacon_chain/gossip_processing/eth2_processor.nim +++ b/beacon_chain/gossip_processing/eth2_processor.nim @@ -13,7 +13,7 @@ import std/tables, - stew/results, bearssl, + stew/results, chronicles, chronos, metrics, taskpools, ../spec/[helpers, forks], ../spec/datatypes/[altair, phase0], @@ -25,7 +25,7 @@ import "."/[gossip_validation, block_processor, batch_validation] export - results, bearssl, taskpools, block_clearance, blockchain_dag, exit_pool, attestation_pool, + results, taskpools, block_clearance, blockchain_dag, exit_pool, attestation_pool, light_client_pool, sync_committee_msg_pool, validator_pool, beacon_clock, gossip_validation, block_processor, batch_validation, block_quarantine @@ -156,7 +156,7 @@ proc new*(T: type Eth2Processor, syncCommitteeMsgPool: ref SyncCommitteeMsgPool, lightClientPool: ref LightClientPool, quarantine: ref Quarantine, - rng: ref BrHmacDrbgContext, + rng: ref HmacDrbgContext, getBeaconTime: GetBeaconTimeFn, taskpool: TaskPoolPtr ): ref Eth2Processor = diff --git a/beacon_chain/light_client.nim b/beacon_chain/light_client.nim index a541d9363..cfa418bb6 100644 --- a/beacon_chain/light_client.nim +++ b/beacon_chain/light_client.nim @@ -54,7 +54,7 @@ func optimisticHeader*(lightClient: LightClient): Opt[BeaconBlockHeader] = proc createLightClient( network: Eth2Node, - rng: ref BrHmacDrbgContext, + rng: ref HmacDrbgContext, dumpEnabled: bool, dumpDirInvalid, dumpDirIncoming: string, cfg: RuntimeConfig, @@ -136,7 +136,7 @@ proc createLightClient( proc createLightClient*( network: Eth2Node, - rng: ref BrHmacDrbgContext, + rng: ref HmacDrbgContext, config: BeaconNodeConf, cfg: RuntimeConfig, forkDigests: ref ForkDigests, @@ -150,7 +150,7 @@ proc createLightClient*( proc createLightClient*( network: Eth2Node, - rng: ref BrHmacDrbgContext, + rng: ref HmacDrbgContext, config: LightClientConf, cfg: RuntimeConfig, forkDigests: ref ForkDigests, diff --git a/beacon_chain/networking/eth2_discovery.nim b/beacon_chain/networking/eth2_discovery.nim index e1357eaa4..930dafbb0 100644 --- a/beacon_chain/networking/eth2_discovery.nim +++ b/beacon_chain/networking/eth2_discovery.nim @@ -9,7 +9,7 @@ import std/[os, strutils], - chronicles, stew/shims/net, stew/results, bearssl, + chronicles, stew/shims/net, stew/results, eth/keys, eth/p2p/discoveryv5/[enr, protocol, node], ".."/[conf, conf_light_client] @@ -80,7 +80,7 @@ proc new*(T: type Eth2DiscoveryProtocol, config: BeaconNodeConf | LightClientConf, enrIp: Option[ValidIpAddress], enrTcpPort, enrUdpPort: Option[Port], pk: PrivateKey, - enrFields: openArray[(string, seq[byte])], rng: ref BrHmacDrbgContext): + enrFields: openArray[(string, seq[byte])], rng: ref HmacDrbgContext): T = # TODO # Implement more configuration options: diff --git a/beacon_chain/networking/eth2_network.nim b/beacon_chain/networking/eth2_network.nim index 49ecf9ab2..acd25ba1a 100644 --- a/beacon_chain/networking/eth2_network.nim +++ b/beacon_chain/networking/eth2_network.nim @@ -12,7 +12,7 @@ import std/[typetraits, os, sequtils, strutils, algorithm, math, tables], # Status libs - stew/[leb128, endians2, results, byteutils, io2, bitops2], bearssl, + stew/[leb128, endians2, results, byteutils, io2, bitops2], stew/shims/net as stewNet, stew/shims/[macros], faststreams/[inputs, outputs, buffers], snappy, snappy/faststreams, @@ -75,7 +75,7 @@ type forkId*: ENRForkID discoveryForkId*: ENRForkID forkDigests*: ref ForkDigests - rng*: ref BrHmacDrbgContext + rng*: ref HmacDrbgContext peers*: Table[PeerId, Peer] validTopics: HashSet[string] peerPingerHeartbeatFut: Future[void] @@ -1645,7 +1645,7 @@ proc new(T: type Eth2Node, switch: Switch, pubsub: GossipSub, ip: Option[ValidIpAddress], tcpPort, udpPort: Option[Port], privKey: keys.PrivateKey, discovery: bool, - rng: ref BrHmacDrbgContext): T {.raises: [Defect, CatchableError].} = + rng: ref HmacDrbgContext): T {.raises: [Defect, CatchableError].} = when not defined(local_testnet): let connectTimeout = chronos.minutes(1) @@ -2034,7 +2034,7 @@ proc initAddress(T: type MultiAddress, str: string): T = template tcpEndPoint(address, port): auto = MultiAddress.init(address, tcpProtocol, port) -proc optimisticgetRandomNetKeys*(rng: var BrHmacDrbgContext): NetKeyPair = +proc optimisticgetRandomNetKeys*(rng: var HmacDrbgContext): NetKeyPair = let res = PrivateKey.random(Secp256k1, rng) if res.isErr(): fatal "Could not generate random network key file" @@ -2045,7 +2045,7 @@ proc optimisticgetRandomNetKeys*(rng: var BrHmacDrbgContext): NetKeyPair = pubKey = privKey.getPublicKey().expect("working public key from random") NetKeyPair(seckey: privKey, pubkey: pubKey) -proc getPersistentNetKeys*(rng: var BrHmacDrbgContext, +proc getPersistentNetKeys*(rng: var HmacDrbgContext, config: BeaconNodeConf): NetKeyPair = case config.cmd of BNStartUpCmd.noCommand, BNStartUpCmd.record: @@ -2178,7 +2178,7 @@ func gossipId( proc newBeaconSwitch(config: BeaconNodeConf | LightClientConf, seckey: PrivateKey, address: MultiAddress, - rng: ref BrHmacDrbgContext): Switch {.raises: [Defect, CatchableError].} = + rng: ref HmacDrbgContext): Switch {.raises: [Defect, CatchableError].} = SwitchBuilder .new() .withPrivateKey(seckey) @@ -2213,7 +2213,7 @@ template gossipMaxSize(T: untyped): uint32 = static: doAssert maxSize <= maxGossipMaxSize() maxSize.uint32 -proc createEth2Node*(rng: ref BrHmacDrbgContext, +proc createEth2Node*(rng: ref HmacDrbgContext, config: BeaconNodeConf | LightClientConf, netKeys: NetKeyPair, cfg: RuntimeConfig, diff --git a/beacon_chain/nimbus_beacon_node.nim b/beacon_chain/nimbus_beacon_node.nim index 549233a6f..a9a06cb17 100644 --- a/beacon_chain/nimbus_beacon_node.nim +++ b/beacon_chain/nimbus_beacon_node.nim @@ -9,7 +9,7 @@ import std/[os, random, sequtils, terminal, times], - bearssl, chronos, chronicles, chronicles/chronos_tools, + chronos, chronicles, chronicles/chronos_tools, metrics, metrics/chronos_httpserver, stew/[byteutils, io2], eth/p2p/discoveryv5/[enr, random2], @@ -223,7 +223,7 @@ proc checkWeakSubjectivityCheckpoint( proc initFullNode( node: BeaconNode, - rng: ref BrHmacDrbgContext, + rng: ref HmacDrbgContext, dag: ChainDAGRef, taskpool: TaskPoolPtr, getBeaconTime: GetBeaconTimeFn) = @@ -347,7 +347,7 @@ const SlashingDbName = "slashing_protection" proc init*(T: type BeaconNode, cfg: RuntimeConfig, - rng: ref BrHmacDrbgContext, + rng: ref HmacDrbgContext, config: BeaconNodeConf, depositContractDeployedAt: BlockHashOrNumber, eth1Network: Option[Eth1Network], @@ -1699,7 +1699,7 @@ when not defined(windows): asyncSpawn statusBarUpdatesPollingLoop() -proc doRunBeaconNode(config: var BeaconNodeConf, rng: ref BrHmacDrbgContext) {.raises: [Defect, CatchableError].} = +proc doRunBeaconNode(config: var BeaconNodeConf, rng: ref HmacDrbgContext) {.raises: [Defect, CatchableError].} = info "Launching beacon node", version = fullVersionStr, bls_backend = $BLS_BACKEND, @@ -1774,7 +1774,7 @@ proc doRunBeaconNode(config: var BeaconNodeConf, rng: ref BrHmacDrbgContext) {.r else: node.start() -proc doCreateTestnet*(config: BeaconNodeConf, rng: var BrHmacDrbgContext) {.raises: [Defect, CatchableError].} = +proc doCreateTestnet*(config: BeaconNodeConf, rng: var HmacDrbgContext) {.raises: [Defect, CatchableError].} = let launchPadDeposits = try: Json.loadFile(config.testnetDepositsFile.string, seq[LaunchPadDeposit]) except SerializationError as err: @@ -1845,7 +1845,7 @@ proc doCreateTestnet*(config: BeaconNodeConf, rng: var BrHmacDrbgContext) {.rais writeFile(bootstrapFile, bootstrapEnr.tryGet().toURI) echo "Wrote ", bootstrapFile -proc doRecord(config: BeaconNodeConf, rng: var BrHmacDrbgContext) {. +proc doRecord(config: BeaconNodeConf, rng: var HmacDrbgContext) {. raises: [Defect, CatchableError].} = case config.recordCmd: of RecordCmd.create: @@ -1873,7 +1873,7 @@ proc doRecord(config: BeaconNodeConf, rng: var BrHmacDrbgContext) {. of RecordCmd.print: echo $config.recordPrint -proc doWeb3Cmd(config: BeaconNodeConf, rng: var BrHmacDrbgContext) +proc doWeb3Cmd(config: BeaconNodeConf, rng: var HmacDrbgContext) {.raises: [Defect, CatchableError].} = case config.web3Cmd: of Web3Cmd.test: diff --git a/beacon_chain/rpc/rest_key_management_api.nim b/beacon_chain/rpc/rest_key_management_api.nim index 5b37d825b..5427adec3 100644 --- a/beacon_chain/rpc/rest_key_management_api.nim +++ b/beacon_chain/rpc/rest_key_management_api.nim @@ -6,7 +6,7 @@ import std/[tables, os, strutils, uri] import chronos, chronicles, confutils, - stew/[base10, results, io2], bearssl, blscurve + stew/[base10, results, io2], blscurve import ".."/validators/slashing_protection import ".."/[conf, version, filepath, beacon_node] import ".."/spec/[keystore, crypto] diff --git a/beacon_chain/spec/crypto.nim b/beacon_chain/spec/crypto.nim index 8c291f1fb..1fbd23384 100644 --- a/beacon_chain/spec/crypto.nim +++ b/beacon_chain/spec/crypto.nim @@ -30,12 +30,12 @@ import stew/[endians2, objects, results, byteutils], blscurve, chronicles, - bearssl, + bearssl/rand, json_serialization from nimcrypto/utils import burnMem -export options, results, json_serialization, blscurve +export options, results, blscurve, rand, json_serialization # Type definitions # ---------------------------------------------------------------------- @@ -488,11 +488,10 @@ func infinity*(T: type ValidatorSig): T = func burnMem*(key: var ValidatorPrivKey) = burnMem(addr key, sizeof(ValidatorPrivKey)) -proc keyGen(rng: var BrHmacDrbgContext): BlsResult[blscurve.SecretKey] = +proc keyGen(rng: var HmacDrbgContext): BlsResult[blscurve.SecretKey] = var - bytes: array[32, byte] pubkey: blscurve.PublicKey - brHmacDrbgGenerate(rng, bytes) + let bytes = rng.generate(array[32, byte]) result.ok default(blscurve.SecretKey) if not keyGen(bytes, pubkey, result.value): return err "key generation failed" @@ -502,7 +501,7 @@ proc secretShareId(x: uint32) : blscurve.ID = blscurve.ID.fromUint32(bytes) func generateSecretShares*(sk: ValidatorPrivKey, - rng: var BrHmacDrbgContext, + rng: var HmacDrbgContext, k: uint32, n: uint32): BlsResult[seq[SecretShare]] = doAssert k > 0 and k <= n @@ -533,10 +532,8 @@ func recoverSignature*(sings: seq[SignatureShare]): CookedSig = proc confirmShares*(pubKey: ValidatorPubKey, shares: seq[SecretShare], - rng: var BrHmacDrbgContext): bool = - var confirmationData: array[32, byte] - brHmacDrbgGenerate(rng, confirmationData) - + rng: var HmacDrbgContext): bool = + let confirmationData = rng.generate(array[32, byte]) var signs: seq[SignatureShare] for share in items(shares): let signature = share.key.blsSign(confirmationData).toSignatureShare(share.id); diff --git a/beacon_chain/spec/engine_authentication.nim b/beacon_chain/spec/engine_authentication.nim index dc6e1c29e..ff008b775 100644 --- a/beacon_chain/spec/engine_authentication.nim +++ b/beacon_chain/spec/engine_authentication.nim @@ -8,10 +8,12 @@ import std/[base64, json, options, os, strutils], chronicles, - bearssl, + bearssl/rand, nimcrypto/[hmac, utils], stew/[byteutils, results] +export rand, results + {.push raises: [Defect].} proc base64urlEncode(x: auto): string = @@ -50,7 +52,7 @@ proc getSignedIatToken*(key: openArray[byte], time: int64): string = getSignedToken(key, $getIatToken(time)) proc checkJwtSecret*( - rng: var BrHmacDrbgContext, dataDir: string, jwtSecret: Option[string]): + rng: var HmacDrbgContext, dataDir: string, jwtSecret: Option[string]): Result[seq[byte], cstring] = # If such a parameter is given, but the file cannot be read, or does not @@ -69,9 +71,7 @@ proc checkJwtSecret*( const jwtSecretFilename = "jwt.hex" let jwtSecretPath = dataDir / jwtSecretFilename - var newSecret: seq[byte] - newSecret.setLen(MIN_SECRET_LEN) - rng.brHmacDrbgGenerate(newSecret) + let newSecret = rng.generateBytes(MIN_SECRET_LEN) try: writeFile(jwtSecretPath, newSecret.to0xHex()) except IOError as exc: diff --git a/beacon_chain/spec/keystore.nim b/beacon_chain/spec/keystore.nim index 46a8e80e6..ef316b2d2 100644 --- a/beacon_chain/spec/keystore.nim +++ b/beacon_chain/spec/keystore.nim @@ -15,7 +15,7 @@ import normalize, # Status libraries stew/[results, bitops2, base10], stew/shims/macros, - bearssl, eth/keyfile/uuid, blscurve, json_serialization, + eth/keyfile/uuid, blscurve, json_serialization, nimcrypto/[sha2, rijndael, pbkdf2, bcmode, hash, scrypt], # Local modules libp2p/crypto/crypto as lcrypto, @@ -261,11 +261,6 @@ func longName*(wallet: Wallet): string = else: wallet.name.string & " (" & wallet.uuid.string & ")" -proc getRandomBytes*(rng: var BrHmacDrbgContext, n: Natural): seq[byte] - {.raises: [Defect].} = - result = newSeq[byte](n) - brHmacDrbgGenerate(rng, result) - macro wordListArray*(filename: static string, maxWords: static int = 0, minWordLen: static int = 0, @@ -357,20 +352,19 @@ template add(m: var Mnemonic, s: cstring) = m.string.add s proc generateMnemonic*( - rng: var BrHmacDrbgContext, + rng: var HmacDrbgContext, words: openArray[cstring] = englishWords, entropyParam: openArray[byte] = @[]): Mnemonic = ## Generates a valid BIP-0039 mnenomic: ## https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki#generating-the-mnemonic - var entropy: seq[byte] - if entropyParam.len == 0: - setLen(entropy, 32) - brHmacDrbgGenerate(rng, entropy) - else: - doAssert entropyParam.len >= 128 and - entropyParam.len <= 256 and - entropyParam.len mod 32 == 0 - entropy = @entropyParam + var entropy = + if entropyParam.len == 0: + rng.generateBytes(32) + else: + doAssert entropyParam.len >= 128 and + entropyParam.len <= 256 and + entropyParam.len mod 32 == 0 + @entropyParam let checksumBits = entropy.len div 4 # ranges from 4 to 8 @@ -836,7 +830,7 @@ proc decryptNetKeystore*(nkeystore: JsonString, return err(exc.formatMsg("")) proc createCryptoField(kdfKind: KdfKind, - rng: var BrHmacDrbgContext, + rng: var HmacDrbgContext, secret: openArray[byte], password = KeystorePass.init "", salt: openArray[byte] = @[], @@ -849,13 +843,13 @@ proc createCryptoField(kdfKind: KdfKind, doAssert salt.len == keyLen @salt else: - getRandomBytes(rng, keyLen) + rng.generateBytes(keyLen) let aesIv = if iv.len > 0: doAssert iv.len == AES.sizeBlock @iv else: - getRandomBytes(rng, AES.sizeBlock) + rng.generateBytes(AES.sizeBlock) var decKey: seq[byte] let kdf = case kdfKind @@ -897,7 +891,7 @@ proc createCryptoField(kdfKind: KdfKind, message: CipherBytes cipherMsg)) proc createNetKeystore*(kdfKind: KdfKind, - rng: var BrHmacDrbgContext, + rng: var HmacDrbgContext, privKey: lcrypto.PrivateKey, password = KeystorePass.init "", description = "", @@ -918,7 +912,7 @@ proc createNetKeystore*(kdfKind: KdfKind, ) proc createKeystore*(kdfKind: KdfKind, - rng: var BrHmacDrbgContext, + rng: var HmacDrbgContext, privKey: ValidatorPrivKey, password = KeystorePass.init "", path = KeyPath "", @@ -960,7 +954,7 @@ proc createRemoteKeystore*(pubKey: ValidatorPubKey, remoteUri: HttpHostUri, ) proc createWallet*(kdfKind: KdfKind, - rng: var BrHmacDrbgContext, + rng: var HmacDrbgContext, seed: KeySeed, name = WalletName "", salt: openArray[byte] = @[], diff --git a/beacon_chain/spec/signatures_batch.nim b/beacon_chain/spec/signatures_batch.nim index 3187dbffc..9af697741 100644 --- a/beacon_chain/spec/signatures_batch.nim +++ b/beacon_chain/spec/signatures_batch.nim @@ -17,12 +17,12 @@ import blscurve, stew/[byteutils, results], taskpools, - bearssl, + bearssl/rand, # Internal "."/[helpers, beaconstate, forks, signatures], "."/datatypes/[altair, bellatrix, phase0] -export results, altair, phase0, taskpools, bearssl, signatures +export results, rand, altair, phase0, taskpools, signatures type TaskPoolPtr* = Taskpool @@ -30,7 +30,7 @@ type BatchVerifier* = object sigVerifCache*: BatchedBLSVerifierCache ##\ ## A cache for batch BLS signature verification contexts - rng*: ref BrHmacDrbgContext ##\ + rng*: ref HmacDrbgContext ##\ ## A reference to the Nimbus application-wide RNG taskpool*: TaskPoolPtr @@ -411,8 +411,7 @@ proc collectSignatureSets*( ok() proc batchVerify*(verifier: var BatchVerifier, sigs: openArray[SignatureSet]): bool = - var bytes: array[32, byte] - verifier.rng[].brHmacDrbgGenerate(bytes) + let bytes = verifier.rng[].generate(array[32, byte]) try: verifier.taskpool.batchVerify(verifier.sigVerifCache, sigs, bytes) except Exception as exc: diff --git a/beacon_chain/sync/light_client_manager.nim b/beacon_chain/sync/light_client_manager.nim index 011d380ce..078da1d68 100644 --- a/beacon_chain/sync/light_client_manager.nim +++ b/beacon_chain/sync/light_client_manager.nim @@ -56,7 +56,7 @@ type LightClientManager* = object network: Eth2Node - rng: ref BrHmacDrbgContext + rng: ref HmacDrbgContext getTrustedBlockRoot: GetTrustedBlockRootCallback bootstrapVerifier: BootstrapVerifier updateVerifier: UpdateVerifier @@ -72,7 +72,7 @@ type func init*( T: type LightClientManager, network: Eth2Node, - rng: ref BrHmacDrbgContext, + rng: ref HmacDrbgContext, getTrustedBlockRoot: GetTrustedBlockRootCallback, bootstrapVerifier: BootstrapVerifier, updateVerifier: UpdateVerifier, diff --git a/beacon_chain/validators/action_tracker.nim b/beacon_chain/validators/action_tracker.nim index 4110a0583..f228e977f 100644 --- a/beacon_chain/validators/action_tracker.nim +++ b/beacon_chain/validators/action_tracker.nim @@ -7,7 +7,6 @@ import std/[sequtils, tables], - bearssl, stew/shims/[sets, hashes], chronicles, eth/p2p/discoveryv5/random2, ../spec/datatypes/base, @@ -39,7 +38,7 @@ type slot*: Slot ActionTracker* = object - rng: ref BrHmacDrbgContext + rng: ref HmacDrbgContext subscribeAllAttnets: bool @@ -263,7 +262,7 @@ func updateActions*( (1'u32 shl (slot mod SLOTS_PER_EPOCH)) func init*( - T: type ActionTracker, rng: ref BrHmacDrbgContext, + T: type ActionTracker, rng: ref HmacDrbgContext, subscribeAllAttnets: bool): T = T( rng: rng, diff --git a/beacon_chain/validators/keystore_management.nim b/beacon_chain/validators/keystore_management.nim index 5a477e6ee..32d9017d2 100644 --- a/beacon_chain/validators/keystore_management.nim +++ b/beacon_chain/validators/keystore_management.nim @@ -10,7 +10,8 @@ import std/[os, strutils, terminal, wordwrap, unicode], chronicles, chronos, json_serialization, zxcvbn, - serialization, blscurve, eth/common/eth_types, eth/keys, confutils, bearssl, + bearssl/rand, + serialization, blscurve, eth/common/eth_types, eth/keys, confutils, nimbus_security_resources, ".."/spec/[eth2_merkleization, keystore, crypto], ".."/spec/datatypes/base, @@ -21,7 +22,7 @@ import ./validator_pool export - keystore, validator_pool, crypto + keystore, validator_pool, crypto, rand when defined(windows): import stew/[windows/acl] @@ -679,7 +680,7 @@ proc loadNetKeystore*(keystorePath: string, else: return -proc saveNetKeystore*(rng: var BrHmacDrbgContext, keystorePath: string, +proc saveNetKeystore*(rng: var HmacDrbgContext, keystorePath: string, netKey: lcrypto.PrivateKey, insecurePwd: Option[string] ): Result[void, KeystoreGenerationError] = let password = @@ -783,7 +784,7 @@ proc createValidatorFiles*(validatorsDir, keystoreDir, keystoreFile, success = true ok() -proc saveKeystore*(rng: var BrHmacDrbgContext, +proc saveKeystore*(rng: var HmacDrbgContext, validatorsDir, secretsDir: string, signingKey: ValidatorPrivKey, signingPubKey: CookedPubKey, @@ -917,7 +918,7 @@ proc importKeystore*(pool: var ValidatorPool, conf: AnyConf, ok(KeystoreData.init(cookedKey, keystore.remotes, keystore.threshold)) proc importKeystore*(pool: var ValidatorPool, - rng: var BrHmacDrbgContext, + rng: var HmacDrbgContext, conf: AnyConf, keystore: Keystore, password: string): ImportResult[KeystoreData] {. raises: [Defect].} = @@ -956,7 +957,7 @@ proc importKeystore*(pool: var ValidatorPool, ok(KeystoreData.init(privateKey, keystore)) -proc generateDistirbutedStore*(rng: var BrHmacDrbgContext, +proc generateDistirbutedStore*(rng: var HmacDrbgContext, shares: seq[SecretShare], pubKey: ValidatorPubKey, validatorIdx: Natural, @@ -967,7 +968,7 @@ proc generateDistirbutedStore*(rng: var BrHmacDrbgContext, threshold: uint32): Result[void, KeystoreGenerationError] = var signers: seq[RemoteSignerInfo] for idx, share in shares: - var password = KeystorePass.init ncrutils.toHex(getRandomBytes(rng, 32)) + var password = KeystorePass.init ncrutils.toHex(rng.generateBytes(32)) # remote signer shares defer: burnMem(password) ? saveKeystore(rng, @@ -987,7 +988,7 @@ proc generateDistirbutedStore*(rng: var BrHmacDrbgContext, saveKeystore(remoteValidatorDir, pubKey, signers, threshold) proc generateDeposits*(cfg: RuntimeConfig, - rng: var BrHmacDrbgContext, + rng: var HmacDrbgContext, seed: KeySeed, firstValidatorIdx, totalNewValidators: int, validatorsDir: string, @@ -1021,7 +1022,7 @@ proc generateDeposits*(cfg: RuntimeConfig, derivedKey = deriveChildKey(derivedKey, 0) # This is the signing key let signingPubKey = derivedKey.toPubKey - var password = KeystorePass.init ncrutils.toHex(getRandomBytes(rng, 32)) + var password = KeystorePass.init ncrutils.toHex(rng.generateBytes(32)) defer: burnMem(password) ? saveKeystore(rng, validatorsDir, secretsDir, derivedKey, signingPubKey, @@ -1121,7 +1122,7 @@ proc resetAttributesNoError() = try: stdout.resetAttributes() except IOError: discard -proc importKeystoresFromDir*(rng: var BrHmacDrbgContext, +proc importKeystoresFromDir*(rng: var HmacDrbgContext, importedDir, validatorsDir, secretsDir: string) = var password: string # TODO consider using a SecretString type defer: burnMem(password) @@ -1161,7 +1162,8 @@ proc importKeystoresFromDir*(rng: var BrHmacDrbgContext, let privKey = ValidatorPrivKey.fromRaw(secret) if privKey.isOk: let pubkey = privKey.value.toPubKey - var password = KeystorePass.init ncrutils.toHex(getRandomBytes(rng, 32)) + var + password = KeystorePass.init ncrutils.toHex(rng.generateBytes(32)) defer: burnMem(password) let status = saveKeystore(rng, validatorsDir, secretsDir, privKey.value, pubkey, @@ -1205,7 +1207,7 @@ template ask(prompt: string): string = except IOError: return err "failure to read data from stdin" -proc pickPasswordAndSaveWallet(rng: var BrHmacDrbgContext, +proc pickPasswordAndSaveWallet(rng: var HmacDrbgContext, config: BeaconNodeConf, seed: KeySeed): Result[WalletPathPair, string] = echoP "When you perform operations with your wallet such as withdrawals " & @@ -1275,7 +1277,7 @@ else: echo "\e[1;1H\e[2J\e[3J" proc createWalletInteractively*( - rng: var BrHmacDrbgContext, + rng: var HmacDrbgContext, config: BeaconNodeConf): Result[CreatedWallet, string] = if config.nonInteractive: @@ -1380,7 +1382,7 @@ proc createWalletInteractively*( let walletPath = ? pickPasswordAndSaveWallet(rng, config, seed) return ok CreatedWallet(walletPath: walletPath, seed: seed) -proc restoreWalletInteractively*(rng: var BrHmacDrbgContext, +proc restoreWalletInteractively*(rng: var HmacDrbgContext, config: BeaconNodeConf) = var enteredMnemonic: string diff --git a/beacon_chain/wallets.nim b/beacon_chain/wallets.nim index c7e16e809..657274396 100644 --- a/beacon_chain/wallets.nim +++ b/beacon_chain/wallets.nim @@ -8,11 +8,10 @@ import std/os, - bearssl, ./validators/keystore_management, ./conf -proc doWallets*(config: BeaconNodeConf, rng: var BrHmacDrbgContext) {. +proc doWallets*(config: BeaconNodeConf, rng: var HmacDrbgContext) {. raises: [Defect, CatchableError].} = case config.walletsCmd: of WalletsCmd.create: diff --git a/ncli/ncli_split_keystore.nim b/ncli/ncli_split_keystore.nim index 0d43f4ab1..cbac76f59 100644 --- a/ncli/ncli_split_keystore.nim +++ b/ncli/ncli_split_keystore.nim @@ -1,6 +1,6 @@ import std/os, - bearssl, nimcrypto/utils, confutils, eth/keys, + nimcrypto/utils, confutils, eth/keys, ../beacon_chain/validators/keystore_management, ../beacon_chain/spec/[keystore, crypto], ../beacon_chain/conf diff --git a/tests/test_discovery.nim b/tests/test_discovery.nim index a2762b821..1c231a73e 100644 --- a/tests/test_discovery.nim +++ b/tests/test_discovery.nim @@ -13,13 +13,13 @@ proc new(T: type Eth2DiscoveryProtocol, enrIp: Option[ValidIpAddress], enrTcpPort, enrUdpPort: Option[Port], bindPort: Port, bindIp: ValidIpAddress, enrFields: openArray[(string, seq[byte])] = [], - rng: ref BrHmacDrbgContext): + rng: ref HmacDrbgContext): T {.raises: [CatchableError, Defect].} = newProtocol(pk, enrIp, enrTcpPort, enrUdpPort, enrFields, bindPort = bindPort, bindIp = bindIp, rng = rng) -proc generateNode(rng: ref BrHmacDrbgContext, port: Port, +proc generateNode(rng: ref HmacDrbgContext, port: Port, enrFields: openArray[(string, seq[byte])] = []): Eth2DiscoveryProtocol = let ip = ValidIpAddress.init("127.0.0.1") Eth2DiscoveryProtocol.new(keys.PrivateKey.random(rng[]), diff --git a/tests/test_key_splitting.nim b/tests/test_key_splitting.nim index 622cca947..9d639dc80 100644 --- a/tests/test_key_splitting.nim +++ b/tests/test_key_splitting.nim @@ -25,9 +25,7 @@ suite "Key spliting": salt = hexToSeqByte "d4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3" iv = hexToSeqByte "264daa3f303d7259501c93d997d84fe6" rng = keys.newRng() - - var msg = newSeq[byte](32) - brHmacDrbgGenerate(rng[], msg) + msg = rng[].generateBytes(32) test "single share": let maybeShares = generateSecretShares(privateKey, rng[], 1, 1) diff --git a/vendor/nim-bearssl b/vendor/nim-bearssl index 65b74302e..4ba7f1337 160000 --- a/vendor/nim-bearssl +++ b/vendor/nim-bearssl @@ -1 +1 @@ -Subproject commit 65b74302e03912ab5bde64b6da10d05896139007 +Subproject commit 4ba7f13372d4d191e464a250051a5744ea1d9416 diff --git a/vendor/nim-chronos b/vendor/nim-chronos index 2a5095505..c6ce4d4fb 160000 --- a/vendor/nim-chronos +++ b/vendor/nim-chronos @@ -1 +1 @@ -Subproject commit 2a5095505f771610f9559d2e774b2a9561f01101 +Subproject commit c6ce4d4fb26a785aabff84793fcd2b86a0ff93af diff --git a/vendor/nim-eth b/vendor/nim-eth index 4463a28fd..1b516682b 160000 --- a/vendor/nim-eth +++ b/vendor/nim-eth @@ -1 +1 @@ -Subproject commit 4463a28fd615561b3614806b69f2c0592fe91047 +Subproject commit 1b516682bdef195174e632bc1772a75c97950e2f diff --git a/vendor/nim-libp2p b/vendor/nim-libp2p index 718374d89..a7e335e1b 160000 --- a/vendor/nim-libp2p +++ b/vendor/nim-libp2p @@ -1 +1 @@ -Subproject commit 718374d890f3997b56bee61cb5971eb367f05b59 +Subproject commit a7e335e1bb0e8f6133f777f67ccc2742b817ed21 diff --git a/vendor/nim-sqlite3-abi b/vendor/nim-sqlite3-abi index 07039dd88..2f040a5bf 160000 --- a/vendor/nim-sqlite3-abi +++ b/vendor/nim-sqlite3-abi @@ -1 +1 @@ -Subproject commit 07039dd887c4e5b57367a16f4be3c18763be1d7b +Subproject commit 2f040a5bfcef78f29b72016dfef98706a0f6dc9f diff --git a/vendor/nim-websock b/vendor/nim-websock index b13d65940..fc6538fa8 160000 --- a/vendor/nim-websock +++ b/vendor/nim-websock @@ -1 +1 @@ -Subproject commit b13d65940074ddf8abd1c3de00b6bcd6a32f994c +Subproject commit fc6538fa85f3742046002f6a94bb0dab33c4e798