From ffe80dc24b93ade948700e346959a1ad1e56c66c Mon Sep 17 00:00:00 2001 From: Diego Date: Thu, 18 Apr 2024 17:30:31 +0200 Subject: [PATCH] use a mock rng in tests --- libp2p/builders.nim | 12 +-- libp2p/crypto/crypto.nim | 8 +- libp2p/crypto/curve25519.nim | 8 +- libp2p/crypto/ecnist.nim | 11 +-- libp2p/crypto/ed25519/ed25519.nim | 11 +-- libp2p/crypto/rsa.nim | 5 +- libp2p/crypto/secp.nim | 12 +-- libp2p/peerid.nim | 5 +- .../connectivity/autonat/service.nim | 5 +- libp2p/protocols/secure/noise.nim | 11 +-- libp2p/services/autorelayservice.nim | 7 +- libp2p/transports/tortransport.nim | 5 +- libp2p/utils/random/rng.nim | 25 ++++++ libp2p/utils/random/securerng.nim | 33 ++++++++ libp2p/utils/random/testrng.nim | 82 +++++++++++++++++++ tests/helpers.nim | 8 +- tests/pubsub/testmcache.nim | 3 +- tests/testautonat.nim | 2 +- tests/testautonatservice.nim | 30 +++---- tests/testautorelay.nim | 8 +- tests/testconnmngr.nim | 26 +++--- tests/testcrypto.nim | 15 ++-- tests/testdiscovery.nim | 2 +- tests/testecnist.nim | 34 ++++---- tests/tested25519.nim | 9 +- tests/testhpservice.nim | 18 ++-- tests/testidentify.nim | 6 +- tests/testinterop.nim | 4 +- tests/testnoise.nim | 41 +++++----- tests/testpeerid.nim | 26 +++--- tests/testpeerinfo.nim | 6 +- tests/testpeerstore.nim | 8 +- tests/testrelayv1.nim | 6 +- tests/testrelayv2.nim | 2 +- tests/testrendezvous.nim | 2 +- tests/testrendezvousinterface.nim | 6 +- tests/testrouting_record.nim | 24 +++--- tests/testrsa.nim | 25 +++--- tests/testsecp256k1.nim | 10 ++- tests/testsigned_envelope.nim | 16 ++-- tests/testswitch.nim | 17 ++-- tests/testtortransport.nim | 5 +- 42 files changed, 378 insertions(+), 221 deletions(-) create mode 100644 libp2p/utils/random/rng.nim create mode 100644 libp2p/utils/random/securerng.nim create mode 100644 libp2p/utils/random/testrng.nim diff --git a/libp2p/builders.nim b/libp2p/builders.nim index d16d1eb065..cd9c9d1842 100644 --- a/libp2p/builders.nim +++ b/libp2p/builders.nim @@ -27,7 +27,7 @@ import protocols/connectivity/[autonat/server, relay/relay, relay/client, relay/rtransport], connmanager, upgrademngrs/muxedupgrade, observedaddrmanager, nameresolving/nameresolver, - errors, utility + errors, utility, utils/random/securerng export switch, peerid, peerinfo, connection, multiaddress, crypto, errors @@ -44,7 +44,7 @@ type secureManagers: seq[SecureProtocol] muxers: seq[MuxerProvider] transports: seq[TransportProvider] - rng: ref HmacDrbgContext + rng: Rng maxConnections: int maxIn: int sendSignedPeerRecord: bool @@ -149,7 +149,7 @@ proc withTransport*(b: SwitchBuilder, prov: TransportProvider): SwitchBuilder {. proc withTcpTransport*(b: SwitchBuilder, flags: set[ServerFlags] = {}): SwitchBuilder {.public.} = b.withTransport(proc(upgr: Upgrade): Transport = TcpTransport.new(flags, upgr)) -proc withRng*(b: SwitchBuilder, rng: ref HmacDrbgContext): SwitchBuilder {.public.} = +proc withRng*(b: SwitchBuilder, rng: Rng): SwitchBuilder {.public.} = b.rng = rng b @@ -215,7 +215,7 @@ proc build*(b: SwitchBuilder): Switch if b.rng == nil: # newRng could fail raise newException(Defect, "Cannot initialize RNG") - let pkRes = PrivateKey.random(b.rng[]) + let pkRes = PrivateKey.random(b.rng) let seckey = b.privKey.get(otherwise = pkRes.expect("Expected default Private Key")) @@ -253,7 +253,7 @@ proc build*(b: SwitchBuilder): Switch b.secureManagers &= SecureProtocol.Noise if isNil(b.rng): - b.rng = newRng() + b.rng = SecureRng.new() let peerStore = block: b.peerStoreCapacity.withValue(capacity): @@ -297,7 +297,7 @@ proc newStandardSwitch*( SecureProtocol.Noise, ], transportFlags: set[ServerFlags] = {}, - rng = newRng(), + rng: Rng = SecureRng.new(), inTimeout: Duration = 5.minutes, outTimeout: Duration = 5.minutes, maxConnections = MaxConnections, diff --git a/libp2p/crypto/crypto.nim b/libp2p/crypto/crypto.nim index 38d60657f9..845b21a232 100644 --- a/libp2p/crypto/crypto.nim +++ b/libp2p/crypto/crypto.nim @@ -188,7 +188,7 @@ proc shuffle*[T]( swap(x[i], x[y]) proc random*(T: typedesc[PrivateKey], scheme: PKScheme, - rng: var HmacDrbgContext, + rng: Rng, bits = RsaDefaultKeySize): CryptoResult[PrivateKey] = ## Generate random private key for scheme ``scheme``. ## @@ -220,7 +220,7 @@ proc random*(T: typedesc[PrivateKey], scheme: PKScheme, else: err(SchemeError) -proc random*(T: typedesc[PrivateKey], rng: var HmacDrbgContext, +proc random*(T: typedesc[PrivateKey], rng: Rng, bits = RsaDefaultKeySize): CryptoResult[PrivateKey] = ## Generate random private key using default public-key cryptography scheme. ## @@ -244,7 +244,7 @@ proc random*(T: typedesc[PrivateKey], rng: var HmacDrbgContext, err(SchemeError) proc random*(T: typedesc[KeyPair], scheme: PKScheme, - rng: var HmacDrbgContext, + rng: Rng, bits = RsaDefaultKeySize): CryptoResult[KeyPair] = ## Generate random key pair for scheme ``scheme``. ## @@ -284,7 +284,7 @@ proc random*(T: typedesc[KeyPair], scheme: PKScheme, else: err(SchemeError) -proc random*(T: typedesc[KeyPair], rng: var HmacDrbgContext, +proc random*(T: typedesc[KeyPair], rng: Rng, bits = RsaDefaultKeySize): CryptoResult[KeyPair] = ## Generate random private pair of keys using default public-key cryptography ## scheme. diff --git a/libp2p/crypto/curve25519.nim b/libp2p/crypto/curve25519.nim index b9d6410884..a91fc8d75e 100644 --- a/libp2p/crypto/curve25519.nim +++ b/libp2p/crypto/curve25519.nim @@ -20,6 +20,9 @@ import bearssl/[ec, rand] import stew/results from stew/assign2 import assign + +import ../utils/random/rng + export results const @@ -79,11 +82,10 @@ proc mulgen(_: type[Curve25519], dst: var Curve25519Key, point: Curve25519Key) = proc public*(private: Curve25519Key): Curve25519Key = Curve25519.mulgen(result, private) -proc random*(_: type[Curve25519Key], rng: var HmacDrbgContext): Curve25519Key = +proc random*(_: type[Curve25519Key], rng: Rng): Curve25519Key = var res: Curve25519Key let defaultBrEc = ecGetDefault() - let len = ecKeygen( - addr rng.vtable, defaultBrEc, nil, addr res[0], EC_curve25519) + let len = ecKeygen(addr rng.vtable, defaultBrEc, nil, addr res[0], EC_curve25519) # Per bearssl documentation, the keygen only fails if the curve is # unrecognised - doAssert len == Curve25519KeySize, "Could not generate curve" diff --git a/libp2p/crypto/ecnist.nim b/libp2p/crypto/ecnist.nim index 8471e0e97e..e296b07688 100644 --- a/libp2p/crypto/ecnist.nim +++ b/libp2p/crypto/ecnist.nim @@ -23,6 +23,7 @@ import minasn1 export minasn1.Asn1Error import stew/[results, ctops] +import ../utils/random/rng import ../utility export results @@ -233,7 +234,7 @@ proc clear*[T: EcPKI|EcKeyPair](pki: var T) = proc random*( T: typedesc[EcPrivateKey], kind: EcCurveKind, - rng: var HmacDrbgContext): EcResult[EcPrivateKey] = + rng: Rng): EcResult[EcPrivateKey] = ## Generate new random EC private key using BearSSL's HMAC-SHA256-DRBG ## algorithm. ## @@ -241,7 +242,7 @@ proc random*( ## secp521r1). var ecimp = ecGetDefault() var res = new EcPrivateKey - if ecKeygen(addr rng.vtable, ecimp, + if ecKeygen(rng.vtable, ecimp, addr res.key, addr res.buffer[0], safeConvert[cint](kind)) == 0: err(EcKeyGenError) @@ -267,7 +268,7 @@ proc getPublicKey*(seckey: EcPrivateKey): EcResult[EcPublicKey] = proc random*( T: typedesc[EcKeyPair], kind: EcCurveKind, - rng: var HmacDrbgContext): EcResult[T] = + rng: Rng): EcResult[T] = ## Generate new random EC private and public keypair using BearSSL's ## HMAC-SHA256-DRBG algorithm. ## @@ -999,7 +1000,7 @@ type ECDHEScheme* = EcCurveKind proc ephemeral*( scheme: ECDHEScheme, - rng: var HmacDrbgContext): EcResult[EcKeyPair] = + rng: Rng): EcResult[EcKeyPair] = ## Generate ephemeral keys used to perform ECDHE. var keypair: EcKeyPair if scheme == Secp256r1: @@ -1011,7 +1012,7 @@ proc ephemeral*( ok(keypair) proc ephemeral*( - scheme: string, rng: var HmacDrbgContext): EcResult[EcKeyPair] = + scheme: string, rng: Rng): EcResult[EcKeyPair] = ## Generate ephemeral keys used to perform ECDHE using string encoding. ## ## Currently supported encoding strings are P-256, P-384, P-521, if encoding diff --git a/libp2p/crypto/ed25519/ed25519.nim b/libp2p/crypto/ed25519/ed25519.nim index dc49d47134..ccbce61ab8 100644 --- a/libp2p/crypto/ed25519/ed25519.nim +++ b/libp2p/crypto/ed25519/ed25519.nim @@ -21,8 +21,9 @@ import nimcrypto/utils as ncrutils import stew/[results, ctops] import ../../utility +import ../../utils/random/rng -export results +export results, rng # This workaround needed because of some bugs in Nim Static[T]. export hash, sha2, rand @@ -1648,14 +1649,14 @@ proc checkScalar*(scalar: openArray[byte]): uint32 = c = -1 result = NEQ(z, 0'u32) and LT0(c) -proc random*(t: typedesc[EdPrivateKey], rng: var HmacDrbgContext): EdPrivateKey = +proc random*(t: typedesc[EdPrivateKey], rng: Rng): EdPrivateKey = ## Generate new random ED25519 private key using the given random number generator var point: GeP3 pk: array[EdPublicKeySize, byte] res: EdPrivateKey - hmacDrbgGenerate(rng, res.data.toOpenArray(0, 31)) + rng.generate(res.data.toOpenArray(0, 31)) var hh = sha512.digest(res.data.toOpenArray(0, 31)) hh.data[0] = hh.data[0] and 0xF8'u8 @@ -1667,14 +1668,14 @@ proc random*(t: typedesc[EdPrivateKey], rng: var HmacDrbgContext): EdPrivateKey res -proc random*(t: typedesc[EdKeyPair], rng: var HmacDrbgContext): EdKeyPair = +proc random*(t: typedesc[EdKeyPair], rng: Rng): EdKeyPair = ## Generate new random ED25519 private and public keypair using OS specific ## CSPRNG. var point: GeP3 res: EdKeyPair - hmacDrbgGenerate(rng, res.seckey.data.toOpenArray(0, 31)) + rng.generate(res.seckey.data.toOpenArray(0, 31)) var hh = sha512.digest(res.seckey.data.toOpenArray(0, 31)) hh.data[0] = hh.data[0] and 0xF8'u8 diff --git a/libp2p/crypto/rsa.nim b/libp2p/crypto/rsa.nim index 53f0985b1c..334312dadb 100644 --- a/libp2p/crypto/rsa.nim +++ b/libp2p/crypto/rsa.nim @@ -20,6 +20,7 @@ import minasn1 import stew/[results, ctops] # We use `ncrutils` for constant-time hexadecimal encoding/decoding procedures. import nimcrypto/utils as ncrutils +import ../utils/random/rng export Asn1Error, results @@ -115,7 +116,7 @@ template trimZeroes(b: seq[byte], pt, ptlen: untyped) = pt = cast[ptr byte](cast[uint](pt) + 1) ptlen -= 1 -proc random*[T: RsaKP](t: typedesc[T], rng: var HmacDrbgContext, +proc random*[T: RsaKP](t: typedesc[T], rng: Rng, bits = DefaultKeySize, pubexp = DefaultPublicExponent): RsaResult[T] = ## Generate new random RSA private key using BearSSL's HMAC-SHA256-DRBG @@ -139,7 +140,7 @@ proc random*[T: RsaKP](t: typedesc[T], rng: var HmacDrbgContext, var keygen = rsaKeygenGetDefault() - if keygen(addr rng.vtable, + if keygen(rng.vtable, addr res.seck, addr res.buffer[sko], addr res.pubk, addr res.buffer[pko], cuint(bits), pubexp) == 0: diff --git a/libp2p/crypto/secp.nim b/libp2p/crypto/secp.nim index caf17c2eed..72e205510b 100644 --- a/libp2p/crypto/secp.nim +++ b/libp2p/crypto/secp.nim @@ -15,6 +15,8 @@ import stew/[byteutils, results], nimcrypto/[hash, sha2] +import ../utils/random/rng + export sha2, results, rand const @@ -32,18 +34,16 @@ type SkSignature* = distinct secp256k1.SkSignature SkKeyPair* = distinct secp256k1.SkKeyPair -proc random*(t: typedesc[SkPrivateKey], rng: var HmacDrbgContext): SkPrivateKey = +proc random*(t: typedesc[SkPrivateKey], rng: rng.Rng): SkPrivateKey = #TODO is there a better way? - var rngPtr = addr rng proc callRng(data: var openArray[byte]) = - hmacDrbgGenerate(rngPtr[], data) + rng.generate(data) SkPrivateKey(SkSecretKey.random(callRng)) -proc random*(t: typedesc[SkKeyPair], rng: var HmacDrbgContext): SkKeyPair = - let rngPtr = addr rng +proc random*(t: typedesc[SkKeyPair], rng: rng.Rng): SkKeyPair = proc callRng(data: var openArray[byte]) = - hmacDrbgGenerate(rngPtr[], data) + rng.generate(data) SkKeyPair(secp256k1.SkKeyPair.random(callRng)) diff --git a/libp2p/peerid.nim b/libp2p/peerid.nim index 4f7e6f9d14..69584be480 100644 --- a/libp2p/peerid.nim +++ b/libp2p/peerid.nim @@ -20,6 +20,7 @@ import utility, ./crypto/crypto, ./multicodec, ./multihash, ./vbuffer, ./protobuf/minprotobuf +import utils/random/securerng export results, utility @@ -178,9 +179,9 @@ func init*(t: typedesc[PeerId], seckey: PrivateKey): Result[PeerId, cstring] = ## Create new peer id from private key ``seckey``. PeerId.init(? seckey.getPublicKey().orError(cstring("invalid private key"))) -proc random*(t: typedesc[PeerId], rng = newRng()): Result[PeerId, cstring] = +proc random*(t: typedesc[PeerId], rng: Rng = SecureRng.new()): Result[PeerId, cstring] = ## Create new peer id with random public key. - let randomKey = PrivateKey.random(Secp256k1, rng[])[] + let randomKey = PrivateKey.random(Secp256k1, rng)[] PeerId.init(randomKey).orError(cstring("failed to generate random key")) func match*(pid: PeerId, pubkey: PublicKey): bool = diff --git a/libp2p/protocols/connectivity/autonat/service.nim b/libp2p/protocols/connectivity/autonat/service.nim index 0a6e0026a4..11ab7ecddb 100644 --- a/libp2p/protocols/connectivity/autonat/service.nim +++ b/libp2p/protocols/connectivity/autonat/service.nim @@ -16,6 +16,7 @@ import ../../../wire import client from core import NetworkReachability, AutonatUnreachableError import ../../../utils/heartbeat +import ../../../utils/random/rng import ../../../crypto/crypto export core.NetworkReachability @@ -35,7 +36,7 @@ type answers: Deque[NetworkReachability] autonatClient: AutonatClient statusAndConfidenceHandler: StatusAndConfidenceHandler - rng: ref HmacDrbgContext + rng: Rng scheduleInterval: Opt[Duration] askNewConnectedPeers: bool numPeersToAsk: int @@ -49,7 +50,7 @@ type proc new*( T: typedesc[AutonatService], autonatClient: AutonatClient, - rng: ref HmacDrbgContext, + rng: Rng, scheduleInterval: Opt[Duration] = Opt.none(Duration), askNewConnectedPeers = true, numPeersToAsk: int = 5, diff --git a/libp2p/protocols/secure/noise.nim b/libp2p/protocols/secure/noise.nim index 0a4032bcef..d1769abb7d 100644 --- a/libp2p/protocols/secure/noise.nim +++ b/libp2p/protocols/secure/noise.nim @@ -21,6 +21,7 @@ import ../../peerinfo import ../../protobuf/minprotobuf import ../../utility import ../../errors +import ../../utils/random/rng import secure, ../../crypto/[crypto, chacha20poly1305, curve25519, hkdf] @@ -78,7 +79,7 @@ type rs: Curve25519Key Noise* = ref object of Secure - rng: ref HmacDrbgContext + rng: Rng localPrivateKey: PrivateKey localPublicKey: seq[byte] noiseKeys: KeyPair @@ -106,7 +107,7 @@ func shortLog*(conn: NoiseConnection): auto = chronicles.formatIt(NoiseConnection): shortLog(it) -proc genKeyPair(rng: var HmacDrbgContext): KeyPair = +proc genKeyPair(rng: Rng): KeyPair = result.privateKey = Curve25519Key.random(rng) result.publicKey = result.privateKey.public() @@ -235,7 +236,7 @@ template write_e: untyped = trace "noise write e" # Sets e (which must be empty) to GENERATE_KEYPAIR(). # Appends e.public_key to the buffer. Calls MixHash(e.public_key). - hs.e = genKeyPair(p.rng[]) + hs.e = genKeyPair(p.rng) msg.add hs.e.publicKey hs.ss.mixHash(hs.e.publicKey) @@ -645,7 +646,7 @@ method init*(p: Noise) {.gcsafe.} = proc new*( T: typedesc[Noise], - rng: ref HmacDrbgContext, + rng: Rng, privateKey: PrivateKey, outgoing: bool = true, commonPrologue: seq[byte] = @[]): T = @@ -658,7 +659,7 @@ proc new*( outgoing: outgoing, localPrivateKey: privateKey, localPublicKey: pkBytes, - noiseKeys: genKeyPair(rng[]), + noiseKeys: genKeyPair(rng), commonPrologue: commonPrologue, ) diff --git a/libp2p/services/autorelayservice.nim b/libp2p/services/autorelayservice.nim index c94aed13da..da61313960 100644 --- a/libp2p/services/autorelayservice.nim +++ b/libp2p/services/autorelayservice.nim @@ -11,7 +11,8 @@ import chronos, chronicles, times, tables, sequtils import ../switch, - ../protocols/connectivity/relay/[client, utils] + ../protocols/connectivity/relay/[client, utils], + ../utils/random/rng logScope: topics = "libp2p autorelay" @@ -30,7 +31,7 @@ type peerAvailable: AsyncEvent onReservation: OnReservationHandler addressMapper: AddressMapper - rng: ref HmacDrbgContext + rng: Rng proc isRunning*(self: AutoRelayService): bool = return self.running @@ -139,7 +140,7 @@ proc new*(T: typedesc[AutoRelayService], numRelays: int, client: RelayClient, onReservation: OnReservationHandler, - rng: ref HmacDrbgContext): T = + rng: Rng): T = T(numRelays: numRelays, client: client, onReservation: onReservation, diff --git a/libp2p/transports/tortransport.nim b/libp2p/transports/tortransport.nim index 54ee9e0ff8..e59679e11b 100644 --- a/libp2p/transports/tortransport.nim +++ b/libp2p/transports/tortransport.nim @@ -21,7 +21,8 @@ import transport, ../builders, ../stream/[lpstream, connection, chronosstream], ../multiaddress, - ../upgrademngrs/upgrade + ../upgrademngrs/upgrade, + ../utils/random/rng const IPTcp = mapAnd(IP, mapEq("tcp")) @@ -252,7 +253,7 @@ type proc new*( T: typedesc[TorSwitch], torServer: TransportAddress, - rng: ref HmacDrbgContext, + rng: Rng, addresses: seq[MultiAddress] = @[], flags: set[ServerFlags] = {}): TorSwitch {.raises: [LPError], public.} = diff --git a/libp2p/utils/random/rng.nim b/libp2p/utils/random/rng.nim new file mode 100644 index 0000000000..268f330f27 --- /dev/null +++ b/libp2p/utils/random/rng.nim @@ -0,0 +1,25 @@ +# Nim-Libp2p +# Copyright (c) 2023 Status Research & Development GmbH +# Licensed under either of +# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) +# * MIT license ([LICENSE-MIT](LICENSE-MIT)) +# at your option. +# This file may not be copied, modified, or distributed except according to +# those terms. + +{.push raises: [].} + +import bearssl/rand +export PrngClass + +type + Rng* = ref object of RootObj + vtable*: ptr ptr PrngClass + +method shuffle*[T]( + rng: Rng, + x: var openArray[T]) {.base.} = + raiseAssert("Not implemented!") + +method generate*(rng: Rng, v: var openArray[byte]) {.base.} = + raiseAssert("Not implemented!") diff --git a/libp2p/utils/random/securerng.nim b/libp2p/utils/random/securerng.nim new file mode 100644 index 0000000000..24ea75f61d --- /dev/null +++ b/libp2p/utils/random/securerng.nim @@ -0,0 +1,33 @@ +# Nim-Libp2p +# Copyright (c) 2023 Status Research & Development GmbH +# Licensed under either of +# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) +# * MIT license ([LICENSE-MIT](LICENSE-MIT)) +# at your option. +# This file may not be copied, modified, or distributed except according to +# those terms. + +{.push raises: [].} + +import rng +import bearssl/rand +import ../../crypto/crypto + +export Rng + +type + SecureRng* = ref object of Rng + hmacDrbgContext: ref HmacDrbgContext + +method shuffle*[T]( + rng: SecureRng, + x: var openArray[T]) = + rng.hmacDrbgContext[].shuffle(x) + +method generate*(rng: SecureRng, v: var openArray[byte]) = + generate(rng.hmacDrbgContext[], v) + +proc new*( + T: typedesc[SecureRng]): T = + var hmacDrbgContext = newRng() + return T(hmacDrbgContext: hmacDrbgContext, vtable: addr hmacDrbgContext.vtable) \ No newline at end of file diff --git a/libp2p/utils/random/testrng.nim b/libp2p/utils/random/testrng.nim new file mode 100644 index 0000000000..05e13983b9 --- /dev/null +++ b/libp2p/utils/random/testrng.nim @@ -0,0 +1,82 @@ +# Nim-Libp2p +# Copyright (c) 2023 Status Research & Development GmbH +# Licensed under either of +# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE)) +# * MIT license ([LICENSE-MIT](LICENSE-MIT)) +# at your option. +# This file may not be copied, modified, or distributed except according to +# those terms. + +{.push raises: [].} + +import rng +import bearssl/rand +import bearssl/hash +import std/random + +export Rng + +type + TestRng* = ref object of Rng + hmacDrbgContext: ref HmacDrbgContextMock + prngClass: PrngClass + + HmacDrbgContextMock* = object + vtable: ptr PrngClass # Mock VTable + K: array[64, byte] # Mock cryptographic key + V: array[64, byte] # Mock cryptographic state + digestClass: ptr HashClass # Point to a mock or dummy hash class + +# Helper to easily cast to correct type +proc toMock(ctx: ptr ptr PrngClass): ptr HmacDrbgContextMock = + return cast[ptr HmacDrbgContextMock](ctx[]) + +proc mockInit(ctx: ptr ptr PrngClass, params: pointer, seed: pointer, seedLen: uint) {.cdecl, noSideEffect, gcsafe.} = + let mockCtx = toMock(ctx) + # Initialize V with a simple pattern or seed data if available + for i in 0.. 0: + let seedBytes = cast[ptr array[0..high(int), byte]](seed) + for i in 0.. 0 @@ -324,7 +326,7 @@ suite "EC NIST-P256/384/521 test suite": for i in 0.. 0 @@ -343,8 +345,8 @@ suite "EC NIST-P256/384/521 test suite": test "[secp256r1] ECDHE test": for i in 0.. 0 @@ -437,7 +439,7 @@ suite "EC NIST-P256/384/521 test suite": for i in 0.. 0 @@ -456,8 +458,8 @@ suite "EC NIST-P256/384/521 test suite": test "[secp384r1] ECDHE test": for i in 0.. 0 @@ -550,7 +552,7 @@ suite "EC NIST-P256/384/521 test suite": for i in 0.. 0 @@ -569,8 +571,8 @@ suite "EC NIST-P256/384/521 test suite": test "[secp521r1] ECDHE test": for i in 0.. 0 @@ -138,7 +139,7 @@ suite "Ed25519 test suite": for i in 0.. 0 @@ -174,7 +175,7 @@ suite "Ed25519 test suite": test "Generate/Sign/Serialize/Deserialize/Verify test": var message = "message to sign" for i in 0.. decode test": let - rng = newRng() - privKey = PrivateKey.random(rng[]).tryGet() + privKey = PrivateKey.random(rng).tryGet() peerId = PeerId.init(privKey).tryGet() multiAddresses = @[MultiAddress.init("/ip4/0.0.0.0/tcp/24").tryGet(), MultiAddress.init("/ip4/0.0.0.0/tcp/25").tryGet()] routingRecord = PeerRecord.init(peerId, multiAddresses, 42) @@ -50,8 +53,7 @@ suite "Routing record": suite "Signed Routing Record": test "Encode -> decode test": let - rng = newRng() - privKey = PrivateKey.random(rng[]).tryGet() + privKey = PrivateKey.random(rng).tryGet() peerId = PeerId.init(privKey).tryGet() multiAddresses = @[MultiAddress.init("/ip4/0.0.0.0/tcp/24").tryGet(), MultiAddress.init("/ip4/0.0.0.0/tcp/25").tryGet()] routingRecord = SignedPeerRecord.init(privKey, PeerRecord.init(peerId, multiAddresses, 42)).tryGet() @@ -68,9 +70,8 @@ suite "Signed Routing Record": test "Can't use mismatched public key": let - rng = newRng() - privKey = PrivateKey.random(rng[]).tryGet() - privKey2 = PrivateKey.random(rng[]).tryGet() + privKey = PrivateKey.random(rng).tryGet() + privKey2 = PrivateKey.random(rng).tryGet() peerId = PeerId.init(privKey).tryGet() multiAddresses = @[MultiAddress.init("/ip4/0.0.0.0/tcp/24").tryGet(), MultiAddress.init("/ip4/0.0.0.0/tcp/25").tryGet()] routingRecord = SignedPeerRecord.init(privKey2, PeerRecord.init(peerId, multiAddresses, 42)).tryGet() @@ -80,8 +81,7 @@ suite "Signed Routing Record": test "Decode doesn't fail if some addresses are invalid": let - rng = newRng() - privKey = PrivateKey.random(rng[]).tryGet() + privKey = PrivateKey.random(rng).tryGet() peerId = PeerId.init(privKey).tryGet() multiAddresses = @[MultiAddress(), MultiAddress.init("/ip4/0.0.0.0/tcp/25").tryGet()] routingRecord = PeerRecord.init(peerId, multiAddresses, 42) @@ -93,8 +93,7 @@ suite "Signed Routing Record": test "Decode doesn't fail if there are no addresses": let - rng = newRng() - privKey = PrivateKey.random(rng[]).tryGet() + privKey = PrivateKey.random(rng).tryGet() peerId = PeerId.init(privKey).tryGet() multiAddresses = newSeq[MultiAddress]() routingRecord = PeerRecord.init(peerId, multiAddresses, 42) @@ -106,8 +105,7 @@ suite "Signed Routing Record": test "Decode fails if all addresses are invalid": let - rng = newRng() - privKey = PrivateKey.random(rng[]).tryGet() + privKey = PrivateKey.random(rng).tryGet() peerId = PeerId.init(privKey).tryGet() multiAddresses = @[MultiAddress(), MultiAddress()] routingRecord = PeerRecord.init(peerId, multiAddresses, 42) diff --git a/tests/testrsa.nim b/tests/testrsa.nim index 8f83c6ef37..3d73d80c03 100644 --- a/tests/testrsa.nim +++ b/tests/testrsa.nim @@ -12,6 +12,7 @@ import unittest2 import nimcrypto/utils import ../libp2p/crypto/[crypto, rsa] +import ../libp2p/utils/random/testrng const NotAllowedPrivateKeys = [ @@ -354,7 +355,7 @@ const ACB51807206B8332127E3692269013B96F0CABD95D7431805E48176ADC5D1366""" ] -let rng = newRng() +let rng = TestRng.new() type RsaPrivateKey = rsa.RsaPrivateKey @@ -364,7 +365,7 @@ suite "RSA 2048/3072/4096 test suite": test "[rsa2048] Private key serialize/deserialize test": var rkey1, rkey2: RsaPrivateKey var skey2 = newSeq[byte](4096) - var key = RsaPrivateKey.random(rng[], 2048).expect("random failed") + var key = RsaPrivateKey.random(rng, 2048).expect("random failed") var skey1 = key.getBytes().expect("bytes") check key.toBytes(skey2).expect("bytes") > 0 check: @@ -381,7 +382,7 @@ suite "RSA 2048/3072/4096 test suite": test "[rsa3072] Private key serialize/deserialize test": var rkey1, rkey2: RsaPrivateKey var skey2 = newSeq[byte](4096) - var key = RsaPrivateKey.random(rng[], 3072).expect("random failed") + var key = RsaPrivateKey.random(rng, 3072).expect("random failed") var skey1 = key.getBytes().expect("bytes") check key.toBytes(skey2).expect("bytes") > 0 check: @@ -400,7 +401,7 @@ suite "RSA 2048/3072/4096 test suite": when defined(release): var rkey1, rkey2: RsaPrivateKey var skey2 = newSeq[byte](4096) - var key = RsaPrivateKey.random(rng[], 4096).expect("random failed") + var key = RsaPrivateKey.random(rng, 4096).expect("random failed") var skey1 = key.getBytes().expect("bytes") check key.toBytes(skey2).expect("bytes") > 0 check: @@ -419,7 +420,7 @@ suite "RSA 2048/3072/4096 test suite": test "[rsa2048] Public key serialize/deserialize test": var rkey1, rkey2: RsaPublicKey var skey2 = newSeq[byte](4096) - var pair = RsaKeyPair.random(rng[], 2048).expect("random failed") + var pair = RsaKeyPair.random(rng, 2048).expect("random failed") var skey1 = pair.pubkey.getBytes().expect("bytes") check: pair.pubkey.toBytes(skey2).expect("bytes") > 0 @@ -436,7 +437,7 @@ suite "RSA 2048/3072/4096 test suite": test "[rsa3072] Public key serialize/deserialize test": var rkey1, rkey2: RsaPublicKey var skey2 = newSeq[byte](4096) - var pair = RsaKeyPair.random(rng[], 3072).expect("random failed") + var pair = RsaKeyPair.random(rng, 3072).expect("random failed") var skey1 = pair.pubkey.getBytes().expect("bytes") check: pair.pubkey.toBytes(skey2).expect("bytes") > 0 @@ -454,7 +455,7 @@ suite "RSA 2048/3072/4096 test suite": when defined(release): var rkey1, rkey2: RsaPublicKey var skey2 = newSeq[byte](4096) - var pair = RsaKeyPair.random(rng[], 4096).expect("random failed") + var pair = RsaKeyPair.random(rng, 4096).expect("random failed") var skey1 = pair.pubkey.getBytes().expect("bytes") check: pair.pubkey.toBytes(skey2).expect("bytes") > 0 @@ -472,7 +473,7 @@ suite "RSA 2048/3072/4096 test suite": test "[rsa2048] Generate/Sign/Serialize/Deserialize/Verify test": var message = "message to sign" - var kp = RsaKeyPair.random(rng[], 2048).expect("RsaPrivateKey.random failed") + var kp = RsaKeyPair.random(rng, 2048).expect("RsaPrivateKey.random failed") var sig = kp.seckey.sign(message).expect("signature") var sersk = kp.seckey.getBytes().expect("bytes") var serpk = kp.pubkey.getBytes().expect("bytes") @@ -487,7 +488,7 @@ suite "RSA 2048/3072/4096 test suite": test "[rsa3072] Generate/Sign/Serialize/Deserialize/Verify test": var message = "message to sign" - var kp = RsaKeyPair.random(rng[], 3072).expect("RsaPrivateKey.random failed") + var kp = RsaKeyPair.random(rng, 3072).expect("RsaPrivateKey.random failed") var sig = kp.seckey.sign(message).expect("signature") var sersk = kp.seckey.getBytes().expect("bytes") var serpk = kp.pubkey.getBytes().expect("bytes") @@ -503,7 +504,7 @@ suite "RSA 2048/3072/4096 test suite": test "[rsa4096] Generate/Sign/Serialize/Deserialize/Verify test": when defined(release): var message = "message to sign" - var kp = RsaKeyPair.random(rng[], 4096).expect("RsaPrivateKey.random failed") + var kp = RsaKeyPair.random(rng, 4096).expect("RsaPrivateKey.random failed") var sig = kp.seckey.sign(message).expect("signature") var sersk = kp.seckey.getBytes().expect("bytes") var serpk = kp.pubkey.getBytes().expect("bytes") @@ -588,7 +589,7 @@ suite "RSA 2048/3072/4096 test suite": csig.verify(Messages[4 + (i + 1) mod 2], pubkey) == false test "[rsa512] not allowed test": - var key1 = RsaPrivateKey.random(rng[], 512) + var key1 = RsaPrivateKey.random(rng, 512) let prvser = fromHex(stripSpaces(NotAllowedPrivateKeys[0])) let pubser = fromHex(stripSpaces(NotAllowedPublicKeys[0])) var key2 = RsaPrivateKey.init(prvser) @@ -602,7 +603,7 @@ suite "RSA 2048/3072/4096 test suite": key3.error == RsaKeyIncorrectError test "[rsa1024] not allowed test": - var key1 = RsaPrivateKey.random(rng[], 1024) + var key1 = RsaPrivateKey.random(rng, 1024) let prvser = fromHex(stripSpaces(NotAllowedPrivateKeys[1])) let pubser = fromHex(stripSpaces(NotAllowedPublicKeys[1])) var key2 = RsaPrivateKey.init(prvser) diff --git a/tests/testsecp256k1.nim b/tests/testsecp256k1.nim index 88d60dfe73..060b59db47 100644 --- a/tests/testsecp256k1.nim +++ b/tests/testsecp256k1.nim @@ -12,7 +12,9 @@ import unittest2 import ../libp2p/crypto/[crypto, secp] -let rng = newRng() +import ../libp2p/utils/random/testrng + +let rng = TestRng.new() suite "Secp256k1 testing suite": const TestsCount = 20 @@ -21,7 +23,7 @@ suite "Secp256k1 testing suite": for i in 0.. 0 @@ -39,7 +41,7 @@ suite "Secp256k1 testing suite": for i in 0.. 0 @@ -55,7 +57,7 @@ suite "Secp256k1 testing suite": test "Generate/Sign/Serialize/Deserialize/Verify test": var message = "message to sign" for i in 0.. decode -> encode -> decode test": let - rng = newRng() - privKey = PrivateKey.random(rng[]).tryGet() + privKey = PrivateKey.random(rng).tryGet() envelope = Envelope.init(privKey, @[byte 12, 0], "payload".toBytes(), "domain").tryGet() buffer = envelope.encode().tryGet() decodedEnvelope = Envelope.decode(buffer, "domain").tryGet() @@ -67,8 +70,7 @@ proc payloadType*(T: typedesc[DummyPayload]): seq[byte] = @[(byte) 0x00, (byte) suite "Signed payload": test "Simple encode -> decode": let - rng = newRng() - privKey = PrivateKey.random(rng[]).tryGet() + privKey = PrivateKey.random(rng).tryGet() dummyPayload = DummyPayload(awesome: 12.byte) signed = SignedDummy.init(privKey, dummyPayload).tryGet() @@ -81,8 +83,7 @@ suite "Signed payload": test "Invalid payload": let - rng = newRng() - privKey = PrivateKey.random(rng[]).tryGet() + privKey = PrivateKey.random(rng).tryGet() dummyPayload = DummyPayload(awesome: 30.byte) signed = SignedDummy.init(privKey, dummyPayload).tryGet() @@ -91,8 +92,7 @@ suite "Signed payload": test "Invalid payload type": let - rng = newRng() - privKey = PrivateKey.random(rng[]).tryGet() + privKey = PrivateKey.random(rng).tryGet() dummyPayload = DummyPayload(awesome: 30.byte) signed = Envelope.init(privKey, @[55.byte], dummyPayload.encode(), DummyPayload.payloadDomain).tryGet() diff --git a/tests/testswitch.nim b/tests/testswitch.nim index b9638cafea..32871bc666 100644 --- a/tests/testswitch.nim +++ b/tests/testswitch.nim @@ -508,9 +508,8 @@ suite "Switch": asyncTest "e2e should trigger peer events only once per peer": let switch1 = newStandardSwitch() - let rng = crypto.newRng() # use same private keys to emulate two connection from same peer - let privKey = PrivateKey.random(rng[]).tryGet() + let privKey = PrivateKey.random(rng).tryGet() let switch2 = newStandardSwitch( privKey = some(privKey), rng = rng) @@ -572,10 +571,9 @@ suite "Switch": switch3.stop()) asyncTest "e2e should allow dropping peer from connection events": - let rng = crypto.newRng() # use same private keys to emulate two connection from same peer let - privateKey = PrivateKey.random(rng[]).tryGet() + privateKey = PrivateKey.random(rng).tryGet() peerInfo = PeerInfo.new(privateKey) var switches: seq[Switch] @@ -609,10 +607,9 @@ suite "Switch": switches.mapIt( it.stop() )) asyncTest "e2e should allow dropping multiple connections for peer from connection events": - let rng = crypto.newRng() # use same private keys to emulate two connection from same peer let - privateKey = PrivateKey.random(rng[]).tryGet() + privateKey = PrivateKey.random(rng).tryGet() peerInfo = PeerInfo.new(privateKey) var conns = 1 @@ -671,7 +668,7 @@ suite "Switch": await switch.start() - var peerId = PeerId.init(PrivateKey.random(ECDSA, rng[]).get()).get() + var peerId = randomPeerId() expect DialFailedError: await switch.connect(peerId, transport.addrs) @@ -723,7 +720,7 @@ suite "Switch": let switch2 = newStandardSwitch(secureManagers = [SecureProtocol.Noise]) await switch2.start() let someAddr = MultiAddress.init("/ip4/127.128.0.99").get() - let seckey = PrivateKey.random(ECDSA, rng[]).get() + let seckey = PrivateKey.random(ECDSA, rng).get() let somePeer = PeerInfo.new(seckey, [someAddr]) expect(DialFailedError): discard await switch2.dial(somePeer.peerId, somePeer.addrs, TestCodec) @@ -980,7 +977,7 @@ suite "Switch": srcWsSwitch = SwitchBuilder.new() .withAddress(wsAddress) - .withRng(crypto.newRng()) + .withRng(rng) .withMplex() .withTransport(proc (upgr: Upgrade): Transport = WsTransport.new(upgr)) .withNameResolver(resolver) @@ -990,7 +987,7 @@ suite "Switch": destSwitch = SwitchBuilder.new() .withAddresses(@[tcpAddress, wsAddress]) - .withRng(crypto.newRng()) + .withRng(rng) .withMplex() .withTransport(proc (upgr: Upgrade): Transport = WsTransport.new(upgr)) .withTcpTransport() diff --git a/tests/testtortransport.nim b/tests/testtortransport.nim index 7b4af7adaa..f38f070c00 100644 --- a/tests/testtortransport.nim +++ b/tests/testtortransport.nim @@ -18,7 +18,8 @@ import ../libp2p/[stream/connection, transports/tortransport, upgrademngrs/upgrade, multiaddress, - builders] + builders, + utils/random/testrng] import ./helpers, ./stubs/torstub, ./commontransport @@ -98,7 +99,7 @@ suite "Tor transport": return T.new(codecs = @[TestCodec], handler = handle) - let rng = newRng() + let rng = TestRng.new() let ma = MultiAddress.init("/ip4/127.0.0.1/tcp/8080/onion3/a2mncbqsbullu7thgm4e6zxda2xccmcgzmaq44oayhdtm6rav5vovcad:80").tryGet()