1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597 | // BANK/1's settlement fold, against test/vectors/fold.json.
//
// Every expectation in that fixture is HAND-COMPUTED beside an `input_desc`
// sentence a reader can check by adding up four numbers; every signature in it
// was produced by @noble/curves in test/vectors/independent.mjs. Nothing in the
// fixture was read out of the implementation, which is the only reason any of
// this counts as evidence.
//
// Two kinds of claim are under test:
//
// · the SETTLEMENT RULES — who wins a slot, what a failure costs, what an ack
// buys — checked scenario by scenario against hand-computed balances;
// · ORDER INDEPENDENCE, which needs no expectation at all: the same entry set
// in three fixed insertion orders must produce a byte-identical snapshot.
// That is the property that keeps two replicas from ever partitioning, and
// it is asserted for EVERY scenario rather than for a chosen few.
//
// Both run against test-dist/testlib.js — the built output — never src/.
import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import * as L from "../test-dist/testlib.js";
import { permutations, makeOrder, entry, opOpen, opPay, CUR, SEED_PAYER, TS_FIXED } from "./vectors/independent.mjs";
const V = JSON.parse(readFileSync(new URL("./vectors/fold.json", import.meta.url), "utf8"));
const A = V.actors;
const BANK = A.bank;
/** idPub -> label, so a failure message reads as words. */
const P2L = Object.fromEntries(Object.entries(A).map(([k, v]) => [v, k]));
const label = (pub) => (pub === null || pub === undefined ? null : P2L[pub] ?? pub);
/** A fresh fold over `entries`, with every order signature verified. */
async function fold(entries, bankerPub = BANK) {
const f = new L.BankFold(bankerPub, null);
for (const e of structuredClone(entries)) f.ingest(e);
await f.awaitVerified();
return f;
}
const snapOf = async (entries, bankerPub) => (await fold(entries, bankerPub)).snapshot();
/**
* The snapshot with every idPub swapped for its label — what the fixture speaks.
*
* EVERY FIELD OF THE SNAPSHOT IS HERE, and it has to be: this projection is what
* the scenario `deepEqual` sees, so a field it drops is a field no scenario
* covers however many scenarios there are. `charter`, `banker`, the `bal` Number
* beside `balExact`, the account `name` and `iseq` were dropped, so they were
* covered only incidentally — the banker's account name, for one, is the empty
* string in every scenario and nothing said so.
*/
function labelled(s) {
return {
ok: s.ok,
banker: label(s.banker),
cur: s.cur,
charter: s.charter,
supplyExact: s.supplyExact,
supply: s.supply,
iseq: s.iseq,
rate: s.rate,
accounts: s.accounts.map((a) => label(a.id)),
names: Object.fromEntries(s.accounts.map((a) => [label(a.id), a.name])),
balances: Object.fromEntries(s.accounts.map((a) => [label(a.id), a.balExact])),
// what each account has OUT in escrow. Zero everywhere in BANK/1, and
// asserted as zero rather than omitted: `supply` is Σ bal + Σ locked, so a
// projection that dropped this could not tell a conserved fold from a leaky
// one. The escrow scenarios live in test/escrow.test.mjs.
locked: Object.fromEntries(s.accounts.map((a) => [label(a.id), a.lockedExact])),
// the Number projection beside the exact one — a rounding above 2^53, and
// the fixture is where you find out which you got
bals: Object.fromEntries(s.accounts.map((a) => [label(a.id), a.bal])),
seqs: Object.fromEntries(s.accounts.map((a) => [label(a.id), a.seq])),
states: Object.fromEntries(s.accounts.map((a) => [label(a.id), a.state])),
payments: s.payments.map((p) => ({
h: p.h, kind: p.kind, actor: label(p.actor), to: label(p.to),
amt: p.amt, seq: p.seq, status: p.status, acked: p.acked, why: p.why,
})),
escrows: s.escrows.map((e) => ({
h: e.h, from: label(e.from), to: label(e.to), amt: e.amt, status: e.status,
})),
pending: s.pending.map((p) => ({ id: label(p.id), name: p.name })),
reqs: s.reqs.map((r) => ({
h: r.h, from: label(r.from), to: label(r.to), amt: r.amt, memo: r.memo, ts: r.ts, clock: r.clock,
})),
};
}
// ---- the scenarios ----------------------------------------------------------
for (const sc of V.scenarios) {
test(`fold: ${sc.name}`, async () => {
const got = labelled(await snapOf(sc.entries));
const want = { ...sc.expect };
assert.deepEqual(got, want, sc.input_desc);
});
}
test("every scenario folds identically in three insertion orders", async () => {
// ORDER INDEPENDENCE. The fold is a pure function of the ENTRY SET, so the
// arrival order of live replication, a device-local replay and a mailbox
// delivery cannot change what anyone believes about the money. Three
// permutations rather than two, because "as given" and "reversed" alone would
// not catch a fold that happened to be symmetric.
for (const sc of V.scenarios) {
const [a, b, c] = permutations(sc.entries);
const [sa, sb, scz] = await Promise.all([snapOf(a), snapOf(b), snapOf(c)]);
assert.equal(JSON.stringify(sb), JSON.stringify(sa), `${sc.name}: reversed`);
assert.equal(JSON.stringify(scz), JSON.stringify(sa), `${sc.name}: stride-3`);
}
});
test("the order-independence check is not vacuous", () => {
// The probe the property owes: permutations() must actually permute, and
// JSON.stringify over this shape must actually be sensitive to a difference.
const xs = [1, 2, 3, 4, 5, 6, 7];
const [p0, p1, p2] = permutations(xs);
assert.deepEqual(p0, xs);
assert.notDeepEqual(p1, xs);
assert.notDeepEqual(p2, xs);
assert.deepEqual([...p2].sort(), [...xs].sort(), "a permutation must keep the same multiset");
// and an order-DEPENDENT function over the same inputs must be caught
const first = (ys) => JSON.stringify(ys[0]);
assert.notEqual(first(p1), first(p0));
});
test("the scenario comparison is sensitive — a perturbed expectation fails", async () => {
// Every scenario above is a deepEqual against a hand-written expectation. If
// the comparison silently ignored a field, every scenario would pass and the
// suite would be decoration. Perturb five different fields of one real
// snapshot; each must be caught.
const sc = V.scenarios.find((s) => s.name === "double-spend-unacked");
const base = labelled(await snapOf(sc.entries));
assert.deepEqual(base, sc.expect);
const clone = () => JSON.parse(JSON.stringify(base));
const bal = clone(); bal.balances.payer = "401";
assert.notDeepEqual(bal, sc.expect, "a one-unit balance drift must be caught");
const status = clone(); status.payments[2].status = "settled";
assert.notDeepEqual(status, sc.expect, "a flipped payment status must be caught");
const why = clone(); why.payments[2].why = "insufficient";
assert.notDeepEqual(why, sc.expect, "a changed decline reason must be caught");
const seq = clone(); seq.seqs.payer = 0;
assert.notDeepEqual(seq, sc.expect, "a released slot must be caught");
const order = clone(); [order.payments[1], order.payments[2]] = [order.payments[2], order.payments[1]];
assert.notDeepEqual(order, sc.expect, "a reordered payments array must be caught");
const supply = clone(); supply.supplyExact = "1001";
assert.notDeepEqual(supply, sc.expect, "a supply drift must be caught");
// the four fields the projection used to DROP, so no scenario covered them
const charter = clone(); charter.charter.join = "open";
assert.notDeepEqual(charter, sc.expect, "a changed join policy must be caught");
const banker = clone(); banker.banker = "bank2";
assert.notDeepEqual(banker, sc.expect, "a changed banker must be caught");
const name = clone(); name.names.bank = "Banca Test";
assert.notDeepEqual(name, sc.expect, "an account name must be caught — the banker's is \"\"");
const num = clone(); num.bals.payer = 401;
assert.notDeepEqual(num, sc.expect, "the Number projection must be caught too, not just the exact one");
const iseq = clone(); iseq.iseq = 0;
assert.notDeepEqual(iseq, sc.expect, "the issuance counter must be caught");
});
test("the projection the scenarios compare drops NOTHING from the snapshot", async () => {
// The gap that let `charter`, `banker`, `bal` and the account `name` go
// uncovered by twenty scenarios: `labelled()` built its own object, so a key
// it forgot was a key no deepEqual could ever see. Assert the cover directly.
const s = await snapOf(V.scenarios.find((x) => x.name === "prelude").entries);
const got = new Set(Object.keys(labelled(s)));
assert.deepEqual(Object.keys(s).filter((k) => !got.has(k)), [],
"every top-level snapshot key must reach the fixture comparison");
// …and every per-account field, each under the name the fixture gives it
assert.deepEqual(Object.keys(s.accounts[0]).sort(),
["bal", "balExact", "id", "locked", "lockedExact", "name", "seq", "state"]);
for (const k of ["accounts", "names", "balances", "bals", "seqs", "states", "locked", "escrows"]) {
assert.ok(got.has(k), k);
}
});
// ---- the two rules, stated as their own tests -------------------------------
test("RULE 1: a failed winner keeps its slot, and a later mint cannot resurrect it", async () => {
// The scenario proves the balances; this states the rule the scenario is for,
// so a future reader deleting the fixture row knows what they are deleting.
const sc = V.scenarios.find((s) => s.name === "overdraft-consumes-the-slot");
const s = await snapOf(sc.entries);
const over = s.payments.find((p) => p.h === "h09");
const retry = s.payments.find((p) => p.h === "h11");
assert.equal(over.status, "failed");
assert.equal(over.why, "insufficient");
assert.equal(retry.status, "failed");
assert.equal(retry.why, "seq", "the retry must lose the SLOT, not the balance check");
// the payer is rich now and the payment is still dead
assert.equal(s.accounts.find((a) => a.id === A.payer).balExact, "10000");
assert.equal(s.accounts.find((a) => a.id === A.payee).balExact, "0");
});
test("RULE 2: a dead banker key leaves the bank limping, not bricked", async () => {
// Everything after the charter is customer traffic. Provisional settlement
// keeps working with no banker act of any kind; nothing finalises and nothing
// new is minted, which is the trade this design makes on purpose.
const sc = V.scenarios.find((s) => s.name === "settled-provisionally");
const s = await snapOf(sc.entries);
assert.equal(s.accounts.find((a) => a.id === A.payee).balExact, "250");
assert.equal(s.payments.find((p) => p.h === "h09").status, "settled");
assert.equal(s.payments.find((p) => p.h === "h09").acked, false);
// and the same set WITH an ack settles the same money, only irreversibly
const acked = V.scenarios.find((x) => x.name === "acked-is-final");
const s2 = await snapOf(acked.entries);
assert.equal(s2.accounts.find((a) => a.id === A.payee).balExact, "250");
assert.equal(s2.payments.find((p) => p.h === "h09").status, "final");
});
test("an ack changes finality and NOTHING about the money", async () => {
const a = await snapOf(V.scenarios.find((s) => s.name === "settled-provisionally").entries);
const b = await snapOf(V.scenarios.find((s) => s.name === "acked-is-final").entries);
const bals = (s) => s.accounts.map((x) => [x.id, x.balExact]);
assert.deepEqual(bals(b), bals(a));
assert.equal(a.supplyExact, b.supplyExact);
assert.notEqual(
a.payments.find((p) => p.h === "h09").status,
b.payments.find((p) => p.h === "h09").status,
);
});
test("the ack is what flips a contested slot, and only the ack", async () => {
// The sharpest pair in the fixture: the same two competing orders, differing
// by one `ack` on the one that LOST the (clock, hash) race.
const un = V.scenarios.find((s) => s.name === "double-spend-unacked");
const ac = V.scenarios.find((s) => s.name === "ack-pins-the-clock-loser");
assert.equal(ac.entries.length, un.entries.length + 1);
assert.equal(ac.entries.at(-1).op.t, "ack");
const [a, b] = [await snapOf(un.entries), await snapOf(ac.entries)];
assert.equal(a.payments.find((p) => p.h === "h09").status, "settled");
assert.equal(b.payments.find((p) => p.h === "h09").status, "failed");
assert.equal(a.payments.find((p) => p.h === "h10").status, "failed");
assert.equal(b.payments.find((p) => p.h === "h10").status, "final");
// exactly 600 moves in both — the ack redirects it, it does not create it
assert.equal(a.supplyExact, b.supplyExact);
});
test("a withheld back-dated entry is bounded by an ack, whenever it arrives", async () => {
const no = V.scenarios.find((s) => s.name === "withheld-backdated-no-ack");
const yes = V.scenarios.find((s) => s.name === "withheld-backdated-after-ack");
// without an ack the withheld entry wins on clock alone and displaces a
// payment everyone had acted on
const a = await snapOf(no.entries);
assert.equal(a.payments.find((p) => p.h === "h08a").status, "settled");
assert.equal(a.payments.find((p) => p.h === "h09").status, "failed");
// with one, it cannot — and "arriving before or after the ack" is not a
// distinguishable event: the fold is a function of the SET
const withheld = yes.entries.find((e) => e.hash === "h08a");
const rest = yes.entries.filter((e) => e.hash !== "h08a");
const first = await snapOf([withheld, ...rest]);
const last = await snapOf([...rest, withheld]);
assert.equal(JSON.stringify(first), JSON.stringify(last));
assert.equal(last.payments.find((p) => p.h === "h09").status, "final");
assert.equal(last.payments.find((p) => p.h === "h08a").status, "failed");
assert.equal(last.payments.find((p) => p.h === "h08a").why, "seq");
});
// ---- authorization ----------------------------------------------------------
test("`pay` is authorized by po.sig; every banker op by entry authorship", async () => {
const relay = V.scenarios.find((s) => s.name === "third-party-relay");
const direct = V.scenarios.find((s) => s.name === "settled-provisionally");
const [r, d] = [await snapOf(relay.entries), await snapOf(direct.entries)];
// the same order, appended by two different people, settles identically
assert.deepEqual(r.accounts.map((a) => a.balExact), d.accounts.map((a) => a.balExact));
// and the ACTOR is the payer, never the appender
assert.equal(r.payments.find((p) => p.h === "h09").actor, A.payer);
assert.equal(relay.entries.at(-1).from, A.third, "the fixture must really be relayed");
});
test("an unverifiable order is not an order at all", async () => {
const sc = V.scenarios.find((s) => s.name === "forged-order-is-not-an-order");
const s = await snapOf(sc.entries);
assert.equal(s.payments.find((p) => p.h === "h09"), undefined, "it must not even be recorded as failed");
assert.equal(s.accounts.find((a) => a.id === A.payer).seq, 0, "and it must not consume a slot");
});
test("a customer cannot mint, burn, approve, ack or set a rate", async () => {
const bad = V.scenarios.find((s) => s.name === "banker-only-ops-from-a-customer");
const base = V.scenarios.find((s) => s.name === "prelude");
// byte-identical to the prelude: five forged authority ops change nothing
assert.equal(JSON.stringify(await snapOf(bad.entries)), JSON.stringify(await snapOf(base.entries)));
assert.equal(bad.entries.length, base.entries.length + 5, "the fixture must really carry five of them");
});
test("a bank with no banker in its link folds to nothing", async () => {
// Authority is a pure function of the link, so a malformed or absent
// bankerPub is a bank that does not exist — not a bank anyone can seize.
const sc = V.scenarios.find((s) => s.name === "prelude");
for (const badBanker of [null, "", "nope", A.bank.slice(0, 42), 7, {}]) {
const f = new L.BankFold(badBanker, null);
for (const e of structuredClone(sc.entries)) f.ingest(e);
await f.awaitVerified();
const s = f.snapshot();
assert.equal(s.ok, false, String(badBanker));
assert.deepEqual(s.accounts, []);
assert.equal(f.bankerPub, null);
}
// and a DIFFERENT valid key is simply a different (uncharted) bank
const other = await snapOf(sc.entries, A.bank2);
assert.equal(other.ok, false);
});
test("a suite identity is required to transact, but not to relay", async () => {
const sc = V.scenarios.find((s) => s.name === "identity-is-required-to-transact");
const s = await snapOf(sc.entries);
assert.equal(s.accounts.length, 4, "the fallback identity must not get an account");
assert.equal(s.accounts.some((a) => a.id === V.fallback_identity.id), false);
assert.deepEqual(s.reqs, [], "its `req` must be ignored");
// …and its RELAY of someone else's signed order settles, because a `pay` is
// authorized by po.sig and never by authorship
assert.equal(s.payments.find((p) => p.h === "h11").status, "settled");
assert.equal(s.payments.find((p) => p.h === "h11").actor, A.payer);
});
// ---- projections ------------------------------------------------------------
test("ingest drops a non-validating op rather than repairing it", async () => {
const base = V.scenarios.find((s) => s.name === "prelude");
const junk = [
{ hash: "z01", from: BANK, clock: 20, op: { t: "mint", ts: 1, seq: 1, to: A.payer, amt: 0 } },
{ hash: "z02", from: BANK, clock: 21, op: { t: "charter", ts: 1, name: "x", code: "GAZ", sym: "g", dec: 2, join: "open" } },
{ hash: "z03", from: BANK, clock: 22, op: null },
{ hash: "z04", from: BANK, clock: 23, op: { t: "mint", ts: 1, seq: 2, to: A.payer, amt: 5, extra: 1 } },
{ hash: null, from: BANK, clock: 24, op: { t: "open", ts: 1, name: "n" } },
];
const a = await snapOf(base.entries);
const b = await snapOf([...base.entries, ...junk]);
assert.equal(JSON.stringify(b), JSON.stringify(a));
});
// ---- the envelope is as untrusted as the op ---------------------------------
test("a hostile Lamport clock cannot make the fold depend on arrival order", async () => {
// F1, and it needs NO FORGERY. rooms-kit reads an entry's clock as
// `entry.clock?.time ?? 0` — a NULLISH coalesce, so any non-null value rides
// through — and @orbitdb/core signs `clock` verbatim while only checking that
// it is not undefined. So an ordinary member SIGNS an entry whose clock.time
// is "abc" and it verifies. `(a.clock - b.clock)` is then NaN, and
// Array.prototype.sort with a NaN comparator orders by INPUT PERMUTATION.
//
// The op below is a perfectly ordinary, valid `open`. One of them used to
// make the whole fold arrival-dependent — seven distinct states over 24
// arrival orders of one entry set, including states where a payment never
// happened and states where the MINT failed, so supply itself diverged.
const o1 = makeOrder({ seed: SEED_PAYER, idN: 0xb1, cur: CUR, amt: 100, seq: 1, to: A.payee });
const o2 = makeOrder({ seed: SEED_PAYER, idN: 0xb2, cur: CUR, amt: 900, seq: 1, to: A.payee });
const base = [
entry("b01", 1, BANK, { t: "charter", ts: TS_FIXED, name: "B", code: "LEI", sym: "L", dec: 2, join: "open" }),
entry("b02", 2, A.payer, opOpen(TS_FIXED, "Payer")),
entry("b03", 3, A.payee, opOpen(TS_FIXED, "Payee")),
entry("b04", 4, BANK, { t: "mint", ts: TS_FIXED, seq: 1, to: A.payer, amt: 1000 }),
// two contenders for payment slot (payer, 1)
entry("b05", 5, A.payer, opPay(TS_FIXED, o1)),
entry("b06", 6, A.payer, opPay(TS_FIXED, o2)),
];
/** 24 deterministic arrival orders. */
const shuffles = (xs) => {
let seed = 12345;
const rnd = () => ((seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff);
return Array.from({ length: 24 }, () => {
const a = [...xs];
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(rnd() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
});
};
const distinct = async (clock) => {
const es = [...base, entry("b07", clock, A.third, opOpen(TS_FIXED, "Mallory"))];
const seen = new Set();
for (const perm of shuffles(es)) {
seen.add(JSON.stringify(await snapOf(perm)));
// …and through the BATCH path too: `ingestMany` is a second entry point
// into `_entries`, so it is a second place the envelope must be judged
const f = new L.BankFold(BANK, null);
f.ingestMany(structuredClone(perm));
await f.awaitVerified();
seen.add(JSON.stringify(f.snapshot()));
}
return seen;
};
const honest = await distinct(7);
assert.equal(honest.size, 1, "an honest clock folds to one state, whatever the arrival order");
for (const hostile of ["abc", NaN, {}, [], true, 1.5, -1, Infinity, null, undefined, 2 ** 53]) {
const got = await distinct(hostile);
assert.equal(got.size, 1, `clock ${String(hostile)} must not partition the bank`);
}
});
test("a hostile clock or hash is DROPPED, never repaired", async () => {
// …and the entry is not merely tamed, it never enters the fold at all: the
// snapshot must be byte-identical to the one without it. Same house rule the
// op validator follows — there is no "close enough" for money.
const base = V.scenarios.find((s) => s.name === "settled-provisionally");
const clean = JSON.stringify(await snapOf(base.entries));
const junk = [
{ hash: "z01", from: A.third, clock: "5", op: { t: "open", ts: 0, name: "S" } },
{ hash: "z02", from: A.third, clock: NaN, op: { t: "open", ts: 0, name: "N" } },
{ hash: "z03", from: A.third, clock: {}, op: { t: "open", ts: 0, name: "O" } },
{ hash: "z04", from: A.third, clock: true, op: { t: "open", ts: 0, name: "B" } },
{ hash: "z05", from: A.third, clock: 1.5, op: { t: "open", ts: 0, name: "F" } },
{ hash: "z06", from: A.third, clock: -1, op: { t: "open", ts: 0, name: "M" } },
{ hash: "z07", from: A.third, clock: 2 ** 53, op: { t: "open", ts: 0, name: "U" } },
{ hash: "z08", from: A.third, clock: Infinity, op: { t: "open", ts: 0, name: "I" } },
{ hash: "z09", from: A.third, clock: null, op: { t: "open", ts: 0, name: "L" } },
{ hash: 7, from: A.third, clock: 5, op: { t: "open", ts: 0, name: "H" } },
{ hash: "", from: A.third, clock: 5, op: { t: "open", ts: 0, name: "E" } },
{ hash: {}, from: A.third, clock: 5, op: { t: "open", ts: 0, name: "J" } },
];
assert.equal(JSON.stringify(await snapOf([...base.entries, ...junk])), clean);
// non-vacuity: the SAME op with a legal envelope does land
const ok = { hash: "z99", from: A.third, clock: 5, op: { t: "open", ts: 0, name: "S" } };
assert.notEqual(JSON.stringify(await snapOf([...base.entries, ok])), clean);
assert.equal(2 ** 53 - 1, Number.MAX_SAFE_INTEGER, "the ceiling really is the safe-integer one");
});
test("an ack naming a slot LOSER still reports acked", async () => {
// F6. The banker acked both contenders, so acked-vs-unacked no longer
// separates them and (clock, hash) decides. The loser is `failed`/"seq" —
// and a valid ack naming it exists, so a UI asking "did the banker answer my
// payment?" must be told yes. The two are carried separately for this case.
const sc = V.scenarios.find((s) => s.name === "an-ack-on-both-contenders");
const s = await snapOf(sc.entries);
const loser = s.payments.find((p) => p.h === "h10");
assert.equal(loser.status, "failed");
assert.equal(loser.why, "seq");
assert.equal(loser.acked, true, "a hard-coded false here would lie about the banker's own act");
assert.equal(sc.entries.filter((e) => e.op.t === "ack").length, 2, "the fixture must really carry two");
});
test("ingestMany is ingest, batched — same fold, one onChange", async () => {
// F7: replay used to cost one refold per entry (and another per verdict), so
// boot was quadratic in a history any member can lengthen for free. Batching
// must not change WHAT is folded, only how often.
const sc = V.scenarios.find((s) => s.name === "overdraft-consumes-the-slot");
const one = new L.BankFold(BANK, null);
let calls = 0;
one.onChange = () => { calls++; };
one.ingestMany(structuredClone(sc.entries));
await one.awaitVerified();
assert.equal(JSON.stringify(one.snapshot()), JSON.stringify(await snapOf(sc.entries)));
// one for the batch, plus one per order-signature verdict that landed
assert.ok(calls <= 1 + sc.entries.filter((e) => e.op.t === "pay").length, `onChange fired ${calls} times`);
// a non-array, and a batch of junk, are both inert rather than throwing
const f = new L.BankFold(BANK, null);
f.ingestMany(null);
f.ingestMany([{ hash: "x", from: BANK, clock: "nope", op: null }]);
assert.equal(f.snapshot().ok, false);
});
test("entries are deduped by hash across every transport", async () => {
const base = V.scenarios.find((s) => s.name === "settled-provisionally");
const doubled = [...base.entries, ...base.entries, ...base.entries];
assert.equal(
JSON.stringify(await snapOf(doubled)),
JSON.stringify(await snapOf(base.entries)),
"a live echo, a local replay and a mailbox delivery of one entry must fold once",
);
});
test("balances are exact BigInt sums, not doubles", async () => {
// 2^50 is the largest single amount and a double is exact only to 2^53, so a
// history holds just EIGHT maximal amounts before a Number fold starts losing
// units while reporting a clean-looking total. Nine maximal mints plus one of
// a single unit is 10133099161583617 — odd, and past 2^53, so it is NOT a
// representable double. The exact total must survive; the Number projection
// beside it must not, which is precisely why `balExact` exists.
const MAXA = 2 ** 50;
const WANT = (BigInt(MAXA) * 9n + 1n).toString();
const entries = [
{ hash: "h01", from: BANK, clock: 1, op: { t: "charter", ts: 0, name: "B", code: "LEI", sym: "L", dec: 2, join: "open" } },
{ hash: "h02", from: A.payer, clock: 2, op: { t: "open", ts: 0, name: "P" } },
];
for (let i = 0; i < 9; i++) {
entries.push({
hash: `h1${i}`, from: BANK, clock: 10 + i,
op: { t: "mint", ts: 0, seq: i + 1, to: A.payer, amt: MAXA },
});
}
entries.push({ hash: "h20", from: BANK, clock: 30, op: { t: "mint", ts: 0, seq: 10, to: A.payer, amt: 1 } });
const s = await snapOf(entries);
const payer = s.accounts.find((a) => a.id === A.payer);
assert.equal(s.supplyExact, WANT);
assert.equal(payer.balExact, WANT);
assert.equal(BigInt(WANT) > 2n ** 53n, true);
assert.notEqual(String(payer.bal), payer.balExact, "the Number projection must have rounded");
assert.equal(String(payer.bal), "10133099161583616", "…by exactly one unit, downward");
});
test("nextSeq never hands out a spent slot", async () => {
const sc = V.scenarios.find((s) => s.name === "overdraft-consumes-the-slot");
const f = await fold(sc.entries);
// payment slot 2 is spent by a permanently failed payment, so the next one is
// 3 — slot 1 was never claimed and is skipped forever, which is the safe
// direction for a counter that must never hand out a spent slot
assert.equal(f.nextSeq(A.payer), 3);
assert.equal(f.nextSeq(A.payee), 1);
assert.equal(f.nextSeq("someone-the-bank-never-heard-of"), 1);
// …and the two ISSUANCE slots the banker spent here are in a different space:
// the banker has made no payment, so the banker's next `wpo.seq` is 1
assert.equal(f.nextSeq(A.bank), 1, "issuance must not move the banker's payment counter");
assert.equal(f.nextIssueSeq(), 3, "two mints, so the next issuance slot is 3");
});
test("the two sequence spaces are disjoint, and the banker can pay out of their own bank", async () => {
// F2. The banker's `wpo.seq` comes from their WALLET (wallet-kit LedgerStore
// derives it from that wallet's own receipts, and a banker's wallet holds
// none) while a mint's `seq` comes from this fold. Two counters, two owners,
// nothing that can keep them in step — so they cannot share a namespace.
const sc = V.scenarios.find((s) => s.name === "the-banker-pays-out-of-their-own-bank");
const f = await fold(sc.entries);
const s = f.snapshot();
const mint = s.payments.find((p) => p.h === "h09");
const pay = s.payments.find((p) => p.h === "h10");
assert.equal(mint.seq, 2);
assert.equal(pay.seq, 1, "the same number a fresh wallet hands out");
assert.equal(mint.status, "settled", "the issuance must not lose its slot to a payment");
assert.equal(pay.status, "settled", "and the payment must not lose its slot to an issuance");
assert.equal(s.supplyExact, "1500", "supply counts every mint that was told to everyone");
assert.equal(f.nextSeq(A.bank), 2, "the banker's next PAYMENT slot");
assert.equal(f.nextIssueSeq(), 3, "the banker's next ISSUANCE slot");
// the prelude mint already took issuance slot 1; under one shared space that
// is the slot this order claims, and one of the two dies `seq` forever
assert.equal(V.scenarios.find((x) => x.name === "prelude").expect.iseq, 1);
});
test("a sequence space can be spent, and nextSeq says so rather than lying", async () => {
// F8. `wpo.seq` is bounded by wallet-kit's seq-no? at AMT_MAX (2^50), and a
// slot is consumed by a monotone max — so one order at the ceiling pins the
// account. AMT_MAX + 1 is a number no order carrying it can ever shape, and
// AMT_MAX is a slot already spent; neither is an answer, so there is none.
const MAXS = 2 ** 50;
const po = makeOrder({ seed: SEED_PAYER, idN: 0xf0, cur: CUR, amt: 1, seq: MAXS, to: A.payee });
const entries = [
{ hash: "h01", from: BANK, clock: 1, op: { t: "charter", ts: 0, name: "B", code: "LEI", sym: "L", dec: 2, join: "open" } },
{ hash: "h02", from: A.payer, clock: 2, op: { t: "open", ts: 0, name: "P" } },
{ hash: "h03", from: A.payee, clock: 3, op: { t: "open", ts: 0, name: "Q" } },
{ hash: "h04", from: BANK, clock: 4, op: { t: "mint", ts: 0, seq: MAXS, to: A.payer, amt: 1000 } },
{ hash: "h05", from: A.payer, clock: 5, op: { t: "pay", ts: 0, po } },
];
const f = await fold(entries);
const s = f.snapshot();
assert.equal(s.payments.find((p) => p.h === "h05").status, "settled", "the ceiling slot itself is usable");
assert.equal(s.accounts.find((a) => a.id === A.payer).seq, MAXS);
assert.equal(s.iseq, MAXS);
assert.equal(f.nextSeq(A.payer), null, "payer's payment space is spent");
assert.equal(f.nextIssueSeq(), null, "the banker's issuance space is spent");
// and one slot below the ceiling still answers with the ceiling
assert.equal(f.nextSeq(A.payee), 1, "an untouched account is unaffected");
});
test("balanceOf distinguishes an empty account from no account at all", async () => {
const f = await fold(V.scenarios.find((s) => s.name === "prelude").entries);
assert.equal(f.balanceOf(A.payee), "0");
assert.equal(f.balanceOf(A.outsider), "0");
const s = f.snapshot();
assert.ok(s.accounts.some((a) => a.id === A.payee), "payee HAS an account, with nothing in it");
assert.equal(s.accounts.some((a) => a.id === A.outsider), false, "the outsider has none");
});
test("full history replay: there is no window and no eviction", async () => {
// The scaffold replays a newest-N tail; a bank cannot. This drives 1200
// entries — well past any window anyone would pick — and asserts the balance
// still counts every one of them.
const N = 1200;
const entries = [
{ hash: "h001", from: BANK, clock: 1, op: { t: "charter", ts: 0, name: "B", code: "LEI", sym: "L", dec: 2, join: "open" } },
{ hash: "h002", from: A.payer, clock: 2, op: { t: "open", ts: 0, name: "P" } },
];
for (let i = 0; i < N; i++) {
entries.push({
hash: `m${String(i).padStart(5, "0")}`, from: BANK, clock: 100 + i,
op: { t: "mint", ts: 0, seq: i + 1, to: A.payer, amt: 1 },
});
}
const s = await snapOf(entries);
assert.equal(s.supplyExact, String(N));
assert.equal(s.accounts.find((a) => a.id === A.payer).balExact, String(N));
assert.equal(s.payments.length, N, "every entry must still be projected — no drop-oldest");
});
|