Skip to content

Commit 451a745

Browse files
committed
fix time granularity
1 parent d5cf20e commit 451a745

2 files changed

Lines changed: 28 additions & 1 deletion

File tree

libp2p/protocols/service_discovery/registrar.nim

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,8 @@ proc updateWaitAfterRetry*(
243243
disco: ServiceDiscovery, ticketOpt: Opt[Ticket], now: Moment, wait: var Duration
244244
) =
245245
ticketOpt.withValue(ticket):
246-
let totalWaitSoFar = now - ticket.tInit.get()
246+
#Always use seconds granularity
247+
let totalWaitSoFar = Moment.init(now.epochSeconds, Second) - ticket.tInit.get()
247248
wait -= totalWaitSoFar
248249

249250
proc isValidTicket(

tests/libp2p/service_discovery/test_registrar.nim

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -898,6 +898,32 @@ suite "Service Discovery Registrar - Retry Ticket Processing":
898898
# totalWaitSoFar = 150 ± 1; tRemaining = 150 ± 1
899899
check abs(tWait.secs - 150) <= 1
900900

901+
test "updateWaitAfterRetry floors elapsed time to whole seconds":
902+
# `now` carries a sub-second part (700 ms). With seconds granularity the
903+
# deducted elapsed time is floored to a whole second; using raw `now`
904+
# instead would deduct the fractional part and leave a sub-second wait.
905+
let disco = setupServiceDiscoveryNode()
906+
let ad = makeAdvertisement(addrs = @[makeMultiAddress("10.0.0.1")])
907+
let adBuf = ad.encode().get()
908+
909+
# tInit sits on a whole-second boundary; now is 150.7s ahead of it.
910+
let tInit = initMoment(1_000_000)
911+
let now = initMoment(1_000_150) + 700.millis # now.epochSeconds == 1_000_150
912+
var ticket = Ticket(
913+
advertisement: adBuf,
914+
tInit: tInit,
915+
tMod: tInit,
916+
tWaitFor: 0.secs,
917+
signature: Opt.none(seq[byte]),
918+
)
919+
920+
var tWait = 300.secs
921+
disco.updateWaitAfterRetry(Opt.some(ticket), now, tWait)
922+
923+
# Seconds granularity: deduct 150s → wait = 150s exactly (a whole second).
924+
# Raw `now`: deduct 150.7s → wait = 149.3s, which would fail this check.
925+
check tWait == 150.secs
926+
901927
suite "Service Discovery Registrar - registration rejects invalid tickets":
902928
# These tests exercise the full registration() path (not just the helper).
903929
# Cryptographically invalid tickets must produce Rejected and must never

0 commit comments

Comments
 (0)