2024-06-28 10:34:57 +00:00
|
|
|
{.push raises: [].}
|
2024-02-13 04:48:02 +00:00
|
|
|
|
2024-03-15 23:08:47 +00:00
|
|
|
import chronos, stew/results, times
|
|
|
|
import ./constants
|
2024-02-13 04:48:02 +00:00
|
|
|
|
2024-03-15 23:08:47 +00:00
|
|
|
export chronos, times, results, constants
|
2024-02-13 04:48:02 +00:00
|
|
|
|
|
|
|
# This module contains the NonceManager interface
|
|
|
|
# The NonceManager is responsible for managing the messageId used to generate RLN proofs
|
|
|
|
# It should be used to fetch a new messageId every time a proof is generated
|
|
|
|
# It refreshes the messageId every `epoch` seconds
|
|
|
|
|
|
|
|
type
|
|
|
|
Nonce* = uint64
|
|
|
|
NonceManager* = ref object of RootObj
|
|
|
|
epoch*: float64
|
|
|
|
nextNonce*: Nonce
|
|
|
|
lastNonceTime*: float64
|
|
|
|
nonceLimit*: Nonce
|
|
|
|
|
|
|
|
NonceManagerErrorKind* = enum
|
|
|
|
NonceLimitReached
|
|
|
|
|
|
|
|
NonceManagerError* = object
|
|
|
|
kind*: NonceManagerErrorKind
|
|
|
|
error*: string
|
|
|
|
|
|
|
|
NonceManagerResult*[T] = Result[T, NonceManagerError]
|
|
|
|
|
|
|
|
proc `$`*(ne: NonceManagerError): string =
|
|
|
|
case ne.kind
|
|
|
|
of NonceLimitReached:
|
|
|
|
return "NonceLimitReached: " & ne.error
|
|
|
|
|
2024-03-12 10:50:30 +00:00
|
|
|
proc init*(T: type NonceManager, nonceLimit: Nonce, epoch = 1.float64): T =
|
2024-03-15 23:08:47 +00:00
|
|
|
return
|
|
|
|
NonceManager(epoch: epoch, nextNonce: 0, lastNonceTime: 0, nonceLimit: nonceLimit)
|
2024-02-13 04:48:02 +00:00
|
|
|
|
2024-03-01 08:45:40 +00:00
|
|
|
proc getNonce*(n: NonceManager): NonceManagerResult[Nonce] =
|
2024-02-13 04:48:02 +00:00
|
|
|
let now = getTime().toUnixFloat()
|
|
|
|
var retNonce = n.nextNonce
|
|
|
|
|
2024-03-15 23:08:47 +00:00
|
|
|
if now - n.lastNonceTime >= n.epoch:
|
|
|
|
retNonce = 0
|
2024-06-20 09:35:21 +00:00
|
|
|
n.lastNonceTime = now
|
|
|
|
|
2024-02-13 04:48:02 +00:00
|
|
|
n.nextNonce = retNonce + 1
|
|
|
|
|
|
|
|
if retNonce >= n.nonceLimit:
|
2024-03-15 23:08:47 +00:00
|
|
|
return err(
|
2024-06-20 09:35:21 +00:00
|
|
|
NonceManagerError(
|
2024-03-15 23:08:47 +00:00
|
|
|
kind: NonceLimitReached,
|
|
|
|
error:
|
|
|
|
"Nonce limit reached. Please wait for the next epoch. requested nonce: " &
|
|
|
|
$retNonce & " & nonceLimit: " & $n.nonceLimit,
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
2024-02-13 04:48:02 +00:00
|
|
|
return ok(retNonce)
|