Budget registration per address; embed difficulty; expiry queue; 404 on empty withdraw

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Heimdall 2026-11-11 09:34:44 +00:00
commit e67257c750
11 changed files with 368 additions and 36 deletions

View file

@ -27,7 +27,9 @@ public sealed class RegistrationChallengeService(
private const int MaxNonceLength = 20;
private readonly IDataProtector protector = dataProtection.CreateProtector(Purpose);
private readonly Dictionary<string, DateTimeOffset> consumed = new(StringComparer.Ordinal);
private readonly HashSet<string> consumed = new(StringComparer.Ordinal);
// Ordered by expiry: a challenge consumed late has an earlier expiry than one consumed before it, so a plain FIFO would strand it.
private readonly PriorityQueue<string, DateTimeOffset> expiries = new();
private readonly object gate = new();
private int Difficulty => options.Value.Captcha.Difficulty;
@ -46,9 +48,10 @@ public sealed class RegistrationChallengeService(
}
var expiresAt = now + Lifetime;
var difficulty = Difficulty;
var id = Convert.ToHexString(RandomNumberGenerator.GetBytes(16));
var challenge = protector.Protect($"{id}.{expiresAt.ToUnixTimeMilliseconds()}");
return new RegistrationChallenge(challenge, Difficulty, expiresAt);
var challenge = protector.Protect($"{id}.{expiresAt.ToUnixTimeMilliseconds()}.{difficulty}");
return new RegistrationChallenge(challenge, difficulty, expiresAt);
}
public bool TryConsume(string? challenge, string? nonce)
@ -59,16 +62,18 @@ public sealed class RegistrationChallengeService(
}
string id;
int difficulty;
DateTimeOffset expiresAt;
try
{
var payload = protector.Unprotect(challenge).Split('.');
if (payload.Length != 2)
if (payload.Length != 3)
{
return false;
}
id = payload[0];
difficulty = int.Parse(payload[2], System.Globalization.CultureInfo.InvariantCulture);
expiresAt = DateTimeOffset.FromUnixTimeMilliseconds(long.Parse(payload[1], System.Globalization.CultureInfo.InvariantCulture));
}
catch (Exception)
@ -83,7 +88,7 @@ public sealed class RegistrationChallengeService(
}
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(challenge + ":" + nonce));
if (LeadingZeroBits(hash) < Difficulty)
if (LeadingZeroBits(hash) < difficulty)
{
return false;
}
@ -91,20 +96,21 @@ public sealed class RegistrationChallengeService(
lock (gate)
{
Purge(now);
if (consumed.Count >= MaxConsumed || consumed.ContainsKey(id))
if (consumed.Count >= MaxConsumed || !consumed.Add(id))
{
return false;
}
consumed[id] = expiresAt;
expiries.Enqueue(id, expiresAt);
return true;
}
}
private void Purge(DateTimeOffset now)
{
foreach (var id in consumed.Where(x => x.Value <= now).Select(x => x.Key).ToList())
while (expiries.TryPeek(out var id, out var expiresAt) && expiresAt <= now)
{
expiries.Dequeue();
consumed.Remove(id);
}
}