2024-06-28 16:04:57 +05:30
|
|
|
{.push raises: [].}
|
2024-02-13 10:18:02 +05:30
|
|
|
|
2024-07-09 13:14:28 +02:00
|
|
|
import chronos, results, times
|
2024-03-16 00:08:47 +01:00
|
|
|
import ./constants
|
2024-02-13 10:18:02 +05:30
|
|
|
|
2024-03-16 00:08:47 +01:00
|
|
|
export chronos, times, results, constants
|
2024-02-13 10:18:02 +05:30
|
|
|
|
|
|
|
# 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 16:20:30 +05:30
|
|
|
proc init*(T: type NonceManager, nonceLimit: Nonce, epoch = 1.float64): T =
|
2024-03-16 00:08:47 +01:00
|
|
|
return
|
|
|
|
NonceManager(epoch: epoch, nextNonce: 0, lastNonceTime: 0, nonceLimit: nonceLimit)
|
2024-02-13 10:18:02 +05:30
|
|
|
|
2024-03-01 14:15:40 +05:30
|
|
|
proc getNonce*(n: NonceManager): NonceManagerResult[Nonce] =
|
2024-02-13 10:18:02 +05:30
|
|
|
let now = getTime().toUnixFloat()
|
|
|
|
var retNonce = n.nextNonce
|
|
|
|
|
2024-03-16 00:08:47 +01:00
|
|
|
if now - n.lastNonceTime >= n.epoch:
|
|
|
|
retNonce = 0
|
2024-06-20 15:05:21 +05:30
|
|
|
n.lastNonceTime = now
|
|
|
|
|
2024-02-13 10:18:02 +05:30
|
|
|
n.nextNonce = retNonce + 1
|
|
|
|
|
|
|
|
if retNonce >= n.nonceLimit:
|
2024-03-16 00:08:47 +01:00
|
|
|
return err(
|
2024-07-09 13:14:28 +02:00
|
|
|
NonceManagerError(
|
2024-03-16 00:08:47 +01:00
|
|
|
kind: NonceLimitReached,
|
|
|
|
error:
|
|
|
|
"Nonce limit reached. Please wait for the next epoch. requested nonce: " &
|
|
|
|
$retNonce & " & nonceLimit: " & $n.nonceLimit,
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
2024-02-13 10:18:02 +05:30
|
|
|
return ok(retNonce)
|