Bump to nim-libp2p 2.0.0

* bump libp2p pin to release/v2.0.0 (c43199378)
* pin nimble.lock: lsquic/websock/boringssl/protobuf_serialization/npeg/jwt
* add libp2p_mix dep and point libp2p/protocols/mix -> libp2p_mix
* migrate rng to libp2p Rng type (prod, channels, noise, tests)
* noise: take Rng, extract bearSslDrbg internally
* waku_switch: TransportConfig factory; withMaxInOut; local MaxConnections
* waku_relay/rendezvous/discv5/kademlia: v2.0.0 API (rng, config, ServiceDiscovery)
* tests: newStandardSwitch shim; PeerId.random(rng); common.rng()/crypto.newRng()
* drop libp2p/utils/semaphore (use chronos AsyncSemaphore)
* add waku/compat/option_valueor shim where needed
* add std/options where transitive re-export dropped
This commit is contained in:
Fabiana Cecin 2026-06-02 15:42:58 -03:00
parent 8b0e21fada
commit 549834203d
No known key found for this signature in database
GPG Key ID: BCAB8A55CB51B6C7
160 changed files with 583 additions and 324 deletions

View File

@ -302,7 +302,7 @@ proc readInput(wfd: AsyncFD) {.thread, raises: [Defect, CatchableError].} =
{.pop.}
# @TODO confutils.nim(775, 17) Error: can raise an unlisted exception: ref IOError
proc processInput(rfd: AsyncFD, rng: ref HmacDrbgContext) {.async.} =
proc processInput(rfd: AsyncFD, rng: crypto.Rng) {.async.} =
let
transp = fromPipe(rfd)
conf = Chat2Conf.load()
@ -310,7 +310,7 @@ proc processInput(rfd: AsyncFD, rng: ref HmacDrbgContext) {.async.} =
if conf.nodekey.isSome():
conf.nodekey.get()
else:
PrivateKey.random(Secp256k1, rng[]).tryGet()
PrivateKey.random(Secp256k1, rng).tryGet()
# set log level
if conf.logLevel != LogLevel.NONE:
@ -565,7 +565,7 @@ proc processInput(rfd: AsyncFD, rng: ref HmacDrbgContext) {.async.} =
runForever()
proc main(rng: ref HmacDrbgContext) {.async.} =
proc main(rng: crypto.Rng) {.async.} =
let (rfd, wfd) = createAsyncPipe()
if rfd == asyncInvalidPipe or wfd == asyncInvalidPipe:
raise newException(ValueError, "Could not initialize pipe!")

View File

@ -271,7 +271,7 @@ when isMainModule:
if conf.nodekey.isSome():
conf.nodekey.get()
else:
crypto.PrivateKey.random(Secp256k1, rng[]).tryGet()
crypto.PrivateKey.random(Secp256k1, rng).tryGet()
let bridge = Chat2Matterbridge.new(
mbHostUri = "http://" & $initTAddress(conf.mbHostAddress, Port(conf.mbHostPort)),

View File

@ -388,7 +388,7 @@ proc maintainSubscription(
{.pop.}
# @TODO confutils.nim(775, 17) Error: can raise an unlisted exception: ref IOError
proc processInput(rfd: AsyncFD, rng: ref HmacDrbgContext) {.async.} =
proc processInput(rfd: AsyncFD, rng: crypto.Rng) {.async.} =
let
transp = fromPipe(rfd)
conf = Chat2Conf.load()
@ -396,7 +396,7 @@ proc processInput(rfd: AsyncFD, rng: ref HmacDrbgContext) {.async.} =
if conf.nodekey.isSome():
conf.nodekey.get()
else:
PrivateKey.random(Secp256k1, rng[]).tryGet()
PrivateKey.random(Secp256k1, rng).tryGet()
# set log level
if conf.logLevel != LogLevel.NONE:
@ -660,7 +660,7 @@ proc processInput(rfd: AsyncFD, rng: ref HmacDrbgContext) {.async.} =
runForever()
proc main(rng: ref HmacDrbgContext) {.async.} =
proc main(rng: crypto.Rng) {.async.} =
let (rfd, wfd) = createAsyncPipe()
if rfd == asyncInvalidPipe or wfd == asyncInvalidPipe:
raise newException(ValueError, "Could not initialize pipe!")

View File

@ -423,7 +423,7 @@ proc initAndStartApp(
let
# some hardcoded parameters
rng = keys.newRng()
key = crypto.PrivateKey.random(Secp256k1, rng[])[]
key = crypto.PrivateKey.random(Secp256k1, rng)[]
nodeTcpPort = Port(60000)
nodeUdpPort = Port(9000)
flags = CapabilitiesBitfield.init(

View File

@ -159,7 +159,7 @@ proc pingNode(
error "Failed to ping the peer", peer = peerInfo, err = msg
return false
proc main(rng: ref HmacDrbgContext): Future[int] {.async.} =
proc main(rng: Rng): Future[int] {.async.} =
let conf: WakuCanaryConf = WakuCanaryConf.load()
# create dns resolver
@ -190,7 +190,7 @@ proc main(rng: ref HmacDrbgContext): Future[int] {.async.} =
quit(QuitFailure)
let
nodeKey = crypto.PrivateKey.random(Secp256k1, rng[])[]
nodeKey = crypto.PrivateKey.random(Secp256k1, rng)[]
bindIp = parseIpAddress("0.0.0.0")
wsBindPort = Port(conf.nodePort + WebSocketPortOffset)
nodeTcpPort = Port(conf.nodePort)

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
## Reliable Channel type.
##
## A `ReliableChannel` orchestrates segmentation, SDS (end-to-end
@ -93,7 +94,7 @@ type
channelId: ChannelId
contentTopic: ContentTopic
senderId: SdsParticipantID
rng: ref HmacDrbgContext
rng: libp2p_crypto.Rng
segmentation: SegmentationHandler
sdsHandler: SdsHandler
rateLimit: RateLimitManager

View File

@ -7,8 +7,8 @@ import
confutils,
libp2p/crypto/crypto,
libp2p/crypto/curve25519,
libp2p/protocols/mix,
libp2p/protocols/mix/curve25519,
libp2p_mix,
libp2p_mix/curve25519,
libp2p/multiaddress,
eth/keys,
eth/p2p/discoveryv5/enr,

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
import std/json
import chronos, chronicles, results, strutils, libp2p/multiaddress, ffi
import

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
import std/[options, json, strutils, net]
import chronos, chronicles, results, confutils, confutils/std/net, ffi

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
import std/[sequtils, strutils, tables]
import chronicles, chronos, results, options, json, ffi
import waku/factory/waku, waku/node/waku_node, waku/node/peer_manager, ../declare_lib

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
import options, std/[strutils, sequtils]
import chronicles, chronos, results, ffi
import

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
import options, std/[json, strformat]
import chronicles, chronos, results, ffi
import

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
import std/[net, sequtils, strutils, json], strformat
import chronicles, chronos, stew/byteutils, results, ffi
import

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
import std/[json, sugar, strutils, options]
import chronos, chronicles, results, stew/byteutils, ffi
import

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
import std/[atomics, options, atomics, macros]
import chronicles, chronos, chronos/threadsync, ffi
import

View File

@ -50,8 +50,8 @@
}
},
"jwt": {
"version": "#18f8378de52b241f321c1f9ea905456e89b95c6f",
"vcsRevision": "18f8378de52b241f321c1f9ea905456e89b95c6f",
"version": "#057ec95eb5af0eea9c49bfe9025b3312c95dc5f2",
"vcsRevision": "057ec95eb5af0eea9c49bfe9025b3312c95dc5f2",
"url": "https://github.com/vacp2p/nim-jwt.git",
"downloadMethod": "git",
"dependencies": [
@ -60,7 +60,7 @@
"bearssl_pkey_decoder"
],
"checksums": {
"sha1": "bcfd6fc9c5e10a52b87117219b7ab5c98136bc8e"
"sha1": "3cd368666fd2bc7f99f253452289e827abcac13c"
}
},
"testutils": {
@ -434,8 +434,8 @@
}
},
"websock": {
"version": "0.3.0",
"vcsRevision": "c105d98e6522e0e2cbe3dfa11b07a273e9fd0e7b",
"version": "0.4.0",
"vcsRevision": "387a8eb7e961e8fdd3b1a717d36bc53b55e4dc5d",
"url": "https://github.com/status-im/nim-websock",
"downloadMethod": "git",
"dependencies": [
@ -450,7 +450,7 @@
"zlib"
],
"checksums": {
"sha1": "1294a66520fa4541e261dec8a6a84f774fb8c0ac"
"sha1": "fd17a854686d9a19af40aba51f05d06b82fc30ec"
}
},
"json_rpc": {
@ -476,8 +476,8 @@
}
},
"lsquic": {
"version": "0.0.1",
"vcsRevision": "4fb03ee7bfb39aecb3316889fdcb60bec3d0936f",
"version": "0.4.1",
"vcsRevision": "00e4b7dfaa197cd120267aa897b33b0914166b45",
"url": "https://github.com/vacp2p/nim-lsquic",
"downloadMethod": "git",
"dependencies": [
@ -487,10 +487,11 @@
"chronos",
"nimcrypto",
"unittest2",
"chronicles"
"chronicles",
"boringssl"
],
"checksums": {
"sha1": "f465fa994346490d0924d162f53d9b5aec62f948"
"sha1": "5e36783661eab239bd4d8566ff3195c8d14f1923"
}
},
"secp256k1": {
@ -582,8 +583,8 @@
}
},
"libp2p": {
"version": "#ff8d51857b4b79a68468e7bcc27b2026cca02996",
"vcsRevision": "ff8d51857b4b79a68468e7bcc27b2026cca02996",
"version": "#c43199378f46d0aaf61be1cad1ee1d63e8f665d6",
"vcsRevision": "c43199378f46d0aaf61be1cad1ee1d63e8f665d6",
"url": "https://github.com/vacp2p/nim-libp2p.git",
"downloadMethod": "git",
"dependencies": [
@ -591,20 +592,22 @@
"nimcrypto",
"dnsclient",
"bearssl",
"boringssl",
"chronicles",
"chronos",
"metrics",
"secp256k1",
"stew",
"websock",
"unittest2",
"results",
"serialization",
"lsquic",
"protobuf_serialization",
"websock",
"jwt"
],
"checksums": {
"sha1": "fa2a7552c6ec860717b77ce34cf0b7afe4570234"
"sha1": "327dc7a0cb7e9d0be3d6083841bd496c4cbc48dc"
}
},
"taskpools": {
@ -653,6 +656,67 @@
"checksums": {
"sha1": "6f9d49375ea1dc71add55c72ac80a808f238e5b0"
}
},
"boringssl": {
"version": "0.0.4",
"vcsRevision": "1c91a4a2579123597df43bbdea70cc575957bdea",
"url": "https://github.com/vacp2p/nim-boringssl",
"downloadMethod": "git",
"dependencies": [
"nim"
],
"checksums": {
"sha1": "3655faa30099538293cb7d60e726783dff9d979a"
}
},
"protobuf_serialization": {
"version": "0.4.0",
"vcsRevision": "38d24eb3bd93e605fb88199da71d36b1ec0ad60d",
"url": "https://github.com/status-im/nim-protobuf-serialization",
"downloadMethod": "git",
"dependencies": [
"nim",
"stew",
"faststreams",
"serialization",
"npeg",
"unittest2"
],
"checksums": {
"sha1": "5a7a80fb8cca29e41899ce9540b74e49c874f8fd"
}
},
"npeg": {
"version": "1.3.0",
"vcsRevision": "409f6796d0e880b3f0222c964d1da7de6e450811",
"url": "https://github.com/zevv/npeg",
"downloadMethod": "git",
"dependencies": [
"nim"
],
"checksums": {
"sha1": "64f15c85a059c889cb11c5fe72372677c50da621"
}
},
"libp2p_mix": {
"version": "0.1.0",
"vcsRevision": "7cb7556d9a228573fc5622af7ffb2dd11741e043",
"url": "https://github.com/logos-co/nim-libp2p-mix",
"downloadMethod": "git",
"dependencies": [
"nim",
"libp2p",
"chronicles",
"chronos",
"metrics",
"nimcrypto",
"stew",
"results",
"unittest2"
],
"checksums": {
"sha1": "8287dda862a4398966cd66a5b3d7d66834c9a9a6"
}
}
},
"tasks": {}

View File

@ -1,3 +1,4 @@
import libp2p/crypto/crypto
# Chronos Test Suite
# (c) Copyright 2022-Present
# Status Research & Development GmbH
@ -17,9 +18,9 @@ import ../../waku/common/rate_limit/timed_map
let proto = "ProtocolDescriptor"
let conn1 = Connection(peerId: PeerId.random().tryGet())
let conn2 = Connection(peerId: PeerId.random().tryGet())
let conn3 = Connection(peerId: PeerId.random().tryGet())
let conn1 = Connection(peerId: PeerId.random(newRng()).tryGet())
let conn2 = Connection(peerId: PeerId.random(newRng()).tryGet())
let conn3 = Connection(peerId: PeerId.random(newRng()).tryGet())
suite "RateLimitSetting":
test "Parse rate limit setting - ok":

View File

@ -1,3 +1,4 @@
import libp2p/crypto/crypto
# Chronos Test Suite
# (c) Copyright 2022-Present
# Status Research & Development GmbH
@ -17,9 +18,9 @@ import ../../waku/common/rate_limit/timed_map
let proto = "ProtocolDescriptor"
let conn1 = Connection(peerId: PeerId.random().tryGet())
let conn2 = Connection(peerId: PeerId.random().tryGet())
let conn3 = Connection(peerId: PeerId.random().tryGet())
let conn1 = Connection(peerId: PeerId.random(newRng()).tryGet())
let conn2 = Connection(peerId: PeerId.random(newRng()).tryGet())
let conn3 = Connection(peerId: PeerId.random(newRng()).tryGet())
suite "RequestRateLimiter":
test "RequestRateLimiter Allow up to main bucket":

View File

@ -1,3 +1,4 @@
import libp2p/crypto/crypto
{.used.}
import
@ -21,9 +22,9 @@ import
../testlib/[common, wakucore, wakunode, testasync, futures, testutils],
../waku_filter_v2/waku_filter_utils
proc generateRequestId(rng: ref HmacDrbgContext): string =
proc generateRequestId(rng: crypto.Rng): string =
var bytes: array[10, byte]
hmacDrbgGenerate(rng[], bytes)
rng.generate(bytes)
return toHex(bytes)
proc createRequest(
@ -31,7 +32,7 @@ proc createRequest(
pubsubTopic = none(PubsubTopic),
contentTopics = newSeq[ContentTopic](),
): FilterSubscribeRequest =
let requestId = generateRequestId(rng)
let requestId = generateRequestId(common.rng())
return FilterSubscribeRequest(
requestId: requestId,

View File

@ -35,10 +35,10 @@ from ../../waku/waku_noise/noise_utils import randomSeqByte
proc buildRandomIdentityCredentials(): IdentityCredential =
# We generate a random identity credential (inter-value constrains are not enforced, otherwise we need to load e.g. zerokit RLN keygen)
let
idTrapdoor = randomSeqByte(rng[], 32)
idNullifier = randomSeqByte(rng[], 32)
idSecretHash = randomSeqByte(rng[], 32)
idCommitment = randomSeqByte(rng[], 32)
idTrapdoor = randomSeqByte(rng, 32)
idNullifier = randomSeqByte(rng, 32)
idSecretHash = randomSeqByte(rng, 32)
idCommitment = randomSeqByte(rng, 32)
IdentityCredential(
idTrapdoor: idTrapdoor,

View File

@ -1,3 +1,4 @@
import libp2p/crypto/rng
import chronos, bearssl/rand, eth/[keys, p2p]
import libp2p/crypto/crypto
@ -9,10 +10,10 @@ proc localAddress*(port: int): Address =
result = Address(udpPort: port, tcpPort: port, ip: parseIpAddress("127.0.0.1"))
proc setupTestNode*(
rng: ref HmacDrbgContext, capabilities: varargs[ProtocolInfo, `protocolInfo`]
rng: crypto.Rng, capabilities: varargs[ProtocolInfo, `protocolInfo`]
): EthereumNode =
let
keys1 = keys.KeyPair.random(rng[])
keys1 = keys.KeyPair.random(keys.newRng()[])
address = localAddress(nextPort)
result = newEthereumNode(
keys1,
@ -29,11 +30,11 @@ proc setupTestNode*(
# Copied from here: https://github.com/status-im/nim-libp2p/blob/d522537b19a532bc4af94fcd146f779c1f23bad0/tests/helpers.nim#L28
type RngWrap = object
rng: ref rand.HmacDrbgContext
rng: crypto.Rng
var rngVar: RngWrap
proc getRng(): ref rand.HmacDrbgContext =
proc getRng(): crypto.Rng =
# TODO if `rngVar` is a threadvar like it should be, there are random and
# spurious compile failures on mac - this is not gcsafe but for the
# purpose of the tests, it's ok as long as we only use a single thread
@ -42,5 +43,5 @@ proc getRng(): ref rand.HmacDrbgContext =
rngVar.rng = crypto.newRng()
rngVar.rng
template rng*(): ref rand.HmacDrbgContext =
template rng*(): crypto.Rng =
getRng()

View File

@ -1,7 +1,7 @@
{.used.}
import
std/[sequtils, times, sugar, net],
std/[sequtils, times, sugar, net, options],
testutils/unittests,
chronos,
json_rpc/rpcserver,
@ -955,7 +955,7 @@ procSuite "Peer Manager":
# Create peer manager
let pm = PeerManager.new(
switch = SwitchBuilder.new().withRng(rng).withMplex().withNoise().build(),
switch = SwitchBuilder.new().withRng(crypto.newRng()).withMplex().withNoise().build(),
storage = nil,
)
@ -1013,7 +1013,7 @@ procSuite "Peer Manager":
let pm = PeerManager.new(
switch = SwitchBuilder
.new()
.withRng(rng)
.withRng(crypto.newRng())
.withMplex()
.withNoise()
.withPeerStore(peerStoreSize)
@ -1027,7 +1027,7 @@ procSuite "Peer Manager":
let pm = PeerManager.new(
switch = SwitchBuilder
.new()
.withRng(rng)
.withRng(crypto.newRng())
.withMplex()
.withNoise()
.withPeerStore(25)
@ -1040,7 +1040,7 @@ procSuite "Peer Manager":
# Create 30 peers and add them to the peerstore
let peers = toSeq(1 .. 30)
.mapIt(parsePeerInfo("/ip4/0.0.0.0/tcp/0/p2p/" & $PeerId.random().get()))
.mapIt(parsePeerInfo("/ip4/0.0.0.0/tcp/0/p2p/" & $PeerId.random(crypto.newRng()).get()))
.filterIt(it.isOk())
.mapIt(it.value)
for p in peers:
@ -1091,7 +1091,7 @@ procSuite "Peer Manager":
let pm = PeerManager.new(
switch = SwitchBuilder
.new()
.withRng(rng)
.withRng(crypto.newRng())
.withMplex()
.withNoise()
.withPeerStore(25)
@ -1148,7 +1148,7 @@ procSuite "Peer Manager":
let pm = PeerManager.new(
switch = SwitchBuilder
.new()
.withRng(rng)
.withRng(crypto.newRng())
.withMplex()
.withNoise()
.withPeerStore(25)
@ -1164,7 +1164,7 @@ procSuite "Peer Manager":
let pm = PeerManager.new(
switch = SwitchBuilder
.new()
.withRng(rng)
.withRng(crypto.newRng())
.withMplex()
.withNoise()
.withPeerStore(25)
@ -1178,7 +1178,7 @@ procSuite "Peer Manager":
let pm = PeerManager.new(
switch = SwitchBuilder
.new()
.withRng(rng)
.withRng(crypto.newRng())
.withMplex()
.withNoise()
.withPeerStore(25)

View File

@ -1,3 +1,4 @@
import libp2p/crypto/rng
{.used.}
import
@ -52,7 +53,7 @@ suite "Waku DNS Discovery":
)
.get() # No link entries
let treeKeys = keys.KeyPair.random(rng[])
let treeKeys = keys.KeyPair.random(keys.newRng()[])
# Sign tree
check:

View File

@ -38,7 +38,7 @@ suite "Waku Keepalive":
(await node2.mountRelay()).isOkOr:
assert false, "Failed to mount relay"
let pingProto = Ping.new(handler = pingHandler)
let pingProto = Ping.new(handler = pingHandler, rng = crypto.newRng())
await pingProto.start()
node2.switch.mount(pingProto)

View File

@ -46,10 +46,10 @@ procSuite "Credentials test suite":
# We generate a random identity credential (inter-value constrains are not enforced, otherwise we need to load e.g. zerokit RLN keygen)
var
idTrapdoor = randomSeqByte(rng[], 32)
idNullifier = randomSeqByte(rng[], 32)
idSecretHash = randomSeqByte(rng[], 32)
idCommitment = randomSeqByte(rng[], 32)
idTrapdoor = randomSeqByte(rng, 32)
idNullifier = randomSeqByte(rng, 32)
idSecretHash = randomSeqByte(rng, 32)
idCommitment = randomSeqByte(rng, 32)
var idCredential = IdentityCredential(
idTrapdoor: idTrapdoor,
@ -85,10 +85,10 @@ procSuite "Credentials test suite":
# We generate two random identity credentials (inter-value constrains are not enforced, otherwise we need to load e.g. zerokit RLN keygen)
var
idTrapdoor = randomSeqByte(rng[], 32)
idNullifier = randomSeqByte(rng[], 32)
idSecretHash = randomSeqByte(rng[], 32)
idCommitment = randomSeqByte(rng[], 32)
idTrapdoor = randomSeqByte(rng, 32)
idNullifier = randomSeqByte(rng, 32)
idSecretHash = randomSeqByte(rng, 32)
idCommitment = randomSeqByte(rng, 32)
idCredential = IdentityCredential(
idTrapdoor: idTrapdoor,
idNullifier: idNullifier,
@ -141,10 +141,10 @@ procSuite "Credentials test suite":
# We generate random identity credentials (inter-value constrains are not enforced, otherwise we need to load e.g. zerokit RLN keygen)
let
idTrapdoor = randomSeqByte(rng[], 32)
idNullifier = randomSeqByte(rng[], 32)
idSecretHash = randomSeqByte(rng[], 32)
idCommitment = randomSeqByte(rng[], 32)
idTrapdoor = randomSeqByte(rng, 32)
idNullifier = randomSeqByte(rng, 32)
idSecretHash = randomSeqByte(rng, 32)
idCommitment = randomSeqByte(rng, 32)
idCredential = IdentityCredential(
idTrapdoor: idTrapdoor,
idNullifier: idNullifier,
@ -193,10 +193,10 @@ procSuite "Credentials test suite":
# We generate random identity credentials (inter-value constrains are not enforced, otherwise we need to load e.g. zerokit RLN keygen)
let
idTrapdoor = randomSeqByte(rng[], 32)
idNullifier = randomSeqByte(rng[], 32)
idSecretHash = randomSeqByte(rng[], 32)
idCommitment = randomSeqByte(rng[], 32)
idTrapdoor = randomSeqByte(rng, 32)
idNullifier = randomSeqByte(rng, 32)
idSecretHash = randomSeqByte(rng, 32)
idCommitment = randomSeqByte(rng, 32)
idCredential = IdentityCredential(
idTrapdoor: idTrapdoor,
idNullifier: idNullifier,
@ -254,10 +254,10 @@ procSuite "Credentials test suite":
# We generate random identity credentials (inter-value constrains are not enforced, otherwise we need to load e.g. zerokit RLN keygen)
let
idTrapdoor = randomSeqByte(rng[], 32)
idNullifier = randomSeqByte(rng[], 32)
idSecretHash = randomSeqByte(rng[], 32)
idCommitment = randomSeqByte(rng[], 32)
idTrapdoor = randomSeqByte(rng, 32)
idNullifier = randomSeqByte(rng, 32)
idSecretHash = randomSeqByte(rng, 32)
idCommitment = randomSeqByte(rng, 32)
idCredential = IdentityCredential(
idTrapdoor: idTrapdoor,
idNullifier: idNullifier,

View File

@ -16,7 +16,7 @@ suite "KeyFile test suite":
removeFile(filepath)
# The secret
var secret = randomSeqByte(rng[], 300)
var secret = randomSeqByte(rng, 300)
# We create a keyfile encrypting the secret with password
let keyfile = createKeyFileJson(secret, password)
@ -42,9 +42,9 @@ suite "KeyFile test suite":
test "Create/Save/Load multiple keyfiles in same file":
# We set different passwords for different keyfiles that will be stored in same file
let password1 = string.fromBytes(randomSeqByte(rng[], 20))
let password1 = string.fromBytes(randomSeqByte(rng, 20))
let password2 = ""
let password3 = string.fromBytes(randomSeqByte(rng[], 20))
let password3 = string.fromBytes(randomSeqByte(rng, 20))
var keyfile: KfResult[JsonNode]
let filepath = "./test.keyfile"
@ -53,40 +53,40 @@ suite "KeyFile test suite":
# We generate 6 different secrets and we encrypt them using 3 different passwords, and we store the obtained keystore
let secret1 = randomSeqByte(rng[], 300)
let secret1 = randomSeqByte(rng, 300)
keyfile = createKeyFileJson(secret1, password1)
check:
keyfile.isOk()
saveKeyFile(filepath, keyfile.get()).isOk()
let secret2 = randomSeqByte(rng[], 300)
let secret2 = randomSeqByte(rng, 300)
keyfile = createKeyFileJson(secret2, password2)
check:
keyfile.isOk()
saveKeyFile(filepath, keyfile.get()).isOk()
let secret3 = randomSeqByte(rng[], 300)
let secret3 = randomSeqByte(rng, 300)
keyfile = createKeyFileJson(secret3, password3)
check:
keyfile.isOk()
saveKeyFile(filepath, keyfile.get()).isOk()
# We encrypt secret4 with password3
let secret4 = randomSeqByte(rng[], 300)
let secret4 = randomSeqByte(rng, 300)
keyfile = createKeyFileJson(secret4, password3)
check:
keyfile.isOk()
saveKeyFile(filepath, keyfile.get()).isOk()
# We encrypt secret5 with password1
let secret5 = randomSeqByte(rng[], 300)
let secret5 = randomSeqByte(rng, 300)
keyfile = createKeyFileJson(secret5, password1)
check:
keyfile.isOk()
saveKeyFile(filepath, keyfile.get()).isOk()
# We encrypt secret6 with password1
let secret6 = randomSeqByte(rng[], 300)
let secret6 = randomSeqByte(rng, 300)
keyfile = createKeyFileJson(secret6, password1)
check:
keyfile.isOk()
@ -343,7 +343,7 @@ suite "KeyFile test suite (adapted from nim-eth keyfile tests)":
test "Scrypt keyfiles":
let
expectedSecret = randomSeqByte(rng[], 300)
expectedSecret = randomSeqByte(rng, 300)
password = "miawmiawcat"
# By default, keyfiles' encryption key is derived from password using PBKDF2.

View File

@ -1,3 +1,4 @@
import std/options
{.used.}
import chronos, confutils/toml/std/net, libp2p/multiaddress, testutils/unittests

View File

@ -27,7 +27,7 @@ procSuite "Waku Noise":
let maxMessageLength = 3 * NoisePaddingBlockSize
for messageLen in 0 .. maxMessageLength:
let
message = randomSeqByte(rng[], messageLen)
message = randomSeqByte(rng, messageLen)
padded = pkcs7_pad(message, NoisePaddingBlockSize)
unpadded = pkcs7_unpad(padded, NoisePaddingBlockSize)
@ -37,11 +37,11 @@ procSuite "Waku Noise":
message == unpadded
test "ChaChaPoly Encryption/Decryption: random byte sequences":
let cipherState = randomChaChaPolyCipherState(rng[])
let cipherState = randomChaChaPolyCipherState(rng)
# We encrypt/decrypt random byte sequences
let
plaintext: seq[byte] = randomSeqByte(rng[], rand(1 .. 128))
plaintext: seq[byte] = randomSeqByte(rng, rand(1 .. 128))
ciphertext: ChaChaPolyCiphertext = encrypt(cipherState, plaintext)
decryptedCiphertext: seq[byte] = decrypt(cipherState, ciphertext)
@ -49,7 +49,7 @@ procSuite "Waku Noise":
plaintext == decryptedCiphertext
test "ChaChaPoly Encryption/Decryption: random strings":
let cipherState = randomChaChaPolyCipherState(rng[])
let cipherState = randomChaChaPolyCipherState(rng)
# We encrypt/decrypt random strings
var plaintext: string
@ -64,10 +64,10 @@ procSuite "Waku Noise":
plaintext.toBytes() == decryptedCiphertext
test "Noise public keys: encrypt and decrypt a public key":
let noisePublicKey: NoisePublicKey = genNoisePublicKey(rng[])
let noisePublicKey: NoisePublicKey = genNoisePublicKey(rng)
let
cs: ChaChaPolyCipherState = randomChaChaPolyCipherState(rng[])
cs: ChaChaPolyCipherState = randomChaChaPolyCipherState(rng)
encryptedPk: NoisePublicKey = encryptNoisePublicKey(cs, noisePublicKey)
decryptedPk: NoisePublicKey = decryptNoisePublicKey(cs, encryptedPk)
@ -75,20 +75,20 @@ procSuite "Waku Noise":
noisePublicKey == decryptedPk
test "Noise public keys: decrypt an unencrypted public key":
let noisePublicKey: NoisePublicKey = genNoisePublicKey(rng[])
let noisePublicKey: NoisePublicKey = genNoisePublicKey(rng)
let
cs: ChaChaPolyCipherState = randomChaChaPolyCipherState(rng[])
cs: ChaChaPolyCipherState = randomChaChaPolyCipherState(rng)
decryptedPk: NoisePublicKey = decryptNoisePublicKey(cs, noisePublicKey)
check:
noisePublicKey == decryptedPk
test "Noise public keys: encrypt an encrypted public key":
let noisePublicKey: NoisePublicKey = genNoisePublicKey(rng[])
let noisePublicKey: NoisePublicKey = genNoisePublicKey(rng)
let
cs: ChaChaPolyCipherState = randomChaChaPolyCipherState(rng[])
cs: ChaChaPolyCipherState = randomChaChaPolyCipherState(rng)
encryptedPk: NoisePublicKey = encryptNoisePublicKey(cs, noisePublicKey)
encryptedPk2: NoisePublicKey = encryptNoisePublicKey(cs, encryptedPk)
@ -96,10 +96,10 @@ procSuite "Waku Noise":
encryptedPk == encryptedPk2
test "Noise public keys: encrypt, decrypt and decrypt a public key":
let noisePublicKey: NoisePublicKey = genNoisePublicKey(rng[])
let noisePublicKey: NoisePublicKey = genNoisePublicKey(rng)
let
cs: ChaChaPolyCipherState = randomChaChaPolyCipherState(rng[])
cs: ChaChaPolyCipherState = randomChaChaPolyCipherState(rng)
encryptedPk: NoisePublicKey = encryptNoisePublicKey(cs, noisePublicKey)
decryptedPk: NoisePublicKey = decryptNoisePublicKey(cs, encryptedPk)
decryptedPk2: NoisePublicKey = decryptNoisePublicKey(cs, decryptedPk)
@ -109,7 +109,7 @@ procSuite "Waku Noise":
test "Noise public keys: serialize and deserialize an unencrypted public key":
let
noisePublicKey: NoisePublicKey = genNoisePublicKey(rng[])
noisePublicKey: NoisePublicKey = genNoisePublicKey(rng)
serializedNoisePublicKey: seq[byte] = serializeNoisePublicKey(noisePublicKey)
deserializedNoisePublicKey: NoisePublicKey =
intoNoisePublicKey(serializedNoisePublicKey)
@ -118,10 +118,10 @@ procSuite "Waku Noise":
noisePublicKey == deserializedNoisePublicKey
test "Noise public keys: encrypt, serialize, deserialize and decrypt a public key":
let noisePublicKey: NoisePublicKey = genNoisePublicKey(rng[])
let noisePublicKey: NoisePublicKey = genNoisePublicKey(rng)
let
cs: ChaChaPolyCipherState = randomChaChaPolyCipherState(rng[])
cs: ChaChaPolyCipherState = randomChaChaPolyCipherState(rng)
encryptedPk: NoisePublicKey = encryptNoisePublicKey(cs, noisePublicKey)
serializedNoisePublicKey: seq[byte] = serializeNoisePublicKey(encryptedPk)
deserializedNoisePublicKey: NoisePublicKey =
@ -134,7 +134,7 @@ procSuite "Waku Noise":
test "PayloadV2: serialize/deserialize PayloadV2 to byte sequence":
let
payload2: PayloadV2 = randomPayloadV2(rng[])
payload2: PayloadV2 = randomPayloadV2(rng)
serializedPayload = serializePayloadV2(payload2)
check:
@ -149,7 +149,7 @@ procSuite "Waku Noise":
test "PayloadV2: Encode/Decode a Waku Message (version 2) to a PayloadV2":
# We encode to a WakuMessage a random PayloadV2
let
payload2 = randomPayloadV2(rng[])
payload2 = randomPayloadV2(rng)
msg = encodePayloadV2(payload2)
check:
@ -173,8 +173,8 @@ procSuite "Waku Noise":
test "Noise State Machine: Diffie-Hellman operation":
#We generate random keypairs
let
aliceKey = genKeyPair(rng[])
bobKey = genKeyPair(rng[])
aliceKey = genKeyPair(rng)
bobKey = genKeyPair(rng)
# A Diffie-Hellman operation between Alice's private key and Bob's public key must be equal to
# a Diffie-hellman operation between Alice's public key and Bob's private key
@ -188,10 +188,10 @@ procSuite "Waku Noise":
test "Noise State Machine: Cipher State primitives":
# We generate a random Cipher State, associated data ad and plaintext
var
cipherState: CipherState = randomCipherState(rng[])
cipherState: CipherState = randomCipherState(rng)
nonce: uint64 = uint64(rand(0 .. int.high))
ad: seq[byte] = randomSeqByte(rng[], rand(1 .. 128))
plaintext: seq[byte] = randomSeqByte(rng[], rand(1 .. 128))
ad: seq[byte] = randomSeqByte(rng, rand(1 .. 128))
plaintext: seq[byte] = randomSeqByte(rng, rand(1 .. 128))
# We set the random nonce generated in the cipher state
setNonce(cipherState, nonce)
@ -218,7 +218,7 @@ procSuite "Waku Noise":
setCipherStateKey(cipherState, EmptyKey)
nonce = getNonce(cipherState)
plaintext = randomSeqByte(rng[], rand(1 .. 128))
plaintext = randomSeqByte(rng, rand(1 .. 128))
ciphertext = encryptWithAd(cipherState, ad, plaintext)
check:
@ -230,7 +230,7 @@ procSuite "Waku Noise":
nonce = getNonce(cipherState)
# Note that we set ciphertext minimum length to 16 to not trigger checks on authentication tag length
ciphertext = randomSeqByte(rng[], rand(16 .. 128))
ciphertext = randomSeqByte(rng, rand(16 .. 128))
plaintext = decryptWithAd(cipherState, ad, ciphertext)
check:
@ -241,9 +241,9 @@ procSuite "Waku Noise":
# Note that NonceMax is uint64.high - 1 = 2^64-1-1 and that nonce is increased after each encryption and decryption operation
# We generate a test Cipher State with nonce set to MaxNonce
cipherState = randomCipherState(rng[])
cipherState = randomCipherState(rng)
setNonce(cipherState, NonceMax)
plaintext = randomSeqByte(rng[], rand(1 .. 128))
plaintext = randomSeqByte(rng, rand(1 .. 128))
# We test if encryption fails with a NoiseNonceMaxError error. Any subsequent encryption call over the Cipher State should fail similarly and leave the nonce unchanged
for _ in [1 .. 5]:
@ -257,9 +257,9 @@ procSuite "Waku Noise":
# Since nonce is increased after decryption as well, we need to generate a proper ciphertext in order to test MaxNonceError error handling
# We cannot call encryptWithAd to encrypt a plaintext using a nonce equal MaxNonce, since this will trigger a MaxNonceError.
# To perform such test, we then need to encrypt a test plaintext using directly ChaChaPoly primitive
cipherState = randomCipherState(rng[])
cipherState = randomCipherState(rng)
setNonce(cipherState, NonceMax)
plaintext = randomSeqByte(rng[], rand(1 .. 128))
plaintext = randomSeqByte(rng, rand(1 .. 128))
# We perform encryption using the Cipher State key, NonceMax and ad
# By Noise specification the nonce is 8 bytes long out of the 12 bytes supported by ChaChaPoly, thus we copy the Little endian conversion of the nonce to a ChaChaPolyNonce
@ -308,7 +308,7 @@ procSuite "Waku Noise":
########################################
# We generate a random byte sequence and execute a mixHash over it
mixHash(symmetricState, randomSeqByte(rng[], rand(1 .. 128)))
mixHash(symmetricState, randomSeqByte(rng, rand(1 .. 128)))
# mixHash changes only the handshake hash value of the Symmetric state
check:
@ -324,7 +324,7 @@ procSuite "Waku Noise":
########################################
# We generate random input key material and we execute mixKey
var inputKeyMaterial = randomSeqByte(rng[], rand(1 .. 128))
var inputKeyMaterial = randomSeqByte(rng, rand(1 .. 128))
mixKey(symmetricState, inputKeyMaterial)
# mixKey changes the Symmetric State's chaining key and encryption key of the embedded Cipher State
@ -345,7 +345,7 @@ procSuite "Waku Noise":
########################################
# We generate random input key material and we execute mixKeyAndHash
inputKeyMaterial = randomSeqByte(rng[], rand(1 .. 128))
inputKeyMaterial = randomSeqByte(rng, rand(1 .. 128))
mixKeyAndHash(symmetricState, inputKeyMaterial)
# mixKeyAndHash executes a mixKey and a mixHash using the input key material
@ -368,7 +368,7 @@ procSuite "Waku Noise":
var initialSymmetricState = symmetricState
# We generate random plaintext and we execute encryptAndHash
var plaintext = randomChaChaPolyKey(rng[])
var plaintext = randomChaChaPolyKey(rng)
var nonce = getNonce(getCipherState(symmetricState))
var ciphertext = encryptAndHash(symmetricState, plaintext)
@ -421,11 +421,11 @@ procSuite "Waku Noise":
let hsPattern = NoiseHandshakePatterns["XX"]
# We initialize Alice's and Bob's Handshake State
let aliceStaticKey = genKeyPair(rng[])
let aliceStaticKey = genKeyPair(rng)
var aliceHS =
initialize(hsPattern = hsPattern, staticKey = aliceStaticKey, initiator = true)
let bobStaticKey = genKeyPair(rng[])
let bobStaticKey = genKeyPair(rng)
var bobHS = initialize(hsPattern = hsPattern, staticKey = bobStaticKey)
var
@ -440,15 +440,15 @@ procSuite "Waku Noise":
###############
# We generate a random transport message
sentTransportMessage = randomSeqByte(rng[], 32)
sentTransportMessage = randomSeqByte(rng, 32)
# By being the handshake initiator, Alice writes a Waku2 payload v2 containing her handshake message
# and the (encrypted) transport message
aliceStep =
stepHandshake(rng[], aliceHS, transportMessage = sentTransportMessage).get()
stepHandshake(rng, aliceHS, transportMessage = sentTransportMessage).get()
# Bob reads Alice's payloads, and returns the (decrypted) transport message Alice sent to him
bobStep = stepHandshake(rng[], bobHS, readPayloadV2 = aliceStep.payload2).get()
bobStep = stepHandshake(rng, bobHS, readPayloadV2 = aliceStep.payload2).get()
check:
bobStep.transportMessage == sentTransportMessage
@ -458,13 +458,13 @@ procSuite "Waku Noise":
###############
# We generate a random transport message
sentTransportMessage = randomSeqByte(rng[], 32)
sentTransportMessage = randomSeqByte(rng, 32)
# At this step, Bob writes and returns a payload
bobStep = stepHandshake(rng[], bobHS, transportMessage = sentTransportMessage).get()
bobStep = stepHandshake(rng, bobHS, transportMessage = sentTransportMessage).get()
# While Alice reads and returns the (decrypted) transport message
aliceStep = stepHandshake(rng[], aliceHS, readPayloadV2 = bobStep.payload2).get()
aliceStep = stepHandshake(rng, aliceHS, readPayloadV2 = bobStep.payload2).get()
check:
aliceStep.transportMessage == sentTransportMessage
@ -474,14 +474,14 @@ procSuite "Waku Noise":
###############
# We generate a random transport message
sentTransportMessage = randomSeqByte(rng[], 32)
sentTransportMessage = randomSeqByte(rng, 32)
# Similarly as in first step, Alice writes a Waku2 payload containing the handshake message and the (encrypted) transport message
aliceStep =
stepHandshake(rng[], aliceHS, transportMessage = sentTransportMessage).get()
stepHandshake(rng, aliceHS, transportMessage = sentTransportMessage).get()
# Bob reads Alice's payloads, and returns the (decrypted) transport message Alice sent to him
bobStep = stepHandshake(rng[], bobHS, readPayloadV2 = aliceStep.payload2).get()
bobStep = stepHandshake(rng, bobHS, readPayloadV2 = aliceStep.payload2).get()
check:
bobStep.transportMessage == sentTransportMessage
@ -494,13 +494,13 @@ procSuite "Waku Noise":
let prevBobHS = bobHS
let bobStep1 =
stepHandshake(rng[], bobHS, transportMessage = sentTransportMessage).get()
stepHandshake(rng, bobHS, transportMessage = sentTransportMessage).get()
let aliceStep1 =
stepHandshake(rng[], aliceHS, readPayloadV2 = bobStep1.payload2).get()
stepHandshake(rng, aliceHS, readPayloadV2 = bobStep1.payload2).get()
let aliceStep2 =
stepHandshake(rng[], aliceHS, transportMessage = sentTransportMessage).get()
stepHandshake(rng, aliceHS, transportMessage = sentTransportMessage).get()
let bobStep2 =
stepHandshake(rng[], bobHS, readPayloadV2 = aliceStep2.payload2).get()
stepHandshake(rng, bobHS, readPayloadV2 = aliceStep2.payload2).get()
check:
aliceStep1 == default(HandshakeStepResult)
@ -529,7 +529,7 @@ procSuite "Waku Noise":
for _ in 0 .. 10:
# Alice writes to Bob
message = randomSeqByte(rng[], 32)
message = randomSeqByte(rng, 32)
payload2 = writeMessage(aliceHSResult, message, defaultMessageNametagBuffer)
readMessage =
readMessage(bobHSResult, payload2, defaultMessageNametagBuffer).get()
@ -538,7 +538,7 @@ procSuite "Waku Noise":
message == readMessage
# Bob writes to Alice
message = randomSeqByte(rng[], 32)
message = randomSeqByte(rng, 32)
payload2 = writeMessage(bobHSResult, message, defaultMessageNametagBuffer)
readMessage =
readMessage(aliceHSResult, payload2, defaultMessageNametagBuffer).get()
@ -550,15 +550,15 @@ procSuite "Waku Noise":
let hsPattern = NoiseHandshakePatterns["XXpsk0"]
# We generate a random psk
let psk = randomSeqByte(rng[], 32)
let psk = randomSeqByte(rng, 32)
# We initialize Alice's and Bob's Handshake State
let aliceStaticKey = genKeyPair(rng[])
let aliceStaticKey = genKeyPair(rng)
var aliceHS = initialize(
hsPattern = hsPattern, staticKey = aliceStaticKey, psk = psk, initiator = true
)
let bobStaticKey = genKeyPair(rng[])
let bobStaticKey = genKeyPair(rng)
var bobHS = initialize(hsPattern = hsPattern, staticKey = bobStaticKey, psk = psk)
var
@ -573,15 +573,15 @@ procSuite "Waku Noise":
###############
# We generate a random transport message
sentTransportMessage = randomSeqByte(rng[], 32)
sentTransportMessage = randomSeqByte(rng, 32)
# By being the handshake initiator, Alice writes a Waku2 payload v2 containing her handshake message
# and the (encrypted) transport message
aliceStep =
stepHandshake(rng[], aliceHS, transportMessage = sentTransportMessage).get()
stepHandshake(rng, aliceHS, transportMessage = sentTransportMessage).get()
# Bob reads Alice's payloads, and returns the (decrypted) transport message Alice sent to him
bobStep = stepHandshake(rng[], bobHS, readPayloadV2 = aliceStep.payload2).get()
bobStep = stepHandshake(rng, bobHS, readPayloadV2 = aliceStep.payload2).get()
check:
bobStep.transportMessage == sentTransportMessage
@ -591,13 +591,13 @@ procSuite "Waku Noise":
###############
# We generate a random transport message
sentTransportMessage = randomSeqByte(rng[], 32)
sentTransportMessage = randomSeqByte(rng, 32)
# At this step, Bob writes and returns a payload
bobStep = stepHandshake(rng[], bobHS, transportMessage = sentTransportMessage).get()
bobStep = stepHandshake(rng, bobHS, transportMessage = sentTransportMessage).get()
# While Alice reads and returns the (decrypted) transport message
aliceStep = stepHandshake(rng[], aliceHS, readPayloadV2 = bobStep.payload2).get()
aliceStep = stepHandshake(rng, aliceHS, readPayloadV2 = bobStep.payload2).get()
check:
aliceStep.transportMessage == sentTransportMessage
@ -607,14 +607,14 @@ procSuite "Waku Noise":
###############
# We generate a random transport message
sentTransportMessage = randomSeqByte(rng[], 32)
sentTransportMessage = randomSeqByte(rng, 32)
# Similarly as in first step, Alice writes a Waku2 payload containing the handshake message and the (encrypted) transport message
aliceStep =
stepHandshake(rng[], aliceHS, transportMessage = sentTransportMessage).get()
stepHandshake(rng, aliceHS, transportMessage = sentTransportMessage).get()
# Bob reads Alice's payloads, and returns the (decrypted) transportMessage alice sent to him
bobStep = stepHandshake(rng[], bobHS, readPayloadV2 = aliceStep.payload2).get()
bobStep = stepHandshake(rng, bobHS, readPayloadV2 = aliceStep.payload2).get()
check:
bobStep.transportMessage == sentTransportMessage
@ -640,7 +640,7 @@ procSuite "Waku Noise":
for _ in 0 .. 10:
# Alice writes to Bob
message = randomSeqByte(rng[], 32)
message = randomSeqByte(rng, 32)
payload2 = writeMessage(aliceHSResult, message, defaultMessageNametagBuffer)
readMessage =
readMessage(bobHSResult, payload2, defaultMessageNametagBuffer).get()
@ -649,7 +649,7 @@ procSuite "Waku Noise":
message == readMessage
# Bob writes to Alice
message = randomSeqByte(rng[], 32)
message = randomSeqByte(rng, 32)
payload2 = writeMessage(bobHSResult, message, defaultMessageNametagBuffer)
readMessage =
readMessage(aliceHSResult, payload2, defaultMessageNametagBuffer).get()
@ -661,8 +661,8 @@ procSuite "Waku Noise":
let hsPattern = NoiseHandshakePatterns["K1K1"]
# We initialize Alice's and Bob's Handshake State
let aliceStaticKey = genKeyPair(rng[])
let bobStaticKey = genKeyPair(rng[])
let aliceStaticKey = genKeyPair(rng)
let bobStaticKey = genKeyPair(rng)
# This handshake has the following pre-message pattern:
# -> s
@ -696,15 +696,15 @@ procSuite "Waku Noise":
###############
# We generate a random transport message
sentTransportMessage = randomSeqByte(rng[], 32)
sentTransportMessage = randomSeqByte(rng, 32)
# By being the handshake initiator, Alice writes a Waku2 payload v2 containing her handshake message
# and the (encrypted) transport message
aliceStep =
stepHandshake(rng[], aliceHS, transportMessage = sentTransportMessage).get()
stepHandshake(rng, aliceHS, transportMessage = sentTransportMessage).get()
# Bob reads Alice's payloads, and returns the (decrypted) transport message Alice sent to him
bobStep = stepHandshake(rng[], bobHS, readPayloadV2 = aliceStep.payload2).get()
bobStep = stepHandshake(rng, bobHS, readPayloadV2 = aliceStep.payload2).get()
check:
bobStep.transportMessage == sentTransportMessage
@ -714,13 +714,13 @@ procSuite "Waku Noise":
###############
# We generate a random transport message
sentTransportMessage = randomSeqByte(rng[], 32)
sentTransportMessage = randomSeqByte(rng, 32)
# At this step, Bob writes and returns a payload
bobStep = stepHandshake(rng[], bobHS, transportMessage = sentTransportMessage).get()
bobStep = stepHandshake(rng, bobHS, transportMessage = sentTransportMessage).get()
# While Alice reads and returns the (decrypted) transport message
aliceStep = stepHandshake(rng[], aliceHS, readPayloadV2 = bobStep.payload2).get()
aliceStep = stepHandshake(rng, aliceHS, readPayloadV2 = bobStep.payload2).get()
check:
aliceStep.transportMessage == sentTransportMessage
@ -730,14 +730,14 @@ procSuite "Waku Noise":
###############
# We generate a random transport message
sentTransportMessage = randomSeqByte(rng[], 32)
sentTransportMessage = randomSeqByte(rng, 32)
# Similarly as in first step, Alice writes a Waku2 payload containing the handshake_message and the (encrypted) transportMessage
aliceStep =
stepHandshake(rng[], aliceHS, transportMessage = sentTransportMessage).get()
stepHandshake(rng, aliceHS, transportMessage = sentTransportMessage).get()
# Bob reads Alice's payloads, and returns the (decrypted) transportMessage alice sent to him
bobStep = stepHandshake(rng[], bobHS, readPayloadV2 = aliceStep.payload2).get()
bobStep = stepHandshake(rng, bobHS, readPayloadV2 = aliceStep.payload2).get()
check:
bobStep.transportMessage == sentTransportMessage
@ -763,7 +763,7 @@ procSuite "Waku Noise":
for _ in 0 .. 10:
# Alice writes to Bob
message = randomSeqByte(rng[], 32)
message = randomSeqByte(rng, 32)
payload2 = writeMessage(aliceHSResult, message, defaultMessageNametagBuffer)
readMessage =
readMessage(bobHSResult, payload2, defaultMessageNametagBuffer).get()
@ -772,7 +772,7 @@ procSuite "Waku Noise":
message == readMessage
# Bob writes to Alice
message = randomSeqByte(rng[], 32)
message = randomSeqByte(rng, 32)
payload2 = writeMessage(bobHSResult, message, defaultMessageNametagBuffer)
readMessage =
readMessage(aliceHSResult, payload2, defaultMessageNametagBuffer).get()
@ -784,8 +784,8 @@ procSuite "Waku Noise":
let hsPattern = NoiseHandshakePatterns["XK1"]
# We initialize Alice's and Bob's Handshake State
let aliceStaticKey = genKeyPair(rng[])
let bobStaticKey = genKeyPair(rng[])
let aliceStaticKey = genKeyPair(rng)
let bobStaticKey = genKeyPair(rng)
# This handshake has the following pre-message pattern:
# <- s
@ -816,15 +816,15 @@ procSuite "Waku Noise":
###############
# We generate a random transport message
sentTransportMessage = randomSeqByte(rng[], 32)
sentTransportMessage = randomSeqByte(rng, 32)
# By being the handshake initiator, Alice writes a Waku2 payload v2 containing her handshake message
# and the (encrypted) transport message
aliceStep =
stepHandshake(rng[], aliceHS, transportMessage = sentTransportMessage).get()
stepHandshake(rng, aliceHS, transportMessage = sentTransportMessage).get()
# Bob reads Alice's payloads, and returns the (decrypted) transport message Alice sent to him
bobStep = stepHandshake(rng[], bobHS, readPayloadV2 = aliceStep.payload2).get()
bobStep = stepHandshake(rng, bobHS, readPayloadV2 = aliceStep.payload2).get()
check:
bobStep.transportMessage == sentTransportMessage
@ -834,13 +834,13 @@ procSuite "Waku Noise":
###############
# We generate a random transport message
sentTransportMessage = randomSeqByte(rng[], 32)
sentTransportMessage = randomSeqByte(rng, 32)
# At this step, Bob writes and returns a payload
bobStep = stepHandshake(rng[], bobHS, transportMessage = sentTransportMessage).get()
bobStep = stepHandshake(rng, bobHS, transportMessage = sentTransportMessage).get()
# While Alice reads and returns the (decrypted) transport message
aliceStep = stepHandshake(rng[], aliceHS, readPayloadV2 = bobStep.payload2).get()
aliceStep = stepHandshake(rng, aliceHS, readPayloadV2 = bobStep.payload2).get()
check:
aliceStep.transportMessage == sentTransportMessage
@ -850,14 +850,14 @@ procSuite "Waku Noise":
###############
# We generate a random transport message
sentTransportMessage = randomSeqByte(rng[], 32)
sentTransportMessage = randomSeqByte(rng, 32)
# Similarly as in first step, Alice writes a Waku2 payload containing the handshake message and the (encrypted) transport message
aliceStep =
stepHandshake(rng[], aliceHS, transportMessage = sentTransportMessage).get()
stepHandshake(rng, aliceHS, transportMessage = sentTransportMessage).get()
# Bob reads Alice's payloads, and returns the (decrypted) transport message Alice sent to him
bobStep = stepHandshake(rng[], bobHS, readPayloadV2 = aliceStep.payload2).get()
bobStep = stepHandshake(rng, bobHS, readPayloadV2 = aliceStep.payload2).get()
check:
bobStep.transportMessage == sentTransportMessage
@ -883,7 +883,7 @@ procSuite "Waku Noise":
for _ in 0 .. 10:
# Alice writes to Bob
message = randomSeqByte(rng[], 32)
message = randomSeqByte(rng, 32)
payload2 = writeMessage(aliceHSResult, message, defaultMessageNametagBuffer)
readMessage =
readMessage(bobHSResult, payload2, defaultMessageNametagBuffer).get()
@ -892,7 +892,7 @@ procSuite "Waku Noise":
message == readMessage
# Bob writes to Alice
message = randomSeqByte(rng[], 32)
message = randomSeqByte(rng, 32)
payload2 = writeMessage(bobHSResult, message, defaultMessageNametagBuffer)
readMessage =
readMessage(aliceHSResult, payload2, defaultMessageNametagBuffer).get()

View File

@ -25,22 +25,22 @@ procSuite "Waku Noise Sessions":
let hsPattern = NoiseHandshakePatterns["WakuPairing"]
# Alice static/ephemeral key initialization and commitment
let aliceStaticKey = genKeyPair(rng[])
let aliceEphemeralKey = genKeyPair(rng[])
let s = randomSeqByte(rng[], 32)
let aliceStaticKey = genKeyPair(rng)
let aliceEphemeralKey = genKeyPair(rng)
let s = randomSeqByte(rng, 32)
let aliceCommittedStaticKey = commitPublicKey(getPublicKey(aliceStaticKey), s)
# Bob static/ephemeral key initialization and commitment
let bobStaticKey = genKeyPair(rng[])
let bobEphemeralKey = genKeyPair(rng[])
let r = randomSeqByte(rng[], 32)
let bobStaticKey = genKeyPair(rng)
let bobEphemeralKey = genKeyPair(rng)
let r = randomSeqByte(rng, 32)
let bobCommittedStaticKey = commitPublicKey(getPublicKey(bobStaticKey), r)
# Content Topic information
let applicationName = "waku-noise-sessions"
let applicationVersion = "0.1"
let shardId = "10"
let qrMessageNametag = randomSeqByte(rng[], MessageNametagLength)
let qrMessageNametag = randomSeqByte(rng, MessageNametagLength)
# Out-of-band Communication
@ -133,7 +133,7 @@ procSuite "Waku Noise Sessions":
# and the (encrypted) transport message
# The message is sent with a messageNametag equal to the one received through the QR code
aliceStep = stepHandshake(
rng[],
rng,
aliceHS,
transportMessage = sentTransportMessage,
messageNametag = qrMessageNametag,
@ -168,7 +168,7 @@ procSuite "Waku Noise Sessions":
# Bob reads Alice's payloads, and returns the (decrypted) transport message Alice sent to him
# Note that Bob verifies if the received payloadv2 has the expected messageNametag set
bobStep = stepHandshake(
rng[], bobHS, readPayloadV2 = readPayloadV2, messageNametag = qrMessageNametag
rng, bobHS, readPayloadV2 = readPayloadV2, messageNametag = qrMessageNametag
)
.get()
@ -199,7 +199,7 @@ procSuite "Waku Noise Sessions":
# At this step, Bob writes and returns a payload
bobStep = stepHandshake(
rng[],
rng,
bobHS,
transportMessage = sentTransportMessage,
messageNametag = bobMessageNametag,
@ -233,7 +233,7 @@ procSuite "Waku Noise Sessions":
# While Alice reads and returns the (decrypted) transport message
aliceStep = stepHandshake(
rng[],
rng,
aliceHS,
readPayloadV2 = readPayloadV2,
messageNametag = aliceMessageNametag,
@ -265,7 +265,7 @@ procSuite "Waku Noise Sessions":
# Similarly as in first step, Alice writes a Waku2 payload containing the handshake message and the (encrypted) transport message
aliceStep = stepHandshake(
rng[],
rng,
aliceHS,
transportMessage = sentTransportMessage,
messageNametag = aliceMessageNametag,
@ -299,7 +299,7 @@ procSuite "Waku Noise Sessions":
# Bob reads Alice's payloads, and returns the (decrypted) transport message Alice sent to him
bobStep = stepHandshake(
rng[], bobHS, readPayloadV2 = readPayloadV2, messageNametag = bobMessageNametag
rng, bobHS, readPayloadV2 = readPayloadV2, messageNametag = bobMessageNametag
)
.get()
@ -333,7 +333,7 @@ procSuite "Waku Noise Sessions":
# Note that we exchange more than the number of messages contained in the nametag buffer to test if they are filled correctly as the communication proceeds
for i in 0 .. 10 * MessageNametagBufferSize:
# Alice writes to Bob
message = randomSeqByte(rng[], 32)
message = randomSeqByte(rng, 32)
payload2 = writeMessage(
aliceHSResult,
message,
@ -350,7 +350,7 @@ procSuite "Waku Noise Sessions":
message == readMessage
# Bob writes to Alice
message = randomSeqByte(rng[], 32)
message = randomSeqByte(rng, 32)
payload2 = writeMessage(
bobHSResult,
message,
@ -368,13 +368,13 @@ procSuite "Waku Noise Sessions":
# We test how nametag buffers help in detecting lost messages
# Alice writes two messages to Bob, but only the second is received
message = randomSeqByte(rng[], 32)
message = randomSeqByte(rng, 32)
payload2 = writeMessage(
aliceHSResult,
message,
outboundMessageNametagBuffer = aliceHSResult.nametagsOutbound,
)
message = randomSeqByte(rng[], 32)
message = randomSeqByte(rng, 32)
payload2 = writeMessage(
aliceHSResult,
message,
@ -390,7 +390,7 @@ procSuite "Waku Noise Sessions":
# We adjust bob nametag buffer for next test (i.e. the missed message is correctly recovered)
delete(bobHSResult.nametagsInbound, 2)
message = randomSeqByte(rng[], 32)
message = randomSeqByte(rng, 32)
payload2 = writeMessage(
bobHSResult, message, outboundMessageNametagBuffer = bobHSResult.nametagsOutbound
)
@ -405,7 +405,7 @@ procSuite "Waku Noise Sessions":
message == readMessage
# We test if a missing nametag is correctly detected
message = randomSeqByte(rng[], 32)
message = randomSeqByte(rng, 32)
payload2 = writeMessage(
aliceHSResult,
message,

View File

@ -1,7 +1,7 @@
{.used.}
import
std/[sequtils, strutils, net],
std/[sequtils, strutils, net, options],
stew/byteutils,
testutils/unittests,
chronicles,

View File

@ -12,13 +12,13 @@ proc randomize*() =
# Copied from here: https://github.com/status-im/nim-libp2p/blob/d522537b19a532bc4af94fcd146f779c1f23bad0/tests/helpers.nim#L28
type Rng = object
rng: ref HmacDrbgContext
rng: crypto.Rng
# Typically having a module variable is considered bad design. This case should
# be considered as an exception and it should be used only in the tests.
var rngVar: Rng
proc getRng(): ref HmacDrbgContext =
proc getRng(): crypto.Rng =
# TODO: if `rngVar` is a threadvar like it should be, there are random and
# spurious compile failures on mac - this is not gcsafe but for the
# purpose of the tests, it's ok as long as we only use a single thread
@ -28,5 +28,5 @@ proc getRng(): ref HmacDrbgContext =
rngVar.rng
template rng*(): ref HmacDrbgContext =
template rng*(): crypto.Rng =
getRng()

View File

@ -22,17 +22,32 @@ proc ts*(offset = 0, origin = now()): Timestamp =
# Switch
proc generateEcdsaKey*(): libp2p_keys.PrivateKey =
libp2p_keys.PrivateKey.random(ECDSA, rng[]).get()
libp2p_keys.PrivateKey.random(ECDSA, common.rng()).get()
proc generateEcdsaKeyPair*(): libp2p_keys.KeyPair =
libp2p_keys.KeyPair.random(ECDSA, rng[]).get()
libp2p_keys.KeyPair.random(ECDSA, common.rng()).get()
proc generateSecp256k1Key*(): libp2p_keys.PrivateKey =
libp2p_keys.PrivateKey.random(Secp256k1, rng[]).get()
libp2p_keys.PrivateKey.random(Secp256k1, common.rng()).get()
proc ethSecp256k1Key*(hex: string): eth_keys.PrivateKey =
eth_keys.PrivateKey.fromHex(hex).get()
proc newStandardSwitch*(
privKey = Opt.none(libp2p_keys.PrivateKey),
addrs: MultiAddress = MultiAddress.init("/ip4/127.0.0.1/tcp/0").get(),
): Switch =
var b = SwitchBuilder
.new()
.withRng(common.rng())
.withAddress(addrs)
.withTcpTransport()
.withMplex()
.withNoise()
if privKey.isSome():
b = b.withPrivateKey(privKey.get())
b.build()
proc newTestSwitch*(
key = none(libp2p_keys.PrivateKey), address = none(MultiAddress)
): Switch =

View File

@ -11,6 +11,7 @@ import
waku/[
waku_node,
waku_core/topics,
node/waku_switch,
node/peer_manager,
waku_enr,
discovery/waku_discv5,
@ -55,7 +56,7 @@ proc newTestWakuNode*(
extPort = none(Port),
extMultiAddrs = newSeq[MultiAddress](),
peerStorage: PeerStorage = nil,
maxConnections = builders.MaxConnections,
maxConnections = MaxConnections,
wsBindPort: Port = (Port) 8000,
wsEnabled: bool = false,
wssEnabled: bool = false,

View File

@ -1,3 +1,4 @@
import libp2p/crypto/rng
{.used.}
import
@ -38,8 +39,8 @@ suite "Waku Discovery v5":
let
rng = eth_keys.newRng()
pk1 = eth_keys.PrivateKey.random(rng[])
pk2 = eth_keys.PrivateKey.random(rng[])
pk1 = eth_keys.PrivateKey.random(eth_keys.newRng()[])
pk2 = eth_keys.PrivateKey.random(eth_keys.newRng()[])
suite "shardingPredicate":
var
@ -423,7 +424,7 @@ suite "Waku Discovery v5":
let myRng = libp2p_keys.newRng()
var confBuilder = defaultTestWakuConfBuilder()
confBuilder.withNodeKey(libp2p_keys.PrivateKey.random(Secp256k1, myRng[])[])
confBuilder.withNodeKey(libp2p_keys.PrivateKey.random(Secp256k1, myRng)[])
confBuilder.discv5Conf.withEnabled(true)
confBuilder.discv5Conf.withUdpPort(9000.Port)
let conf = confBuilder.build().valueOr:
@ -434,7 +435,7 @@ suite "Waku Discovery v5":
(waitFor startWaku(addr waku0)).isOkOr:
raiseAssert error
confBuilder.withNodeKey(crypto.PrivateKey.random(Secp256k1, myRng[])[])
confBuilder.withNodeKey(crypto.PrivateKey.random(Secp256k1, myRng)[])
confBuilder.discv5Conf.withBootstrapNodes(@[waku0.node.enr.toURI()])
confBuilder.discv5Conf.withEnabled(true)
confBuilder.discv5Conf.withUdpPort(9001.Port)
@ -454,7 +455,7 @@ suite "Waku Discovery v5":
confBuilder.discv5Conf.withBootstrapNodes(@[waku1.node.enr.toURI()])
confBuilder.withP2pTcpPort(60003.Port)
confBuilder.discv5Conf.withUdpPort(9003.Port)
confBuilder.withNodeKey(crypto.PrivateKey.random(Secp256k1, myRng[])[])
confBuilder.withNodeKey(crypto.PrivateKey.random(Secp256k1, myRng)[])
let conf2 = confBuilder.build().valueOr:
raiseAssert error

View File

@ -36,7 +36,7 @@ proc newTestWakuFilter*(
proc newTestWakuFilterClient*(switch: Switch): Future[WakuFilterClient] {.async.} =
let
peerManager = PeerManager.new(switch)
proto = WakuFilterClient.new(peerManager, rng)
proto = WakuFilterClient.new(peerManager, common.rng())
await proto.start()
switch.mount(proto)

View File

@ -20,7 +20,7 @@ proc newTestWakuLightpushNode*(
peerManager = PeerManager.new(switch)
wakuAutoSharding = Sharding(clusterId: 1, shardCountGenZero: 8)
proto = WakuLightPush.new(
peerManager, rng, handler, some(wakuAutoSharding), rateLimitSetting
peerManager, crypto.newRng(), handler, some(wakuAutoSharding), rateLimitSetting
)
await proto.start()
@ -30,4 +30,4 @@ proc newTestWakuLightpushNode*(
proc newTestWakuLightpushClient*(switch: Switch): WakuLightPushClient =
let peerManager = PeerManager.new(switch)
WakuLightPushClient.new(peerManager, rng)
WakuLightPushClient.new(peerManager, crypto.newRng())

View File

@ -19,7 +19,7 @@ proc newTestWakuLegacyLightpushNode*(
): Future[WakuLegacyLightPush] {.async.} =
let
peerManager = PeerManager.new(switch)
proto = WakuLegacyLightPush.new(peerManager, rng, handler, rateLimitSetting)
proto = WakuLegacyLightPush.new(peerManager, crypto.newRng(), handler, rateLimitSetting)
await proto.start()
switch.mount(proto)
@ -28,4 +28,4 @@ proc newTestWakuLegacyLightpushNode*(
proc newTestWakuLegacyLightpushClient*(switch: Switch): WakuLegacyLightPushClient =
let peerManager = PeerManager.new(switch)
WakuLegacyLightPushClient.new(peerManager, rng)
WakuLegacyLightPushClient.new(peerManager, crypto.newRng())

View File

@ -1,7 +1,7 @@
{.used.}
import
std/[os, strutils, sequtils, sysrand, math],
std/[os, strutils, sequtils, sysrand, math, options],
stew/byteutils,
testutils/unittests,
chronos,

View File

@ -1,7 +1,7 @@
{.used.}
import
std/[strutils, sequtils, tempfiles],
std/[strutils, sequtils, tempfiles, options],
stew/byteutils,
chronos,
chronicles,

View File

@ -1,3 +1,4 @@
import std/options
import std/tempfiles
import

View File

@ -1,7 +1,7 @@
{.used.}
import
std/[sequtils, tempfiles],
std/[sequtils, tempfiles, options],
stew/byteutils,
chronos,
chronicles,

View File

@ -1,3 +1,4 @@
import libp2p/crypto/rng
{.used.}
{.push raises: [].}
@ -446,7 +447,7 @@ proc createEthAccount*(
let gasPrice = Quantity(await web3.provider.eth_gasPrice())
web3.defaultAccount = accounts[0]
let pk = keys.PrivateKey.random(rng[])
let pk = keys.PrivateKey.random(keys.newRng()[])
let acc = Address(toCanonicalAddress(pk.toPublicKey()))
var tx: TransactionArgs
@ -464,7 +465,7 @@ proc createEthAccount*(
return (pk, acc)
proc createEthAccount*(web3: Web3): (keys.PrivateKey, Address) =
let pk = keys.PrivateKey.random(rng[])
let pk = keys.PrivateKey.random(keys.newRng()[])
let acc = Address(toCanonicalAddress(pk.toPublicKey()))
return (pk, acc)

View File

@ -10,7 +10,7 @@ proc newTestWakuStore*(
): Future[WakuStore] {.async.} =
let
peerManager = PeerManager.new(switch)
proto = WakuStore.new(peerManager, rng, handler)
proto = WakuStore.new(peerManager, common.rng(), handler)
await proto.start()
switch.mount(proto)
@ -19,4 +19,4 @@ proc newTestWakuStore*(
proc newTestWakuStoreClient*(switch: Switch): WakuStoreClient {.gcsafe.} =
let peerManager = PeerManager.new(switch)
WakuStoreClient.new(peerManager, rng)
WakuStoreClient.new(peerManager, common.rng())

View File

@ -1,7 +1,7 @@
{.used.}
import
std/sequtils,
std/[sequtils, options],
testutils/unittests,
chronicles,
chronos,

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
{.used.}
import

View File

@ -1,7 +1,7 @@
{.used.}
import
std/[sequtils, sysrand, math],
std/[sequtils, sysrand, math, options],
testutils/unittests,
chronos,
libp2p/crypto/crypto,

View File

@ -1,3 +1,4 @@
import std/options
{.used.}
import
@ -22,7 +23,7 @@ type TestResponseTuple = tuple[status: int, data: string, headers: HttpTable]
proc testWakuNode(): WakuNode =
let
privkey = crypto.PrivateKey.random(Secp256k1, rng[]).tryGet()
privkey = crypto.PrivateKey.random(Secp256k1, rng).tryGet()
bindIp = parseIpAddress("0.0.0.0")
extIp = parseIpAddress("127.0.0.1")
port = Port(0)

View File

@ -25,7 +25,7 @@ import
proc testWakuNode(): WakuNode =
let
privkey = crypto.PrivateKey.random(Secp256k1, rng[]).tryGet()
privkey = crypto.PrivateKey.random(Secp256k1, rng).tryGet()
bindIp = parseIpAddress("0.0.0.0")
extIp = parseIpAddress("127.0.0.1")
port = Port(0)

View File

@ -1,3 +1,4 @@
import std/options
{.used.}
import results, stew/byteutils, testutils/unittests, json_serialization

View File

@ -1,3 +1,4 @@
import std/options
{.used.}
import

View File

@ -1,7 +1,7 @@
{.used.}
import
std/[tempfiles, osproc],
std/[tempfiles, osproc, options],
testutils/unittests,
presto,
presto/client as presto_client,
@ -29,7 +29,7 @@ import
proc testWakuNode(): WakuNode =
let
privkey = crypto.PrivateKey.random(Secp256k1, rng[]).tryGet()
privkey = crypto.PrivateKey.random(Secp256k1, rng).tryGet()
bindIp = parseIpAddress("0.0.0.0")
extIp = parseIpAddress("127.0.0.1")
port = Port(0)

View File

@ -1,3 +1,4 @@
import std/options
{.used.}
import

View File

@ -1,3 +1,4 @@
import std/options
{.used.}
import

View File

@ -1,7 +1,7 @@
{.used.}
import
std/[sequtils, strformat, tempfiles, osproc],
std/[sequtils, strformat, tempfiles, osproc, options],
stew/byteutils,
testutils/unittests,
presto,

View File

@ -1,3 +1,4 @@
import std/options
{.used.}
import results, stew/byteutils, unittest2, json_serialization

View File

@ -27,7 +27,7 @@ requires "nim >= 2.2.4",
"toml_serialization",
"faststreams",
# Networking & P2P
"https://github.com/vacp2p/nim-libp2p.git#ff8d51857b4b79a68468e7bcc27b2026cca02996",
"https://github.com/vacp2p/nim-libp2p.git#c43199378f46d0aaf61be1cad1ee1d63e8f665d6",
"eth",
"nat_traversal",
"dnsdisc",
@ -75,6 +75,7 @@ requires "https://github.com/NagyZoltanPeter/nim-brokers.git#v2.0.1"
requires "https://github.com/vacp2p/nim-lsquic"
requires "https://github.com/vacp2p/nim-jwt.git#057ec95eb5af0eea9c49bfe9025b3312c95dc5f2"
requires "https://github.com/logos-co/nim-libp2p-mix#7cb7556d9a228573fc5622af7ffb2dd11741e043"
proc getMyCPU(): string =
## Need to set cpu more explicit manner to avoid arch issues between dependencies

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
import chronicles, chronos, results
import waku/factory/waku

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
import std/[net, options]
import results

View File

@ -1,3 +1,5 @@
import waku/compat/option_valueor
import libp2p/crypto/crypto
{.push raises: [].}
import bearssl/rand, std/times, chronos
@ -23,7 +25,7 @@ type
PartiallyConnected
Connected
proc new*(T: typedesc[RequestId], rng: ref HmacDrbgContext): T =
proc new*(T: typedesc[RequestId], rng: crypto.Rng): T =
## Generate a new RequestId using the provided RNG.
RequestId(request_utils.generateRequestId(rng))

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
import
std/[times, strutils, os, sets, strformat, tables],
results,

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
# Simple async pool driver for postgress.
# Inspired by: https://github.com/treeform/pg/
{.push raises: [].}

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
{.push raises: [].}
# The code in this file is an adaptation of the Sqlite KV Store found in nim-eth.
# https://github.com/status-im/nim-eth/blob/master/eth/db/kvstore_sqlite3.nim

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
{.push raises: [].}
import std/options, results, eth/keys as eth_keys, libp2p/crypto/crypto as libp2p_crypto

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
## RequestRateLimiter
##
## RequestRateLimiter is a general service protection mechanism.

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
import std/[strutils, math], results, regex
proc parseMsgSize*(input: string): Result[uint64, string] =

View File

@ -0,0 +1,35 @@
## Polyfill: `valueOr` / `withValue` templates for `std/options.Option[T]`.
##
## Previously provided transitively by `libp2p/utility`, removed in
## nim-libp2p PR #2162 (commit 8a9943145). logos-delivery uses these
## templates pervasively on `Option[T]`. The shim restores them here while
## we adapt to upstream churn; collocated under `waku/compat/` so the
## category is explicit (compatibility with upstream API drift), not a
## generic dumping ground.
{.push raises: [].}
import std/[macros, options]
template valueOr*[T](self: Option[T], body: untyped): untyped =
let temp = (self)
if temp.isSome:
temp.get()
else:
body
template withValue*[T](self: Option[T], value, body: untyped): untyped =
let temp = (self)
if temp.isSome:
let `value` {.inject.} = temp.get()
body
macro withValue*[T](self: Option[T], value, body, elseStmt: untyped): untyped =
let elseBody = elseStmt[0]
quote:
let temp = (`self`)
if temp.isSome:
let `value` {.inject.} = temp.get()
`body`
else:
`elseBody`

View File

@ -1,3 +1,4 @@
import libp2p/crypto/crypto
import
chronos,
chronicles,
@ -7,7 +8,7 @@ import
const AutonatCheckInterval = Opt.some(chronos.seconds(30))
proc getAutonatService*(rng: ref HmacDrbgContext): AutonatService =
proc getAutonatService*(rng: crypto.Rng): AutonatService =
## AutonatService request other peers to dial us back
## flagging us as Reachable or NotReachable.
## minConfidence is used as threshold to determine the state.

View File

@ -1,3 +1,6 @@
import libp2p/crypto/crypto
import libp2p/crypto/rng
import waku/compat/option_valueor
{.push raises: [].}
import
@ -80,7 +83,7 @@ proc shardingPredicate*(
proc new*(
T: type WakuDiscoveryV5,
rng: ref HmacDrbgContext,
rng: crypto.Rng,
conf: WakuDiscoveryV5Config,
record: Option[waku_enr.Record],
peerManager: Option[PeerManager] = none(PeerManager),
@ -88,7 +91,7 @@ proc new*(
newAsyncEventQueue[SubscriptionEvent](30),
): T =
let protocol = newProtocol(
rng = rng,
rng = rng.bearSslDrbgRef,
config = conf.discv5Config.get(protocol.defaultDiscoveryConfig),
bindPort = conf.port,
bindIp = conf.address,
@ -405,7 +408,7 @@ proc setupDiscoveryV5*(
nodeTopicSubscriptionQueue: AsyncEventQueue[SubscriptionEvent],
conf: Discv5Conf,
dynamicBootstrapNodes: seq[RemotePeerInfo],
rng: ref HmacDrbgContext,
rng: crypto.Rng,
key: crypto.PrivateKey,
p2pListenAddress: IpAddress,
portsShift: uint16,
@ -461,7 +464,7 @@ proc setupAndStartDiscv5*(
nodeTopicSubscriptionQueue: AsyncEventQueue[SubscriptionEvent],
conf: Discv5Conf,
dynamicBootstrapNodes: seq[RemotePeerInfo],
rng: ref HmacDrbgContext,
rng: crypto.Rng,
key: crypto.PrivateKey,
p2pListenAddress: IpAddress,
portsShift: uint16,

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
{.push raises: [].}
## A set of utilities to integrate EIP-1459 DNS-based discovery

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
{.push raises: [].}
import std/[options, sequtils]
@ -9,9 +10,9 @@ import
libp2p/[peerid, multiaddress, switch],
libp2p/extended_peer_record,
libp2p/crypto/curve25519,
libp2p/protocols/[kademlia, kad_disco],
libp2p/protocols/kademlia_discovery/types as kad_types,
libp2p/protocols/mix/mix_protocol
libp2p/protocols/[kademlia, service_discovery],
libp2p/protocols/service_discovery/types as svdisc_types,
libp2p_mix/mix_protocol
import waku/waku_core, waku/node/peer_manager
@ -32,7 +33,7 @@ type
advertiseMix*: bool = false
WakuKademlia* = ref object
protocol*: KademliaDiscovery
protocol*: ServiceDiscovery
peerManager: PeerManager
discoveryLoop: Future[void]
running*: bool
@ -50,13 +51,14 @@ proc new*(
if params.bootstrapNodes.len == 0:
info "creating kademlia discovery as seed node (no bootstrap nodes)"
let kademlia = KademliaDiscovery.new(
let kademlia = ServiceDiscovery.new(
switch,
bootstrapNodes = params.bootstrapNodes,
config = KadDHTConfig.new(
validator = kad_types.ExtEntryValidator(), selector = kad_types.ExtEntrySelector()
validator = svdisc_types.ExtEntryValidator(), selector = svdisc_types.ExtEntrySelector()
),
codec = ExtendedKademliaDiscoveryCodec,
rng = switch.rng,
codec = ExtendedServiceDiscoveryCodec,
)
try:
@ -68,11 +70,9 @@ proc new*(
# initial self-signed peer record published to the DHT
if params.advertiseMix:
if params.mixPubKey.isSome():
let alreadyAdvertising = kademlia.startAdvertising(
kademlia.startAdvertising(
ServiceInfo(id: MixProtocolID, data: @(params.mixPubKey.get()))
)
if alreadyAdvertising:
warn "mix service was already being advertised"
debug "extended kademlia advertising mix service",
keyHex = byteutils.toHex(params.mixPubKey.get()),
bootstrapNodes = params.bootstrapNodes.len
@ -164,7 +164,9 @@ proc lookupMixPeers*(
let mixService = ServiceInfo(id: MixProtocolID, data: @[])
var records: seq[ExtendedPeerRecord]
try:
records = await wk.protocol.lookup(mixService)
let advertisements = (await wk.protocol.lookup(mixService)).valueOr:
return err("mix peer lookup failed: " & $error)
records = advertisements.mapIt(it.data)
except CatchableError:
return err("mix peer lookup failed: " & getCurrentExceptionMsg())
@ -202,7 +204,7 @@ proc runDiscoveryLoop(
var records: seq[ExtendedPeerRecord]
try:
records = await wk.protocol.randomRecords()
records = await wk.protocol.lookupRandom()
except CatchableError as e:
warn "extended kademlia discovery failed", error = e.msg
await sleepAsync(interval)

View File

@ -15,13 +15,14 @@ import
../waku_enr,
../discovery/waku_discv5,
../waku_node,
../node/waku_switch,
../node/peer_manager,
../common/rate_limit/setting,
../common/utils/parse_size_units
type
WakuNodeBuilder* = object # General
nodeRng: Option[ref crypto.HmacDrbgContext]
nodeRng: Option[crypto.Rng]
nodeKey: Option[crypto.PrivateKey]
netConfig: Option[NetConfig]
record: Option[enr.Record]
@ -57,7 +58,7 @@ proc init*(T: type WakuNodeBuilder): WakuNodeBuilder =
## General
proc withRng*(builder: var WakuNodeBuilder, rng: ref crypto.HmacDrbgContext) =
proc withRng*(builder: var WakuNodeBuilder, rng: crypto.Rng) =
builder.nodeRng = some(rng)
proc withNodeKey*(builder: var WakuNodeBuilder, nodeKey: crypto.PrivateKey) =
@ -157,7 +158,7 @@ proc withSwitchConfiguration*(
## Build
proc build*(builder: WakuNodeBuilder): Result[WakuNode, string] =
var rng: ref crypto.HmacDrbgContext
var rng: crypto.Rng
if builder.nodeRng.isNone():
rng = crypto.newRng()
else:
@ -190,7 +191,7 @@ proc build*(builder: WakuNodeBuilder): Result[WakuNode, string] =
wsAddress = builder.netConfig.get().wsHostAddress,
transportFlags = {ServerFlags.ReuseAddr, ServerFlags.TcpNoDelay},
rng = rng,
maxConnections = builder.switchMaxConnections.get(builders.MaxConnections),
maxConnections = builder.switchMaxConnections.get(MaxConnections),
wssEnabled = builder.netConfig.get().wssEnabled,
secureKeyPath = builder.switchSslSecureKey.get(""),
secureCertPath = builder.switchSslSecureCert.get(""),
@ -210,7 +211,7 @@ proc build*(builder: WakuNodeBuilder): Result[WakuNode, string] =
maxServicePeers = some(builder.maxServicePeers),
colocationLimit = builder.colocationLimit,
shardedPeerManagement = builder.shardAware,
maxConnections = builder.switchMaxConnections.get(builders.MaxConnections),
maxConnections = builder.switchMaxConnections.get(MaxConnections),
)
var node: WakuNode

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
import chronicles, std/options, results
import libp2p/[peerid, multiaddress, peerinfo]
import waku/factory/waku_conf

View File

@ -1,5 +1,6 @@
import waku/compat/option_valueor
import chronicles, std/options, results
import libp2p/crypto/crypto, libp2p/crypto/curve25519, libp2p/protocols/mix/curve25519
import libp2p/crypto/crypto, libp2p/crypto/curve25519, libp2p_mix/curve25519
import ../waku_conf, waku/waku_mix
logScope:

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
import chronicles, std/[net, options], results
import waku/common/rate_limit/setting

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
import std/[options, strutils, sequtils]
import chronicles, results, chronos
import ../waku_conf, ./store_sync_conf_builder

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
import
libp2p/crypto/crypto,
libp2p/multiaddress,
@ -293,13 +294,13 @@ proc withStaticNodes*(builder: var WakuConfBuilder, staticNodes: seq[string]) =
## Building
proc nodeKey(
builder: WakuConfBuilder, rng: ref HmacDrbgContext
builder: WakuConfBuilder, rng: crypto.Rng
): Result[crypto.PrivateKey, string] =
if builder.nodeKey.isSome():
return ok(builder.nodeKey.get())
else:
warn "missing node key, generating new set"
let nodeKey = crypto.PrivateKey.random(Secp256k1, rng[]).valueOr:
let nodeKey = crypto.PrivateKey.random(Secp256k1, rng).valueOr:
error "Failed to generate key", error = error
return err("Failed to generate key: " & $error)
return ok(nodeKey)
@ -443,7 +444,7 @@ proc applyNetworkConf(builder: var WakuConfBuilder) =
warn "Failed to process entry nodes from network conf", error = processed.error()
proc build*(
builder: var WakuConfBuilder, rng: ref HmacDrbgContext = crypto.newRng()
builder: var WakuConfBuilder, rng: crypto.Rng = crypto.newRng()
): Result[WakuConf, string] =
## Return a WakuConf that contains all mandatory parameters
## Applies some sane defaults that are applicable across any usage

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
import
chronicles,
chronos,

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
import
std/[options, sequtils],
chronicles,
@ -54,7 +55,7 @@ proc setupPeerStorage(): Result[Option[WakuPeerStorage], string] =
proc initNode(
conf: WakuConf,
netConfig: NetConfig,
rng: ref HmacDrbgContext,
rng: crypto.Rng,
record: enr.Record,
peerStore: Option[WakuPeerStorage],
relay: Relay,
@ -458,7 +459,7 @@ proc startNode*(
return ok()
proc setupNode*(
wakuConf: WakuConf, rng: ref HmacDrbgContext = crypto.newRng(), relay: Relay
wakuConf: WakuConf, rng: crypto.Rng = crypto.newRng(), relay: Relay
): Future[Result[WakuNode, string]] {.async.} =
let netConfig = (
await networkConfiguration(

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
{.push raises: [].}
import
@ -60,7 +61,7 @@ const git_version* {.strdefine.} = "n/a"
type Waku* = ref object
stateInfo*: WakuStateInfo
conf*: WakuConf
rng*: ref HmacDrbgContext
rng*: crypto.Rng
key: crypto.PrivateKey
@ -82,7 +83,7 @@ type Waku* = ref object
brokerCtx*: BrokerContext
proc setupSwitchServices(
waku: Waku, conf: WakuConf, circuitRelay: Relay, rng: ref HmacDrbgContext
waku: Waku, conf: WakuConf, circuitRelay: Relay, rng: crypto.Rng
) =
proc onReservation(addresses: seq[MultiAddress]) {.gcsafe, raises: [].} =
info "circuit relay handler new reserve event",

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
import std/[options, sets], chronos, web3, stew/byteutils, stint, results, chronicles
import waku/incentivization/rpc, tests/waku_rln_relay/utils_onchain

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
## This module is in charge of taking care of the messages that this node is expecting to
## receive and is backed by store-v3 requests to get an additional degree of certainty
##

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
import std/[options, times], chronos
import brokers/broker_context
import waku/waku_core, waku/api/types, waku/requests/node_requests

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
import chronicles, chronos, results
import std/options
import brokers/broker_context

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
import std/options
import chronos, chronicles
import brokers/broker_context

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
## This module reinforces the publish operation with regular store-v3 requests.
##

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
import std/[sequtils, sets, tables, options, strutils], chronos, chronicles, results
import libp2p/[peerid, peerinfo]
import brokers/broker_context

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
{.push raises: [].}
import

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
{.push raises: [].}
import

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
{.push raises: [].}
import
@ -17,7 +18,7 @@ import
libp2p/transports/tcptransport,
libp2p/transports/wstransport,
libp2p/utility,
libp2p/protocols/mix
libp2p_mix
import
../waku_node,

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
{.push raises: [].}
import

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
{.push raises: [].}
import

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
{.push raises: [].}
import

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
{.push raises: [].}
import

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
{.push raises: [].}
import
@ -25,6 +26,7 @@ import
common/callbacks,
common/utils/parse_size_units,
node/health_monitor/online_monitor,
node/waku_switch,
],
./peer_store/peer_storage,
./waku_peer_store

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
{.push raises: [].}
import

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
{.push raises: [].}
import
@ -7,7 +8,8 @@ import
eth/p2p/discoveryv5/enr,
libp2p/builders,
libp2p/peerstore,
libp2p/crypto/curve25519
libp2p/crypto/curve25519,
libp2p_mix/pool
import
../../waku_core,

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
{.push raises: [].}
import chronicles, chronos, metrics, metrics/chronos_httpserver

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
{.push raises: [].}
import
@ -23,8 +24,8 @@ import
libp2p/transports/wstransport,
libp2p/utility,
libp2p/utils/offsettedseq,
libp2p/protocols/mix,
libp2p/protocols/mix/mix_protocol,
libp2p_mix,
libp2p_mix/mix_protocol,
brokers/broker_context,
brokers/request_broker
@ -126,7 +127,7 @@ type
wakuAutoSharding*: Option[Sharding]
enr*: enr.Record
libp2pPing*: Ping
rng*: ref rand.HmacDrbgContext
rng*: crypto.Rng
brokerCtx*: BrokerContext
wakuRendezvous*: WakuRendezVous
wakuRendezvousClient*: rendezvous_client.WakuRendezVousClient
@ -207,7 +208,7 @@ proc new*(
peerManager: PeerManager,
rateLimitSettings: ProtocolRateLimitSettings = DefaultProtocolRateLimit,
# TODO: make this argument required after tests are updated
rng: ref HmacDrbgContext = crypto.newRng(),
rng: crypto.Rng = crypto.newRng(),
): T {.raises: [Defect, LPError, IOError, TLSStreamProtocolError].} =
## Creates a Waku Node instance.

View File

@ -18,10 +18,12 @@ import
# override nim-libp2p default value (which is also 1)
const MaxConnectionsPerPeer* = 1
const MaxConnections* = 50
proc withWsTransport*(b: SwitchBuilder): SwitchBuilder =
b.withTransport(
proc(upgr: Upgrade, privateKey: crypto.PrivateKey): Transport =
WsTransport.new(upgr)
proc(config: TransportConfig): Transport =
WsTransport.new(config.upgr, rng = config.rng)
)
proc getSecureKey(path: string): TLSPrivateKey {.raises: [Defect, IOError].} =
@ -59,7 +61,7 @@ proc newWakuSwitch*(
wsAddress = none(MultiAddress),
secureManagers: openarray[SecureProtocol] = [SecureProtocol.Noise],
transportFlags: set[ServerFlags] = {},
rng: ref HmacDrbgContext,
rng: crypto.Rng,
inTimeout: Duration = 5.minutes,
outTimeout: Duration = 5.minutes,
maxConnections = MaxConnections,
@ -80,8 +82,7 @@ proc newWakuSwitch*(
.new()
.withRng(rng)
.withMaxConnections(maxConnections)
.withMaxIn(maxIn)
.withMaxOut(maxOut)
.withMaxInOut(maxIn, maxOut)
.withMaxConnsPerPeer(maxConnsPerPeer)
.withYamux()
.withMplex(inTimeout, outTimeout)
@ -112,6 +113,6 @@ proc newWakuSwitch*(
b = b.withAddress(address)
if not rendezvous.isNil():
b = b.withRendezVous(rendezvous)
b = b.withRendezVous()
b.build()

View File

@ -1,3 +1,4 @@
import waku/compat/option_valueor
## Public facade and main driver types for the persistency library.
##
## ``Persistency`` is the per-root coordinator; one instance owns one

Some files were not shown because too many files have changed in this diff Show More