Sealed ballot: freeze the reveal set at close (RevealSeq token), HTTP tests for replay/non-voter/late reveal/close, doc corrected on the ballot schema
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
96da1b7a8c
commit
264233e08f
8 changed files with 281 additions and 15 deletions
|
|
@ -1,7 +1,7 @@
|
|||
# Sealed-ballot motions
|
||||
|
||||
A blind choice among named candidates (first use: which Mind writes the swarm's story). Commit-reveal, one atomic
|
||||
publication at close, no mediator. Code: `Features/Motions/SealedBallotService.cs`. Ballot type: `gamecult.sealed_ballot.v0`.
|
||||
publication at close, no mediator. Code: `Features/Motions/SealedBallotService.cs`. Ballot shape: the JSON record `SealedBallotDocument` carrying the string constant `gamecult.sealed_ballot.v0`.
|
||||
|
||||
## Protocol
|
||||
|
||||
|
|
@ -14,13 +14,19 @@ publication at close, no mediator. Code: `Features/Motions/SealedBallotService.c
|
|||
page, audit event or export until close.
|
||||
4. **Close** at the reveal deadline, mechanically: the first read of `/result` after the deadline, or the once-a-minute
|
||||
`SealedBallotCloser` sweep if nobody reads, writes status `Closed` and a digest of all commitments, then returns every revealed ballot (voter, candidate, one-sentence reason, salt, commitment) at
|
||||
once. Anyone can recompute each commitment from the published fields. Nobody can close early, extend, edit or break a tie.
|
||||
once. The close freezes the reveal set: `Motion.RevealSeq` (bumped by every accepted reveal) and `Status` are concurrency
|
||||
tokens, so a reveal racing the close either lands before it (the close re-reads and its digest covers that reveal) or is
|
||||
refused with 409; the digest covers `reveals:<RevealSeq>` plus every commitment's revealed/unrevealed state. A reveal after
|
||||
the deadline or after close is refused. Anyone can recompute each commitment from the published fields. Nobody can close early, extend, edit or break a tie.
|
||||
|
||||
Canonical document (`gamecult.sealed_ballot.v0`): `{schema, motionId, round, candidate, reason, salt}`. Commitment =
|
||||
`sha256(utf8("gamecult.sealed_ballot.v0\n{motionId}\n{voterUserAccountId}\n{round}\n{candidate}\n{reason}\n{salt}"))`, lowercase
|
||||
hex. `salt` is 32 to 128 hex characters (128 bits at least) the voter generates and keeps; without it a four-candidate hash is
|
||||
guessable. The voter's account id is in the hash, so a commitment cannot be replayed by another member. A Delphi second round
|
||||
is another motion carrying the same document type with `round` + 1 and `priorMotionId`.
|
||||
guessable. The voter's account id is in the hash, so a commitment cannot be replayed by another member. `gamecult.sealed_ballot.v0` is only a string
|
||||
constant on a JSON record (`SealedBallotDocument`); it is **not** a CultCache or CultNet schema, and nothing here registers
|
||||
one. A second Delphi round is modelled as another motion (`Round` and `PriorMotionId` columns) whose ballots have the same JSON
|
||||
shape. A real typed document schema, with CultCache/CultNet registration so a round-two ballot is the same registered type, is
|
||||
a follow-up (Bifrost issue linked in the PR).
|
||||
|
||||
## Decisions
|
||||
|
||||
|
|
|
|||
|
|
@ -278,6 +278,7 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
|
|||
entity.Property(x => x.Status).HasConversion<string>();
|
||||
entity.Property(x => x.ApprovalThreshold).HasPrecision(6, 3);
|
||||
entity.Property(x => x.Kind).HasConversion<string>();
|
||||
entity.Property(x => x.RevealSeq).IsConcurrencyToken();
|
||||
entity.Property(x => x.Status).IsConcurrencyToken();
|
||||
entity.HasOne(x => x.Project)
|
||||
.WithMany(x => x.Motions)
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ namespace Bifrost.Web.Data.Migrations
|
|||
migrationBuilder.AddColumn<string>(name: "Kind", table: "Motions", type: "text", nullable: false, defaultValue: "Standard");
|
||||
migrationBuilder.AddColumn<Guid>(name: "PriorMotionId", table: "Motions", type: "uuid", nullable: true);
|
||||
migrationBuilder.AddColumn<string>(name: "ResultDigest", table: "Motions", type: "text", nullable: false, defaultValue: "");
|
||||
migrationBuilder.AddColumn<int>(name: "RevealSeq", table: "Motions", type: "integer", nullable: false, defaultValue: 0);
|
||||
migrationBuilder.AddColumn<int>(name: "Round", table: "Motions", type: "integer", nullable: false, defaultValue: 1);
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
|
|
@ -50,7 +51,7 @@ namespace Bifrost.Web.Data.Migrations
|
|||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(name: "SealedBallots");
|
||||
foreach (var column in new[] { "Candidates", "CommitClosesAtUtc", "Kind", "PriorMotionId", "ResultDigest", "Round" })
|
||||
foreach (var column in new[] { "Candidates", "CommitClosesAtUtc", "Kind", "PriorMotionId", "ResultDigest", "RevealSeq", "Round" })
|
||||
{
|
||||
migrationBuilder.DropColumn(name: column, table: "Motions");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -929,6 +929,10 @@ namespace Bifrost.Web.Data.Migrations
|
|||
b.Property<DateTimeOffset?>("ResolvedAtUtc")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<int>("RevealSeq")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<string>("ResultDigest")
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
|
|
|||
|
|
@ -705,6 +705,10 @@ public sealed class Motion
|
|||
|
||||
public Guid? PriorMotionId { get; set; }
|
||||
|
||||
// Sealed-ballot motions only: bumped by every accepted reveal. A concurrency token, so a reveal and the close cannot both
|
||||
// succeed on the same row version: the close freezes exactly the reveals it counted.
|
||||
public int RevealSeq { get; set; }
|
||||
|
||||
// Sealed-ballot motions only: SHA-256 over the sorted commitments, written once at finalization.
|
||||
public string ResultDigest { get; set; } = string.Empty;
|
||||
|
||||
|
|
|
|||
|
|
@ -160,7 +160,17 @@ public sealed class SealedBallotService(
|
|||
ballot.RevealedReason = reason;
|
||||
ballot.Salt = document.Salt;
|
||||
ballot.RevealedAtUtc = now;
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
motion.RevealSeq++;
|
||||
try
|
||||
{
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
// The close froze the reveal set between the phase check and this write: this reveal is not in it.
|
||||
throw new SealedBallotException(SealedBallotFailure.WrongPhase, "The motion closed; the reveal window is over.");
|
||||
}
|
||||
|
||||
await auditTrailService.RecordAsync(
|
||||
user.Id, nameof(Motion), motionId, "sealed.revealed",
|
||||
$"{actor.DisplayName} submitted a reveal for commitment {ballot.Commitment}; content stays sealed until close.",
|
||||
|
|
@ -201,16 +211,27 @@ public sealed class SealedBallotService(
|
|||
throw new SealedBallotException(SealedBallotFailure.WrongPhase, "Ballots stay sealed until the motion closes.");
|
||||
}
|
||||
|
||||
var ballots = await dbContext.SealedBallots
|
||||
.Include(x => x.UserAccount).ThenInclude(x => x.MemberProfile)
|
||||
.Where(x => x.MotionId == motionId)
|
||||
.ToListAsync(cancellationToken);
|
||||
// Freeze: the close counts the reveals it read and succeeds only if no reveal landed since (RevealSeq is a concurrency
|
||||
// token); a conflict re-reads and retries, so the digest always covers exactly the set that is published.
|
||||
for (var attempt = 0; motion.Status == MotionStatus.Open && attempt < 5; attempt++)
|
||||
{
|
||||
var frozen = await dbContext.SealedBallots.AsNoTracking().Where(x => x.MotionId == motionId).ToListAsync(cancellationToken);
|
||||
if (await FinalizeAsync(motion, frozen, now, cancellationToken))
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (motion.Status == MotionStatus.Open)
|
||||
{
|
||||
await FinalizeAsync(motion, ballots, now, cancellationToken);
|
||||
throw new SealedBallotException(SealedBallotFailure.WrongPhase, "The close is contended; read again.");
|
||||
}
|
||||
|
||||
var ballots = await dbContext.SealedBallots.AsNoTracking()
|
||||
.Include(x => x.UserAccount).ThenInclude(x => x.MemberProfile)
|
||||
.Where(x => x.MotionId == motionId)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var revealed = ballots.Where(x => x.RevealedAtUtc != null).OrderBy(x => x.Id).ToList();
|
||||
var tally = CandidatesOf(motion)
|
||||
.Select(c => new SealedTally(c, revealed.Count(x => x.RevealedCandidate == c)))
|
||||
|
|
@ -251,10 +272,11 @@ public sealed class SealedBallotService(
|
|||
/// Closes the motion once. Motion.Status is a concurrency token, so of two racing closers exactly one SaveChanges wins;
|
||||
/// the loser reloads the winner's result and writes nothing (no second audit event).
|
||||
/// </summary>
|
||||
private async Task FinalizeAsync(Motion motion, List<SealedBallot> ballots, DateTimeOffset now, CancellationToken cancellationToken)
|
||||
private async Task<bool> FinalizeAsync(Motion motion, List<SealedBallot> ballots, DateTimeOffset now, CancellationToken cancellationToken)
|
||||
{
|
||||
var lines = ballots.OrderBy(x => x.UserAccountId)
|
||||
.Select(x => $"{x.UserAccountId:D}:{x.Commitment}:{(x.RevealedAtUtc != null ? "revealed" : "unrevealed")}");
|
||||
.Select(x => $"{x.UserAccountId:D}:{x.Commitment}:{(x.RevealedAtUtc != null ? "revealed" : "unrevealed")}")
|
||||
.Prepend($"reveals:{motion.RevealSeq}");
|
||||
motion.ResultDigest = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(string.Join('\n', lines)))).ToLowerInvariant();
|
||||
motion.Status = MotionStatus.Closed;
|
||||
motion.ResolvedAtUtc = now;
|
||||
|
|
@ -270,13 +292,14 @@ public sealed class SealedBallotService(
|
|||
await entry.ReloadAsync(cancellationToken);
|
||||
}
|
||||
|
||||
return;
|
||||
return motion.Status != MotionStatus.Open;
|
||||
}
|
||||
|
||||
await auditTrailService.RecordAsync(
|
||||
null, nameof(Motion), motion.Id, "sealed.closed",
|
||||
$"Closed sealed-ballot motion {motion.Title}; commitment digest {motion.ResultDigest}.",
|
||||
cancellationToken);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Closes every sealed-ballot motion whose deadline has passed, so a motion nobody reads still closes.</summary>
|
||||
|
|
@ -288,7 +311,7 @@ public sealed class SealedBallotService(
|
|||
.ToListAsync(cancellationToken);
|
||||
foreach (var motion in due)
|
||||
{
|
||||
var ballots = await dbContext.SealedBallots.Where(x => x.MotionId == motion.Id).ToListAsync(cancellationToken);
|
||||
var ballots = await dbContext.SealedBallots.AsNoTracking().Where(x => x.MotionId == motion.Id).ToListAsync(cancellationToken);
|
||||
await FinalizeAsync(motion, ballots, now, cancellationToken);
|
||||
}
|
||||
|
||||
|
|
|
|||
138
tests/Bifrost.Web.Tests/SealedBallotCloseHttpTests.cs
Normal file
138
tests/Bifrost.Web.Tests/SealedBallotCloseHttpTests.cs
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using Bifrost.Web.Data;
|
||||
using Bifrost.Web.Domain;
|
||||
using Bifrost.Web.Features.Motions;
|
||||
using Bifrost.Web.Tests.Support;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Bifrost.Web.Tests;
|
||||
|
||||
public sealed class SealedBallotCloseHttpTests(TestWebApplicationFactory factory) : IClassFixture<TestWebApplicationFactory>
|
||||
{
|
||||
private const string Salt = "00112233445566778899aabbccddeeff";
|
||||
private const string Reason = "Distinctive-close-reason-plugh.";
|
||||
private static int _next = 7000;
|
||||
|
||||
private sealed record W(Guid RevealA, Guid RevealB, Guid LateMotion, Guid ClosedWithBallot, string Ana, string Bo, string Cy);
|
||||
|
||||
private async Task<W> SeedAsync()
|
||||
{
|
||||
using (var warmup = factory.CreateClient()) { _ = await warmup.GetAsync("/App"); }
|
||||
var n = Interlocked.Add(ref _next, 10);
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
using var scope = factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<BifrostDbContext>();
|
||||
UserAccount Make(long gh, string name)
|
||||
{
|
||||
var u = new UserAccount { GitHubUserId = gh, GitHubLogin = name, NormalizedGitHubLogin = name.ToUpperInvariant(), DisplayName = name };
|
||||
u.MemberProfile = new MemberProfile { UserAccountId = u.Id, Nickname = name, Headline = "seed", UpdatedAtUtc = now };
|
||||
u.Membership = new Domain.Membership { UserAccountId = u.Id, Status = MembershipStatus.Active, CreatedAtUtc = now };
|
||||
Bifrost.Web.Features.Shared.ApplicationBootstrapper.EnsureRole(u.Membership, MemberRole.StandardMember, null, now, "seed");
|
||||
db.UserAccounts.Add(u);
|
||||
return u;
|
||||
}
|
||||
|
||||
var ana = Make(n + 1, $"ana{n}");
|
||||
Make(n + 2, $"bo{n}");
|
||||
Make(n + 3, $"cy{n}");
|
||||
Motion M(DateTimeOffset commitCloses, DateTimeOffset closes)
|
||||
{
|
||||
var m = new Motion
|
||||
{
|
||||
CreatedByUserAccountId = ana.Id, Scope = MotionScope.Management, Kind = MotionKind.SealedBallot, Title = "t", Summary = "s",
|
||||
Candidates = "Ana\nBo", OpensAtUtc = now.AddHours(-3), CommitClosesAtUtc = commitCloses, ClosesAtUtc = closes, CreatedAtUtc = now
|
||||
};
|
||||
db.Motions.Add(m);
|
||||
return m;
|
||||
}
|
||||
|
||||
var a = M(now.AddHours(-1), now.AddHours(1)); // reveal phase: Ana's real ballot
|
||||
var b = M(now.AddHours(-1), now.AddHours(1)); // reveal phase: Ana's commitment from A replayed here
|
||||
var late = M(now.AddHours(-2), now.AddHours(-1)); // past deadline, Ana committed and never revealed
|
||||
var done = M(now.AddHours(-2), now.AddHours(-1)); // past deadline, Ana's reveal is in
|
||||
string Commit(Guid motion) => SealedBallotDocument.Commit(new(SealedBallotDocument.SchemaId, motion, 1, "Bo", Reason, Salt), ana.Id);
|
||||
db.SealedBallots.Add(new SealedBallot { MotionId = a.Id, UserAccountId = ana.Id, CommittedAtUtc = now.AddHours(-2), Commitment = Commit(a.Id) });
|
||||
db.SealedBallots.Add(new SealedBallot { MotionId = b.Id, UserAccountId = ana.Id, CommittedAtUtc = now.AddHours(-2), Commitment = Commit(a.Id) });
|
||||
db.SealedBallots.Add(new SealedBallot { MotionId = late.Id, UserAccountId = ana.Id, CommittedAtUtc = now.AddHours(-3), Commitment = Commit(late.Id) });
|
||||
db.SealedBallots.Add(new SealedBallot
|
||||
{
|
||||
MotionId = done.Id, UserAccountId = ana.Id, CommittedAtUtc = now.AddHours(-3), Commitment = Commit(done.Id),
|
||||
RevealedCandidate = "Bo", RevealedReason = Reason, Salt = Salt, RevealedAtUtc = now.AddHours(-1.5)
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
return new W(a.Id, b.Id, late.Id, done.Id, (n + 1).ToString(), (n + 2).ToString(), (n + 3).ToString());
|
||||
}
|
||||
|
||||
private HttpClient As(string id, string login)
|
||||
{
|
||||
var c = factory.CreateClient();
|
||||
c.DefaultRequestHeaders.Add("X-Test-GitHub-Id", id);
|
||||
c.DefaultRequestHeaders.Add("X-Test-GitHub-Login", login);
|
||||
return c;
|
||||
}
|
||||
|
||||
private static SealedBallotDocument Doc(Guid motion) => new(SealedBallotDocument.SchemaId, motion, 1, "Bo", Reason, Salt);
|
||||
|
||||
private static async Task Refused(HttpResponseMessage r, HttpStatusCode expected)
|
||||
{
|
||||
var body = await r.Content.ReadAsStringAsync();
|
||||
Assert.True(r.StatusCode == expected, $"{r.StatusCode}: {body}");
|
||||
Assert.DoesNotContain(Reason, body);
|
||||
Assert.DoesNotContain(Salt, body);
|
||||
Assert.DoesNotContain("\"Bo\"", body);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_commit_or_reveal_replayed_into_another_motion_is_refused()
|
||||
{
|
||||
var w = await SeedAsync();
|
||||
var ana = As(w.Ana, "ana");
|
||||
// A's document aimed at B: wrong motion id inside, and B's stored commitment is A's hash, which no B-bound document reproduces.
|
||||
await Refused(await ana.PostAsJsonAsync($"/api/sealed-motions/{w.RevealB}/reveal", Doc(w.RevealA)), HttpStatusCode.BadRequest);
|
||||
await Refused(await ana.PostAsJsonAsync($"/api/sealed-motions/{w.RevealB}/reveal", Doc(w.RevealB)), HttpStatusCode.BadRequest);
|
||||
// A's commit hash sent into a motion that is no longer in its commit window.
|
||||
await Refused(await ana.PostAsJsonAsync($"/api/sealed-motions/{w.RevealB}/commit", new { commitment = new string('a', 64) }), HttpStatusCode.Conflict);
|
||||
Assert.Equal(HttpStatusCode.OK, (await ana.PostAsJsonAsync($"/api/sealed-motions/{w.RevealA}/reveal", Doc(w.RevealA))).StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_non_voter_cannot_reveal()
|
||||
{
|
||||
var w = await SeedAsync();
|
||||
await Refused(await As(w.Cy, "cy").PostAsJsonAsync($"/api/sealed-motions/{w.RevealA}/reveal", Doc(w.RevealA)), HttpStatusCode.NotFound);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_reveal_after_the_deadline_is_refused_and_the_voter_is_shown_unrevealed()
|
||||
{
|
||||
var w = await SeedAsync();
|
||||
var ana = As(w.Ana, "ana");
|
||||
await Refused(await ana.PostAsJsonAsync($"/api/sealed-motions/{w.LateMotion}/reveal", Doc(w.LateMotion)), HttpStatusCode.Conflict);
|
||||
var result = await As(w.Bo, "bo").GetAsync($"/api/sealed-motions/{w.LateMotion}/result");
|
||||
var body = await result.Content.ReadAsStringAsync();
|
||||
Assert.True(result.StatusCode == HttpStatusCode.OK, body);
|
||||
Assert.Contains("committed but did not reveal", body);
|
||||
Assert.DoesNotContain(Reason, body);
|
||||
// Still refused after the close has run, and the published result did not change.
|
||||
await Refused(await ana.PostAsJsonAsync($"/api/sealed-motions/{w.LateMotion}/reveal", Doc(w.LateMotion)), HttpStatusCode.Conflict);
|
||||
Assert.Equal(body, await (await As(w.Cy, "cy").GetAsync($"/api/sealed-motions/{w.LateMotion}/result")).Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Close_with_ballots_publishes_them_once_with_a_stable_digest()
|
||||
{
|
||||
var w = await SeedAsync();
|
||||
var first = await (await As(w.Bo, "bo").GetAsync($"/api/sealed-motions/{w.ClosedWithBallot}/result")).Content.ReadAsStringAsync();
|
||||
Assert.Contains(Reason, first);
|
||||
Assert.Contains(Salt, first);
|
||||
Assert.Contains("\"outcome\":\"winner\"", first);
|
||||
var second = await (await As(w.Cy, "cy").GetAsync($"/api/sealed-motions/{w.ClosedWithBallot}/result")).Content.ReadAsStringAsync();
|
||||
Assert.Equal(first, second);
|
||||
|
||||
using var db = factory.Services.CreateScope().ServiceProvider.GetRequiredService<BifrostDbContext>();
|
||||
Assert.Equal(1, await db.AuditEvents.CountAsync(x => x.Action == "sealed.closed" && x.EntityId == w.ClosedWithBallot.ToString()));
|
||||
Assert.Equal(MotionStatus.Closed, (await db.Motions.SingleAsync(x => x.Id == w.ClosedWithBallot)).Status);
|
||||
}
|
||||
}
|
||||
|
|
@ -4,6 +4,9 @@ using Bifrost.Web.Domain;
|
|||
using Bifrost.Web.Features.Motions;
|
||||
using Bifrost.Web.Features.Shared;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Bifrost.Web.Tests;
|
||||
|
||||
|
|
@ -268,4 +271,90 @@ public sealed class SealedBallotTests
|
|||
Assert.Equal(0, await rig.Service.FinalizeDueAsync(default));
|
||||
Assert.Equal(1, await rig.Db.AuditEvents.CountAsync(x => x.Action == "sealed.closed"));
|
||||
}
|
||||
|
||||
// Runs a callback once, just before the first save that closes a motion: the window between the close reading its ballots and writing.
|
||||
private sealed class BeforeCloseSave(Func<Task> action) : SaveChangesInterceptor
|
||||
{
|
||||
private bool _done;
|
||||
|
||||
public override async ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!_done && eventData.Context!.ChangeTracker.Entries<Motion>().Any(e => e.State == EntityState.Modified && e.Entity.Status == MotionStatus.Closed))
|
||||
{
|
||||
_done = true;
|
||||
await action();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
private static (BifrostDbContext Db, Clock Clock, SealedBallotService Service) Peer(string name, DateTimeOffset at, IInterceptor? interceptor = null)
|
||||
{
|
||||
var clock = new Clock(at);
|
||||
var options = new DbContextOptionsBuilder<BifrostDbContext>().UseInMemoryDatabase(name);
|
||||
if (interceptor is not null) options.AddInterceptors(interceptor);
|
||||
var db = new BifrostDbContext(options.Options);
|
||||
return (db, clock, new SealedBallotService(db, new AuditTrailService(db, clock), clock));
|
||||
}
|
||||
|
||||
private static async Task<(CurrentBifrostActor Actor, SealedMotionState Motion)> SeedPeerWorld(BifrostDbContext db, SealedBallotService service)
|
||||
{
|
||||
var user = new UserAccount { DisplayName = "Ana", GitHubLogin = "ana", BifrostIdentity = "ana", NormalizedBifrostIdentity = "ANA", NormalizedGitHubLogin = "ANA" };
|
||||
user.Membership = new Membership { UserAccountId = user.Id, Status = MembershipStatus.Active, CanModerateMotions = true };
|
||||
db.UserAccounts.Add(user);
|
||||
await db.SaveChangesAsync();
|
||||
var actor = new CurrentBifrostActor(true, user);
|
||||
var motion = await service.OpenAsync(actor, new OpenSealedMotionCommand("t", "s", ["Ana", "Bo"], T0.AddHours(1), T0.AddHours(2)), default);
|
||||
var doc = new SealedBallotDocument(SealedBallotDocument.SchemaId, motion.Id, 1, "Ana", "Mine.", Salt);
|
||||
await service.CommitAsync(actor, motion.Id, SealedBallotDocument.Commit(doc, user.Id), default);
|
||||
return (actor, motion);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_reveal_that_loses_the_race_to_the_close_is_refused_and_is_not_in_the_frozen_set()
|
||||
{
|
||||
var name = $"sealed-freeze-a-{Guid.NewGuid():N}";
|
||||
var closer = Peer(name, T0);
|
||||
var (actor, motion) = await SeedPeerWorld(closer.Db, closer.Service);
|
||||
closer.Clock.Now = T0.AddMinutes(90);
|
||||
var revealer = Peer(name, T0.AddMinutes(90)); // its clock still says "reveal window"
|
||||
_ = await revealer.Db.Motions.ToListAsync(); // and it holds a stale, Open copy of the motion
|
||||
|
||||
closer.Clock.Now = T0.AddHours(3);
|
||||
var result = await closer.Service.GetResultAsync(actor, motion.Id, default);
|
||||
Assert.Empty(result.Ballots);
|
||||
|
||||
var ex = await Assert.ThrowsAsync<SealedBallotException>(() =>
|
||||
revealer.Service.RevealAsync(actor, motion.Id, new SealedBallotDocument(SealedBallotDocument.SchemaId, motion.Id, 1, "Ana", "Mine.", Salt), default));
|
||||
Assert.Equal(SealedBallotFailure.WrongPhase, ex.Failure);
|
||||
|
||||
await using var check = Peer(name, T0.AddHours(4)).Db;
|
||||
Assert.Null((await check.SealedBallots.AsNoTracking().SingleAsync()).RevealedAtUtc);
|
||||
Assert.Equal(result.CommitmentDigest, (await check.Motions.AsNoTracking().SingleAsync()).ResultDigest);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_close_that_read_before_a_reveal_landed_retries_and_the_digest_covers_that_reveal()
|
||||
{
|
||||
var name = $"sealed-freeze-b-{Guid.NewGuid():N}";
|
||||
var revealer = Peer(name, T0);
|
||||
var (actor, motion) = await SeedPeerWorld(revealer.Db, revealer.Service);
|
||||
revealer.Clock.Now = T0.AddMinutes(90);
|
||||
var doc = new SealedBallotDocument(SealedBallotDocument.SchemaId, motion.Id, 1, "Ana", "Mine.", Salt);
|
||||
// The reveal lands after the close read its ballots and before the close wrote.
|
||||
var closer = Peer(name, T0.AddHours(3), new BeforeCloseSave(() => revealer.Service.RevealAsync(actor, motion.Id, doc, default)));
|
||||
|
||||
var result = await closer.Service.GetResultAsync(actor, motion.Id, default);
|
||||
|
||||
Assert.Single(result.Ballots);
|
||||
Assert.Empty(result.Unrevealed);
|
||||
await using var check = Peer(name, T0.AddHours(4)).Db;
|
||||
var stored = await check.Motions.AsNoTracking().SingleAsync();
|
||||
Assert.Equal(1, stored.RevealSeq);
|
||||
var ballot = await check.SealedBallots.AsNoTracking().SingleAsync();
|
||||
var expected = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes($"reveals:1\n{ballot.UserAccountId:D}:{ballot.Commitment}:revealed"))).ToLowerInvariant();
|
||||
Assert.Equal(expected, stored.ResultDigest); // the digest covers the reveal that raced the close
|
||||
Assert.Equal(1, await check.AuditEvents.CountAsync(x => x.Action == "sealed.closed"));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue