rename rln-relay types to rln

This commit is contained in:
stubbsta 2026-06-24 09:09:41 +02:00
parent d04f107071
commit c069799fc5
No known key found for this signature in database
27 changed files with 124 additions and 136 deletions

View File

@ -9,7 +9,7 @@ import
waku_rln/conversion_utils,
waku_rln/group_manager/on_chain/group_manager,
],
tests/waku_rln/utils_onchain
tests/waku_rln_relay/utils_onchain
proc benchmark(
manager: OnChainGroupManager, registerCount: int, messageLimit: int

View File

@ -521,7 +521,7 @@ proc processInput(rfd: AsyncFD, rng: crypto.Rng) {.async.} =
topic = DefaultPubsubTopic, error = error
if conf.rlnRelay:
info "WakuRLNRelay is enabled"
info "WakuRln is enabled"
proc spamHandler(wakuMessage: WakuMessage) {.gcsafe, closure.} =
info "spam handler is called"
@ -538,7 +538,7 @@ proc processInput(rfd: AsyncFD, rng: crypto.Rng) {.async.} =
chainId: UInt256.fromBytesBE(conf.rlnRelayChainId.toBytesBE()),
ethClientUrls: conf.ethClientUrls.mapIt(string(it)),
creds: some(
RlnRelayCreds(
RlnCreds(
path: conf.rlnRelayCredPath, password: conf.rlnRelayCredPassword
)
),
@ -554,8 +554,8 @@ proc processInput(rfd: AsyncFD, rng: crypto.Rng) {.async.} =
echo "your rln identity commitment key is: ",
identityCredential.idCommitment.inHex()
else:
info "WakuRLNRelay is disabled"
echo "WakuRLNRelay is disabled, please enable it by passing in the --rln-relay flag"
info "WakuRln is disabled"
echo "WakuRln is disabled, please enable it by passing in the --rln-relay flag"
if conf.metricsLogging:
startMetricsLog()

View File

@ -614,7 +614,7 @@ when isMainModule:
ethContractAddress: conf.rlnRelayEthContractAddress,
ethClientUrls: conf.ethClientUrls.mapIt(string(it)),
epochSizeSec: conf.rlnEpochSizeSec,
creds: none(RlnRelayCreds),
creds: none(RlnCreds),
onFatalErrorAction: onFatalErrorAction,
)

View File

@ -65,7 +65,7 @@ proc setupSendProcessorChain(
peerManager: PeerManager,
lightpushClient: WakuLightPushClient,
relay: WakuRelay,
rlnRelay: WakuRLNRelay,
rlnRelay: WakuRln,
brokerCtx: BrokerContext,
): Result[BaseSendProcessor, string] =
let isRelayAvail = not relay.isNil()
@ -77,9 +77,9 @@ proc setupSendProcessorChain(
var processors = newSeq[BaseSendProcessor]()
if isRelayAvail:
let rln: Option[WakuRLNRelay] =
let rln: Option[WakuRln] =
if rlnRelay.isNil():
none[WakuRLNRelay]()
none[WakuRln]()
else:
some(rlnRelay)
let publishProc = getRelayPushHandler(relay, rln)

View File

@ -12,7 +12,7 @@ const
##############################
## RLN Relay Config Builder ##
##############################
type RlnRelayConfBuilder* = object
type RlnConfBuilder* = object
enabled*: Option[bool]
chainId*: Option[UInt256]
ethClientUrls*: Option[seq[string]]
@ -24,58 +24,58 @@ type RlnRelayConfBuilder* = object
epochSizeSec*: Option[uint64]
userMessageLimit*: Option[uint64]
proc init*(T: type RlnRelayConfBuilder): RlnRelayConfBuilder =
RlnRelayConfBuilder()
proc init*(T: type RlnConfBuilder): RlnConfBuilder =
RlnConfBuilder()
proc withEnabled*(b: var RlnRelayConfBuilder, enabled: bool) =
proc withEnabled*(b: var RlnConfBuilder, enabled: bool) =
b.enabled = some(enabled)
proc withChainId*(b: var RlnRelayConfBuilder, chainId: uint | UInt256) =
proc withChainId*(b: var RlnConfBuilder, chainId: uint | UInt256) =
when chainId is uint:
b.chainId = some(UInt256.fromBytesBE(chainId.toBytesBE()))
else:
b.chainId = some(chainId)
proc withCredIndex*(b: var RlnRelayConfBuilder, credIndex: uint) =
proc withCredIndex*(b: var RlnConfBuilder, credIndex: uint) =
b.credIndex = some(credIndex)
proc withCredPassword*(b: var RlnRelayConfBuilder, credPassword: string) =
proc withCredPassword*(b: var RlnConfBuilder, credPassword: string) =
b.credPassword = some(credPassword)
proc withCredPath*(b: var RlnRelayConfBuilder, credPath: string) =
proc withCredPath*(b: var RlnConfBuilder, credPath: string) =
b.credPath = some(credPath)
proc withDynamic*(b: var RlnRelayConfBuilder, dynamic: bool) =
proc withDynamic*(b: var RlnConfBuilder, dynamic: bool) =
b.dynamic = some(dynamic)
proc withEthClientUrls*(b: var RlnRelayConfBuilder, ethClientUrls: seq[string]) =
proc withEthClientUrls*(b: var RlnConfBuilder, ethClientUrls: seq[string]) =
b.ethClientUrls = some(ethClientUrls)
proc withEthContractAddress*(b: var RlnRelayConfBuilder, ethContractAddress: string) =
proc withEthContractAddress*(b: var RlnConfBuilder, ethContractAddress: string) =
b.ethContractAddress = some(ethContractAddress)
proc withEpochSizeSec*(b: var RlnRelayConfBuilder, epochSizeSec: uint64) =
proc withEpochSizeSec*(b: var RlnConfBuilder, epochSizeSec: uint64) =
b.epochSizeSec = some(epochSizeSec)
proc withUserMessageLimit*(b: var RlnRelayConfBuilder, userMessageLimit: uint64) =
proc withUserMessageLimit*(b: var RlnConfBuilder, userMessageLimit: uint64) =
b.userMessageLimit = some(userMessageLimit)
proc build*(b: RlnRelayConfBuilder): Result[Option[RlnRelayConf], string] =
proc build*(b: RlnConfBuilder): Result[Option[RlnConf], string] =
if not b.enabled.get(DefaultRlnRelayEnabled):
return ok(none(RlnRelayConf))
return ok(none(RlnConf))
if b.chainId.isNone():
return err("RLN Relay Chain Id is not specified")
let creds =
if b.credPath.isSome() and b.credPassword.isSome():
some(RlnRelayCreds(path: b.credPath.get(), password: b.credPassword.get()))
some(RlnCreds(path: b.credPath.get(), password: b.credPassword.get()))
elif b.credPath.isSome() and b.credPassword.isNone():
return err("RLN Relay Credential Password is not specified but path is")
elif b.credPath.isNone() and b.credPassword.isSome():
return err("RLN Relay Credential Path is not specified but password is")
else:
none(RlnRelayCreds)
none(RlnCreds)
if b.dynamic.isNone():
return err("rlnRelay.dynamic is not specified")
@ -85,7 +85,7 @@ proc build*(b: RlnRelayConfBuilder): Result[Option[RlnRelayConf], string] =
return err("rlnRelay.ethContractAddress is not specified")
return ok(
some(
RlnRelayConf(
RlnConf(
chainId: b.chainId.get(),
credIndex: b.credIndex,
creds: creds,

View File

@ -116,7 +116,7 @@ type WakuConfBuilder* = object
filterServiceConf*: FilterServiceConfBuilder
metricsServerConf*: MetricsServerConfBuilder
restServerConf*: RestServerConfBuilder
rlnRelayConf*: RlnRelayConfBuilder
rlnRelayConf*: RlnConfBuilder
storeServiceConf*: StoreServiceConfBuilder
mixConf*: MixConfBuilder
webSocketConf*: WebSocketConfBuilder
@ -181,7 +181,7 @@ proc init*(T: type WakuConfBuilder): WakuConfBuilder =
filterServiceConf: FilterServiceConfBuilder.init(),
metricsServerConf: MetricsServerConfBuilder.init(),
restServerConf: RestServerConfBuilder.init(),
rlnRelayConf: RlnRelayConfBuilder.init(),
rlnRelayConf: RlnConfBuilder.init(),
storeServiceConf: StoreServiceConfBuilder.init(),
webSocketConf: WebSocketConfBuilder.init(),
quicConf: QuicConfBuilder.init(),

View File

@ -25,7 +25,7 @@ import
../waku_mix,
./conf_builder/kademlia_discovery_conf_builder
export RlnRelayConf, RlnRelayCreds, RestServerConf, Discv5Conf, MetricsServerConf
export RlnConf, RlnCreds, RestServerConf, Discv5Conf, MetricsServerConf
logScope:
topics = "waku conf"
@ -113,7 +113,7 @@ type WakuConf* {.requiresInit.} = ref object
dnsDiscoveryConf*: Option[DnsDiscoveryConf]
filterServiceConf*: Option[FilterServiceConf]
storeServiceConf*: Option[StoreServiceConf]
rlnRelayConf*: Option[RlnRelayConf]
rlnRelayConf*: Option[RlnConf]
restServerConf*: Option[RestServerConf]
metricsServerConf*: Option[MetricsServerConf]
webSocketConf*: Option[WebSocketConf]

View File

@ -1,7 +1,7 @@
import logos_delivery/waku/compat/option_valueor
import std/[options, sets], chronos, web3, stew/byteutils, stint, results, chronicles
import logos_delivery/waku/incentivization/rpc, tests/waku_rln/utils_onchain
import logos_delivery/waku/incentivization/rpc, tests/waku_rln_relay/utils_onchain
const SimpleTransferGasUsed = Quantity(21000)
const TxReceiptQueryTimeout = 3.seconds

View File

@ -110,7 +110,7 @@ type
wakuStoreTransfer*: SyncTransfer
wakuFilter*: waku_filter_v2.WakuFilter
wakuFilterClient*: filter_client.WakuFilterClient
wakuRlnRelay*: WakuRLNRelay
wakuRlnRelay*: WakuRln
wakuLegacyLightPush*: WakuLegacyLightPush
wakuLegacyLightpushClient*: WakuLegacyLightPushClient
wakuLightPush*: WakuLightPush

View File

@ -50,7 +50,7 @@ proc mountLegacyLightPush*(
let rlnPeer =
if node.wakuRlnRelay.isNil():
info "mounting legacy lightpush without rln-relay"
none(WakuRLNRelay)
none(WakuRln)
else:
info "mounting legacy lightpush with rln-relay"
some(node.wakuRlnRelay)
@ -161,7 +161,7 @@ proc mountLightPush*(
let rlnPeer =
if node.wakuRlnRelay.isNil():
info "mounting lightpush without rln-relay"
none(WakuRLNRelay)
none(WakuRln)
else:
info "mounting lightpush with rln-relay"
some(node.wakuRlnRelay)

View File

@ -195,11 +195,11 @@ proc mountRlnRelay*(
if node.wakuRelay.isNil():
raise newException(
CatchableError, "WakuRelay protocol is not mounted, cannot mount WakuRlnRelay"
CatchableError, "WakuRelay protocol is not mounted, cannot mount WakuRln"
)
let rlnRelay = (await WakuRlnRelay.new(rlnConf, registrationHandler)).valueOr:
raise newException(CatchableError, "failed to mount WakuRlnRelay: " & error)
let rlnRelay = (await WakuRln.new(rlnConf, registrationHandler)).valueOr:
raise newException(CatchableError, "failed to mount WakuRln: " & error)
if (rlnConf.userMessageLimit > rlnRelay.groupManager.rlnRelayMaxMessageLimit):
error "rln-relay-user-message-limit can't exceed the MAX_MESSAGE_LIMIT in the rln contract"
let validator = generateRlnValidator(rlnRelay, spamHandler)

View File

@ -13,7 +13,7 @@ import
import std/times, libp2p/peerid, stew/byteutils
proc checkAndGenerateRLNProof*(
rlnPeer: Option[WakuRLNRelay], message: WakuMessage
rlnPeer: Option[WakuRln], message: WakuMessage
): Future[Result[WakuMessage, string]] {.async.} =
# check if the message already has RLN proof
if message.proof.len > 0:
@ -40,7 +40,7 @@ proc getNilPushHandler*(): PushMessageHandler =
return lightpushResultInternalError("no waku relay found")
proc getRelayPushHandler*(
wakuRelay: WakuRelay, rlnPeer: Option[WakuRLNRelay] = none[WakuRLNRelay]()
wakuRelay: WakuRelay, rlnPeer: Option[WakuRln] = none[WakuRln]()
): PushMessageHandler =
return proc(
pubsubTopic: string, message: WakuMessage

View File

@ -11,7 +11,7 @@ import
import std/times, libp2p/peerid, stew/byteutils
proc checkAndGenerateRLNProof*(
rlnPeer: Option[WakuRLNRelay], message: WakuMessage
rlnPeer: Option[WakuRln], message: WakuMessage
): Future[Result[WakuMessage, string]] {.async.} =
# check if the message already has RLN proof
if message.proof.len > 0:
@ -38,7 +38,7 @@ proc getNilPushHandler*(): PushMessageHandler =
return err("no waku relay found")
proc getRelayPushHandler*(
wakuRelay: WakuRelay, rlnPeer: Option[WakuRLNRelay] = none[WakuRLNRelay]()
wakuRelay: WakuRelay, rlnPeer: Option[WakuRln] = none[WakuRln]()
): PushMessageHandler =
return proc(
pubsubTopic: string, message: WakuMessage

View File

@ -16,7 +16,7 @@ logScope:
topics = "waku rln_relay adapter"
proc generateRlnValidator*(
wakuRlnRelay: WakuRLNRelay, spamHandler = none(SpamHandler)
wakuRlnRelay: WakuRln, spamHandler = none(SpamHandler)
): WakuValidatorHandler =
## Bridges RLN's protocol-agnostic message validation into a relay
## (gossipsub) validator. The core decision is made by

View File

@ -4,11 +4,11 @@ import std/options, stint
import logos_delivery/waku/common/error_handling
type RlnRelayCreds* {.requiresInit.} = object
type RlnCreds* {.requiresInit.} = object
path*: string
password*: string
type RlnRelayConf* = object of RootObj
type RlnConf* = object of RootObj
# TODO: severals parameters are only needed when it's dynamic
# change the config to either nest or use enum/type variant so it's obvious
# and then it can be set to `requiresInit`
@ -17,10 +17,10 @@ type RlnRelayConf* = object of RootObj
ethContractAddress*: string
ethClientUrls*: seq[string]
chainId*: UInt256
creds*: Option[RlnRelayCreds]
creds*: Option[RlnCreds]
epochSizeSec*: uint64
userMessageLimit*: uint64
ethPrivateKey*: Option[string]
type WakuRlnConfig* = object of RlnRelayConf
type WakuRlnConfig* = object of RlnConf
onFatalErrorAction*: OnFatalErrorHandler

View File

@ -9,8 +9,8 @@ logScope:
topics = "waku rln_relay nullifier_log"
proc hasDuplicate*(
rlnPeer: WakuRLNRelay, epoch: Epoch, proofMetadata: ProofMetadata
): RlnRelayResult[bool] =
rlnPeer: WakuRln, epoch: Epoch, proofMetadata: ProofMetadata
): RlnResult[bool] =
## returns true if there is another message in the `nullifierLog` of the `rlnPeer` with the same
## epoch and nullifier as `proofMetadata`'s epoch and nullifier
## otherwise, returns false
@ -31,8 +31,8 @@ proc hasDuplicate*(
return err("the epoch was not found: " & getCurrentExceptionMsg())
proc updateLog*(
rlnPeer: WakuRLNRelay, epoch: Epoch, proofMetadata: ProofMetadata
): RlnRelayResult[void] =
rlnPeer: WakuRln, epoch: Epoch, proofMetadata: ProofMetadata
): RlnResult[void] =
## saves supplied proofMetadata `proofMetadata`
## in the `nullifierLog` of the `rlnPeer`
## Returns an error if it cannot update the log
@ -55,7 +55,7 @@ proc updateLog*(
return
err("the epoch was not found: " & getCurrentExceptionMsg()) # should never happen
proc clearNullifierLog*(rlnPeer: WakuRlnRelay) =
proc clearNullifierLog*(rlnPeer: WakuRln) =
# clear the first MaxEpochGap epochs of the nullifer log
# if more than MaxEpochGap epochs are in the log
let currentEpoch = fromEpoch(rlnPeer.getCurrentEpoch())

View File

@ -7,14 +7,14 @@ import ./types, ./protocol_types, ./conversion_utils, ./group_manager, ./nonce_m
import logos_delivery/waku/waku_core
proc calcEpoch*(rlnPeer: WakuRLNRelay, t: float64): Epoch =
proc calcEpoch*(rlnPeer: WakuRln, t: float64): Epoch =
## gets time `t` as `flaot64` with subseconds resolution in the fractional part
## and returns its corresponding rln `Epoch` value
let e = uint64(t / rlnPeer.rlnEpochSizeSec.float64)
return toEpoch(e)
proc nextEpoch*(rlnPeer: WakuRLNRelay, time: float64): float64 =
proc nextEpoch*(rlnPeer: WakuRln, time: float64): float64 =
let
currentEpoch = uint64(time / rlnPeer.rlnEpochSizeSec.float64)
nextEpochTime = float64(currentEpoch + 1) * rlnPeer.rlnEpochSizeSec.float64
@ -26,7 +26,7 @@ proc nextEpoch*(rlnPeer: WakuRLNRelay, time: float64): float64 =
else:
return epochTime()
proc getCurrentEpoch*(rlnPeer: WakuRLNRelay): Epoch =
proc getCurrentEpoch*(rlnPeer: WakuRln): Epoch =
return rlnPeer.calcEpoch(epochTime())
proc absDiff*(e1, e2: Epoch): uint64 =
@ -55,8 +55,8 @@ proc toRLNSignal*(wakumessage: WakuMessage): seq[byte] =
return output
proc generateRLNProof*(
rlnPeer: WakuRLNRelay, input: seq[byte], senderEpochTime: float64
): Future[RlnRelayResult[seq[byte]]] {.async.} =
rlnPeer: WakuRln, input: seq[byte], senderEpochTime: float64
): Future[RlnResult[seq[byte]]] {.async.} =
let epoch = rlnPeer.calcEpoch(senderEpochTime)
let nonce = rlnPeer.nonceManager.getNonce().valueOr:
return err("could not get new message id to generate an rln proof: " & $error)

View File

@ -5,11 +5,11 @@ import ../waku_core, ../waku_keystore, ../common/protobuf
export waku_keystore, waku_core
type RlnRelayResult*[T] = Result[T, string]
type RlnResult*[T] = Result[T, string]
## RLN is a Nim wrapper for the data types used in zerokit RLN
type RLN* {.incompleteStruct.} = object
type RLNResult* = RlnRelayResult[ptr RLN]
type RlnInstanceResult* = RlnResult[ptr RLN]
type
MerkleNode* = array[32, byte]
@ -78,8 +78,8 @@ type
Invalid
Spam
MerkleNodeResult* = RlnRelayResult[MerkleNode]
RateLimitProofResult* = RlnRelayResult[RateLimitProof]
MerkleNodeResult* = RlnResult[MerkleNode]
RateLimitProofResult* = RlnResult[RateLimitProof]
# Protobufs enc and init
proc init*(T: type RateLimitProof, buffer: seq[byte]): ProtoResult[T] =

View File

@ -35,13 +35,13 @@ import
# Re-export the submodules so existing `import waku_rln`
# (and `import waku_rln/rln`) callers see the moved symbols
# (WakuRLNRelay, WakuRlnConfig, generateRLNProof, etc.).
# (WakuRln, WakuRlnConfig, generateRLNProof, etc.).
export types, config, proof, nullifier_log
logScope:
topics = "waku rln_relay"
proc stop*(rlnPeer: WakuRLNRelay) {.async: (raises: [Exception]).} =
proc stop*(rlnPeer: WakuRln) {.async: (raises: [Exception]).} =
## stops the rln-relay protocol
## Throws an error if it cannot stop the rln-relay protocol
@ -51,7 +51,7 @@ proc stop*(rlnPeer: WakuRLNRelay) {.async: (raises: [Exception]).} =
await rlnPeer.groupManager.stop()
proc validateMessage*(
rlnPeer: WakuRLNRelay, msg: WakuMessage
rlnPeer: WakuRln, msg: WakuMessage
): Future[MessageValidationResult] {.async.} =
## validate the supplied `msg` based on the waku-rln-relay routing protocol i.e.,
## the `msg`'s epoch is within MaxEpochGap of the current epoch
@ -146,7 +146,7 @@ proc validateMessage*(
return MessageValidationResult.Valid
proc validateMessageAndUpdateLog*(
rlnPeer: WakuRLNRelay, msg: WakuMessage
rlnPeer: WakuRln, msg: WakuMessage
): Future[MessageValidationResult] {.async.} =
## validates the message and updates the log to prevent double messaging
## in future messages
@ -166,7 +166,7 @@ proc validateMessageAndUpdateLog*(
return isValidMessage
proc monitorEpochs(wakuRlnRelay: WakuRLNRelay) {.async.} =
proc monitorEpochs(wakuRlnRelay: WakuRln) {.async.} =
while true:
try:
if wakuRlnRelay.groupManager.userMessageLimit.isSome():
@ -184,10 +184,10 @@ proc monitorEpochs(wakuRlnRelay: WakuRLNRelay) {.async.} =
proc mount(
conf: WakuRlnConfig, registrationHandler = none(RegistrationHandler)
): Future[RlnRelayResult[WakuRlnRelay]] {.async.} =
): Future[RlnResult[WakuRln]] {.async.} =
var
groupManager: GroupManager
wakuRlnRelay: WakuRLNRelay
wakuRlnRelay: WakuRln
# create an RLN instance
let rlnInstance = createRLNInstance().valueOr:
return err("could not create RLN instance: " & $error)
@ -216,7 +216,7 @@ proc mount(
(await groupManager.init()).isOkOr:
return err("could not initialize the group manager: " & $error)
wakuRlnRelay = WakuRLNRelay(
wakuRlnRelay = WakuRln(
groupManager: groupManager,
nonceManager: NonceManager.init(conf.userMessageLimit, conf.epochSizeSec.float),
rlnEpochSizeSec: conf.epochSizeSec,
@ -245,7 +245,7 @@ proc mount(
return ok(wakuRlnRelay)
proc isReady*(rlnPeer: WakuRLNRelay): Future[bool] {.async.} =
proc isReady*(rlnPeer: WakuRln): Future[bool] {.async.} =
## returns true if the rln-relay protocol is ready to relay messages
## returns false otherwise
@ -260,10 +260,10 @@ proc isReady*(rlnPeer: WakuRLNRelay): Future[bool] {.async.} =
return false
proc new*(
T: type WakuRlnRelay,
T: type WakuRln,
conf: WakuRlnConfig,
registrationHandler = none(RegistrationHandler),
): Future[RlnRelayResult[WakuRlnRelay]] {.async.} =
): Future[RlnResult[WakuRln]] {.async.} =
## Mounts the rln-relay protocol on the node.
## The rln-relay protocol can be mounted in two modes: on-chain and off-chain.
## Returns an error if the rln-relay protocol could not be mounted.

View File

@ -318,14 +318,14 @@ proc vecToSeq*(data: Vec_uint8): seq[byte] =
if result.len > 0:
copyMem(addr result[0], data.dataPtr, result.len)
proc seqToFixed32*(data: openArray[byte]): RlnRelayResult[array[32, byte]] =
proc seqToFixed32*(data: openArray[byte]): RlnResult[array[32, byte]] =
if data.len != FieldElementSize:
return err("Expected 32 bytes, got " & $data.len)
var output: array[32, byte]
copyMem(addr output[0], unsafeAddr data[0], FieldElementSize)
ok(output)
proc cfrToBytesLe*(cfr: ptr CFr): RlnRelayResult[array[32, byte]] =
proc cfrToBytesLe*(cfr: ptr CFr): RlnResult[array[32, byte]] =
let bytes = ffi_cfr_to_bytes_le(cfr)
defer:
ffi_vec_u8_free(bytes)
@ -333,7 +333,7 @@ proc cfrToBytesLe*(cfr: ptr CFr): RlnRelayResult[array[32, byte]] =
return err("Invalid field byte length: " & $bytes.len)
seqToFixed32(vecToSeq(bytes))
proc bytesToCfrLe*(data: openArray[byte]): RlnRelayResult[ptr CFr] =
proc bytesToCfrLe*(data: openArray[byte]): RlnResult[ptr CFr] =
## Allocate a ptr CFr from raw bytes. Caller MUST ffi_cfr_free(x).
var vec = toVecUint8(data)
let res = ffi_bytes_le_to_cfr(addr vec)
@ -343,7 +343,7 @@ proc bytesToCfrLe*(data: openArray[byte]): RlnRelayResult[ptr CFr] =
proc cfrResultToBytes*(
res: CResultCFrPtrVecU8, prefix: string
): RlnRelayResult[array[32, byte]] =
): RlnResult[array[32, byte]] =
## Consume a CResultCFrPtrVecU8: read bytes if ok, free the CFr, or
## propagate the error (also freeing the error string).
if res.ok.isNil:
@ -352,7 +352,7 @@ proc cfrResultToBytes*(
ffi_cfr_free(res.ok)
cfrToBytesLe(res.ok)
proc hashToFieldLe*(data: openArray[byte]): RlnRelayResult[ptr CFr] =
proc hashToFieldLe*(data: openArray[byte]): RlnResult[ptr CFr] =
## Caller MUST ffi_cfr_free the returned ptr.
var vec = toVecUint8(data)
let cfr = ffi_hash_to_field_le(addr vec)
@ -360,7 +360,7 @@ proc hashToFieldLe*(data: openArray[byte]): RlnRelayResult[ptr CFr] =
return err("Failed to hash to field")
ok(cfr)
proc poseidonPairLe*(a, b: openArray[byte]): RlnRelayResult[array[32, byte]] =
proc poseidonPairLe*(a, b: openArray[byte]): RlnResult[array[32, byte]] =
## Poseidon hash of exactly two 32-byte field elements (little-endian).
## zerokit v2 FFI only exposes pair-input Poseidon; unary is not supported.
let aPtr = bytesToCfrLe(a).valueOr:

View File

@ -12,9 +12,9 @@ logScope:
# Forward decl; body defined below.
proc generateExternalNullifier*(
epoch: Epoch, rlnIdentifier: RlnIdentifier
): RlnRelayResult[ExternalNullifier]
): RlnResult[ExternalNullifier]
proc toRootVec(validRoots: seq[MerkleNode]): RlnRelayResult[Vec_CFr] =
proc toRootVec(validRoots: seq[MerkleNode]): RlnResult[Vec_CFr] =
## Caller MUST ffi_vec_cfr_free the returned Vec_CFr.
var roots = ffi_vec_cfr_new(csize_t(validRoots.len))
for root in validRoots:
@ -27,7 +27,7 @@ proc toRootVec(validRoots: seq[MerkleNode]): RlnRelayResult[Vec_CFr] =
proc proofPtrToRateLimitProof(
proofPtr: ptr FFI_RLNProof, epoch: Epoch, rlnIdentifier: RlnIdentifier
): RlnRelayResult[RateLimitProof] =
): RlnResult[RateLimitProof] =
var proofHandle = proofPtr
let proofBytesRes = ffi_rln_proof_to_bytes_le(addr proofHandle)
if hasError(proofBytesRes.err):
@ -93,7 +93,7 @@ proc proofPtrToRateLimitProof(
ok(output)
proc parseCredentialVec(vec: var Vec_CFr): RlnRelayResult[IdentityCredential] =
proc parseCredentialVec(vec: var Vec_CFr): RlnResult[IdentityCredential] =
## Vec_CFr order: idTrapdoor, idNullifier, idSecretHash, idCommitment.
if int(ffi_vec_cfr_len(addr vec)) != 4:
return err("Unexpected credential element count")
@ -120,13 +120,13 @@ proc parseCredentialVec(vec: var Vec_CFr): RlnRelayResult[IdentityCredential] =
)
)
proc membershipKeyGen*(): RlnRelayResult[IdentityCredential] =
proc membershipKeyGen*(): RlnResult[IdentityCredential] =
var vec = ffi_extended_key_gen()
defer:
ffi_vec_cfr_free(vec)
parseCredentialVec(vec)
proc createRLNInstanceLocal(): RLNResult =
proc createRLNInstanceLocal(): RlnInstanceResult =
## Creates a stateless RLN instance (no local Merkle tree).
let res = ffi_rln_new()
if res.ok.isNil():
@ -135,18 +135,18 @@ proc createRLNInstanceLocal(): RLNResult =
return err(msg)
ok(res.ok)
proc createRLNInstance*(): RLNResult =
proc createRLNInstance*(): RlnInstanceResult =
## Wraps createRLNInstanceLocal with metrics timing.
var res: RLNResult
var res: RlnInstanceResult
waku_rln_instance_creation_duration_seconds.nanosecondTime:
res = createRLNInstanceLocal()
return res
proc poseidon*(left, right: seq[byte]): RlnRelayResult[array[32, byte]] =
proc poseidon*(left, right: seq[byte]): RlnResult[array[32, byte]] =
## Poseidon hash of exactly 2 inputs; zerokit v2 FFI only exposes the pair variant.
poseidonPairLe(left, right)
proc toLeaf*(rateCommitment: RateCommitment): RlnRelayResult[seq[byte]] =
proc toLeaf*(rateCommitment: RateCommitment): RlnResult[seq[byte]] =
let idCommitment = rateCommitment.idCommitment
var userMessageLimit: array[32, byte]
try:
@ -164,7 +164,7 @@ proc toLeaf*(rateCommitment: RateCommitment): RlnRelayResult[seq[byte]] =
retLeaf[i] = leaf[i]
return ok(retLeaf)
proc toLeaves*(rateCommitments: seq[RateCommitment]): RlnRelayResult[seq[seq[byte]]] =
proc toLeaves*(rateCommitments: seq[RateCommitment]): RlnResult[seq[seq[byte]]] =
var leaves = newSeq[seq[byte]]()
for rateCommitment in rateCommitments:
let leaf = toLeaf(rateCommitment).valueOr:
@ -174,7 +174,7 @@ proc toLeaves*(rateCommitments: seq[RateCommitment]): RlnRelayResult[seq[seq[byt
proc generateExternalNullifier*(
epoch: Epoch, rlnIdentifier: RlnIdentifier
): RlnRelayResult[ExternalNullifier] =
): RlnResult[ExternalNullifier] =
## externalNullifier = Poseidon(H(epoch), H(rlnIdentifier)); H = ffi_hash_to_field_le.
let epochFr = hashToFieldLe(@epoch).valueOr:
return err("Failed to hash epoch to field: " & error)
@ -194,7 +194,7 @@ proc generateExternalNullifier*(
"Failed to serialize external nullifier: " & e
)
proc extractMetadata*(proof: RateLimitProof): RlnRelayResult[ProofMetadata] =
proc extractMetadata*(proof: RateLimitProof): RlnResult[ProofMetadata] =
let externalNullifier = generateExternalNullifier(proof.epoch, proof.rlnIdentifier).valueOr:
return err("Failed to compute external nullifier: " & error)
return ok(
@ -208,7 +208,7 @@ proc extractMetadata*(proof: RateLimitProof): RlnRelayResult[ProofMetadata] =
proc buildPathElementsVec(
pathElements: seq[byte], depth: int
): RlnRelayResult[Vec_CFr] =
): RlnResult[Vec_CFr] =
## Caller MUST ffi_vec_cfr_free the returned Vec_CFr.
var vec = ffi_vec_cfr_new(csize_t(depth))
for i in 0 ..< depth:
@ -226,7 +226,7 @@ proc buildPathElementsVec(
proc buildWitnessInput(
witness: RLNWitnessInput
): RlnRelayResult[ptr FFI_RLNWitnessInput] =
): RlnResult[ptr FFI_RLNWitnessInput] =
## ffi_rln_witness_input_new copies all inputs, so the intermediate CFrs/vecs
## are freed here. Caller MUST ffi_rln_witness_input_free the returned handle.
let depth = witness.identity_path_index.len
@ -291,7 +291,7 @@ proc generateRlnProofWithWitness*(
witness: RLNWitnessInput,
epoch: Epoch,
rlnIdentifier: RlnIdentifier,
): RlnRelayResult[RateLimitProof] =
): RlnResult[RateLimitProof] =
let witnessHandle = buildWitnessInput(witness).valueOr:
return
err("failed call to buildWitnessInput in generateRlnProofWithWitness: " & error)
@ -310,7 +310,7 @@ proc generateRlnProofWithWitness*(
proc buildRlnProof(
proof: RateLimitProof, externalNullifier: ExternalNullifier
): RlnRelayResult[ptr FFI_RLNProof] =
): RlnResult[ptr FFI_RLNProof] =
## ffi_rln_proof_new copies all inputs, so the intermediate CFrs are freed
## here. Caller MUST ffi_rln_proof_free the returned handle.
var groth16Vec = toVecUint8(proof.proof)
@ -349,7 +349,7 @@ proc verifyRlnProof*(
proof: RateLimitProof,
signal: openArray[byte],
validRoots: seq[MerkleNode],
): RlnRelayResult[bool] =
): RlnResult[bool] =
if validRoots.len == 0:
return err("verifyRlnProof requires at least one valid root (stateless mode)")

View File

@ -7,7 +7,7 @@ import ./group_manager, ./nonce_manager, ./protocol_types
import logos_delivery/waku/common/error_handling
type WakuRLNRelay* = ref object of RootObj
type WakuRln* = ref object of RootObj
# the log of nullifiers and Shamir shares of the past messages grouped per epoch
nullifierLog*: OrderedTable[Epoch, Table[Nullifier, ProofMetadata]]
lastEpoch*: Epoch # the epoch of the last published rln message

View File

@ -85,8 +85,8 @@ proc getWakuRlnConfigOnChain*(
ethClientAddress: ethClientAddress.get(EthClient),
epochSizeSec: 1,
onFatalErrorAction: fatalErrorHandler.get(fatalErrorVoidHandler),
# If these are used, initialisation fails with "failed to mount WakuRlnRelay: could not initialize the group manager: the commitment does not have a membership"
creds: some(RlnRelayCreds(path: keystorePath, password: password)),
# If these are used, initialisation fails with "failed to mount WakuRln: could not initialize the group manager: the commitment does not have a membership"
creds: some(RlnCreds(path: keystorePath, password: password)),
)
proc setupRelayWithOnChainRln*(
@ -143,7 +143,7 @@ suite "Waku RlnRelay - End to End - Static":
server.wakuRelay == nil
server.wakuRlnRelay == nil
catchRes.error()[].msg ==
"WakuRelay protocol is not mounted, cannot mount WakuRlnRelay"
"WakuRelay protocol is not mounted, cannot mount WakuRln"
asyncTest "Pubsub topics subscribed before mounting RlnRelay are added to it":
# Given the node enables Relay and Rln while subscribing to a pubsub topic
@ -236,7 +236,7 @@ suite "Waku RlnRelay - End to End - Static":
await node.mountRlnRelay(wakuRlnConfig)
except CatchableError as e:
check e.msg ==
"failed to mount WakuRlnRelay: rln-relay-user-message-limit can't exceed the MAX_MESSAGE_LIMIT in the rln contract"
"failed to mount WakuRln: rln-relay-user-message-limit can't exceed the MAX_MESSAGE_LIMIT in the rln contract"
suite "Analysis of Bandwith Limitations":
asyncTest "Valid Payload Sizes":

View File

@ -4,16 +4,16 @@ import std/tempfiles
import
logos_delivery/waku/waku_rln,
logos_delivery/waku/waku_rln/[
group_manager, bindings, conversion_utils, constants, protocol_types, protocol_metrics,
nonce_manager,
group_manager, bindings, conversion_utils, constants, protocol_types,
protocol_metrics, nonce_manager,
]
proc createRLNInstanceWrapper*(): RLNResult =
proc createRLNInstanceWrapper*(): RlnInstanceResult =
return createRlnInstance()
proc unsafeAppendRLNProof*(
rlnPeer: WakuRLNRelay, msg: var WakuMessage, epoch: Epoch, messageId: MessageId
): RlnRelayResult[void] =
rlnPeer: WakuRln, msg: var WakuMessage, epoch: Epoch, messageId: MessageId
): RlnResult[void] =
## Test helper derived from the publish-path proof flow.
## - Skips nonce validation to intentionally allow generating "bad" message IDs for tests.
## - Forces a real-time on-chain Merkle root refresh via `updateRoots()` and fetches Merkle

View File

@ -5,11 +5,8 @@
import std/[options, os], results, testutils/unittests, chronos, web3
import
logos_delivery/waku/[
waku_rln,
waku_rln/conversion_utils,
waku_rln/group_manager/on_chain/group_manager,
],
logos_delivery/waku/
[waku_rln, waku_rln/conversion_utils, waku_rln/group_manager/on_chain/group_manager],
./utils_onchain
suite "Token and RLN Contract Deployment":

View File

@ -12,13 +12,8 @@ import
import brokers/broker_context
import
logos_delivery/waku/[
waku_core,
waku_rln,
waku_rln/bindings,
waku_rln/protocol_metrics,
waku_keystore,
],
logos_delivery/waku/
[waku_core, waku_rln, waku_rln/bindings, waku_rln/protocol_metrics, waku_keystore],
./rln/waku_rln_relay_utils,
./utils_onchain,
../testlib/[wakucore, futures, wakunode, testutils]
@ -159,7 +154,7 @@ suite "Waku rln relay":
test "updateLog and hasDuplicate tests":
let
wakuRlnRelay = WakuRLNRelay()
wakuRlnRelay = WakuRln()
epoch = wakuRlnRelay.getCurrentEpoch()
# create some dummy nullifiers and secret shares
@ -232,9 +227,9 @@ suite "Waku rln relay":
let index = MembershipIndex(5)
let wakuRlnConfig = getWakuRlnConfig(manager = manager, index = index)
var wakuRlnRelay: WakuRlnRelay
var wakuRlnRelay: WakuRln
lockNewGlobalBrokerContext:
wakuRlnRelay = (await WakuRlnRelay.new(wakuRlnConfig)).valueOr:
wakuRlnRelay = (await WakuRln.new(wakuRlnConfig)).valueOr:
raiseAssert $error
let manager = cast[OnchainGroupManager](wakuRlnRelay.groupManager)
@ -288,9 +283,9 @@ suite "Waku rln relay":
let wakuRlnConfig = getWakuRlnConfig(manager = manager, index = index)
var wakuRlnRelay: WakuRlnRelay
var wakuRlnRelay: WakuRln
lockNewGlobalBrokerContext:
wakuRlnRelay = (await WakuRlnRelay.new(wakuRlnConfig)).valueOr:
wakuRlnRelay = (await WakuRln.new(wakuRlnConfig)).valueOr:
raiseAssert $error
let manager = cast[OnchainGroupManager](wakuRlnRelay.groupManager)
@ -337,9 +332,9 @@ suite "Waku rln relay":
asyncTest "multiple senders with same external nullifier":
let index1 = MembershipIndex(5)
let rlnConf1 = getWakuRlnConfig(manager = manager, index = index1)
var wakuRlnRelay1: WakuRlnRelay
var wakuRlnRelay1: WakuRln
lockNewGlobalBrokerContext:
wakuRlnRelay1 = (await WakuRlnRelay.new(rlnConf1)).valueOr:
wakuRlnRelay1 = (await WakuRln.new(rlnConf1)).valueOr:
raiseAssert "failed to create waku rln relay: " & $error
let manager1 = cast[OnchainGroupManager](wakuRlnRelay1.groupManager)
@ -350,9 +345,9 @@ suite "Waku rln relay":
let index2 = MembershipIndex(6)
let rlnConf2 = getWakuRlnConfig(manager = manager, index = index2)
var wakuRlnRelay2: WakuRlnRelay
var wakuRlnRelay2: WakuRln
lockNewGlobalBrokerContext:
wakuRlnRelay2 = (await WakuRlnRelay.new(rlnConf2)).valueOr:
wakuRlnRelay2 = (await WakuRln.new(rlnConf2)).valueOr:
raiseAssert "failed to create waku rln relay: " & $error
let manager2 = cast[OnchainGroupManager](wakuRlnRelay2.groupManager)
@ -481,9 +476,9 @@ suite "Waku rln relay":
let wakuRlnConfig = getWakuRlnConfig(
manager = manager, index = index, epochSizeSec = rlnEpochSizeSec.uint64
)
var wakuRlnRelay: WakuRlnRelay
var wakuRlnRelay: WakuRln
lockNewGlobalBrokerContext:
wakuRlnRelay = (await WakuRlnRelay.new(wakuRlnConfig)).valueOr:
wakuRlnRelay = (await WakuRln.new(wakuRlnConfig)).valueOr:
raiseAssert $error
let rlnMaxEpochGap = wakuRlnRelay.rlnMaxEpochGap

View File

@ -20,12 +20,8 @@ import
results
import
logos_delivery/waku/[
waku_rln,
waku_rln/protocol_types,
waku_rln/constants,
waku_rln/bindings,
],
logos_delivery/waku/
[waku_rln, waku_rln/protocol_types, waku_rln/constants, waku_rln/bindings],
../testlib/common
const CHAIN_ID* = 1234'u256
@ -42,7 +38,7 @@ proc generateCredentials*(): IdentityCredential =
proc getRateCommitment*(
idCredential: IdentityCredential, userMessageLimit: UserMessageLimit
): RlnRelayResult[RawRateCommitment] =
): RlnResult[RawRateCommitment] =
return RateCommitment(
idCommitment: idCredential.idCommitment, userMessageLimit: userMessageLimit
).toLeaf()