banca / client / test / vectors / build-vectors.mjs
   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
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
/**
 * Writes test/vectors/{order,receipts,fold}.json.
 *
 * Run it deliberately, never as part of `npm test`:
 *
 *     node test/vectors/build-vectors.mjs
 *
 * ---------------------------------------------------------------------------
 * WHAT IS DERIVED WHERE, because this is the only thing that makes a fixture
 * evidence rather than a screenshot:
 *
 *   · every SIGNATURE and every PREIMAGE comes from ./independent.mjs —
 *     @noble/curves and a canonical-JSON re-implementation, with the preimages
 *     also written out as literal templates. Not one byte of it comes from
 *     banca's compiled code.
 *
 *   · every FOLD EXPECTATION below is HAND-COMPUTED and written as a literal,
 *     beside an `input_desc` sentence a reader can check by adding up four
 *     numbers. Nothing here runs the fold and records what it said. If the
 *     implementation and a hand-computed expectation disagree, the fixture is
 *     the claim and the implementation is the thing on trial.
 *
 *   · the wpo fixture in order.json is COPIED VERBATIM out of
 *     wallet-kit/test/vectors/artifacts.json, which was itself independently
 *     derived in that repo. banca calls the kit's preimage assembly (it is
 *     sha-pinned in package.json), so what this fixture checks is that the
 *     PINNED CODE still produces the bytes the kit published — a bump that
 *     moved the wire goes red here rather than silently in a bank.
 *
 * ORDER INDEPENDENCE needs no expectation at all: it is the property that the
 * same entry set folds to a byte-identical snapshot in every insertion order,
 * and the test asserts it over three fixed permutations of every scenario here.
 */

import { writeFileSync } from "node:fs";
import {
  ACTORS, CUR, CUR2, TS_FIXED, SEED_BANK, SEED_BANK2, SEED_PAYER, SEED_PAYEE,
  makeOrder, signReceipt, signIssuance, orderPreimageByHand, receiptPreimageByHand,
  issuancePreimageByHand, unsignedIssuanceByHand,
  canonIndependent, unsignedOrderByHand, entry, sha256b64url,
  opCharter, opOpen, opAcct, opMint, opBurn, opPay, opAck, opRate, opReq,
} from "./independent.mjs";

const here = (n) => new URL(n, import.meta.url).pathname;
const write = (n, v) => writeFileSync(here(n), JSON.stringify(v, null, 1) + "\n");

const A = ACTORS;
/** label -> idPub, so a fixture reads as words and a test resolves them. */
const LABELS = {
  bank: A.bankPub, bank2: A.bank2Pub, payer: A.payerPub,
  payee: A.payeePub, third: A.thirdPub, outsider: A.outsiderPub,
};

const TS = TS_FIXED;

// =============================================================================
// order.json — the wallet-kit seam
// =============================================================================

// wallet-kit's own published wpo fixture, transcribed here so this repo's tests
// do not read across a filesystem boundary (house rule 9: no local path in a
// committed file). Regenerate by copying artifacts.json's `artifacts.wpo`.
const WPO_FIXTURE = {
  wire: {
    v: 1,
    t: "wpo",
    id: "oKGio6SlpqeoqaqrrK2urw",
    cur: "0EqyMnQrtKs6E2i9RhXk5tAiSrcaAWuvhSCjMsl3hzc.LEI",
    amt: 100,
    seq: 7,
    from: "A6EHv_POEL4dcN0Y50vAmWfk1jCbpQ1fHdyGZBJVMbg",
    to: "Kay64UG8yvCyLhqU000LxzYeUm0L_hLIl5S8kyKWbdc",
    ctx: "stake:demo",
    memo: "cafea ☕",
    ts: 1735689600000,
    exp: 1735690200000,
    sig: "4xufyzCb0x42I4BknCkpPeAQD0-A8-TZGuryd0YN-5o7cyD62hFve5w3oXsKLRxo4_bdnIANzsjyWJb8--pDCQ",
  },
  wire_json:
    '{"v":1,"t":"wpo","id":"oKGio6SlpqeoqaqrrK2urw","cur":"0EqyMnQrtKs6E2i9RhXk5tAiSrcaAWuvhSCjMsl3hzc.LEI",' +
    '"amt":100,"seq":7,"from":"A6EHv_POEL4dcN0Y50vAmWfk1jCbpQ1fHdyGZBJVMbg",' +
    '"to":"Kay64UG8yvCyLhqU000LxzYeUm0L_hLIl5S8kyKWbdc","ctx":"stake:demo","memo":"cafea ☕",' +
    '"ts":1735689600000,"exp":1735690200000,' +
    '"sig":"4xufyzCb0x42I4BknCkpPeAQD0-A8-TZGuryd0YN-5o7cyD62hFve5w3oXsKLRxo4_bdnIANzsjyWJb8--pDCQ"}',
  preimage:
    'wpay-ord|v1|{"amt":100,"ctx":"stake:demo","cur":"0EqyMnQrtKs6E2i9RhXk5tAiSrcaAWuvhSCjMsl3hzc.LEI",' +
    '"exp":1735690200000,"from":"A6EHv_POEL4dcN0Y50vAmWfk1jCbpQ1fHdyGZBJVMbg","id":"oKGio6SlpqeoqaqrrK2urw",' +
    '"memo":"cafea ☕","seq":7,"t":"wpo","to":"Kay64UG8yvCyLhqU000LxzYeUm0L_hLIl5S8kyKWbdc",' +
    '"ts":1735689600000,"v":1}',
};

const W = WPO_FIXTURE.wire;
const mut = (patch) => ({ ...W, ...patch });
const drop = (k) => { const o = { ...W }; delete o[k]; return o; };

const shapeRejects = [
  { why: "a fourteenth key — v1 has no extension slot, and a stray key would ride the wire without riding the preimage", order: mut({ extra: 1 }) },
  { why: "a missing key (`ctx`)", order: drop("ctx") },
  { why: "wrong `t`", order: mut({ t: "wpr" }) },
  { why: "wrong `v`", order: mut({ v: 2 }) },
  { why: "amt 0 — below AMT_MIN", order: mut({ amt: 0 }) },
  { why: "amt 2^50 + 1 — above AMT_MAX, where a double stops being exact enough to fold", order: mut({ amt: 1125899906842625 }) },
  { why: "amt is not an integer", order: mut({ amt: 100.5 }) },
  { why: "seq 0 — a slot is 1-based", order: mut({ seq: 0 }) },
  { why: "the reserved neutral unit, which nobody can mint and nobody can settle", order: mut({ cur: "~.GAZ" }) },
  { why: "a currency id with a lowercase code", order: mut({ cur: W.cur.replace(".LEI", ".lei") }) },
  { why: "a non-canonical base64url signature — the same 64 bytes with the spare padding bits set, which would be a second dedup key for one signature", order: mut({ sig: W.sig.slice(0, 85) + "R" }) },
  { why: "exp not after ts", order: mut({ exp: W.ts }) },
  { why: "exp further than MAX_TTL_MS past ts", order: mut({ exp: W.ts + 90 * 86400000 + 1 }) },
  { why: "a negative ts", order: mut({ ts: -1, exp: 1 }) },
  { why: "`from` is not a canonical 43-character key", order: mut({ from: W.from.slice(0, 42) }) },
  { why: "null", order: null },
  { why: "an array", order: [] },
  { why: "a string", order: "wpo" },
];

write("order.json", {
  _doc:
    "banca's wallet-kit seam (client/src/banca/lib/wallet.cljs), pinned. The kit is sha-pinned and the seam " +
    "calls it rather than transcribing it; this fixture checks what the pinned code produces against the " +
    "kit's OWN published vector and against a by-hand canonical-JSON template. Everything here is derived in " +
    "test/vectors/independent.mjs — never from banca's compiled code.",
  input_desc: {
    provenance:
      "`wpo` is copied verbatim from wallet-kit/test/vectors/artifacts.json, where it was derived with " +
      "@noble/curves from seeds: payer = 32 bytes 0x00..0x1f, payee = 0x20..0x3f, bank = 32 bytes of 0x11. " +
      "The seed IS the raw Ed25519 private key.",
    clock_free:
      "banca calls wallet-kit's orderShape with its admission clock set to `null` — NO CLOCK: a fold must be " +
      "a pure function of the entry set, so an order whose `ts` sits years in the reader's future must still " +
      "SHAPE. The kit's DEFAULT (an omitted clock) rejects it, correctly, for a wallet deciding whether to " +
      "sign. Deterministic, not weaker — every other bound is kept. See lib/wallet.cljs's header.",
    lengths_by_hand: { identity_pub_b64url: 43, ed25519_sig_b64url: 86, order_id_b64url: 22, sha256_b64url: 43 },
  },
  consts: {
    _doc: "wallet-kit/src/ardegazu/wallet/consts.cljs, written out here as hand-written literals so the pin is checked rather than echoed.",
    DOM_PAY_ORD: "wpay-ord",
    DOM_PAY_RCP: "wpay-rcp",
    AMT_MIN: 1,
    AMT_MAX: 1125899906842624,
    CTX_MAX: 128,
    MEMO_MAX: 140,
    NEUTRAL_CODE: "GAZ",
    NEUTRAL_UNIT: "~.GAZ",
    DECLINE_REASONS: ["insufficient", "unknown-payer", "expired", "cur", "seq"],
  },
  actors: LABELS,
  wpo: WPO_FIXTURE,
  order_id: sha256b64url(canonIndependent(unsignedOrderByHand(W))),
  // Control characters are named by CODE POINT rather than written into the
  // fixture, so this file and the JSON beside it stay printable — the publish
  // gate decompresses every object and a raw NUL or U+2028 in a tracked file is
  // a fight with every editor, diff and scanner between here and the mirror.
  // The test builds `"a" + String.fromCodePoint(cp) + "b"` for each field.
  control_chars: {
    _doc:
      "`ctx` and `memo` are the two fields a third party matches on and a UI displays, so neither may smuggle " +
      "a line break into a log or a display. The class is C0, DEL, C1 AND U+2028/U+2029 — the last two are " +
      "not control characters by Unicode category but ARE line terminators in ECMAScript, and a C0-only class " +
      "let them straight through in an earlier wallet-kit draft.",
    rejected: [
      { field: "memo", cp: 0, why: "NUL" },
      { field: "memo", cp: 10, why: "LF" },
      { field: "ctx", cp: 13, why: "CR" },
      { field: "ctx", cp: 127, why: "DEL" },
      { field: "memo", cp: 155, why: "a C1 control" },
      { field: "ctx", cp: 8232, why: "U+2028 LINE SEPARATOR" },
      { field: "memo", cp: 8233, why: "U+2029 PARAGRAPH SEPARATOR" },
    ],
    // the non-vacuity half: orderShape is signature-free, so a merely-different
    // memo must still SHAPE. Without these the reject rows would pass against a
    // predicate that rejected everything.
    accepted: [
      { field: "memo", cp: 9731, why: "a snowman is not a control character" },
      { field: "ctx", cp: 32, why: "a space is not a control character" },
    ],
  },
  length_bounds: {
    _doc: "Bounded in CODE POINTS, not UTF-16 units, so an emoji costs one.",
    ctx_max: 128,
    memo_max: 140,
    cases: [
      { field: "ctx", cp: 9731, len: 128, shapes: true },
      { field: "ctx", cp: 9731, len: 129, shapes: false },
      { field: "memo", cp: 9731, len: 140, shapes: true },
      { field: "memo", cp: 9731, len: 141, shapes: false },
      { field: "memo", cp: 128512, len: 140, shapes: true, note: "a non-BMP emoji is TWO UTF-16 units and ONE code point; a UTF-16 count would reject this" },
    ],
  },
  currency: {
    _doc: "A currency id is `<43-char canonical b64url bankerPub>.<CODE>`; the issuing identity IS the namespace.",
    ok: [[LABELS.bank, "LEI", `${LABELS.bank}.LEI`], [LABELS.bank2, "RON", `${LABELS.bank2}.RON`]],
    rejected: [
      [LABELS.bank, "GAZ", "the reserved neutral code, refused for EVERY banker so no bank can mint a `~.GAZ` lookalike"],
      [LABELS.bank, "lei", "lowercase"],
      [LABELS.bank, "AB", "shorter than three characters"],
      [LABELS.bank, "ABCDEFGHI", "longer than eight characters"],
      [LABELS.bank.slice(0, 42), "LEI", "a banker key that is not canonical 43-character base64url"],
    ],
    payable: [[`${LABELS.bank}.LEI`, true], ["~.GAZ", false], [`${LABELS.bank}.gaz`, false]],
  },
  clock_free_order: makeOrder({
    seed: SEED_PAYER, idN: 0xb0, cur: CUR, amt: 1, seq: 1, to: A.payeePub,
    ts: TS + 10 * 365 * 86400000, ttl: 600000,
  }),
  shape_rejects: shapeRejects,
});

// =============================================================================
// receipts.json — the double-signed portable receipt
// =============================================================================

const RCPT_ORDER = makeOrder({
  seed: SEED_PAYER, idN: 0xc0, cur: CUR, amt: 250, seq: 1, to: A.payeePub, memo: "chirie",
});
const RCPT_LOGREF = "h09";
const RCPT_TS = TS + 60000;
const RCPT_BSIG = signReceipt({ bankSeed: SEED_BANK, po: RCPT_ORDER, logRef: RCPT_LOGREF, ts: RCPT_TS });
const RCPT_WIRE = {
  v: 1, t: "wrc", po: RCPT_ORDER, seq: RCPT_LOGREF, ts: RCPT_TS, bank: A.bankPub, bsig: RCPT_BSIG,
};

// a signature that is well-shaped and simply wrong: the banker's signature over
// a DIFFERENT log ref. Nothing about it is malformed.
const WRONG_BSIG = signReceipt({ bankSeed: SEED_BANK, po: RCPT_ORDER, logRef: "h99", ts: RCPT_TS });

// A receipt that is VALID IN EVERY WAY — for a different bank. bank2's paper,
// bank2's own signature, every internal check passing. Only `expectedBankPub`
// tells it apart from the receipt you were actually waiting for, which is why
// banca's `verify-settlement` refuses to run without one.
const OTHER_ORDER = makeOrder({
  seed: SEED_PAYER, idN: 0xd0, cur: CUR2, amt: 42, seq: 1, to: A.payeePub, ctx: "bank2",
});
const OTHER_WIRE = {
  v: 1, t: "wrc", po: OTHER_ORDER, seq: "b2-17", ts: RCPT_TS, bank: A.bank2Pub,
  bsig: signReceipt({ bankSeed: SEED_BANK2, po: OTHER_ORDER, logRef: "b2-17", ts: RCPT_TS }),
};

// ---- the issuance receipt (`wri`) -------------------------------------------
//
// The mint being made final is the fold prelude's h08: issuance slot 1, 1000
// minor units to the payer. `h` is the MINT ENTRY'S HASH — what `ack.h` names —
// and `ts` is the ack's, which is the wri's own (the banker signs the wri first
// and the ack carries its ts, the exact discipline the wrc has).
const WRI_TS = TS + 60000;
const WRI_PARTS = { cur: CUR, seq: 1, to: A.payerPub, amt: 1000, h: "h08", ts: WRI_TS, bank: A.bankPub };
const WRI_BSIG = signIssuance({ bankSeed: SEED_BANK, cur: CUR, seq: 1, to: A.payerPub, amt: 1000, h: "h08", ts: WRI_TS });
const WRI_WIRE = {
  v: 1, t: "wri", cur: CUR, seq: 1, to: A.payerPub, amt: 1000, h: "h08", ts: WRI_TS,
  bank: A.bankPub, bsig: WRI_BSIG,
};

// well-shaped and simply wrong: the banker's signature over a DIFFERENT amount.
// "Never emit two wri amounts for one entry hash" is banca's rule to keep —
// issuanceKey is blind to amt on purpose, so this pair IS a signed contradiction.
const WRI_WRONG_BSIG = signIssuance({ bankSeed: SEED_BANK, cur: CUR, seq: 1, to: A.payerPub, amt: 999, h: "h08", ts: WRI_TS });

// a perfectly valid issuance by SOME OTHER BANK, of its own currency. Only
// expectedBankPub tells it from the one you were told about.
const WRI_OTHER = {
  v: 1, t: "wri", cur: CUR2, seq: 1, to: A.payerPub, amt: 1000, h: "b2-h08", ts: WRI_TS,
  bank: A.bank2Pub,
  bsig: signIssuance({ bankSeed: SEED_BANK2, cur: CUR2, seq: 1, to: A.payerPub, amt: 1000, h: "b2-h08", ts: WRI_TS }),
};

write("receipts.json", {
  _doc:
    "The `wrc` banca rebuilds from a `pay` entry and the banker's `ack`, and the `wri` it rebuilds from a " +
    "`mint` entry and the banker's `ack`. Both halves of each already exist in the log, " +
    "so a receipt is not a new artifact — it is a projection every member can compute. `wrc.seq` is the " +
    "bank's own log reference and banca uses THE PAY ENTRY'S HASH, which is exactly what `ack.h` names; " +
    "`wri.h` is the MINT ENTRY'S HASH, the same identifier under the key that says what it is.",
  input_desc: {
    order: "payer -> payee, 250 minor units, slot 1, memo \"chirie\", ts 2025-01-01T00:00:00Z, ttl 10 minutes.",
    log_ref: "\"h09\" — the pay entry's hash in the fixture log. A real one is a base58btc CID; the fold never parses it.",
    ts: "the ACK op's timestamp, one minute after the order. A settlement may not predate its order by more than SKEW_MS.",
    bsig: "Ed25519 by the bank seed over the by-hand `wpay-rcp|v1|` preimage in independent.mjs. Note `wrc.seq` is a STRING (the bank's log ref) while `wpo.seq` is a NUMBER (the payer's slot) — a second implementation must not conflate them.",
  },
  preimage: receiptPreimageByHand({ po: RCPT_ORDER, seq: RCPT_LOGREF, ts: RCPT_TS, bank: A.bankPub }),
  unsigned_canon: canonIndependent({
    v: 1, t: "wrc", po: RCPT_ORDER, seq: RCPT_LOGREF, ts: RCPT_TS, bank: A.bankPub,
  }),
  // wallet-kit's OWN published wrc preimage, copied verbatim out of
  // wallet-kit/test/vectors/artifacts.json. It pins the one thing a by-hand
  // template beside it cannot: that the template is right. The first draft of
  // that template used the UNSIGNED order and this string is what settled it —
  // `po.sig` IS inside the preimage, which is the whole reason the signed order
  // travels inside the receipt.
  wallet_kit_wrc: {
    _doc: "Provenance: wallet-kit/test/vectors/artifacts.json, artifacts.wrc. Not derived here.",
    wire: {
      v: 1, t: "wrc",
      po: WPO_FIXTURE.wire,
      seq: "L-42",
      ts: 1735689601000,
      bank: "0EqyMnQrtKs6E2i9RhXk5tAiSrcaAWuvhSCjMsl3hzc",
    },
    preimage:
      'wpay-rcp|v1|{"bank":"0EqyMnQrtKs6E2i9RhXk5tAiSrcaAWuvhSCjMsl3hzc","po":' +
      '{"amt":100,"ctx":"stake:demo","cur":"0EqyMnQrtKs6E2i9RhXk5tAiSrcaAWuvhSCjMsl3hzc.LEI",' +
      '"exp":1735690200000,"from":"A6EHv_POEL4dcN0Y50vAmWfk1jCbpQ1fHdyGZBJVMbg",' +
      '"id":"oKGio6SlpqeoqaqrrK2urw","memo":"cafea ☕","seq":7,' +
      '"sig":"4xufyzCb0x42I4BknCkpPeAQD0-A8-TZGuryd0YN-5o7cyD62hFve5w3oXsKLRxo4_bdnIANzsjyWJb8--pDCQ",' +
      '"t":"wpo","to":"Kay64UG8yvCyLhqU000LxzYeUm0L_hLIl5S8kyKWbdc","ts":1735689600000,"v":1},' +
      '"seq":"L-42","t":"wrc","ts":1735689601000,"v":1}',
  },
  key_order: ["v", "t", "po", "seq", "ts", "bank", "bsig"],
  wire: RCPT_WIRE,
  wire_json: JSON.stringify(RCPT_WIRE),
  parts: { po: RCPT_ORDER, logRef: RCPT_LOGREF, ts: RCPT_TS, bank: A.bankPub, bsig: RCPT_BSIG },
  other_bank: {
    _doc:
      "A receipt issued by bank2 for bank2's own paper. Structurally perfect and cryptographically sound — " +
      "it verifies against expectedBankPub = bank2 and must NOT verify against bank1. Nothing else in the " +
      "artifact distinguishes the two, which is the whole reason the parameter exists.",
    wire: OTHER_WIRE,
  },
  rejects: [
    {
      why: "a well-formed banker signature over a DIFFERENT log ref. The fold still calls the payment `final` — a banker's ack is attributable, and finality is authorship — but the exported receipt does not verify for a third party. That asymmetry is the honest one, and it is stated in docs/PROTOCOL.md §8.",
      wire: { ...RCPT_WIRE, bsig: WRONG_BSIG },
    },
    {
      why: "the wrong bank: banker(po.cur) must BE the signing bank, or a bank could settle another bank's paper",
      wire: { ...RCPT_WIRE, bank: A.bank2Pub },
    },
    {
      why: "a tampered amount inside the embedded order — the order's own signature no longer covers it",
      wire: { ...RCPT_WIRE, po: { ...RCPT_ORDER, amt: 999 } },
    },
    { why: "an eighth key", wire: { ...RCPT_WIRE, extra: 1 } },
    { why: "an empty log ref", wire: { ...RCPT_WIRE, seq: "" } },
    { why: "a decline (`wrj`) is not a receipt, even though both share a signature domain", wire: { v: 1, t: "wrj", po: RCPT_ORDER, why: "insufficient", ts: RCPT_TS, bank: A.bankPub, bsig: RCPT_BSIG } },
  ],

  wri: {
    _doc:
      "The issuance receipt banca rebuilds from a `mint` entry and the banker's `ack` on it. TEN keys, wire " +
      "order v,t,cur,seq,to,amt,h,ts,bank,bsig; domain \"wpay-iss\"; preimage over the receipt minus bsig. " +
      "This is the artifact that closes the confiscation window: before it, an ack on a mint had nothing to " +
      "sign, and a banker could withhold a back-dated second mint on the same issuance slot and empty the " +
      "recipient's balance. MINT ONLY — a burn names no recipient, so a burn-wri would be signed content " +
      "with no natural meaning, and burns stay unpinnable by design.",
    input_desc: {
      mint: "the fold prelude's h08: issuance slot 1, 1000 minor units to payer.",
      h: "\"h08\" — the MINT ENTRY'S hash, exactly what the ack names in `h`. Opaque: the fold never parses one.",
      ts: "the ACK op's timestamp, which is the wri's own — the banker signs the wri first and the ack carries its ts, the wrc's exact discipline.",
      seq: "wri.seq is the BANK's issuance slot NUMBER — a third meaning of the word: wpo.seq is the payer's number, wrc.seq is the bank's log-ref STRING.",
      bsig: "Ed25519 by the bank seed over the by-hand `wpay-iss|v1|` template in independent.mjs.",
    },
    key_order: ["v", "t", "cur", "seq", "to", "amt", "h", "ts", "bank", "bsig"],
    preimage: issuancePreimageByHand(WRI_PARTS),
    unsigned_canon: canonIndependent(unsignedIssuanceByHand(WRI_PARTS)),
    // wallet-kit's OWN published wri fixture, copied verbatim out of
    // wallet-kit/test/vectors/artifacts.json (artifacts.wri; seeds as in
    // order.json's provenance note). It pins the one thing the template beside
    // it cannot: that the template is right.
    wallet_kit_wri: {
      _doc: "Provenance: wallet-kit/test/vectors/artifacts.json, artifacts.wri. Not derived here.",
      wire: {
        v: 1,
        t: "wri",
        cur: "0EqyMnQrtKs6E2i9RhXk5tAiSrcaAWuvhSCjMsl3hzc.LEI",
        seq: 7,
        to: "Kay64UG8yvCyLhqU000LxzYeUm0L_hLIl5S8kyKWbdc",
        amt: 100,
        h: "zdpuAtq8kqPXzS3rVGkD1nDNJCoCUqfEC97WQMg4vDeqQm3wg",
        ts: 1735689603000,
        bank: "0EqyMnQrtKs6E2i9RhXk5tAiSrcaAWuvhSCjMsl3hzc",
        bsig: "OAMjHK82Th2xZrAXK61rZvpEFoK1d39YCv7lD48_arwuIEhvHMYzuhphu_xkaGhxvz6vINGZ7R2dukVdtpKpDQ",
      },
      preimage:
        'wpay-iss|v1|{"amt":100,"bank":"0EqyMnQrtKs6E2i9RhXk5tAiSrcaAWuvhSCjMsl3hzc",' +
        '"cur":"0EqyMnQrtKs6E2i9RhXk5tAiSrcaAWuvhSCjMsl3hzc.LEI",' +
        '"h":"zdpuAtq8kqPXzS3rVGkD1nDNJCoCUqfEC97WQMg4vDeqQm3wg","seq":7,"t":"wri",' +
        '"to":"Kay64UG8yvCyLhqU000LxzYeUm0L_hLIl5S8kyKWbdc","ts":1735689603000,"v":1}',
    },
    wire: WRI_WIRE,
    wire_json: JSON.stringify(WRI_WIRE),
    parts: WRI_PARTS,
    bsig: WRI_BSIG,
    other_bank: {
      _doc:
        "An issuance receipt by bank2, for bank2's own currency and log. Structurally perfect and " +
        "cryptographically sound — it verifies against expectedBankPub = bank2 and must NOT verify against " +
        "bank1. The parameter is the only thing that tells them apart, which is why banca's verify-issuance " +
        "refuses to run without one.",
      wire: WRI_OTHER,
    },
    rejects: [
      {
        why: "a well-formed banker signature over a DIFFERENT amount for the same entry hash. The fold still calls the mint `final` — finality is authorship — but the rebuilt receipt does not verify for a third party. The same honest asymmetry §8 states for the wrc, and the signed contradiction issuanceKey's (bank, h) blindness exists to expose.",
        wire: { ...WRI_WIRE, bsig: WRI_WRONG_BSIG },
      },
      {
        why: "the wrong bank: banker(cur) must BE the signing bank, or any bank could finalize another bank's issuance",
        wire: { ...WRI_WIRE, bank: A.bank2Pub },
      },
      {
        why: "a tampered amount — the signature no longer covers it",
        wire: { ...WRI_WIRE, amt: 999 },
      },
      { why: "an eleventh key — v1 has no extension slot", wire: { ...WRI_WIRE, extra: 1 } },
      { why: "an empty entry hash", wire: { ...WRI_WIRE, h: "" } },
      { why: "a settlement (`wrc`) is not an issuance receipt — different t, different domain", wire: RCPT_WIRE },
      {
        why: "a bsig lifted off a PAYMENT ack — the wpay-rcp and wpay-iss domains keep the two signing acts apart, so a settlement signature can never dress up as an issuance receipt",
        wire: { ...WRI_WIRE, bsig: RCPT_BSIG },
      },
    ],
  },
});

// =============================================================================
// fold.json — the settlement fold
// =============================================================================
//
// A shared prelude every scenario starts from, so each scenario's `input_desc`
// only has to describe what it adds. Hand-computed prelude state:
//
//   accounts (in the order the fold first sees them): bank, payer, payee, third
//   balances: bank 0, payer 1000, payee 0, third 0        supply 1000
//   the mint credits `to` and raises supply; it does NOT touch the banker's own
//   balance, so the four balances sum to the supply and always will.

const ord = (o) => makeOrder(o);

const prelude = () => [
  entry("h01", 1, A.bankPub, opCharter(TS, "Banca Test", "LEI", "L", 2, "approve")),
  entry("h02", 2, A.payerPub, opOpen(TS, "Payer")),
  entry("h03", 3, A.payeePub, opOpen(TS, "Payee")),
  entry("h04", 4, A.thirdPub, opOpen(TS, "Third")),
  entry("h05", 5, A.bankPub, opAcct(TS, A.payerPub, "approve")),
  entry("h06", 6, A.bankPub, opAcct(TS, A.payeePub, "approve")),
  entry("h07", 7, A.bankPub, opAcct(TS, A.thirdPub, "approve")),
  entry("h08", 8, A.bankPub, opMint(TS, 1, A.payerPub, 1000)),
];

// EVERY BANK/1 scenario states `locked` and `escrows` rather than omitting them.
// `supply` is the sum of balances PLUS escrow, so a fixture that left them out
// could not tell a conserved fold from a leaky one — and a projection that
// dropped them would put the whole escrow surface outside the twenty-eight
// scenarios' reach. Each `locked` map carries its own scenario's account keys,
// all zero; the scenarios where they are NOT zero live in test/escrow.test.mjs.

const PRELUDE_ACCOUNTS = ["bank", "payer", "payee", "third"];
/** The banker's account is created by the CHARTER and never by an `open`, so it
 *  carries no name — the one account in the fixture whose name is "". */
const PRELUDE_NAMES = { bank: "", payer: "Payer", payee: "Payee", third: "Third" };
const CHARTER_LEI = { name: "Banca Test", code: "LEI", sym: "L", dec: 2, join: "approve" };
const PRELUDE_MINT = {
  h: "h08", kind: "mint", actor: "bank", to: "payer", amt: 1000, seq: 1,
  status: "settled", acked: false, why: null,
};

/** A pay entry plus the ack that would finalise it, sharing one order. */
const ackFor = (hash, po, ts) => ({
  bsig: signReceipt({ bankSeed: SEED_BANK, po, logRef: hash, ts }),
  ts,
});

/** A mint entry's ack: `bsig` over the wri preimage, `ts` the wri's own. */
const wriAckFor = (hash, { seq, to, amt }, ts) => ({
  bsig: signIssuance({ bankSeed: SEED_BANK, cur: CUR, seq, to, amt, h: hash, ts }),
  ts,
});

// the prelude's mint (h08): issuance slot 1, 1000 to payer — and the wri that
// pins it, signed the way banca's banker screen signs one
const WRI_ACK_H08 = wriAckFor("h08", { seq: 1, to: A.payerPub, amt: 1000 }, TS + 60000);

// ---- S1: the happy path, provisional then final -----------------------------
const po1 = ord({ seed: SEED_PAYER, idN: 0x10, cur: CUR, amt: 250, seq: 1, to: A.payeePub, memo: "cafea" });
const ack1 = ackFor("h09", po1, TS + 60000);

// ---- S2/S3: two orders contending for slot (payer, 1) -----------------------
const poA = ord({ seed: SEED_PAYER, idN: 0x20, cur: CUR, amt: 600, seq: 1, to: A.payeePub, ctx: "A" });
const poB = ord({ seed: SEED_PAYER, idN: 0x30, cur: CUR, amt: 600, seq: 1, to: A.thirdPub, ctx: "B" });
const ackB = ackFor("h10", poB, TS + 60000);

// ---- S4: a withheld, back-dated entry ---------------------------------------
const poC = ord({ seed: SEED_PAYER, idN: 0x40, cur: CUR, amt: 600, seq: 1, to: A.thirdPub, ctx: "withheld" });
const ackA = ackFor("h09", poA, TS + 60000);

// ---- S5: overdraft, then a mint that must not resurrect it ------------------
const poD = ord({ seed: SEED_PAYER, idN: 0x50, cur: CUR, amt: 5000, seq: 2, to: A.payeePub, ctx: "over" });

// ---- S8: relayed by a third party; and a forged order -----------------------
const poForged = { ...po1, sig: po1.sig.slice(0, 85) + (po1.sig[85] === "A" ? "Q" : "A") };

// ---- S10: another bank's paper ----------------------------------------------
const poOther = ord({ seed: SEED_PAYER, idN: 0x60, cur: CUR2, amt: 100, seq: 1, to: A.payeePub });

// ---- the banker is also a payer, and the two sequence spaces are DISJOINT ----
//
// The banker's wallet derives `wpo.seq` from its own receipts alone (wallet-kit
// LedgerStore) and a banker's wallet holds none, so its first order carries
// seq 1 — the number the banker's FIRST MINT already used. Two counters, two
// owners, no way to keep them in step, so the slot key carries its class.
const poBank = ord({ seed: SEED_BANK, idN: 0x90, cur: CUR, amt: 100, seq: 1, to: A.payeePub, ctx: "banker pays" });

// ---- the banker acks BOTH contenders for one slot ---------------------------
// Equivocation the fold has an answer for: acked-vs-unacked no longer separates
// them, so (clock, hash) decides — and the LOSER still reports `acked: true`,
// because an ack naming it exists and a UI asking "did the banker answer my
// payment?" must not be told no.
const ackA9 = ackFor("h09", poA, TS + 60000);

// ---- a closed account under join:"open" --------------------------------------
// The ONE sanction a banker has is closing an account. Under join:"approve" a
// self-`open` is only ever a knock, so the readmission guard is unreachable
// there and a fixture that used it would pass with the guard deleted; under
// join:"open" an `open` DOES admit, which is where the guard has to hold.
const poClosed = ord({ seed: SEED_PAYER, idN: 0xa0, cur: CUR, amt: 100, seq: 1, to: A.payeePub, ctx: "after close" });

/** An OrbitDB per-device fallback identity id: secp256k1, hex, 66 characters. */
const FALLBACK_ID = "03" + "ab".repeat(32);

const scenarios = [
  {
    name: "prelude",
    input_desc:
      "Charter (LEI, join:\"approve\"), three knocks, three approvals, and a mint of 1000 to payer. " +
      "Hand-computed: bank 0, payer 1000, payee 0, third 0; supply 1000.",
    entries: prelude(),
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: CHARTER_LEI,
      supplyExact: "1000", supply: 1000, iseq: 1, rate: null,
      accounts: PRELUDE_ACCOUNTS,
      names: PRELUDE_NAMES,
      balances: { bank: "0", payer: "1000", payee: "0", third: "0" },
      locked: { bank: "0", payer: "0", payee: "0", third: "0" },
      escrows: [],
      bals: { bank: 0, payer: 1000, payee: 0, third: 0 },
      seqs: { bank: 0, payer: 0, payee: 0, third: 0 },
      states: { bank: "open", payer: "open", payee: "open", third: "open" },
      payments: [PRELUDE_MINT],
      pending: [], reqs: [],
    },
  },
  {
    name: "settled-provisionally",
    input_desc:
      "Prelude + payer pays payee 250 in slot 1, with NO ack. The banker is asleep and the payment " +
      "settles anyway. Hand-computed: payer 1000 - 250 = 750, payee 0 + 250 = 250; supply unchanged at 1000.",
    entries: [...prelude(), entry("h09", 9, A.payerPub, opPay(TS, po1))],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: CHARTER_LEI,
      supplyExact: "1000", supply: 1000, iseq: 1, rate: null,
      accounts: PRELUDE_ACCOUNTS,
      names: PRELUDE_NAMES,
      balances: { bank: "0", payer: "750", payee: "250", third: "0" },
      locked: { bank: "0", payer: "0", payee: "0", third: "0" },
      escrows: [],
      bals: { bank: 0, payer: 750, payee: 250, third: 0 },
      seqs: { bank: 0, payer: 1, payee: 0, third: 0 },
      states: { bank: "open", payer: "open", payee: "open", third: "open" },
      payments: [
        PRELUDE_MINT,
        { h: "h09", kind: "pay", actor: "payer", to: "payee", amt: 250, seq: 1, status: "settled", acked: false, why: null },
      ],
      pending: [], reqs: [],
    },
  },
  {
    name: "acked-is-final",
    input_desc:
      "The same payment, plus the banker's ack. NOTHING about the money changes — an ack is finality, " +
      "not validity — only the status moves from \"settled\" to \"final\".",
    entries: [
      ...prelude(),
      entry("h09", 9, A.payerPub, opPay(TS, po1)),
      entry("h10", 10, A.bankPub, opAck(ack1.ts, "h09", ack1.bsig)),
    ],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: CHARTER_LEI,
      supplyExact: "1000", supply: 1000, iseq: 1, rate: null,
      accounts: PRELUDE_ACCOUNTS,
      names: PRELUDE_NAMES,
      balances: { bank: "0", payer: "750", payee: "250", third: "0" },
      locked: { bank: "0", payer: "0", payee: "0", third: "0" },
      escrows: [],
      bals: { bank: 0, payer: 750, payee: 250, third: 0 },
      seqs: { bank: 0, payer: 1, payee: 0, third: 0 },
      states: { bank: "open", payer: "open", payee: "open", third: "open" },
      payments: [
        PRELUDE_MINT,
        { h: "h09", kind: "pay", actor: "payer", to: "payee", amt: 250, seq: 1, status: "final", acked: true, why: null },
      ],
      pending: [], reqs: [],
    },
  },
  {
    name: "double-spend-unacked",
    input_desc:
      "Payer signs TWO orders for slot 1 — 600 to payee (h09) and 600 to third (h10) — and both reach the log " +
      "at Lamport clock 9. Payer holds 1000, so only one can be honoured. With no ack, (clock, hash)-first " +
      "wins and \"h09\" < \"h10\". Hand-computed: payer 400, payee 600, third 0; h10 fails with why \"seq\".",
    entries: [
      ...prelude(),
      entry("h09", 9, A.payerPub, opPay(TS, poA)),
      entry("h10", 9, A.payerPub, opPay(TS, poB)),
    ],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: CHARTER_LEI,
      supplyExact: "1000", supply: 1000, iseq: 1, rate: null,
      accounts: PRELUDE_ACCOUNTS,
      names: PRELUDE_NAMES,
      balances: { bank: "0", payer: "400", payee: "600", third: "0" },
      locked: { bank: "0", payer: "0", payee: "0", third: "0" },
      escrows: [],
      bals: { bank: 0, payer: 400, payee: 600, third: 0 },
      seqs: { bank: 0, payer: 1, payee: 0, third: 0 },
      states: { bank: "open", payer: "open", payee: "open", third: "open" },
      payments: [
        PRELUDE_MINT,
        { h: "h09", kind: "pay", actor: "payer", to: "payee", amt: 600, seq: 1, status: "settled", acked: false, why: null },
        { h: "h10", kind: "pay", actor: "payer", to: "third", amt: 600, seq: 1, status: "failed", acked: false, why: "seq" },
      ],
      pending: [], reqs: [],
    },
  },
  {
    name: "ack-pins-the-clock-loser",
    input_desc:
      "The identical entry set as double-spend-unacked, plus ONE ack — on h10, the order that LOST the " +
      "(clock, hash) race. An acked entry beats an unacked one, so the winner flips. Hand-computed: " +
      "payer 400, payee 0, third 600; h09 now fails with why \"seq\" and h10 is final. This pair is the " +
      "whole argument for the ack rule: the banker's notary act is what decides, and it is visible to " +
      "everyone.",
    entries: [
      ...prelude(),
      entry("h09", 9, A.payerPub, opPay(TS, poA)),
      entry("h10", 9, A.payerPub, opPay(TS, poB)),
      entry("h11", 11, A.bankPub, opAck(ackB.ts, "h10", ackB.bsig)),
    ],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: CHARTER_LEI,
      supplyExact: "1000", supply: 1000, iseq: 1, rate: null,
      accounts: PRELUDE_ACCOUNTS,
      names: PRELUDE_NAMES,
      balances: { bank: "0", payer: "400", payee: "0", third: "600" },
      locked: { bank: "0", payer: "0", payee: "0", third: "0" },
      escrows: [],
      bals: { bank: 0, payer: 400, payee: 0, third: 600 },
      seqs: { bank: 0, payer: 1, payee: 0, third: 0 },
      states: { bank: "open", payer: "open", payee: "open", third: "open" },
      payments: [
        PRELUDE_MINT,
        { h: "h09", kind: "pay", actor: "payer", to: "payee", amt: 600, seq: 1, status: "failed", acked: false, why: "seq" },
        { h: "h10", kind: "pay", actor: "payer", to: "third", amt: 600, seq: 1, status: "final", acked: true, why: null },
      ],
      pending: [], reqs: [],
    },
  },
  {
    name: "withheld-backdated-no-ack",
    input_desc:
      "A member signs an order and WITHHOLDS the entry, releasing it weeks later with a back-dated Lamport " +
      "clock of 8 and hash \"h08a\" — which sorts immediately after the prelude's mint (\"h08\" < \"h08a\") " +
      "and therefore before h09, the payment everyone has already acted on. With no ack anywhere, " +
      "(clock, hash)-first is blind to when an entry actually arrived, so the withheld order takes slot 1. " +
      "Hand-computed: payer 1000 - 600 = 400, payee 0, third 600 — the money went somewhere else, and h09 " +
      "flips from settled to failed with why \"seq\". THIS IS THE HOLE THE ACK CLOSES; the next scenario " +
      "closes it, on the same entry set plus one ack.",
    entries: [
      ...prelude(),
      entry("h09", 9, A.payerPub, opPay(TS, poA)),
      entry("h08a", 8, A.payerPub, opPay(TS, poC)),
    ],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: CHARTER_LEI,
      supplyExact: "1000", supply: 1000, iseq: 1, rate: null,
      accounts: PRELUDE_ACCOUNTS,
      names: PRELUDE_NAMES,
      balances: { bank: "0", payer: "400", payee: "0", third: "600" },
      locked: { bank: "0", payer: "0", payee: "0", third: "0" },
      escrows: [],
      bals: { bank: 0, payer: 400, payee: 0, third: 600 },
      seqs: { bank: 0, payer: 1, payee: 0, third: 0 },
      states: { bank: "open", payer: "open", payee: "open", third: "open" },
      payments: [
        PRELUDE_MINT,
        { h: "h08a", kind: "pay", actor: "payer", to: "third", amt: 600, seq: 1, status: "settled", acked: false, why: null },
        { h: "h09", kind: "pay", actor: "payer", to: "payee", amt: 600, seq: 1, status: "failed", acked: false, why: "seq" },
      ],
      pending: [], reqs: [],
    },
  },
  {
    name: "withheld-backdated-after-ack",
    input_desc:
      "The same withheld, back-dated entry — but the banker acked h09. An acked entry beats an unacked one " +
      "whatever its clock says, so the withheld order can no longer displace anything. Hand-computed: " +
      "payer 400, payee 600, third 0; h08a fails with why \"seq\". " +
      "\"Arriving before or after the ack\" has no meaning in a fold that is a pure function of its entry " +
      "set, and that is the point: the test folds this set with h08a inserted FIRST and LAST and asserts the " +
      "two snapshots are byte-identical. What decides is whether the ack EXISTS, not when anything showed up.",
    entries: [
      ...prelude(),
      entry("h09", 9, A.payerPub, opPay(TS, poA)),
      entry("h12", 10, A.bankPub, opAck(ackA.ts, "h09", ackA.bsig)),
      entry("h08a", 8, A.payerPub, opPay(TS, poC)),
    ],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: CHARTER_LEI,
      supplyExact: "1000", supply: 1000, iseq: 1, rate: null,
      accounts: PRELUDE_ACCOUNTS,
      names: PRELUDE_NAMES,
      balances: { bank: "0", payer: "400", payee: "600", third: "0" },
      locked: { bank: "0", payer: "0", payee: "0", third: "0" },
      escrows: [],
      bals: { bank: 0, payer: 400, payee: 600, third: 0 },
      seqs: { bank: 0, payer: 1, payee: 0, third: 0 },
      states: { bank: "open", payer: "open", payee: "open", third: "open" },
      payments: [
        PRELUDE_MINT,
        { h: "h08a", kind: "pay", actor: "payer", to: "third", amt: 600, seq: 1, status: "failed", acked: false, why: "seq" },
        { h: "h09", kind: "pay", actor: "payer", to: "payee", amt: 600, seq: 1, status: "final", acked: true, why: null },
      ],
      pending: [], reqs: [],
    },
  },
  {
    name: "withheld-backdated-mint-displaces-an-issuance",
    input_desc:
      "THE SAME HOLE, ON THE ISSUANCE SIDE, and it is the one the ack cannot be asked to close. The banker " +
      "withholds a second `mint` claiming issuance slot 1 — 1 minor unit to the banker's own account — and " +
      "releases it later with a back-dated Lamport clock of 7 and hash \"h07a\", which sorts before the " +
      "prelude's h08 (clock 8). No ack exists, so (clock, hash)-first decides and the withheld issuance takes " +
      "the slot. Hand-computed: bank 1, payer 0, payee 0, third 0; supply 1, not 1000. h08 flips from settled " +
      "to failed with why \"seq\", and the payer's 1000 — money they had been shown as theirs — is gone. " +
      "This is the ONE way a banker can take money out of a customer's account: `burn` debits only the " +
      "banker's own, and `acct close` freezes a balance rather than emptying it. Attributable (both mints " +
      "are signed by the banker and every member holds both) and, with no ack anywhere, not prevented. " +
      "THIS IS THE CONFISCATION WINDOW; the wri-ack scenario below closes it, on the same entry set plus " +
      "one ack.",
    entries: [
      ...prelude(),
      entry("h07a", 7, A.bankPub, opMint(TS, 1, A.bankPub, 1)),
    ],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: CHARTER_LEI,
      supplyExact: "1", supply: 1, iseq: 1, rate: null,
      accounts: PRELUDE_ACCOUNTS,
      names: PRELUDE_NAMES,
      balances: { bank: "1", payer: "0", payee: "0", third: "0" },
      locked: { bank: "0", payer: "0", payee: "0", third: "0" },
      escrows: [],
      bals: { bank: 1, payer: 0, payee: 0, third: 0 },
      seqs: { bank: 0, payer: 0, payee: 0, third: 0 },
      states: { bank: "open", payer: "open", payee: "open", third: "open" },
      payments: [
        { h: "h07a", kind: "mint", actor: "bank", to: "bank", amt: 1, seq: 1, status: "settled", acked: false, why: null },
        { h: "h08", kind: "mint", actor: "bank", to: "payer", amt: 1000, seq: 1, status: "failed", acked: false, why: "seq" },
      ],
      pending: [], reqs: [],
    },
  },
  {
    name: "a-wri-ack-closes-the-confiscation-window",
    input_desc:
      "THE MONEY VECTOR OF THE ISSUANCE RECEIPT: the same withheld back-dated mint, plus the banker's ack on " +
      "h08 — and since the wri, that ack finally SIGNS something. Its `bsig` is Ed25519 over the wallet-kit " +
      "issuance preimage (`wpay-iss|v1|` + canon of the wri minus bsig) for h08's mint — cur, issuance slot " +
      "1, 1000 to payer, h = \"h08\" — and its `ts` is the wri's own, the wrc's exact discipline. The fold's " +
      "ack pre-pass is BLIND TO KIND, so the mechanism works exactly as it does for a payment: acked beats " +
      "unacked whatever the clock says, h08 keeps issuance slot 1 and goes `final`, and the withheld h07a " +
      "fails with why \"seq\". Hand-computed: bank 0, payer 1000; supply 1000 — the payer's money stays " +
      "theirs, which is the window closing. `receiptFor(\"h08\")` now rebuilds the wri and it verifies for " +
      "a third party; the recipient keeps it, and no back-dated log entry can displace what it names.",
    entries: [
      ...prelude(),
      entry("h07a", 7, A.bankPub, opMint(TS, 1, A.bankPub, 1)),
      entry("h20", 20, A.bankPub, opAck(WRI_ACK_H08.ts, "h08", WRI_ACK_H08.bsig)),
    ],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: CHARTER_LEI,
      supplyExact: "1000", supply: 1000, iseq: 1, rate: null,
      accounts: PRELUDE_ACCOUNTS,
      names: PRELUDE_NAMES,
      balances: { bank: "0", payer: "1000", payee: "0", third: "0" },
      locked: { bank: "0", payer: "0", payee: "0", third: "0" },
      escrows: [],
      bals: { bank: 0, payer: 1000, payee: 0, third: 0 },
      seqs: { bank: 0, payer: 0, payee: 0, third: 0 },
      states: { bank: "open", payer: "open", payee: "open", third: "open" },
      payments: [
        { h: "h07a", kind: "mint", actor: "bank", to: "bank", amt: 1, seq: 1, status: "failed", acked: false, why: "seq" },
        { h: "h08", kind: "mint", actor: "bank", to: "payer", amt: 1000, seq: 1, status: "final", acked: true, why: null },
      ],
      pending: [], reqs: [],
    },
  },
  {
    name: "overdraft-consumes-the-slot",
    input_desc:
      "Payer holds 1000 and signs an order for 5000 in slot 2 (h09) — it fails with why \"insufficient\", and " +
      "THE SLOT IS SPENT ANYWAY. The banker then mints 9000 to payer (h10), and the SAME order is re-appended " +
      "by a relay as a new entry (h11). Hand-computed: payer 1000 + 9000 = 10000, payee 0; supply 10000. " +
      "h09 stays permanently failed and h11 loses the slot to it with why \"seq\". If a failure released its " +
      "slot, h11 would settle here and the same money would move twice, months apart, with no equivocation " +
      "anywhere in the log. `seqs.payer` is 2: slot 1 was never claimed and is now skipped forever, which is " +
      "the safe direction for a counter that must never hand out a spent slot.",
    entries: [
      ...prelude(),
      entry("h09", 9, A.payerPub, opPay(TS, poD)),
      entry("h10", 10, A.bankPub, opMint(TS, 2, A.payerPub, 9000)),
      entry("h11", 11, A.thirdPub, opPay(TS, poD)),
    ],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: CHARTER_LEI,
      supplyExact: "10000", supply: 10000, iseq: 2, rate: null,
      accounts: PRELUDE_ACCOUNTS,
      names: PRELUDE_NAMES,
      balances: { bank: "0", payer: "10000", payee: "0", third: "0" },
      locked: { bank: "0", payer: "0", payee: "0", third: "0" },
      escrows: [],
      bals: { bank: 0, payer: 10000, payee: 0, third: 0 },
      seqs: { bank: 0, payer: 2, payee: 0, third: 0 },
      states: { bank: "open", payer: "open", payee: "open", third: "open" },
      payments: [
        PRELUDE_MINT,
        { h: "h09", kind: "pay", actor: "payer", to: "payee", amt: 5000, seq: 2, status: "failed", acked: false, why: "insufficient" },
        { h: "h10", kind: "mint", actor: "bank", to: "payer", amt: 9000, seq: 2, status: "settled", acked: false, why: null },
        { h: "h11", kind: "pay", actor: "payer", to: "payee", amt: 5000, seq: 2, status: "failed", acked: false, why: "seq" },
      ],
      pending: [], reqs: [],
    },
  },
  {
    name: "third-party-relay",
    input_desc:
      "The payer is offline. `third` pulls the payer's signed order out of the mailbox and appends it. " +
      "The entry's AUTHOR is third; the payment's actor is the PAYER, because a `pay` is authorized by " +
      "`po.sig` and not by who appended it. Hand-computed: identical to settled-provisionally — payer 750, " +
      "payee 250. This is what makes offline payment work at all.",
    entries: [...prelude(), entry("h09", 9, A.thirdPub, opPay(TS, po1))],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: CHARTER_LEI,
      supplyExact: "1000", supply: 1000, iseq: 1, rate: null,
      accounts: PRELUDE_ACCOUNTS,
      names: PRELUDE_NAMES,
      balances: { bank: "0", payer: "750", payee: "250", third: "0" },
      locked: { bank: "0", payer: "0", payee: "0", third: "0" },
      escrows: [],
      bals: { bank: 0, payer: 750, payee: 250, third: 0 },
      seqs: { bank: 0, payer: 1, payee: 0, third: 0 },
      states: { bank: "open", payer: "open", payee: "open", third: "open" },
      payments: [
        PRELUDE_MINT,
        { h: "h09", kind: "pay", actor: "payer", to: "payee", amt: 250, seq: 1, status: "settled", acked: false, why: null },
      ],
      pending: [], reqs: [],
    },
  },
  {
    name: "forged-order-is-not-an-order",
    input_desc:
      "The same relay, but one bit of `po.sig` is flipped. The order does not verify, so it is not a slot " +
      "contender and is not recorded at all. Hand-computed: exactly the prelude.",
    entries: [...prelude(), entry("h09", 9, A.thirdPub, opPay(TS, poForged))],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: CHARTER_LEI,
      supplyExact: "1000", supply: 1000, iseq: 1, rate: null,
      accounts: PRELUDE_ACCOUNTS,
      names: PRELUDE_NAMES,
      balances: { bank: "0", payer: "1000", payee: "0", third: "0" },
      locked: { bank: "0", payer: "0", payee: "0", third: "0" },
      escrows: [],
      bals: { bank: 0, payer: 1000, payee: 0, third: 0 },
      seqs: { bank: 0, payer: 0, payee: 0, third: 0 },
      states: { bank: "open", payer: "open", payee: "open", third: "open" },
      payments: [PRELUDE_MINT],
      pending: [], reqs: [],
    },
  },
  {
    name: "another-banks-paper",
    input_desc:
      "A valid order denominated in bank2's LEI, appended into bank1's log. It fails with why \"cur\" and it " +
      "consumes NO slot here — one bank's sequence space is not another's. Hand-computed: balances unchanged, " +
      "`seqs.payer` still 0.",
    entries: [...prelude(), entry("h09", 9, A.payerPub, opPay(TS, poOther))],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: CHARTER_LEI,
      supplyExact: "1000", supply: 1000, iseq: 1, rate: null,
      accounts: PRELUDE_ACCOUNTS,
      names: PRELUDE_NAMES,
      balances: { bank: "0", payer: "1000", payee: "0", third: "0" },
      locked: { bank: "0", payer: "0", payee: "0", third: "0" },
      escrows: [],
      bals: { bank: 0, payer: 1000, payee: 0, third: 0 },
      seqs: { bank: 0, payer: 0, payee: 0, third: 0 },
      states: { bank: "open", payer: "open", payee: "open", third: "open" },
      payments: [
        PRELUDE_MINT,
        { h: "h09", kind: "pay", actor: "payer", to: "payee", amt: 100, seq: 1, status: "failed", acked: false, why: "cur" },
      ],
      pending: [], reqs: [],
    },
  },
  {
    name: "banker-only-ops-from-a-customer",
    input_desc:
      "The payer appends a mint, a burn, an account approval, a rate and an ack. Every one of them is " +
      "banker-only and none folds. Hand-computed: byte-identical to the prelude — no balance moves, no " +
      "account is created, `rate` stays null, and nothing is even recorded as failed, because an op the " +
      "fold has no authority to judge is an op it drops.",
    entries: [
      ...prelude(),
      entry("h09", 9, A.payerPub, opMint(TS, 5, A.payerPub, 999999)),
      entry("h10", 10, A.payerPub, opBurn(TS, 6, 100)),
      entry("h11", 11, A.payerPub, opAcct(TS, A.outsiderPub, "approve")),
      entry("h12", 12, A.payerPub, opRate(TS, 3, 2)),
      entry("h13", 13, A.payerPub, opAck(TS, "h08", ack1.bsig)),
    ],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: CHARTER_LEI,
      supplyExact: "1000", supply: 1000, iseq: 1, rate: null,
      accounts: PRELUDE_ACCOUNTS,
      names: PRELUDE_NAMES,
      balances: { bank: "0", payer: "1000", payee: "0", third: "0" },
      locked: { bank: "0", payer: "0", payee: "0", third: "0" },
      escrows: [],
      bals: { bank: 0, payer: 1000, payee: 0, third: 0 },
      seqs: { bank: 0, payer: 0, payee: 0, third: 0 },
      states: { bank: "open", payer: "open", payee: "open", third: "open" },
      payments: [PRELUDE_MINT],
      pending: [], reqs: [],
    },
  },
  {
    name: "identity-is-required-to-transact",
    input_desc:
      "Two entries authored by a per-device OrbitDB FALLBACK identity (a 66-character secp256k1 hex id, not a " +
      "canonical 43-character suite key). Its `open` does not create an account and its `req` is ignored — an " +
      "identity-less visitor is read-only. Its RELAY of the payer's signed order does settle, because a `pay` " +
      "is authorized by `po.sig` and never by authorship. Hand-computed: payer 750, payee 250, no fifth account.",
    entries: [
      ...prelude(),
      entry("h09", 9, FALLBACK_ID, opOpen(TS, "Ghost")),
      entry("h10", 10, FALLBACK_ID, opReq(TS, A.payerPub, 5)),
      entry("h11", 11, FALLBACK_ID, opPay(TS, po1)),
    ],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: CHARTER_LEI,
      supplyExact: "1000", supply: 1000, iseq: 1, rate: null,
      accounts: PRELUDE_ACCOUNTS,
      names: PRELUDE_NAMES,
      balances: { bank: "0", payer: "750", payee: "250", third: "0" },
      locked: { bank: "0", payer: "0", payee: "0", third: "0" },
      escrows: [],
      bals: { bank: 0, payer: 750, payee: 250, third: 0 },
      seqs: { bank: 0, payer: 1, payee: 0, third: 0 },
      states: { bank: "open", payer: "open", payee: "open", third: "open" },
      payments: [
        PRELUDE_MINT,
        { h: "h11", kind: "pay", actor: "payer", to: "payee", amt: 250, seq: 1, status: "settled", acked: false, why: null },
      ],
      pending: [], reqs: [],
    },
  },
  {
    name: "burn-debits-the-banker-only",
    input_desc:
      "The banker mints 500 to itself (slot 2) and burns 200 (slot 3), then tries to burn 100000 (slot 4). " +
      "Hand-computed: bank 500 - 200 = 300; supply 1000 + 500 - 200 = 1300. The over-burn fails with why " +
      "\"insufficient\" and its slot stays spent. A banker cannot burn a CUSTOMER's balance — `burn` names no " +
      "account and always debits the author, who must be the banker.",
    entries: [
      ...prelude(),
      entry("h09", 9, A.bankPub, opMint(TS, 2, A.bankPub, 500)),
      entry("h10", 10, A.bankPub, opBurn(TS, 3, 200)),
      entry("h11", 11, A.bankPub, opBurn(TS, 4, 100000)),
    ],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: CHARTER_LEI,
      supplyExact: "1300", supply: 1300, iseq: 4, rate: null,
      accounts: PRELUDE_ACCOUNTS,
      names: PRELUDE_NAMES,
      balances: { bank: "300", payer: "1000", payee: "0", third: "0" },
      locked: { bank: "0", payer: "0", payee: "0", third: "0" },
      escrows: [],
      bals: { bank: 300, payer: 1000, payee: 0, third: 0 },
      seqs: { bank: 0, payer: 0, payee: 0, third: 0 },
      states: { bank: "open", payer: "open", payee: "open", third: "open" },
      payments: [
        PRELUDE_MINT,
        { h: "h09", kind: "mint", actor: "bank", to: "bank", amt: 500, seq: 2, status: "settled", acked: false, why: null },
        { h: "h10", kind: "burn", actor: "bank", to: null, amt: 200, seq: 3, status: "settled", acked: false, why: null },
        { h: "h11", kind: "burn", actor: "bank", to: null, amt: 100000, seq: 4, status: "failed", acked: false, why: "insufficient" },
      ],
      pending: [], reqs: [],
    },
  },
  {
    name: "closed-accounts",
    input_desc:
      "The banker closes payee (h09). A payment to a closed account fails with why \"unknown-payer\" and its " +
      "slot is spent (h10). Re-opening is the BANKER's act, never the customer's: payee's own `open` (h11) " +
      "cannot reopen it, and only `acct approve` (h12) does. A payment after that settles (h13). " +
      "Hand-computed: payer 1000 - 250 = 750, payee 250; `seqs.payer` 2.",
    entries: [
      ...prelude(),
      entry("h09", 9, A.bankPub, opAcct(TS, A.payeePub, "close")),
      entry("h10", 10, A.payerPub, opPay(TS, ord({ seed: SEED_PAYER, idN: 0x70, cur: CUR, amt: 250, seq: 1, to: A.payeePub }))),
      entry("h11", 11, A.payeePub, opOpen(TS, "Payee")),
      entry("h12", 12, A.bankPub, opAcct(TS, A.payeePub, "approve")),
      entry("h13", 13, A.payerPub, opPay(TS, ord({ seed: SEED_PAYER, idN: 0x80, cur: CUR, amt: 250, seq: 2, to: A.payeePub }))),
    ],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: CHARTER_LEI,
      supplyExact: "1000", supply: 1000, iseq: 1, rate: null,
      accounts: PRELUDE_ACCOUNTS,
      names: PRELUDE_NAMES,
      balances: { bank: "0", payer: "750", payee: "250", third: "0" },
      locked: { bank: "0", payer: "0", payee: "0", third: "0" },
      escrows: [],
      bals: { bank: 0, payer: 750, payee: 250, third: 0 },
      seqs: { bank: 0, payer: 2, payee: 0, third: 0 },
      states: { bank: "open", payer: "open", payee: "open", third: "open" },
      payments: [
        PRELUDE_MINT,
        { h: "h10", kind: "pay", actor: "payer", to: "payee", amt: 250, seq: 1, status: "failed", acked: false, why: "unknown-payer" },
        { h: "h13", kind: "pay", actor: "payer", to: "payee", amt: 250, seq: 2, status: "settled", acked: false, why: null },
      ],
      pending: [], reqs: [],
    },
  },
  {
    name: "rate-and-req",
    input_desc:
      "The banker asserts a rate of 3/2 GAZ per unit (h09, then 7/4 at h10 — last writer in (clock, hash) " +
      "order wins). Payer asks payee for 500 (h11); the outsider, who holds no account, asks for 9 (h12) and " +
      "is ignored. `rate` is an ASSERTION, not an oracle, and a `req` is a hint nothing in the fold consumes.",
    entries: [
      ...prelude(),
      entry("h09", 9, A.bankPub, opRate(TS, 3, 2)),
      entry("h10", 10, A.bankPub, opRate(TS, 7, 4)),
      entry("h11", 11, A.payerPub, opReq(TS, A.payeePub, 500, "chirie")),
      entry("h12", 12, A.outsiderPub, opReq(TS, A.payeePub, 9)),
    ],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: CHARTER_LEI,
      supplyExact: "1000", supply: 1000, iseq: 1, rate: { num: 7, den: 4 },
      accounts: PRELUDE_ACCOUNTS,
      names: PRELUDE_NAMES,
      balances: { bank: "0", payer: "1000", payee: "0", third: "0" },
      locked: { bank: "0", payer: "0", payee: "0", third: "0" },
      escrows: [],
      bals: { bank: 0, payer: 1000, payee: 0, third: 0 },
      seqs: { bank: 0, payer: 0, payee: 0, third: 0 },
      states: { bank: "open", payer: "open", payee: "open", third: "open" },
      payments: [PRELUDE_MINT],
      pending: [],
      reqs: [{ h: "h11", from: "payer", to: "payee", amt: 500, memo: "chirie", ts: TS, clock: 11 }],
    },
  },
  {
    name: "join-open-self-serves",
    input_desc:
      "A charter with join:\"open\". An `open` admits the author immediately, with no banker act at all — the " +
      "bank works with the banker permanently offline. Hand-computed: three accounts (bank, payer, payee), " +
      "all open, no pending list, no money.",
    entries: [
      entry("h01", 1, A.bankPub, opCharter(TS, "Banca Deschisa", "RON", "lei", 2, "open")),
      entry("h02", 2, A.payerPub, opOpen(TS, "Payer")),
      entry("h03", 3, A.payeePub, opOpen(TS, "Payee")),
    ],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.RON`, charter: { name: "Banca Deschisa", code: "RON", sym: "lei", dec: 2, join: "open" },
      supplyExact: "0", supply: 0, iseq: 0, rate: null,
      accounts: ["bank", "payer", "payee"],
      names: { bank: "", payer: "Payer", payee: "Payee" },
      balances: { bank: "0", payer: "0", payee: "0" },
      locked: { bank: "0", payer: "0", payee: "0" },
      escrows: [],
      bals: { bank: 0, payer: 0, payee: 0 },
      seqs: { bank: 0, payer: 0, payee: 0 },
      states: { bank: "open", payer: "open", payee: "open" },
      payments: [], pending: [], reqs: [],
    },
  },
  {
    name: "knocks-wait-for-the-banker",
    input_desc:
      "join:\"approve\": two knocks, one approval. Hand-computed: payer is open, payee is pending and appears " +
      "in the pending list under the name it knocked with.",
    entries: [
      entry("h01", 1, A.bankPub, opCharter(TS, "Banca Test", "LEI", "L", 2, "approve")),
      entry("h02", 2, A.payerPub, opOpen(TS, "Payer")),
      entry("h03", 3, A.payeePub, opOpen(TS, "Payee")),
      entry("h04", 4, A.bankPub, opAcct(TS, A.payerPub, "approve")),
    ],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: CHARTER_LEI,
      supplyExact: "0", supply: 0, iseq: 0, rate: null,
      accounts: ["bank", "payer", "payee"],
      names: { bank: "", payer: "Payer", payee: "Payee" },
      balances: { bank: "0", payer: "0", payee: "0" },
      locked: { bank: "0", payer: "0", payee: "0" },
      escrows: [],
      bals: { bank: 0, payer: 0, payee: 0 },
      seqs: { bank: 0, payer: 0, payee: 0 },
      states: { bank: "open", payer: "open", payee: "pending" },
      payments: [],
      pending: [{ id: "payee", name: "Payee" }],
      reqs: [],
    },
  },
  {
    name: "first-charter-from-the-banker-wins",
    input_desc:
      "The banker charters LEI at clock 1 (hLEI) and RON at clock 5 (hRON), and a customer charters something " +
      "at clock 0. Only the banker's count, and the FIRST of those in (clock, hash) order is the bank — so a " +
      "banker cannot redenominate a bank out from under its customers, and the attempt stays in the log " +
      "forever. Hand-computed: cur ends \".LEI\".",
    entries: [
      entry("hCUS", 0, A.payerPub, opCharter(TS, "Not A Bank", "USD", "$", 2, "open")),
      entry("hLEI", 1, A.bankPub, opCharter(TS, "Banca Test", "LEI", "L", 2, "open")),
      entry("hRON", 5, A.bankPub, opCharter(TS, "Banca Test", "RON", "lei", 2, "open")),
    ],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: { name: "Banca Test", code: "LEI", sym: "L", dec: 2, join: "open" },
      supplyExact: "0", supply: 0, iseq: 0, rate: null,
      accounts: ["bank"],
      names: { bank: "" },
      balances: { bank: "0" },
      locked: { bank: "0" },
      escrows: [],
      bals: { bank: 0 },
      seqs: { bank: 0 },
      states: { bank: "open" },
      payments: [], pending: [], reqs: [],
    },
  },
  {
    name: "no-charter-no-bank",
    input_desc:
      "A log full of activity and no charter from the banker. Nothing folds: the bank does not exist until it " +
      "is chartered, so a payment cannot precede the currency it is denominated in.",
    entries: [
      entry("h02", 2, A.payerPub, opOpen(TS, "Payer")),
      entry("h03", 3, A.bankPub, opAcct(TS, A.payerPub, "approve")),
      entry("h04", 4, A.bankPub, opMint(TS, 1, A.payerPub, 1000)),
    ],
    expect: {
      ok: false, banker: null, cur: null, charter: null,
      supplyExact: "0", supply: 0, iseq: 0, rate: null,
      accounts: [],
      names: {},
      balances: {},
      locked: {  },
      escrows: [],
      bals: {},
      seqs: {},
      states: {},
      payments: [], pending: [], reqs: [],
    },
  },
  {
    name: "code-GAZ-is-refused",
    input_desc:
      "The banker charters code \"GAZ\". `~.GAZ` is the suite's reserved neutral unit of account — quote-only, " +
      "permanently unissued, never payable — and a bank minting its own GAZ would read as the neutral unit in " +
      "every UI that shows a code without its banker. The charter does not validate, so it is dropped at " +
      "ingest and there is no bank at all.",
    entries: [
      entry("h01", 1, A.bankPub, opCharter(TS, "Fake Gaz", "GAZ", "g", 2, "open")),
      entry("h02", 2, A.payerPub, opOpen(TS, "Payer")),
    ],
    expect: {
      ok: false, banker: null, cur: null, charter: null,
      supplyExact: "0", supply: 0, iseq: 0, rate: null,
      accounts: [],
      names: {},
      balances: {},
      locked: {  },
      escrows: [],
      bals: {},
      seqs: {},
      states: {},
      payments: [], pending: [], reqs: [],
    },
  },
  {
    name: "the-banker-pays-out-of-their-own-bank",
    input_desc:
      "Prelude (which already spent ISSUANCE slot 1 on the mint to payer), then the banker mints 500 to " +
      "itself at issuance slot 2, then the BANKER PAYS payee 100 with a wallet order carrying seq 1 — the " +
      "number a fresh wallet hands out, because the banker's wallet holds no receipts of its own. " +
      "Hand-computed: bank 500 - 100 = 400, payer 1000, payee 100, third 0; supply 1000 + 500 = 1500; " +
      "iseq 2 and seqs.bank 1. TWO SEQUENCE SPACES: issuance is \"i|<banker>|n\" and payment is " +
      "\"p|<payer>|n\", so the banker's mint at 1 and the banker's order at 1 are different slots. Under one " +
      "shared space they were the same slot and one of the two died `why:\"seq\"` permanently — the payment " +
      "if the mint sorted first, the ISSUANCE if the order did, which made supply itself diverge from what " +
      "everyone was told had been minted. Neither is retryable: a consumed slot is permanent, and a banca " +
      "`failed` is not a `wrj`, so the wallet's counter never learns to move.",
    entries: [
      ...prelude(),
      entry("h09", 9, A.bankPub, opMint(TS, 2, A.bankPub, 500)),
      entry("h10", 10, A.bankPub, opPay(TS, poBank)),
    ],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: CHARTER_LEI,
      supplyExact: "1500", supply: 1500, iseq: 2, rate: null,
      accounts: PRELUDE_ACCOUNTS,
      names: PRELUDE_NAMES,
      balances: { bank: "400", payer: "1000", payee: "100", third: "0" },
      locked: { bank: "0", payer: "0", payee: "0", third: "0" },
      escrows: [],
      bals: { bank: 400, payer: 1000, payee: 100, third: 0 },
      seqs: { bank: 1, payer: 0, payee: 0, third: 0 },
      states: { bank: "open", payer: "open", payee: "open", third: "open" },
      payments: [
        PRELUDE_MINT,
        { h: "h09", kind: "mint", actor: "bank", to: "bank", amt: 500, seq: 2, status: "settled", acked: false, why: null },
        { h: "h10", kind: "pay", actor: "bank", to: "payee", amt: 100, seq: 1, status: "settled", acked: false, why: null },
      ],
      pending: [], reqs: [],
    },
  },
  {
    name: "an-ack-on-both-contenders",
    input_desc:
      "The double-spend pair again — h09 and h10 both claiming payment slot (payer, 1) at Lamport clock 9 — " +
      "and the banker acks BOTH. Equivocation, and the fold has an answer for it: acked-vs-unacked no longer " +
      "separates the two, so (clock, hash) decides and \"h09\" < \"h10\". Hand-computed: payer 400, payee 600, " +
      "third 0. h10 is `failed` with why \"seq\" AND `acked: true` — a valid ack naming it exists, and a UI " +
      "asking \"did the banker answer my payment?\" must not be told no. The two are carried separately for " +
      "exactly this case.",
    entries: [
      ...prelude(),
      entry("h09", 9, A.payerPub, opPay(TS, poA)),
      entry("h10", 9, A.payerPub, opPay(TS, poB)),
      entry("h11", 11, A.bankPub, opAck(ackA9.ts, "h09", ackA9.bsig)),
      entry("h12", 12, A.bankPub, opAck(ackB.ts, "h10", ackB.bsig)),
    ],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: CHARTER_LEI,
      supplyExact: "1000", supply: 1000, iseq: 1, rate: null,
      accounts: PRELUDE_ACCOUNTS,
      names: PRELUDE_NAMES,
      balances: { bank: "0", payer: "400", payee: "600", third: "0" },
      locked: { bank: "0", payer: "0", payee: "0", third: "0" },
      escrows: [],
      bals: { bank: 0, payer: 400, payee: 600, third: 0 },
      seqs: { bank: 0, payer: 1, payee: 0, third: 0 },
      states: { bank: "open", payer: "open", payee: "open", third: "open" },
      payments: [
        PRELUDE_MINT,
        { h: "h09", kind: "pay", actor: "payer", to: "payee", amt: 600, seq: 1, status: "final", acked: true, why: null },
        { h: "h10", kind: "pay", actor: "payer", to: "third", amt: 600, seq: 1, status: "failed", acked: true, why: "seq" },
      ],
      pending: [], reqs: [],
    },
  },
  {
    name: "an-acked-mint-is-final-with-a-wri",
    input_desc:
      "The prelude plus the banker's ack on its OWN mint (h08), `bsig` over the wri preimage and `ts` the " +
      "wri's own. Hand-computed: the money is exactly the prelude's — an ack never moves anything — and the " +
      "mint's status goes \"settled\" -> \"final\". receiptFor(\"h08\") rebuilds the ten-key wri out of the " +
      "mint entry (seq, to, amt), the charter's cur, the entry hash and this ack's ts/bsig, and it verifies " +
      "against the banker's key. A BURN in the same position would still answer null — a burn names no " +
      "recipient, so there is no receipt to rebuild, by design and not by omission.",
    entries: [
      ...prelude(),
      entry("h20", 20, A.bankPub, opAck(WRI_ACK_H08.ts, "h08", WRI_ACK_H08.bsig)),
    ],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: CHARTER_LEI,
      supplyExact: "1000", supply: 1000, iseq: 1, rate: null,
      accounts: PRELUDE_ACCOUNTS,
      names: PRELUDE_NAMES,
      balances: { bank: "0", payer: "1000", payee: "0", third: "0" },
      locked: { bank: "0", payer: "0", payee: "0", third: "0" },
      escrows: [],
      bals: { bank: 0, payer: 1000, payee: 0, third: 0 },
      seqs: { bank: 0, payer: 0, payee: 0, third: 0 },
      states: { bank: "open", payer: "open", payee: "open", third: "open" },
      payments: [
        { h: "h08", kind: "mint", actor: "bank", to: "payer", amt: 1000, seq: 1, status: "final", acked: true, why: null },
      ],
      pending: [], reqs: [],
    },
  },
  {
    name: "a-mint-cannot-credit-a-closed-or-pending-account",
    input_desc:
      "join:\"approve\". Payer knocks and is never approved (state `pending`); payee is approved and then " +
      "CLOSED. The banker mints 100 to payer (issuance slot 1), 200 to payee (slot 2) and 700 to itself " +
      "(slot 3). Hand-computed: only the third moves anything — bank 700, payer 0, payee 0; supply 700, not " +
      "1000. `to` must be an OPEN account, else `failed`/\"unknown-payer\", and the issuance slot is spent " +
      "anyway. This is what stops a banker's mint from landing in an unapproved knock, and what stops one " +
      "from reviving a closed account's balance without the `acct approve` that would be visible in the log.",
    entries: [
      entry("h01", 1, A.bankPub, opCharter(TS, "Banca Test", "LEI", "L", 2, "approve")),
      entry("h02", 2, A.payerPub, opOpen(TS, "Payer")),
      entry("h03", 3, A.payeePub, opOpen(TS, "Payee")),
      entry("h04", 4, A.bankPub, opAcct(TS, A.payeePub, "approve")),
      entry("h05", 5, A.bankPub, opAcct(TS, A.payeePub, "close")),
      entry("h06", 6, A.bankPub, opMint(TS, 1, A.payerPub, 100)),
      entry("h07", 7, A.bankPub, opMint(TS, 2, A.payeePub, 200)),
      entry("h08", 8, A.bankPub, opMint(TS, 3, A.bankPub, 700)),
    ],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: CHARTER_LEI,
      supplyExact: "700", supply: 700, iseq: 3, rate: null,
      accounts: ["bank", "payer", "payee"],
      names: { bank: "", payer: "Payer", payee: "Payee" },
      balances: { bank: "700", payer: "0", payee: "0" },
      locked: { bank: "0", payer: "0", payee: "0" },
      escrows: [],
      bals: { bank: 700, payer: 0, payee: 0 },
      seqs: { bank: 0, payer: 0, payee: 0 },
      states: { bank: "open", payer: "pending", payee: "closed" },
      payments: [
        { h: "h06", kind: "mint", actor: "bank", to: "payer", amt: 100, seq: 1, status: "failed", acked: false, why: "unknown-payer" },
        { h: "h07", kind: "mint", actor: "bank", to: "payee", amt: 200, seq: 2, status: "failed", acked: false, why: "unknown-payer" },
        { h: "h08", kind: "mint", actor: "bank", to: "bank", amt: 700, seq: 3, status: "settled", acked: false, why: null },
      ],
      pending: [{ id: "payer", name: "Payer" }],
      reqs: [],
    },
  },
  {
    name: "a-closed-account-cannot-readmit-itself",
    input_desc:
      "join:\"open\", where an `open` really does admit — which is the only setting in which the readmission " +
      "guard is reachable at all. Payer and payee self-open, payer is minted 1000, the banker CLOSES payer " +
      "(h05), and payer appends its own `open` (h06) to get back in. It must not work: only `acct approve` " +
      "reopens, because closing an account is the one sanction a banker has and a sanction a customer can " +
      "lift is not one. Hand-computed: payer stays `closed`, its payment (h07) fails with " +
      "\"unknown-payer\" and spends payment slot 1 anyway — payer 1000, payee 0; supply 1000.",
    entries: [
      entry("h01", 1, A.bankPub, opCharter(TS, "Banca Deschisa", "LEI", "L", 2, "open")),
      entry("h02", 2, A.payerPub, opOpen(TS, "Payer")),
      entry("h03", 3, A.payeePub, opOpen(TS, "Payee")),
      entry("h04", 4, A.bankPub, opMint(TS, 1, A.payerPub, 1000)),
      entry("h05", 5, A.bankPub, opAcct(TS, A.payerPub, "close")),
      entry("h06", 6, A.payerPub, opOpen(TS, "Payer")),
      entry("h07", 7, A.payerPub, opPay(TS, poClosed)),
    ],
    expect: {
      ok: true, banker: "bank", cur: `${A.bankPub}.LEI`, charter: { name: "Banca Deschisa", code: "LEI", sym: "L", dec: 2, join: "open" },
      supplyExact: "1000", supply: 1000, iseq: 1, rate: null,
      accounts: ["bank", "payer", "payee"],
      names: { bank: "", payer: "Payer", payee: "Payee" },
      balances: { bank: "0", payer: "1000", payee: "0" },
      locked: { bank: "0", payer: "0", payee: "0" },
      escrows: [],
      bals: { bank: 0, payer: 1000, payee: 0 },
      seqs: { bank: 0, payer: 1, payee: 0 },
      states: { bank: "open", payer: "closed", payee: "open" },
      payments: [
        { h: "h04", kind: "mint", actor: "bank", to: "payer", amt: 1000, seq: 1, status: "settled", acked: false, why: null },
        { h: "h07", kind: "pay", actor: "payer", to: "payee", amt: 100, seq: 1, status: "failed", acked: false, why: "unknown-payer" },
      ],
      pending: [], reqs: [],
    },
  },
];

write("fold.json", {
  _doc:
    "banca's settlement fold. Every expectation below is HAND-COMPUTED from the input_desc sentence beside " +
    "it — no expectation was read out of the implementation. Every signature was produced by @noble/curves " +
    "in test/vectors/independent.mjs. The test additionally folds each scenario in three fixed insertion " +
    "orders and asserts the snapshots are byte-identical, which is the property that keeps two replicas from " +
    "ever partitioning.",
  input_desc: {
    seeds:
      "bank = 32 bytes of 0x11, payer = 0x00..0x1f, payee = 0x20..0x3f, third = 32 bytes of 0x55, " +
      "outsider = 0x77, bank2 = 0x33. The seed IS the raw Ed25519 private key. These are wallet-kit's own " +
      "fixture seeds, so the actor keys can be checked against wallet-kit/test/vectors/artifacts.json.",
    hashes:
      "Entry hashes are short sortable names (\"h01\", \"h02\", \"hW0\"). A real one is a ~49-character " +
      "base58btc CID; the fold treats a hash as an OPAQUE COMPARABLE STRING and never parses one, so these " +
      "exercise the same tie-break path and let a reader work out (clock, hash) order by eye.",
    clocks: "Lamport times, written explicitly on every entry so the sort order is visible rather than implied.",
    ts: "Every op's `ts` is 2025-01-01T00:00:00Z, in the past and fixed. The fold never reads a wall clock.",
    labels: "Balances, states and payment parties are written as LABELS; `actors` below resolves each to its idPub.",
  },
  op_key_order: {
    _doc:
      "KEY ORDER IS THE WIRE: every op is JSON.stringify'd before it is sealed, so its key order is part of " +
      "the bytes a peer verifies. These lists come from independent.mjs's own hand-written op builders, not " +
      "from lib/protocol.cljs, so the two have to agree. No op reaches nine pairs — the width at which a " +
      "`#js {}` literal silently switches to hash order — but every builder uses j/ordered anyway.",
    charter: Object.keys(opCharter(TS, "n", "LEI", "L", 2, "open")),
    open: Object.keys(opOpen(TS, "n")),
    acct: Object.keys(opAcct(TS, A.payerPub, "approve")),
    mint: Object.keys(opMint(TS, 1, A.payerPub, 1)),
    mint_with_memo: Object.keys(opMint(TS, 1, A.payerPub, 1, "m")),
    burn: Object.keys(opBurn(TS, 1, 1)),
    pay: Object.keys(opPay(TS, po1)),
    ack: Object.keys(opAck(TS, "h09", ack1.bsig)),
    rate: Object.keys(opRate(TS, 1, 2)),
    req: Object.keys(opReq(TS, A.payerPub, 1)),
    req_with_memo: Object.keys(opReq(TS, A.payerPub, 1, "m")),
  },
  op_samples: {
    _doc: "One valid op of each type, for the validators' non-vacuity probe.",
    charter: opCharter(TS, "Banca Test", "LEI", "L", 2, "approve"),
    open: opOpen(TS, "Payer"),
    acct: opAcct(TS, A.payerPub, "approve"),
    mint: opMint(TS, 1, A.payerPub, 1000),
    mint_with_memo: opMint(TS, 1, A.payerPub, 1000, "salariu"),
    burn: opBurn(TS, 2, 100),
    pay: opPay(TS, po1),
    ack: opAck(ack1.ts, "h09", ack1.bsig),
    rate: opRate(TS, 3, 2),
    req: opReq(TS, A.payeePub, 500),
    req_with_memo: opReq(TS, A.payeePub, 500, "chirie"),
  },
  actors: LABELS,
  fallback_identity: {
    id: FALLBACK_ID,
    _doc:
      "A per-device OrbitDB fallback identity id: secp256k1, hex, 66 characters — not a canonical " +
      "43-character base64url suite key, which is exactly how the fold tells them apart.",
  },
  scenarios,
});

process.stdout.write("wrote order.json, receipts.json, fold.json\n");

static mirror of HEAD · about · clone: git clone https://git.ardegazu.ro/banca.git