From 1b516682bdef195174e632bc1772a75c97950e2f Mon Sep 17 00:00:00 2001 From: Jacek Sieka Date: Fri, 17 Jun 2022 22:45:37 +0200 Subject: [PATCH] bearssl: use split api (#510) --- eth/keys.nim | 24 +++----- eth/p2p.nim | 2 +- eth/p2p/auth.nim | 58 +++++++++---------- eth/p2p/discovery.nim | 2 +- eth/p2p/discoveryv5/encoding.nim | 50 ++++++++-------- eth/p2p/discoveryv5/node.nim | 7 +-- eth/p2p/discoveryv5/protocol.nim | 4 +- eth/p2p/discoveryv5/random2.nim | 17 +++--- eth/p2p/discoveryv5/routing_table.nim | 7 ++- eth/p2p/ecies.nim | 11 ++-- eth/p2p/kademlia.nim | 11 +--- eth/p2p/private/p2p_types.nim | 4 +- .../rlpx_protocols/whisper/whisper_types.nim | 17 +++--- eth/utp/packets.nim | 8 +-- eth/utp/utp_protocol.nim | 2 +- eth/utp/utp_router.nim | 4 +- eth/utp/utp_socket.nim | 6 +- .../discoveryv5/fuzz_decode_packet.nim | 6 +- tests/keys/test_keys.nim | 5 +- tests/p2p/discv5_test_helper.nim | 16 ++--- tests/p2p/p2p_test_helper.nim | 4 +- tests/p2p/test_discoveryv5.nim | 2 +- tests/p2p/test_discoveryv5_encoding.nim | 16 ++--- tests/p2p/test_routing_table.nim | 5 +- tests/p2p/test_shh_connect.nim | 2 +- tests/utp/test_discv5_protocol.nim | 9 +-- tests/utp/test_protocol.nim | 26 ++++----- tests/utp/test_protocol_integration.nim | 48 +++++++-------- tests/utp/test_utils.nim | 15 ++--- tests/utp/test_utp_router.nim | 6 +- tests/utp/test_utp_socket.nim | 28 ++++----- tests/utp/test_utp_socket_sack.nim | 30 +++++----- 32 files changed, 206 insertions(+), 246 deletions(-) diff --git a/eth/keys.nim b/eth/keys.nim index 0c89b4b..cd43a47 100644 --- a/eth/keys.nim +++ b/eth/keys.nim @@ -16,12 +16,13 @@ import std/strformat, - secp256k1, bearssl, stew/[byteutils, objects, results], + secp256k1, bearssl/hash as bhash, bearssl/rand, + stew/[byteutils, objects, results], nimcrypto/[hash, keccak] from nimcrypto/utils import burnMem -export secp256k1, results, bearssl +export secp256k1, results, rand const KeyLength* = SkEcdhRawSecretSize - 1 @@ -51,24 +52,15 @@ type template pubkey*(v: KeyPair): PublicKey = PublicKey(SkKeyPair(v).pubkey) template seckey*(v: KeyPair): PrivateKey = PrivateKey(SkKeyPair(v).seckey) -proc newRng*(): ref BrHmacDrbgContext = +proc newRng*(): ref HmacDrbgContext = # You should only create one instance of the RNG per application / library # Ref is used so that it can be shared between components - # TODO consider moving to bearssl - var seeder = brPrngSeederSystem(nil) - if seeder == nil: - return nil + HmacDrbgContext.new() - var rng = (ref BrHmacDrbgContext)() - brHmacDrbgInit(addr rng[], addr sha256Vtable, nil, 0) - if seeder(addr rng.vtable) == 0: - return nil - rng - -proc random*(T: type PrivateKey, rng: var BrHmacDrbgContext): T = +proc random*(T: type PrivateKey, rng: var HmacDrbgContext): T = let rngPtr = unsafeAddr rng # doesn't escape proc callRng(data: var openArray[byte]) = - brHmacDrbgGenerate(rngPtr[], data) + generate(rngPtr[], data) T(SkSecretKey.random(callRng)) @@ -106,7 +98,7 @@ func toRaw*(pubkey: PublicKey): array[RawPublicKeySize, byte] = func toRawCompressed*(pubkey: PublicKey): array[33, byte] {.borrow.} -proc random*(T: type KeyPair, rng: var BrHmacDrbgContext): T = +proc random*(T: type KeyPair, rng: var HmacDrbgContext): T = let seckey = SkSecretKey(PrivateKey.random(rng)) KeyPair(SkKeyPair( seckey: seckey, diff --git a/eth/p2p.nim b/eth/p2p.nim index ea2ea4d..a0b6bcb 100644 --- a/eth/p2p.nim +++ b/eth/p2p.nim @@ -9,7 +9,7 @@ import std/[tables, algorithm, random], - bearssl, chronos, chronos/timer, chronicles, + chronos, chronos/timer, chronicles, ./keys, ./common/eth_types, ./p2p/private/p2p_types, ./p2p/[kademlia, discovery, enode, peer_pool, rlpx] diff --git a/eth/p2p/auth.nim b/eth/p2p/auth.nim index 0360c35..89a9fd1 100644 --- a/eth/p2p/auth.nim +++ b/eth/p2p/auth.nim @@ -13,8 +13,8 @@ {.push raises: [Defect].} import - nimcrypto/[rijndael, keccak, utils], bearssl, - stew/[byteutils, endians2, objects, results], + nimcrypto/[rijndael, keccak, utils], + stew/[arrayops, byteutils, endians2, objects, results], ".."/[keys, rlp], ./ecies @@ -88,15 +88,11 @@ type template toa(a, b, c: untyped): untyped = toOpenArray((a), (b), (b) + (c) - 1) -proc `xor`[N: static int](a, b: array[N, byte]): array[N, byte] = - for i in 0 ..< len(a): - result[i] = a[i] xor b[i] - proc mapErrTo[T, E](r: Result[T, E], v: static AuthError): AuthResult[T] = r.mapErr(proc (e: E): AuthError = v) proc init*( - T: type Handshake, rng: var BrHmacDrbgContext, host: KeyPair, + T: type Handshake, rng: var HmacDrbgContext, host: KeyPair, flags: set[HandshakeFlag] = {Initiator}, version: uint8 = SupportedRlpxVersion): T = ## Create new `Handshake` object. @@ -108,10 +104,10 @@ proc init*( if Initiator in flags: expectedLength = AckMessageV4Length - brHmacDrbgGenerate(rng, initiatorNonce) + rng.generate(initiatorNonce) else: expectedLength = AuthMessageV4Length - brHmacDrbgGenerate(rng, responderNonce) + rng.generate(responderNonce) return T( version: version, @@ -124,7 +120,7 @@ proc init*( ) proc authMessagePreEIP8(h: var Handshake, - rng: var BrHmacDrbgContext, + rng: var HmacDrbgContext, pubkey: PublicKey, output: var openArray[byte], outlen: var int, @@ -163,7 +159,7 @@ proc authMessagePreEIP8(h: var Handshake, ok() proc authMessageEIP8(h: var Handshake, - rng: var BrHmacDrbgContext, + rng: var HmacDrbgContext, pubkey: PublicKey, output: var openArray[byte], outlen: var int, @@ -172,7 +168,6 @@ proc authMessageEIP8(h: var Handshake, ## Create EIP8 authentication message. var buffer: array[PlainAuthMessageMaxEIP8, byte] - padsize: array[1, byte] doAssert(EIP8 in h.flags) outlen = 0 @@ -192,29 +187,33 @@ proc authMessageEIP8(h: var Handshake, let pencsize = eciesEncryptedLength(len(payload)) - while true: - brHmacDrbgGenerate(rng, padsize) - if int(padsize[0]) > (AuthMessageV4Length - (pencsize + 2)): - break + var padsize = int(rng.generate(byte)) # aka rand(max) + while padsize <= (AuthMessageV4Length - (pencsize + 2)): + padsize = int(rng.generate(byte)) + # It is possible to make packet size constant by uncommenting this line # padsize = 24 - let wosize = pencsize + int(padsize[0]) - let fullsize = wosize + 2 - brHmacDrbgGenerate( - rng, toa(buffer, PlainAuthMessageEIP8Length, int(padsize[0]))) + let + wosize = pencsize + padsize + fullsize = wosize + 2 + + rng.generate(toa(buffer, PlainAuthMessageEIP8Length, padsize)) + if encrypt: - copyMem(addr buffer[0], addr payload[0], len(payload)) if len(output) < fullsize: return err(BufferOverrun) + + copyMem(addr buffer[0], addr payload[0], len(payload)) + let wosizeBE = uint16(wosize).toBytesBE() output[0..<2] = wosizeBE - if eciesEncrypt(rng, toa(buffer, 0, len(payload) + int(padsize[0])), + if eciesEncrypt(rng, toa(buffer, 0, len(payload) + padsize), toa(output, 2, wosize), pubkey, toa(output, 0, 2)).isErr: return err(EciesError) outlen = fullsize else: - let plainsize = len(payload) + int(padsize[0]) + let plainsize = len(payload) + padsize if len(output) < plainsize: return err(BufferOverrun) copyMem(addr output[0], addr buffer[0], plainsize) @@ -223,7 +222,7 @@ proc authMessageEIP8(h: var Handshake, ok() proc ackMessagePreEIP8(h: var Handshake, - rng: var BrHmacDrbgContext, + rng: var HmacDrbgContext, output: var openArray[byte], outlen: var int, flag: byte = 0, @@ -250,7 +249,7 @@ proc ackMessagePreEIP8(h: var Handshake, ok() proc ackMessageEIP8(h: var Handshake, - rng: var BrHmacDrbgContext, + rng: var HmacDrbgContext, output: var openArray[byte], outlen: var int, flag: byte = 0, @@ -267,7 +266,7 @@ proc ackMessageEIP8(h: var Handshake, outlen = 0 let pencsize = eciesEncryptedLength(len(payload)) while true: - brHmacDrbgGenerate(rng, padsize) + generate(rng, padsize) if int(padsize[0]) > (AckMessageV4Length - (pencsize + 2)): break # It is possible to make packet size constant by uncommenting this line @@ -275,8 +274,7 @@ proc ackMessageEIP8(h: var Handshake, let wosize = pencsize + int(padsize[0]) let fullsize = wosize + 2 if int(padsize[0]) > 0: - brHmacDrbgGenerate( - rng, toa(buffer, PlainAckMessageEIP8Length, int(padsize[0]))) + rng.generate(toa(buffer, PlainAckMessageEIP8Length, int(padsize[0]))) copyMem(addr buffer[0], addr payload[0], len(payload)) if encrypt: @@ -311,7 +309,7 @@ template ackSize*(h: Handshake, encrypt: bool = true): int = else: if encrypt: (AckMessageV4Length) else: (PlainAckMessageV4Length) -proc authMessage*(h: var Handshake, rng: var BrHmacDrbgContext, +proc authMessage*(h: var Handshake, rng: var HmacDrbgContext, pubkey: PublicKey, output: var openArray[byte], outlen: var int, flag: byte = 0, @@ -323,7 +321,7 @@ proc authMessage*(h: var Handshake, rng: var BrHmacDrbgContext, else: authMessagePreEIP8(h, rng, pubkey, output, outlen, flag, encrypt) -proc ackMessage*(h: var Handshake, rng: var BrHmacDrbgContext, +proc ackMessage*(h: var Handshake, rng: var HmacDrbgContext, output: var openArray[byte], outlen: var int, flag: byte = 0, encrypt: bool = true): AuthResult[void] = diff --git a/eth/p2p/discovery.nim b/eth/p2p/discovery.nim index eddb43e..0c0000e 100644 --- a/eth/p2p/discovery.nim +++ b/eth/p2p/discovery.nim @@ -9,7 +9,7 @@ import std/times, - chronos, stint, nimcrypto/keccak, chronicles, bearssl, + chronos, stint, nimcrypto/keccak, chronicles, stew/[objects, results], ".."/[keys, rlp], "."/[kademlia, enode] diff --git a/eth/p2p/discoveryv5/encoding.nim b/eth/p2p/discoveryv5/encoding.nim index 19e9e0f..b46cd51 100644 --- a/eth/p2p/discoveryv5/encoding.nim +++ b/eth/p2p/discoveryv5/encoding.nim @@ -15,7 +15,7 @@ import std/[tables, options, hashes, net], - nimcrypto, stint, chronicles, bearssl, stew/[results, byteutils], metrics, + nimcrypto, stint, chronicles, stew/[results, byteutils], metrics, ".."/../[rlp, keys], "."/[messages, node, enr, hkdf, sessions] @@ -193,18 +193,19 @@ proc encodeStaticHeader*(flag: Flag, nonce: AESGCMNonce, authSize: int): # TODO: assert on authSize of > 2^16? result.add((uint16(authSize)).toBytesBE()) -proc encodeMessagePacket*(rng: var BrHmacDrbgContext, c: var Codec, +proc encodeMessagePacket*(rng: var HmacDrbgContext, c: var Codec, toId: NodeId, toAddr: Address, message: openArray[byte]): (seq[byte], AESGCMNonce) = - var nonce: AESGCMNonce - brHmacDrbgGenerate(rng, nonce) # Random AESGCM nonce - var iv: array[ivSize, byte] - brHmacDrbgGenerate(rng, iv) # Random IV + let + nonce = rng.generate(AESGCMNonce) # Random AESGCM nonce + iv = rng.generate(array[ivSize, byte]) # Random IV # static-header - let authdata = c.localNode.id.toByteArrayBE() - let staticHeader = encodeStaticHeader(Flag.OrdinaryMessage, nonce, - authdata.len()) + let + authdata = c.localNode.id.toByteArrayBE() + staticHeader = encodeStaticHeader(Flag.OrdinaryMessage, nonce, + authdata.len()) + # header = static-header || authdata var header: seq[byte] header.add(staticHeader) @@ -224,8 +225,7 @@ proc encodeMessagePacket*(rng: var BrHmacDrbgContext, c: var Codec, # message. 16 bytes for the gcm tag and 4 bytes for ping with requestId of # 1 byte (e.g "01c20101"). Could increase to 27 for 8 bytes requestId in # case this must not look like a random packet. - var randomData: array[gcmTagSize + 4, byte] - brHmacDrbgGenerate(rng, randomData) + let randomData = rng.generate(array[gcmTagSize + 4, byte]) messageEncrypted.add(randomData) discovery_session_lru_cache_misses.inc() @@ -238,11 +238,11 @@ proc encodeMessagePacket*(rng: var BrHmacDrbgContext, c: var Codec, return (packet, nonce) -proc encodeWhoareyouPacket*(rng: var BrHmacDrbgContext, c: var Codec, +proc encodeWhoareyouPacket*(rng: var HmacDrbgContext, c: var Codec, toId: NodeId, toAddr: Address, requestNonce: AESGCMNonce, recordSeq: uint64, pubkey: Option[PublicKey]): seq[byte] = - var idNonce: IdNonce - brHmacDrbgGenerate(rng, idNonce) + let + idNonce = rng.generate(IdNonce) # authdata var authdata: seq[byte] @@ -258,10 +258,9 @@ proc encodeWhoareyouPacket*(rng: var BrHmacDrbgContext, c: var Codec, header.add(staticHeader) header.add(authdata) - var iv: array[ivSize, byte] - brHmacDrbgGenerate(rng, iv) # Random IV - - let maskedHeader = encryptHeader(toId, iv, header) + let + iv = rng.generate(array[ivSize, byte]) # Random IV + maskedHeader = encryptHeader(toId, iv, header) var packet: seq[byte] packet.add(iv) @@ -280,14 +279,12 @@ proc encodeWhoareyouPacket*(rng: var BrHmacDrbgContext, c: var Codec, return packet -proc encodeHandshakePacket*(rng: var BrHmacDrbgContext, c: var Codec, +proc encodeHandshakePacket*(rng: var HmacDrbgContext, c: var Codec, toId: NodeId, toAddr: Address, message: openArray[byte], whoareyouData: WhoareyouData, pubkey: PublicKey): seq[byte] = - var header: seq[byte] - var nonce: AESGCMNonce - brHmacDrbgGenerate(rng, nonce) - var iv: array[ivSize, byte] - brHmacDrbgGenerate(rng, iv) # Random IV + let + nonce = rng.generate(AESGCMNonce) + iv = rng.generate(array[ivSize, byte]) # Random IV var authdata: seq[byte] var authdataHead: seq[byte] @@ -316,6 +313,7 @@ proc encodeHandshakePacket*(rng: var BrHmacDrbgContext, c: var Codec, let staticHeader = encodeStaticHeader(Flag.HandshakeMessage, nonce, authdata.len()) + var header: seq[byte] header.add(staticHeader) header.add(authdata) @@ -611,9 +609,9 @@ proc decodePacket*(c: var Codec, fromAddr: Address, input: openArray[byte]): input.toOpenArray(0, ivSize - 1), header, input.toOpenArray(ivSize + header.len, input.high)) -proc init*(T: type RequestId, rng: var BrHmacDrbgContext): T = +proc init*(T: type RequestId, rng: var HmacDrbgContext): T = var reqId = RequestId(id: newSeq[byte](8)) # RequestId must be <= 8 bytes - brHmacDrbgGenerate(rng, reqId.id) + rng.generate(reqId.id) reqId proc numFields(T: typedesc): int = diff --git a/eth/p2p/discoveryv5/node.nim b/eth/p2p/discoveryv5/node.nim index 3b311b9..12b7cf0 100644 --- a/eth/p2p/discoveryv5/node.nim +++ b/eth/p2p/discoveryv5/node.nim @@ -86,11 +86,8 @@ func `==`*(a, b: Node): bool = func hash*(id: NodeId): Hash = hash(id.toByteArrayBE) -proc random*(T: type NodeId, rng: var BrHmacDrbgContext): T = - var id: NodeId - brHmacDrbgGenerate(addr rng, addr id, csize_t(sizeof(id))) - - id +proc random*(T: type NodeId, rng: var HmacDrbgContext): T = + rng.generate(T) func `$`*(id: NodeId): string = id.toHex() diff --git a/eth/p2p/discoveryv5/protocol.nim b/eth/p2p/discoveryv5/protocol.nim index a3bb3b2..16e405d 100644 --- a/eth/p2p/discoveryv5/protocol.nim +++ b/eth/p2p/discoveryv5/protocol.nim @@ -83,7 +83,7 @@ import std/[tables, sets, options, math, sequtils, algorithm], stew/shims/net as stewNet, json_serialization/std/net, - stew/[endians2, results], chronicles, chronos, stint, bearssl, metrics, + stew/[endians2, results], chronicles, chronos, stint, metrics, ".."/../[rlp, keys, async_utils], "."/[messages, encoding, node, routing_table, enr, random2, sessions, ip_vote, nodes_verification] @@ -147,7 +147,7 @@ type enrAutoUpdate: bool talkProtocols*: Table[seq[byte], TalkProtocol] # TODO: Table is a bit of # overkill here, use sequence - rng*: ref BrHmacDrbgContext + rng*: ref HmacDrbgContext PendingRequest = object node: Node diff --git a/eth/p2p/discoveryv5/random2.nim b/eth/p2p/discoveryv5/random2.nim index 0ec72f0..02d69e4 100644 --- a/eth/p2p/discoveryv5/random2.nim +++ b/eth/p2p/discoveryv5/random2.nim @@ -1,22 +1,25 @@ -import bearssl +import + bearssl/rand -## Random helpers: similar as in stdlib, but with BrHmacDrbgContext rng +export rand + +## Random helpers: similar as in stdlib, but with HmacDrbgContext rng # TODO: Move these somewhere else? const randMax = 18_446_744_073_709_551_615'u64 -proc rand*(rng: var BrHmacDrbgContext, max: Natural): int = +proc rand*(rng: var HmacDrbgContext, max: Natural): int = if max == 0: return 0 var x: uint64 while true: - brHmacDrbgGenerate(addr rng, addr x, csize_t(sizeof(x))) + rng.generate(x) if x < randMax - (randMax mod (uint64(max) + 1'u64)): # against modulo bias return int(x mod (uint64(max) + 1'u64)) -proc sample*[T](rng: var BrHmacDrbgContext, a: openArray[T]): T = - result = a[rng.rand(a.high)] +proc sample*[T](rng: var HmacDrbgContext, a: openArray[T]): T = + a[rng.rand(a.high)] -proc shuffle*[T](rng: var BrHmacDrbgContext, a: var openArray[T]) = +proc shuffle*[T](rng: var HmacDrbgContext, a: var openArray[T]) = for i in countdown(a.high, 1): let j = rng.rand(i) swap(a[i], a[j]) diff --git a/eth/p2p/discoveryv5/routing_table.nim b/eth/p2p/discoveryv5/routing_table.nim index 136ad39..00f2965 100644 --- a/eth/p2p/discoveryv5/routing_table.nim +++ b/eth/p2p/discoveryv5/routing_table.nim @@ -9,7 +9,8 @@ import std/[algorithm, times, sequtils, bitops, sets, options], - stint, chronicles, metrics, bearssl, chronos, stew/shims/net as stewNet, + bearssl/rand, + stint, chronicles, metrics, chronos, stew/shims/net as stewNet, ../../net/utils, "."/[node, random2, enr] @@ -42,7 +43,7 @@ type ipLimits: IpLimits ## IP limits for total routing table: all buckets and ## replacement caches. distanceCalculator: DistanceCalculator - rng: ref BrHmacDrbgContext + rng: ref HmacDrbgContext KBucket = ref object istart, iend: NodeId ## Range of NodeIds this KBucket covers. This is not a @@ -260,7 +261,7 @@ proc computeSharedPrefixBits(nodes: openArray[NodeId]): int = doAssert(false, "Unable to calculate number of shared prefix bits") proc init*(T: type RoutingTable, localNode: Node, bitsPerHop = DefaultBitsPerHop, - ipLimits = DefaultTableIpLimits, rng: ref BrHmacDrbgContext, + ipLimits = DefaultTableIpLimits, rng: ref HmacDrbgContext, distanceCalculator = XorDistanceCalculator): T = ## Initialize the routing table for provided `Node` and bitsPerHop value. ## `bitsPerHop` is default set to 5 as recommended by original Kademlia paper. diff --git a/eth/p2p/ecies.nim b/eth/p2p/ecies.nim index d32167a..164cc3c 100644 --- a/eth/p2p/ecies.nim +++ b/eth/p2p/ecies.nim @@ -13,7 +13,7 @@ {.push raises: [Defect].} import - bearssl, stew/[results, endians2], + stew/[results, endians2], nimcrypto/[rijndael, bcmode, hash, hmac, sha2, utils], ../keys @@ -93,7 +93,7 @@ proc kdf*(data: openArray[byte]): array[KeyLength, byte] {.noinit.} = ctx.clear() # clean ctx copyMem(addr result[0], addr storage[0], KeyLength) -proc eciesEncrypt*(rng: var BrHmacDrbgContext, input: openArray[byte], +proc eciesEncrypt*(rng: var HmacDrbgContext, input: openArray[byte], output: var openArray[byte], pubkey: PublicKey, sharedmac: openArray[byte] = emptyMac): EciesResult[void] = ## Encrypt data with ECIES method using given public key `pubkey`. @@ -107,13 +107,10 @@ proc eciesEncrypt*(rng: var BrHmacDrbgContext, input: openArray[byte], encKey: array[aes128.sizeKey, byte] cipher: CTR[aes128] ctx: HMAC[sha256] - iv: array[aes128.sizeBlock, byte] if len(output) < eciesEncryptedLength(len(input)): return err(BufferOverrun) - brHmacDrbgGenerate(rng, iv) - var ephemeral = KeyPair.random(rng) secret = ecdhRaw(ephemeral.seckey, pubkey) @@ -130,13 +127,13 @@ proc eciesEncrypt*(rng: var BrHmacDrbgContext, input: openArray[byte], var header = cast[ptr EciesHeader](addr output[0]) header.version = 0x04 header.pubkey = ephemeral.pubkey.toRaw() - header.iv = iv + rng.generate(header[].iv) clear(ephemeral) var so = eciesDataPos() var eo = so + len(input) - cipher.init(encKey, iv) + cipher.init(encKey, header.iv) cipher.encrypt(input, toOpenArray(output, so, eo)) burnMem(encKey) cipher.clear() diff --git a/eth/p2p/kademlia.nim b/eth/p2p/kademlia.nim index c904647..c75b502 100644 --- a/eth/p2p/kademlia.nim +++ b/eth/p2p/kademlia.nim @@ -9,7 +9,7 @@ import std/[tables, hashes, times, algorithm, sets, sequtils, random], - chronos, bearssl, chronicles, stint, nimcrypto/keccak, + chronos, chronicles, stint, nimcrypto/keccak, ../keys, ./enode @@ -26,7 +26,7 @@ type pongFutures: Table[seq[byte], Future[bool]] pingFutures: Table[Node, Future[bool]] neighboursCallbacks: Table[Node, proc(n: seq[Node]) {.gcsafe, raises: [Defect].}] - rng: ref BrHmacDrbgContext + rng: ref HmacDrbgContext NodeId* = UInt256 @@ -452,12 +452,7 @@ proc lookup*(k: KademliaProtocol, nodeId: NodeId): Future[seq[Node]] {.async.} = result = closest proc lookupRandom*(k: KademliaProtocol): Future[seq[Node]] = - var id: NodeId - var buf: array[sizeof(id), byte] - brHmacDrbgGenerate(k.rng[], buf) - copyMem(addr id, addr buf[0], sizeof(id)) - - k.lookup(id) + k.lookup(k.rng[].generate(NodeId)) proc resolve*(k: KademliaProtocol, id: NodeId): Future[Node] {.async.} = let closest = await k.lookup(id) diff --git a/eth/p2p/private/p2p_types.nim b/eth/p2p/private/p2p_types.nim index e9a2042..24d81d0 100644 --- a/eth/p2p/private/p2p_types.nim +++ b/eth/p2p/private/p2p_types.nim @@ -8,7 +8,7 @@ import std/[deques, tables], - bearssl, chronos, + chronos, stew/results, ".."/../[rlp, keys], ".."/../common/eth_types, ".."/[enode, kademlia, discovery, rlpxcrypt] @@ -38,7 +38,7 @@ type discovery*: DiscoveryProtocol when useSnappy: protocolVersion*: uint - rng*: ref BrHmacDrbgContext + rng*: ref HmacDrbgContext Peer* = ref object remote*: Node diff --git a/eth/p2p/rlpx_protocols/whisper/whisper_types.nim b/eth/p2p/rlpx_protocols/whisper/whisper_types.nim index b14fadb..2c5dec1 100644 --- a/eth/p2p/rlpx_protocols/whisper/whisper_types.nim +++ b/eth/p2p/rlpx_protocols/whisper/whisper_types.nim @@ -9,7 +9,7 @@ import std/[algorithm, bitops, math, options, tables, times, hashes], - chronicles, stew/[byteutils, endians2], metrics, bearssl, + chronicles, stew/[byteutils, endians2], metrics, nimcrypto/[bcmode, hash, keccak, rijndael], ".."/../../[keys, rlp, p2p], ../../ecies @@ -160,10 +160,8 @@ proc topicBloom*(topic: Topic): Bloom = doAssert idx <= 511 result[idx div 8] = result[idx div 8] or byte(1 shl (idx and 7'u16)) -proc generateRandomID*(rng: var BrHmacDrbgContext): string = - var bytes: array[256 div 8, byte] - brHmacDrbgGenerate(rng, bytes) - toHex(bytes) +proc generateRandomID*(rng: var HmacDrbgContext): string = + toHex(rng.generate(array[256 div 8, byte])) proc `or`(a, b: Bloom): Bloom = for i in 0..