wallet-kit / src / ardegazu / wallet / shapes.cljs
   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
;; The four wallet artifacts: build and verify.
;;
;; The model is RECEIPT-FIRST. A wallet does not replicate a bank's log; it
;; holds what it has been given. Paying is signing an ORDER and delivering it;
;; the bank settles it later and issues a RECEIPT. Until that receipt exists
;; nothing has moved, and the API is shaped so the difference cannot be blurred:
;; an order is never a balance, only a receipt folds.
;;
;;   wpr  payment request   signed by the PAYEE   domain "wpay-req"
;;   wpo  payment order     signed by the PAYER   domain "wpay-ord"
;;   wrc  settlement        signed by the BANK    domain "wpay-rcp"
;;   wrj  decline           signed by the BANK    domain "wpay-rcp"
;;   wri  issuance receipt  signed by the BANK    domain "wpay-iss"
;;
;; and three more for BANK/2 escrow — money a bank holds against a hashlock, so
;; two banks can settle one trade atomically without trusting each other:
;;
;;   wlk  escrow lock order  signed by the PAYER        domain "wpay-lock"
;;   wlr  lock receipt       signed by the BANK         domain "wpay-rcp"
;;   wrl  release            signed by the BENEFICIARY  domain "wpay-rel"
;;
;; Every signature is Ed25519 over
;;     "<domain>|v1|" + canon(<the artifact minus its signature field>)
;; where `canon` is social-kit's canonical JSON — sorted keys, no whitespace,
;; throws on undefined. So the SIGNATURE is order-independent (canon sorts),
;; while the TRANSMITTED BYTES are `JSON.stringify(artifact)` in insertion
;; order. Both facts are golden-vectored; both matter, for different reasons.
;;
;; Two disciplines run through this file and a second implementation has to
;; keep both:
;;
;;   build* THROWS (rejects) on bad input. A wallet that would sign nonsense
;;   should find out at the call site, not ship it.
;;
;;   verify* returns null on ANY failure and NEVER throws. Every parse here is
;;   of hostile bytes and the discipline is drop-silently, so there is exactly
;;   one shape for failure.
;;
;; EXACT KEY SETS. Each verify* checks Object.keys(raw).length against the
;; artifact's key count and rejects anything else. Without it a stray key would
;; be malleable — it rides along in the transmitted JSON but not in the
;; preimage this file rebuilds, so an attacker could staple data onto someone
;; else's valid signature. There are no optional keys in v1 and no extension
;; slot; a v2 gets a new `v`.
;;
;; EXPIRY IS NOT A VERIFY FAILURE. `exp` is sanity-checked (finite, ordered
;; after `ts`, inside MAX-TTL-MS) but a merely-expired artifact still verifies:
;; a bank has to be able to read an expired order in order to decline it with
;; why "expired", and a wallet has to be able to show why a request went stale.
;; Liveness is `expired`, and it is the caller's decision.
;;
;; ADMISSION TAKES AN EXPLICIT CLOCK, AND MAY TAKE NONE. Every shape check and
;; every verify* here ends in an optional `nowMs`, read by `clock` below:
;; absent means this reader's wall clock (what these functions have always
;; done), a number means that instant, and `null` means NO CLOCK AT ALL. The
;; third case is not a convenience. A REPLICATED FOLD — a bank folding signed
;; orders out of its log, two replicas of it three minutes apart — must reach
;; byte-identical state from the same entries, and a wall clock inside the shape
;; check makes "is this entry a valid order?" a question the two replicas answer
;; differently. That is a partition bug in a money ledger. `orderShape(e, null)`
;; is the deterministic form such a fold must use; it drops the wall-clock
;; bounds and NOTHING else, so every bound a timestamp carries relative to
;; itself (exp > ts, exp <= ts + MAX-TTL-MS, a settlement no earlier than its
;; order) is still enforced.
;;
;; JS objects only, no ClojureScript collections — the artifacts are handed to
;; app code and to a hand-authored .d.ts, and social-kit measured the first
;; Clojure collection reachable from a shared module at ~+19 KB gzipped.
(ns ardegazu.wallet.shapes
  (:require [ardegazu.id.crypto :as id-crypto]
            [ardegazu.id.identity :as id-identity]
            [ardegazu.social.canon :as soc-canon]
            [ardegazu.wallet.consts :as consts])
  (:require-macros [ardegazu.wallet.macros :refer [awaits obj oget]]))

;; ---- JS boundary helpers -----------------------------------------------------

(defn- js-object?
  "`v` is a non-null, non-array JavaScript object. NOT cljs.core/object?, which
  is `(identical? (type x) js/Object)` and answers false for anything with a
  prototype — the opposite of what a shape check wants."
  [v]
  (and (some? v)
       (identical? (js* "typeof ~{}" v) "object")
       (not (js/Array.isArray v))))

(defn- key-count [o] (.-length (js/Object.keys o)))

(defn- byte-length
  "UTF-8 bytes of a value's JSON, or a number larger than any ceiling when it
  will not serialize at all. Bytes, not `.length`: a size limit that counts
  UTF-16 units lets an all-emoji memo weigh double what it measures."
  [v]
  (try (.-length (id-crypto/utf8 (js/JSON.stringify v)))
       (catch :default _ js/Number.MAX_SAFE_INTEGER)))

;; C0, DEL, C1 — and U+2028 LINE SEPARATOR / U+2029 PARAGRAPH SEPARATOR, which
;; are not control characters by Unicode category but are LINE TERMINATORS in
;; ECMAScript and in most log and console renderers. `ctx` is the field a third
;; party matches on and both fields get displayed; the whole point of the class
;; is that neither can smuggle a line break into a log or a display, and a
;; C0-only class let two characters that do exactly that straight through.
;;
;; A constructed RegExp rather than a `#"…"` literal so the SOURCE of this file
;; stays printable — a literal would have to carry the actual control bytes, NUL
;; included, and every editor, diff and publish gate then has an opinion about
;; the file. The two separators are written as escapes for the same reason.
;;
;; WIRE-VISIBLE: an artifact whose ctx or memo carries U+2028/U+2029 verified
;; under an earlier draft and does not now. `clean-text` strips them on the build
;; side, so the two halves stay symmetric; a second implementation must use this
;; exact class.
(def ^:private ctl-pattern "[\\u0000-\\u001F\\u007F-\\u009F\\u2028\\u2029]")
(def ^:private ctl-re (js/RegExp. ctl-pattern))
(def ^:private ctl-re-g (js/RegExp. ctl-pattern "g"))

(defn- amount? [n]
  (and (number? n) (js/Number.isInteger n) (>= n consts/AMT-MIN) (<= n consts/AMT-MAX)))

(defn- pub? [s] (and (string? s) (.test consts/PUB-RE s)))
(defn- sig? [s] (and (string? s) (.test consts/SIG-RE s)))

(defn- digest?
  "A sha256 digest or a hashlock preimage: 32 bytes, canonical base64url. Both
  halves of a hashlock share this shape — see the HASHLOCK note in consts."
  [s]
  (and (string? s) (.test consts/DIGEST-RE s)))

(defn- seq-no?
  "A per-payer-per-bank sequence number: a positive integer, bounded by the same
  exact-double ceiling as an amount so a fold over sequence numbers can never
  lose precision either."
  [n]
  (and (number? n) (js/Number.isInteger n) (>= n 1) (<= n consts/AMT-MAX)))

(defn- clock
  "Resolve an admission check's `nowMs` argument. THREE cases, and the third is
  the reason this exists:

    absent / undefined  this reader's wall clock — what every one of these
                        functions did before the argument existed, and still
                        the default;
    a finite number     that instant, so a verdict can be reproduced;
    null                NO CLOCK. Every wall-clock bound is skipped; every bound
                        a timestamp carries relative to itself still applies.

  Pass `null` from a REPLICATED FOLD. Two replicas of one bank's log, clocks
  three minutes apart, must not disagree about whether an entry is a valid
  order — that disagreement is two different balances for one set of receipts.

  Anything else (a string, NaN, an object) reads as absent, not as `null`: this
  is an admission check and a garbled clock argument must never silently become
  the most permissive setting."
  [now-ms]
  (cond
    (and (number? now-ms) (js/Number.isFinite now-ms)) now-ms
    ;; `nil?` is `== null` in ClojureScript and so covers undefined too; only an
    ;; EXPLICIT null selects the clock-free path
    (and (nil? now-ms) (not (identical? now-ms js/undefined))) nil
    :else (js/Date.now)))

(defn- ts?
  "A timestamp we did not generate: a non-negative integer, and — when the
  caller supplied a clock — never further into that clock's future than
  SKEW-MS. `now` nil is the clock-free form: the skew bound is the only check
  here that needs a clock, so dropping it costs nothing else."
  [n now]
  (and (number? n) (js/Number.isInteger n) (>= n 0)
       (or (nil? now) (<= n (+ now consts/SKEW-MS)))))

(defn- text?
  "An untrusted free-text field as it must arrive on the wire: a string, free of
  control characters, at most `max-cp` CODE POINTS. Rejected rather than
  cleaned — the signature is over the exact bytes, so rewriting it here would
  only produce something that no longer verifies."
  [s max-cp]
  (and (string? s)
       (not (.test ctl-re s))
       (<= (.-length (js/Array.from s)) max-cp)))

;; ---- currency ids -------------------------------------------------------------

(defn is-neutral-unit [cur] (identical? cur consts/NEUTRAL-UNIT))

(defn parse-currency
  "\"<bankerIdPub>.<CODE>\" -> {banker, code}, or null.

  Accepts the reserved neutral unit and reports banker \"~\" for it: a pricing
  layer needs to parse a quote. Use `isPayableCurrency` to decide whether
  anything may be denominated in it."
  [cur]
  (if (is-neutral-unit cur)
    (obj "banker" consts/NEUTRAL-BANKER "code" consts/NEUTRAL-CODE)
    (let [m (when (string? cur) (.match cur consts/CUR-RE))]
      (when (some? m)
        (obj "banker" (aget m 1) "code" (aget m 2))))))

(defn is-payable-currency
  "Can an instrument of payment be denominated in this? Every build* and every
  verify* in this file asks exactly this question. \"~.GAZ\" answers false: `~`
  is not a base64url character, so no identity holds it and nobody can ever
  settle paper drawn on it."
  [cur]
  (and (string? cur) (not (is-neutral-unit cur)) (.test consts/CUR-RE cur)))

(defn banker-of
  "The issuing identity of a currency id, or null."
  [cur]
  (let [p (parse-currency cur)]
    (when (some? p) (oget p "banker"))))

;; ---- text clamps (build side) -------------------------------------------------

(defn- clean-text [s max-cp]
  (if-not (string? s)
    ""
    (let [trimmed (.trim (.replace s ctl-re-g ""))
          cps (js/Array.from trimmed)]
      (if (> (.-length cps) max-cp)
        (.join (.slice cps 0 max-cp) "")
        trimmed))))

(defn sanitize-ctx [s] (clean-text s consts/CTX-MAX))
(defn sanitize-memo [s] (clean-text s consts/MEMO-MAX))

;; ---- signature preimages ------------------------------------------------------
;;
;; Exported: these ARE the contract. A second implementation that reproduces
;; these four strings byte-for-byte interoperates, and one that does not cannot
;; be made to by any amount of agreement about anything else.

(defn unsigned-pay-request [r]
  (obj "v" 1
       "t" "wpr"
       "cur" (oget r "cur")
       "amt" (oget r "amt")
       "to" (oget r "to")
       "tox" (oget r "tox")
       "ctx" (oget r "ctx")
       "memo" (oget r "memo")
       "exp" (oget r "exp")))

(defn unsigned-order [o]
  ;; TWELVE pairs. `obj`, never #js{} or js-obj: at nine pairs those switch to
  ;; hash order silently, and `wpo` is the reason this kit has the macro.
  (obj "v" 1
       "t" "wpo"
       "id" (oget o "id")
       "cur" (oget o "cur")
       "amt" (oget o "amt")
       "seq" (oget o "seq")
       "from" (oget o "from")
       "to" (oget o "to")
       "ctx" (oget o "ctx")
       "memo" (oget o "memo")
       "ts" (oget o "ts")
       "exp" (oget o "exp")))

(defn unsigned-settlement
  "The bank's preimage object. `t` is inside it, which is what keeps a decline
  from ever being re-read as a receipt even though both share a domain."
  [s]
  (if (identical? (oget s "t") "wrj")
    (obj "v" 1 "t" "wrj" "po" (oget s "po") "why" (oget s "why")
         "ts" (oget s "ts") "bank" (oget s "bank"))
    (obj "v" 1 "t" "wrc" "po" (oget s "po") "seq" (oget s "seq")
         "ts" (oget s "ts") "bank" (oget s "bank"))))

(defn unsigned-issuance
  "The bank's issuance preimage object. TEN pairs on the wire (bsig included),
  nine here — through `obj`, past the nine-pair cliff, like every artifact."
  [i]
  (obj "v" 1
       "t" "wri"
       "cur" (oget i "cur")
       "seq" (oget i "seq")
       "to" (oget i "to")
       "amt" (oget i "amt")
       "h" (oget i "h")
       "ts" (oget i "ts")
       "bank" (oget i "bank")))

(defn pay-request-preimage [r]
  (str consts/DOM-PAY-REQ "|v1|" (soc-canon/canon (unsigned-pay-request r))))

(defn order-preimage [o]
  (str consts/DOM-PAY-ORD "|v1|" (soc-canon/canon (unsigned-order o))))

(defn settlement-preimage [s]
  (str consts/DOM-PAY-RCP "|v1|" (soc-canon/canon (unsigned-settlement s))))

(defn issuance-preimage [i]
  (str consts/DOM-PAY-ISS "|v1|" (soc-canon/canon (unsigned-issuance i))))

;; ---- dedup keys ---------------------------------------------------------------

(defn order-id
  "The stable dedup key of an order: sha256B64url(canon(order minus sig)).

  Over the UNSIGNED order, not the transmitted one, so it is a function of what
  the order SAYS. `po.id` is 16 bytes of the payer's randomness and is not a
  substitute — a payer can reuse it, and a hostile one will."
  [po]
  (awaits [_ (js/Promise.resolve nil)]
    (soc-canon/sha256-b64url (soc-canon/canon (unsigned-order po)))))

(defn receipt-key
  "The stable dedup key of a settlement: sha256B64url of the canonical JSON of
  {v, t, bank, oid}, where `oid` is orderId(rc.po).

  Deliberately NOT over the whole settlement. A bank that re-issues the same
  answer with a fresh `ts`, or under a different log ref, has settled the same
  order once — folding it twice would double a balance. `t` and `bank` are in,
  so a decline never collides with a receipt and two banks answering the same
  order stay distinct."
  [rc]
  (awaits [_ (js/Promise.resolve nil)
           oid (order-id (oget rc "po"))]
    (soc-canon/sha256-b64url
     (soc-canon/canon (obj "v" 1 "t" (oget rc "t") "bank" (oget rc "bank") "oid" oid)))))

(defn issuance-key
  "The stable dedup key of an issuance receipt: sha256B64url of the canonical
  JSON of {v, t:\"wri\", bank, h} — receiptKey's shape, with the mint entry's
  log hash where the order id sits.

  WHY {bank, h} AND NOTHING ELSE. What a wri settles is not an amount but a LOG
  ENTRY: `h` names exactly one entry of one bank's log, so (bank, h) IS the
  fact being made final — \"this bank pinned this mint\". `ts` is when the bank
  said so, and a receipt re-issued with a fresh `ts` is the same fact said
  twice; folding it twice would double a credit, so `ts` must not be in the
  key (the same reason receiptKey ignores it). `cur`, `seq`, `to` and `amt`
  are all properties of the entry `h` names — a bank that signs two receipts
  with one `h` and two amounts has signed a contradiction, and this key makes
  the ledger fold the first and refuse the second rather than credit both:
  under equivocation the conservative verdict is one credit, and the two
  signed artifacts remain the evidence. `t` is in so the key can never collide
  with a receiptKey, and `bank` is in so two banks' logs stay distinct spaces
  even if their entry hashes ever collide."
  [i]
  (awaits [_ (js/Promise.resolve nil)]
    (soc-canon/sha256-b64url
     (soc-canon/canon (obj "v" 1 "t" "wri" "bank" (oget i "bank") "h" (oget i "h"))))))

;; ---- liveness -----------------------------------------------------------------

;; How far `expired` will descend through `po` before giving up. A settlement
;; wraps exactly one order, so the real depth is two; anything deeper is a
;; hand-built or JSON.parse'd chain, and `{"po":{"po":{"po":…}}}` nested a few
;; hundred thousand times used to blow the stack rather than answer.
(def ^:private MAX-PO-DEPTH 8)

(defn expired
  "Has this artifact's expiry passed? Separate from verification on purpose —
  see this file's header. A settlement has no expiry of its own; its order's
  governs, which is what lets a wallet explain a why-\"expired\" decline.

  TOTAL: false on anything it cannot read, including a hostile object whose
  getters throw and a `po` chain of any depth. Iterative and depth-bounded, not
  recursive — a `{po:{po:…}}` chain out of JSON.parse is free to build and used
  to be a stack overflow in a function whose declared type is `boolean`.

  `nowMs` is the caller's clock. Pass it to make a verdict reproducible; see the
  wall-clock note in consts.cljs.

  NO CLOCK-FREE FORM, unlike the shape checks: liveness IS the clock question,
  so `null` here means the wall clock rather than \"skip it\". A fold that needs
  determinism pins `nowMs` to a number it agreed on."
  [a now-ms]
  (try
    (let [now (if (number? now-ms) now-ms (js/Date.now))]
      (loop [x a d 0]
        (if (or (nil? x) (> d MAX-PO-DEPTH))
          false
          (let [exp (oget x "exp")]
            (if (number? exp)
              (> now exp)
              (recur (oget x "po") (inc d)))))))
    (catch :default _ false)))

;; ---- structural shape checks (synchronous, signature-free) ---------------------
;;
;; Each returns a REBUILT artifact in the documented key order, or null. They
;; are exactly what verify* does MINUS the signature, and they exist as their
;; own step for one reason: LedgerStore reads its own localStorage on every
;; construction, synchronously, and must not trust those bytes just because they
;; came from this browser. Signatures are checked once, by verify*, before an
;; artifact is ever handed to the store.
;;
;; Rebuilding rather than returning `raw` is deliberate. The caller gets the
;; documented key order, no inherited prototype junk, and an object that
;; canon()s identically to what was signed — which is why the preimage may be
;; taken over the rebuild.
;;
;; ALL THREE ARE TOTAL, and that is not decoration. They are the ONLY inspection
;; the ledger does of an artifact off the network or out of localStorage, and
;; every read below is a property read on an object this process did not build:
;; a Proxy whose `get` or `ownKeys` trap throws, a revoked Proxy (`Array.isArray`
;; alone throws on one), or a plain `{get v(){throw}}` all turn `orderShape(x)`
;; into a THROW where the declared type is `PayOrder | null` — and one rung up
;; that is `await store.applyReceipt(fromNetwork)` becoming an unhandled
;; rejection instead of `false`. The `catch` goes around the whole body, the
;; key-count read included, because there is no first read that is safe.

(defn pay-request-shape
  "`nowMs`: absent = this reader's wall clock, a number = that instant, null =
  no clock. A `wpr` carries no `ts`, so the clock-free form drops its ONLY
  clock-relative bound (`exp` no further out than now + MAX-TTL-MS + SKEW-MS)
  and keeps `exp` a positive integer. Say `null` only where determinism is worth
  more than that bound — a replicated fold — not to be permissive."
  [raw now-ms]
  (try
    (if-not (and (js-object? raw)
                 (identical? 10 (key-count raw))
                 (identical? 1 (oget raw "v"))
                 (identical? "wpr" (oget raw "t"))
                 (<= (byte-length raw) consts/MAX-ARTIFACT-BYTES))
      nil
      (let [cur (oget raw "cur")
            amt (oget raw "amt")
            to (oget raw "to")
            tox (oget raw "tox")
            ctx (oget raw "ctx")
            memo (oget raw "memo")
            exp (oget raw "exp")
            sig (oget raw "sig")
            now (clock now-ms)]
        (if-not (and (is-payable-currency cur)
                     (amount? amt)
                     (pub? to)
                     (pub? tox)
                     (text? ctx consts/CTX-MAX)
                     (text? memo consts/MEMO-MAX)
                     (number? exp) (js/Number.isInteger exp) (> exp 0)
                     (or (nil? now)
                         (<= exp (+ now consts/MAX-TTL-MS consts/SKEW-MS)))
                     (sig? sig))
          nil
          (let [out (js/Object.assign (js-obj) (unsigned-pay-request raw))]
            (unchecked-set out "sig" sig)
            out))))
    (catch :default _ nil)))

(defn order-shape
  "`nowMs`: absent = this reader's wall clock, a number = that instant, null =
  no clock.

  THE CLOCK-FREE FORM IS THE ONE A REPLICATED FOLD MUST CALL. A bank folding
  signed orders out of its log has to reach the same state on every replica, and
  with a wall clock in here two replicas three minutes apart disagree about
  whether one entry is a valid order — two balances for one set of entries. The
  only bound `null` drops is `ts` no further into the future than SKEW-MS; every
  ts-relative bound (`exp > ts`, `exp <= ts + MAX-TTL-MS`) is still enforced, so
  it is a DETERMINISTIC check, not a weaker one."
  [raw now-ms]
  (try
    (if-not (and (js-object? raw)
                 (identical? 13 (key-count raw))
                 (identical? 1 (oget raw "v"))
                 (identical? "wpo" (oget raw "t"))
                 (<= (byte-length raw) consts/MAX-ARTIFACT-BYTES))
      nil
      (let [oid (oget raw "id")
            cur (oget raw "cur")
            amt (oget raw "amt")
            sq (oget raw "seq")
            from (oget raw "from")
            to (oget raw "to")
            ctx (oget raw "ctx")
            memo (oget raw "memo")
            ts (oget raw "ts")
            exp (oget raw "exp")
            sig (oget raw "sig")]
        (if-not (and (string? oid) (.test consts/ORDER-ID-RE oid)
                     (is-payable-currency cur)
                     (amount? amt)
                     (seq-no? sq)
                     (pub? from)
                     (pub? to)
                     (text? ctx consts/CTX-MAX)
                     (text? memo consts/MEMO-MAX)
                     (ts? ts (clock now-ms))
                     (number? exp) (js/Number.isInteger exp)
                     (> exp ts) (<= exp (+ ts consts/MAX-TTL-MS))
                     (sig? sig))
          nil
          (let [out (js/Object.assign (js-obj) (unsigned-order raw))]
            (unchecked-set out "sig" sig)
            out))))
    (catch :default _ nil)))

(defn- decline-reason? [w]
  (and (string? w) (>= (.indexOf consts/DECLINE-REASONS w) 0)))

(defn- log-ref?
  "A bank's own log entry reference. Opaque to everyone else — a string, so a
  bank may use whatever its log actually produces — but bounded and
  control-character-free like every other untrusted text field.

  Note the name collision with `wpo.seq`, which is a NUMBER and means something
  else entirely: the payer's sequence slot in the bank's fold. Both are called
  `seq` on the wire because that is what each is in its own log, and a second
  implementation must not conflate them."
  [s]
  (and (string? s) (not (identical? s "")) (text? s consts/CTX-MAX)))

(defn- entry-hash?
  "The log-entry hash a wri makes final: a non-empty string, bounded and
  control-character-free — the same envelope `log-ref?` gives the bank's log
  ref, and deliberately NOT a multibase grammar. banca's entry hashes are
  multibase strings today, but the hash belongs to whatever log produced it,
  and pinning one base here would make the artifact layer take a position on a
  log format it never reads. What the bound buys is what every untrusted text
  bound here buys: it cannot smuggle a line break into a display and it cannot
  be grown without limit inside a signed blob. Equality is the only operation
  this kit ever performs on it."
  [s]
  (and (string? s) (not (identical? s "")) (text? s consts/CTX-MAX)))

(defn settlement-shape
  "wrc or wrj, with its embedded order structurally re-checked and rebuilt.

  Enforces the invariant that makes a settlement mean anything: the signing bank
  IS the banker named by po.cur. A bank cannot settle another bank's paper, and
  since the neutral unit's banker is `~` — which no key can spell — it cannot be
  settled at all.

  `nowMs` is resolved once and passed down to the embedded order, so a
  settlement and its order are always judged against ONE clock. The clock-free
  form keeps `ts >= po.ts - SKEW-MS` — a settlement still cannot predate the
  order it settles — and drops only the skew bound on `ts` itself."
  [raw now-ms]
  (try
    (let [t (when (js-object? raw) (oget raw "t"))
          receipt? (identical? t "wrc")
          decline? (identical? t "wrj")]
      (if-not (and (js-object? raw)
                   (identical? 7 (key-count raw))
                   (identical? 1 (oget raw "v"))
                   (or receipt? decline?)
                   (<= (byte-length raw) consts/MAX-SETTLEMENT-BYTES))
        nil
        (let [bank (oget raw "bank")
              bsig (oget raw "bsig")
              ts (oget raw "ts")
              sq (oget raw "seq")
              why (oget raw "why")
              now (clock now-ms)
              order (order-shape (oget raw "po") now)]
          (if-not (and (pub? bank)
                       (sig? bsig)
                       (ts? ts now)
                       (if receipt? (log-ref? sq) (decline-reason? why))
                       (some? order)
                       (identical? (banker-of (oget order "cur")) bank)
                       ;; a settlement cannot predate the order it settles
                       (>= ts (- (oget order "ts") consts/SKEW-MS)))
            nil
            (let [unsigned (if receipt?
                             (obj "v" 1 "t" "wrc" "po" order "seq" sq "ts" ts "bank" bank)
                             (obj "v" 1 "t" "wrj" "po" order "why" why "ts" ts "bank" bank))
                  out (js/Object.assign (js-obj) unsigned)]
              (unchecked-set out "bsig" bsig)
              out)))))
    (catch :default _ nil)))

(defn issuance-shape
  "wri — the bank's issuance receipt, the artifact that gives a MINT finality.

  A bank's fold pins an issuance to one slot the moment the bank acks it, but
  before this artifact existed there was nothing for that ack to SIGN: a wrc's
  bsig covers a payment preimage, and a mint has no payment inside it. So an
  acked mint had no receipt the recipient could hold, and a banker could
  withhold a back-dated second mint on the same issuance slot and displace the
  first — the one way a banker could empty a customer's account. A wri is the
  signable preimage that closes that: `seq` is the bank's own issuance slot
  (analogous to wpo.seq but the BANK's counter), `h` is the log-entry hash of
  the mint being made final, and the recipient keeps the receipt.

  MINT ONLY — a wri never covers a burn; see buildIssuanceReceipt.

  Enforces the same binding a settlement enforces: the signing bank IS the
  banker named by `cur`. Without it any bank could \"finalize\" another bank's
  issuance, and the neutral unit — whose banker `~` no key can spell — could
  acquire receipts for money nobody can mint.

  `nowMs`: absent = this reader's wall clock, a number = that instant, null =
  no clock. A wri carries no `exp`, so the clock-free form drops exactly one
  bound — `ts` no further ahead than SKEW-MS — and every other rule stands;
  it is the form banca's replicated fold and this ledger's storage read use."
  [raw now-ms]
  (try
    (if-not (and (js-object? raw)
                 (identical? 10 (key-count raw))
                 (identical? 1 (oget raw "v"))
                 (identical? "wri" (oget raw "t"))
                 (<= (byte-length raw) consts/MAX-ARTIFACT-BYTES))
      nil
      (let [cur (oget raw "cur")
            sq (oget raw "seq")
            to (oget raw "to")
            amt (oget raw "amt")
            h (oget raw "h")
            ts (oget raw "ts")
            bank (oget raw "bank")
            bsig (oget raw "bsig")]
        (if-not (and (is-payable-currency cur)
                     (seq-no? sq)
                     (pub? to)
                     (amount? amt)
                     (entry-hash? h)
                     (ts? ts (clock now-ms))
                     (pub? bank)
                     ;; the signing bank IS the banker of the issued currency
                     (identical? (banker-of cur) bank)
                     (sig? bsig))
          nil
          (let [out (js/Object.assign (js-obj) (unsigned-issuance raw))]
            (unchecked-set out "bsig" bsig)
            out))))
    (catch :default _ nil)))

;; ---- build: payment request ---------------------------------------------------

(defn- fail! [what] (throw (js/Error. (str "wallet-kit: " what))))

(defn build-pay-request
  "Sign a request to be paid. The signer IS the payee, so `to` is not an
  argument — a request that named someone else as payee would be a request for
  someone else's money.

  opts: {cur, amt, tox, ctx?, memo?, expMs?}
    expMs is an ABSOLUTE epoch-ms expiry (buildOrder takes a RELATIVE ttlMs; the
    two names differ because the two meanings do). Default: one hour."
  [identity opts]
  (awaits [_ (js/Promise.resolve nil)]
    (let [cur (oget opts "cur")
          amt (oget opts "amt")
          tox (oget opts "tox")
          to (oget identity "publicKeyB64")
          exp-in (oget opts "expMs")
          exp (if (identical? exp-in js/undefined) (+ (js/Date.now) consts/REQ-TTL-MS) exp-in)]
      (when (is-neutral-unit cur)
        (fail! "the neutral unit is quote-only — nobody can mint or settle it"))
      (when-not (is-payable-currency cur) (fail! "bad currency id"))
      (when-not (amount? amt) (fail! "amt must be an integer in minor units, 1..2^50"))
      (when-not (pub? tox) (fail! "tox must be the payee's suite X25519 public key"))
      (when-not (pub? to) (fail! "identity has no usable public key"))
      (when-not (and (number? exp) (js/Number.isInteger exp) (> exp 0)
                     (<= exp (+ (js/Date.now) consts/MAX-TTL-MS)))
        (fail! "expMs out of range"))
      (let [unsigned (obj "v" 1 "t" "wpr" "cur" cur "amt" amt "to" to "tox" tox
                          "ctx" (sanitize-ctx (oget opts "ctx"))
                          "memo" (sanitize-memo (oget opts "memo"))
                          "exp" exp)]
        (awaits [raw-sig (.signRaw ^js identity (id-crypto/utf8 (pay-request-preimage unsigned)))]
          (let [out (js/Object.assign (js-obj) unsigned)]
            ;; sig is appended, never part of what it signs
            (unchecked-set out "sig" (id-crypto/to-b64url raw-sig))
            out))))))

(defn verify-pay-request
  "Full verification; null = reject, never throws. `nowMs` is the shape check's
  clock — see `pay-request-shape`; the SIGNATURE never depends on it."
  [raw now-ms]
  (-> (js/Promise.resolve nil)
      (.then (fn [_]
               (let [r (pay-request-shape raw now-ms)]
                 (if (nil? r)
                   nil
                   (awaits [ok (id-identity/verify-raw (oget r "to") (oget r "sig")
                                                       (id-crypto/utf8 (pay-request-preimage r)))]
                     (when ok r))))))
      (.catch (fn [_] nil))))

;; ---- build: payment order -----------------------------------------------------

(defn build-order
  "Sign an instruction to pay. The signer IS the payer.

  opts: {cur, amt, to, seq, ctx?, memo?, ttlMs?}
    seq   the payer's next sequence number FOR THAT BANK — the bank's ledger
          fold binds an order to exactly one slot, which is its double-spend
          defense. LedgerStore.nextSeq derives it from your own history.
    ttlMs relative; default ten minutes."
  [identity opts]
  (awaits [_ (js/Promise.resolve nil)]
    (let [cur (oget opts "cur")
          amt (oget opts "amt")
          to (oget opts "to")
          sq (oget opts "seq")
          from (oget identity "publicKeyB64")
          ttl-in (oget opts "ttlMs")
          ttl (if (identical? ttl-in js/undefined) consts/ORDER-TTL-MS ttl-in)]
      (when (is-neutral-unit cur)
        (fail! "the neutral unit is quote-only — an order cannot be denominated in it"))
      (when-not (is-payable-currency cur) (fail! "bad currency id"))
      (when-not (amount? amt) (fail! "amt must be an integer in minor units, 1..2^50"))
      (when-not (pub? to) (fail! "to must be the payee's identity public key"))
      (when-not (pub? from) (fail! "identity has no usable public key"))
      (when-not (seq-no? sq) (fail! "seq must be a positive integer"))
      (when-not (and (number? ttl) (js/Number.isInteger ttl) (> ttl 0) (<= ttl consts/MAX-TTL-MS))
        (fail! "ttlMs out of range"))
      (let [ts (js/Date.now)
            unsigned (obj "v" 1 "t" "wpo"
                          "id" (id-crypto/to-b64url (id-crypto/random-bytes 16))
                          "cur" cur "amt" amt "seq" sq "from" from "to" to
                          "ctx" (sanitize-ctx (oget opts "ctx"))
                          "memo" (sanitize-memo (oget opts "memo"))
                          "ts" ts "exp" (+ ts ttl))]
        (awaits [raw-sig (.signRaw ^js identity (id-crypto/utf8 (order-preimage unsigned)))]
          (let [out (js/Object.assign (js-obj) unsigned)]
            (unchecked-set out "sig" (id-crypto/to-b64url raw-sig))
            out))))))

(defn verify-order
  "Full verification; null = reject, never throws. Does NOT check liveness —
  `expired` does, and a bank needs to be able to read an expired order in order
  to decline it.

  `nowMs` is the shape check's clock. `verifyOrder(e, null)` is the form a
  replicated fold must use: the signature never depends on a clock, so with the
  clock-free shape check the whole verdict is a pure function of the entry."
  [raw now-ms]
  (-> (js/Promise.resolve nil)
      (.then (fn [_]
               (let [o (order-shape raw now-ms)]
                 (if (nil? o)
                   nil
                   (awaits [ok (id-identity/verify-raw (oget o "from") (oget o "sig")
                                                       (id-crypto/utf8 (order-preimage o)))]
                     (when ok o))))))
      (.catch (fn [_] nil))))

;; ---- build: settlement / decline ----------------------------------------------

(defn build-settlement
  "The banker side: answer one order, with a receipt or a decline.

  opts: {seq, decline?}
    seq      the bank's own log entry reference for this settlement (a STRING —
             not wpo's numeric seq). Required for a receipt, ignored for a
             decline.
    decline  one of \"insufficient\" | \"unknown-payer\" | \"expired\" | \"cur\"
             | \"seq\". Present => a wrj, absent => a wrc.

  The order is re-verified here, signature included, and the settlement embeds
  the REBUILT one — so a bank can never co-sign a shape it did not itself
  accept. A bank may only settle its own paper: banker(po.cur) must be this
  identity."
  [identity po opts]
  (awaits [_ (js/Promise.resolve nil)
           ;; the bank's OWN wall clock: signing is an act in the present, and a
           ;; bank that would not admit an order should not co-sign it
           order (verify-order po js/undefined)]
    (let [opts (if (identical? opts js/undefined) (js-obj) opts)
          bank (oget identity "publicKeyB64")
          why (oget opts "decline")
          log-ref (oget opts "seq")
          ts (js/Date.now)]
      (when (nil? order) (fail! "the order does not verify — nothing to settle"))
      (when-not (pub? bank) (fail! "identity has no usable public key"))
      (when-not (identical? (banker-of (oget order "cur")) bank)
        (fail! "this identity is not the banker of that currency"))
      (let [decline? (not (identical? why js/undefined))]
        (when (and decline? (not (decline-reason? why))) (fail! "unknown decline reason"))
        (when (and (not decline?) (not (log-ref? log-ref)))
          (fail! "seq must be the bank's log entry reference"))
        (let [unsigned (if decline?
                         (obj "v" 1 "t" "wrj" "po" order "why" why "ts" ts "bank" bank)
                         (obj "v" 1 "t" "wrc" "po" order "seq" log-ref "ts" ts "bank" bank))]
          (awaits [raw-sig (.signRaw ^js identity (id-crypto/utf8 (settlement-preimage unsigned)))]
            (let [out (js/Object.assign (js-obj) unsigned)]
              (unchecked-set out "bsig" (id-crypto/to-b64url raw-sig))
              out)))))))

(defn verify-settlement
  "Full verification of a receipt or a decline; null = reject, never throws.

  Verifies the EMBEDDED ORDER's signature too — an unverified order inside a
  valid bank signature would let a bank launder a forgery — and, via
  settlement-shape, that banker(po.cur) is the signing bank.

  `expectedBankPub` is the CALLER's expectation: the bank whose answer was being
  waited for. Pass it. Without it, a perfectly valid settlement by some other
  bank is indistinguishable from the one you asked for, which is exactly the
  replay a wallet must not fold. undefined/null skips only that comparison; the
  internal banker(po.cur) === bank invariant always holds.

  `nowMs` is the THIRD argument, after `expectedBankPub` — the shape check's
  clock, `null` for the deterministic form a replicated fold needs."
  [raw expected-bank-pub now-ms]
  (-> (js/Promise.resolve nil)
      (.then (fn [_]
               (let [s (settlement-shape raw now-ms)
                     bank (when (some? s) (oget s "bank"))]
                 (if (or (nil? s)
                         (not (or (identical? expected-bank-pub js/undefined)
                                  (nil? expected-bank-pub)
                                  (identical? expected-bank-pub bank))))
                   nil
                   (let [order (oget s "po")]
                     (awaits [order-ok (id-identity/verify-raw
                                        (oget order "from") (oget order "sig")
                                        (id-crypto/utf8 (order-preimage order)))]
                       (if-not order-ok
                         nil
                         (awaits [ok (id-identity/verify-raw
                                      bank (oget s "bsig")
                                      (id-crypto/utf8 (settlement-preimage s)))]
                           (when ok s)))))))))
      (.catch (fn [_] nil))))

;; ---- build: issuance receipt ----------------------------------------------------

(defn build-issuance-receipt
  "The banker side: co-sign one MINT of this bank's own currency, so the ack
  that pins its issuance slot has a preimage to cover and the recipient holds
  a receipt no later log entry can displace.

  opts: {cur, seq, to, amt, h, ts?}
    seq  the bank's OWN issuance slot number — the bank's counter, not any
         payer's (a third meaning of the word: wpo.seq is the payer's number,
         wrc.seq is the bank's log-ref string, wri.seq is the bank's issuance
         NUMBER).
    h    the log-entry hash of the mint being made final. Opaque here: a
         non-empty bounded string, whatever the bank's log produces.
    ts   epoch ms; default now. Accepted so a banker replaying its log can
         stamp the receipt with the mint's own time.

  MINT ONLY, by decision rather than omission. A burn debits the banker's own
  account and names no recipient, so displacing a burn moves only the money of
  the party doing the displacing — the self-inflicted case needs no receipt,
  and the confiscation window this artifact closes cannot be opened through a
  burn. Covering burns anyway would mean signing content with no natural
  meaning: a `to` that is really a `from`, an amount whose direction lives in
  a convention outside the signature. A future artifact that needs to pin
  burns says so in its own `t`, under its own domain."
  [identity opts]
  (awaits [_ (js/Promise.resolve nil)]
    (let [cur (oget opts "cur")
          sq (oget opts "seq")
          to (oget opts "to")
          amt (oget opts "amt")
          h (oget opts "h")
          bank (oget identity "publicKeyB64")
          ts-in (oget opts "ts")
          ts (if (identical? ts-in js/undefined) (js/Date.now) ts-in)]
      (when (is-neutral-unit cur)
        (fail! "the neutral unit is quote-only — nobody can mint it"))
      (when-not (is-payable-currency cur) (fail! "bad currency id"))
      (when-not (pub? bank) (fail! "identity has no usable public key"))
      (when-not (identical? (banker-of cur) bank)
        (fail! "this identity is not the banker of that currency"))
      (when-not (seq-no? sq) (fail! "seq must be the bank's issuance slot, a positive integer"))
      (when-not (pub? to) (fail! "to must be the recipient's identity public key"))
      (when-not (amount? amt) (fail! "amt must be an integer in minor units, 1..2^50"))
      (when-not (entry-hash? h) (fail! "h must be the mint entry's log hash, a non-empty string"))
      (when-not (and (number? ts) (js/Number.isInteger ts) (>= ts 0))
        (fail! "ts must be a non-negative integer epoch-ms"))
      (let [unsigned (obj "v" 1 "t" "wri" "cur" cur "seq" sq "to" to
                          "amt" amt "h" h "ts" ts "bank" bank)]
        (awaits [raw-sig (.signRaw ^js identity (id-crypto/utf8 (issuance-preimage unsigned)))]
          (let [out (js/Object.assign (js-obj) unsigned)]
            (unchecked-set out "bsig" (id-crypto/to-b64url raw-sig))
            out))))))

(defn verify-issuance-receipt
  "Full verification of an issuance receipt; null = reject, never throws.

  `expectedBankPub` has verifySettlement's exact semantics: it is the CALLER's
  expectation — the bank whose mint this is supposed to be. Pass it. Without
  it, a perfectly valid issuance by some OTHER bank is indistinguishable from
  the one you were told about, which is the replay a wallet must not fold.
  undefined/null skips only that comparison; the internal banker(cur) === bank
  binding always holds.

  `nowMs` is the shape check's clock — `null` for the deterministic form a
  replicated fold needs. A wri has no exp, so clock-free drops only the
  SKEW-MS bound on `ts`."
  [raw expected-bank-pub now-ms]
  (-> (js/Promise.resolve nil)
      (.then (fn [_]
               (let [i (issuance-shape raw now-ms)
                     bank (when (some? i) (oget i "bank"))]
                 (if (or (nil? i)
                         (not (or (identical? expected-bank-pub js/undefined)
                                  (nil? expected-bank-pub)
                                  (identical? expected-bank-pub bank))))
                   nil
                   (awaits [ok (id-identity/verify-raw bank (oget i "bsig")
                                                       (id-crypto/utf8 (issuance-preimage i)))]
                     (when ok i))))))
      (.catch (fn [_] nil))))

;; ==== ESCROW (BANK/2) ==========================================================
;;
;; A LOCK is money a bank holds against a condition instead of moving. It is
;; released one of two ways and one of them is not a timeout:
;;
;;   CLAIM    whoever produces a preimage of `wlk.hash` is paid. Authorized by
;;            the preimage itself, so anyone may relay a claim.
;;   RETURN   the money goes back to the payer, authorized either by the bank
;;            (attesting that the lock's advisory `exp` has passed) or by a
;;            `wrl` — the beneficiary handing it back voluntarily.
;;
;; WHY THIS EXISTS. A trade of one bank's paper for another's is two payments in
;; two independent logs with no shared ordering. Lock both legs to ONE hashlock
;; and the trade becomes atomic: the secret-holder claims first and thereby
;; publishes the secret, and the counterparty claims with it. Either both legs
;; complete or neither does.
;;
;; THE SECRET-HOLDER MUST LOCK FIRST. Otherwise they could claim the other leg
;; while never having locked anything themselves. This is not a convention; the
;; construction does not hold without it.
;;
;; WHAT THIS KIT DOES NOT DECIDE. Ordering between a claim and a return is a
;; FOLD rule, not an artifact rule, and it lives in the bank (banca: a claim
;; beats a return for the same lock, unconditionally, decided in a pre-pass over
;; the whole entry set). Nothing here can express it, and nothing here should
;; try — this file signs and checks paper.

;; ---- hashlocks ----------------------------------------------------------------

(defn new-hashlock
  "A fresh {pre, hash}: 32 random bytes as canonical base64url, and
  sha256B64url of THAT TEXT. See the HASHLOCK note in consts for why the digest
  is over the text rather than the bytes.

  `pre` is a SECRET until it is claimed with and public forever after. Use one
  per lock: the first claim publishes it, and any other lock sharing the digest
  becomes claimable by anyone watching. A quote that can be partially filled by
  several takers therefore needs one hashlock PER FILL, never one for the quote."
  []
  (awaits [_ (js/Promise.resolve nil)]
    (let [pre (id-crypto/to-b64url (id-crypto/random-bytes 32))]
      (awaits [h (soc-canon/sha256-b64url pre)]
        (obj "pre" pre "hash" h)))))

(defn hashlock-matches
  "Does `pre` open `hash`? Total: false on anything malformed, and it never
  throws. The comparison is over canonical base64url on both sides, so there is
  exactly one spelling of a match."
  [pre hash]
  (-> (js/Promise.resolve nil)
      (.then (fn [_]
               (if-not (and (digest? pre) (digest? hash))
                 false
                 (awaits [h (soc-canon/sha256-b64url pre)]
                   (identical? h hash)))))
      (.catch (fn [_] false))))

;; ---- preimages ----------------------------------------------------------------

(defn unsigned-lock
  "THIRTEEN pairs — `wpo`'s twelve with `hash` between `to` and `ctx`, so the
  parties-and-condition group stays together and the ctx/memo/ts/exp tail sits
  byte-for-byte where a reader of an order expects it. `obj`, never #js{}."
  [l]
  (obj "v" 1
       "t" "wlk"
       "id" (oget l "id")
       "cur" (oget l "cur")
       "amt" (oget l "amt")
       "seq" (oget l "seq")
       "from" (oget l "from")
       "to" (oget l "to")
       "hash" (oget l "hash")
       "ctx" (oget l "ctx")
       "memo" (oget l "memo")
       "ts" (oget l "ts")
       "exp" (oget l "exp")))

(defn unsigned-lock-receipt
  "The bank's preimage for a CLAIMED lock. `t` is inside it, which is what lets
  this share wrc's domain without either being re-readable as the other."
  [r]
  (obj "v" 1 "t" "wlr" "lk" (oget r "lk") "seq" (oget r "seq")
       "ts" (oget r "ts") "bank" (oget r "bank")))

(defn unsigned-release
  "The beneficiary's preimage. `lh` is the LOCK ENTRY's hash in the bank's log —
  not the lock's `id`, which the payer chooses and a hostile one reuses. One
  append has one entry hash, forever, so a release names exactly one lock and
  can never be replayed against a re-appended copy of the same paper."
  [r]
  (obj "v" 1 "t" "wrl" "cur" (oget r "cur") "lh" (oget r "lh")
       "to" (oget r "to") "ts" (oget r "ts")))

(defn lock-preimage [l]
  (str consts/DOM-PAY-LOCK "|v1|" (soc-canon/canon (unsigned-lock l))))

(defn lock-receipt-preimage [r]
  (str consts/DOM-PAY-RCP "|v1|" (soc-canon/canon (unsigned-lock-receipt r))))

(defn release-preimage [r]
  (str consts/DOM-PAY-REL "|v1|" (soc-canon/canon (unsigned-release r))))

;; ---- dedup keys ---------------------------------------------------------------

(defn lock-id
  "The stable dedup key of a lock: sha256B64url(canon(lock minus sig)) — orderId
  for escrow, and a function of what the lock SAYS. `lk.id` is the payer's own
  randomness and is not a substitute."
  [lk]
  (awaits [_ (js/Promise.resolve nil)]
    (soc-canon/sha256-b64url (soc-canon/canon (unsigned-lock lk)))))

(defn lock-receipt-key
  "The stable dedup key of a lock receipt: sha256B64url(canon({v, t, bank,
  lkid})) — receiptKey's shape with a lock id where the order id sits, and blind
  to `ts` and the log ref for receiptKey's reason: a bank re-issuing the same
  answer with a fresh stamp has answered once, and folding it twice would double
  a balance."
  [r]
  (awaits [_ (js/Promise.resolve nil)
           lkid (lock-id (oget r "lk"))]
    (soc-canon/sha256-b64url
     (soc-canon/canon (obj "v" 1 "t" "wlr" "bank" (oget r "bank") "lkid" lkid)))))

;; ---- shapes -------------------------------------------------------------------

(defn lock-shape
  "`wlk`. Every rule `order-shape` applies, plus a well-formed hashlock.

  `nowMs`: absent = this reader's wall clock, a number = that instant, null = no
  clock. THE CLOCK-FREE FORM IS THE ONE A BANK'S FOLD MUST CALL, for exactly the
  reason order-shape's is: a lock a replica admits and its sibling rejects is two
  different balances for one log."
  [raw now-ms]
  (try
    (if-not (and (js-object? raw)
                 (identical? 14 (key-count raw))
                 (identical? 1 (oget raw "v"))
                 (identical? "wlk" (oget raw "t"))
                 (<= (byte-length raw) consts/MAX-ARTIFACT-BYTES))
      nil
      (let [lid (oget raw "id")
            cur (oget raw "cur")
            amt (oget raw "amt")
            sq (oget raw "seq")
            from (oget raw "from")
            to (oget raw "to")
            h (oget raw "hash")
            ctx (oget raw "ctx")
            memo (oget raw "memo")
            ts (oget raw "ts")
            exp (oget raw "exp")
            sig (oget raw "sig")]
        (if-not (and (string? lid) (.test consts/ORDER-ID-RE lid)
                     (is-payable-currency cur)
                     (amount? amt)
                     (seq-no? sq)
                     (pub? from)
                     (pub? to)
                     (digest? h)
                     (text? ctx consts/CTX-MAX)
                     (text? memo consts/MEMO-MAX)
                     (ts? ts (clock now-ms))
                     (number? exp) (js/Number.isInteger exp)
                     (> exp ts) (<= exp (+ ts consts/MAX-TTL-MS))
                     (sig? sig))
          nil
          (let [out (js/Object.assign (js-obj) (unsigned-lock raw))]
            (unchecked-set out "sig" sig)
            out))))
    (catch :default _ nil)))

(defn lock-receipt-shape
  "`wlr`, with its embedded lock structurally re-checked and rebuilt. Enforces
  the same binding a settlement does: the signing bank IS the banker named by
  `lk.cur`, so no bank can issue a receipt over another's paper and the neutral
  unit — whose banker `~` no key can spell — can never acquire one.

  RECEIPT ONLY, no decline twin. A `wrj` exists because a bank must be able to
  tell a payer WHY their order will not settle, and the payer is waiting on that
  answer to know whether to re-sequence. A lock that does not settle is RETURNED
  instead, and the return is itself the answer: the money is back and the bank's
  own entry says so. A decline artifact here would be a second way to say a
  thing already said, and the two could disagree."
  [raw now-ms]
  (try
    (if-not (and (js-object? raw)
                 (identical? 7 (key-count raw))
                 (identical? 1 (oget raw "v"))
                 (identical? "wlr" (oget raw "t"))
                 (<= (byte-length raw) consts/MAX-SETTLEMENT-BYTES))
      nil
      (let [bank (oget raw "bank")
            bsig (oget raw "bsig")
            ts (oget raw "ts")
            sq (oget raw "seq")
            now (clock now-ms)
            lk (lock-shape (oget raw "lk") now)]
        (if-not (and (pub? bank)
                     (sig? bsig)
                     (ts? ts now)
                     (log-ref? sq)
                     (some? lk)
                     (identical? (banker-of (oget lk "cur")) bank)
                     ;; a receipt cannot predate the lock it settles
                     (>= ts (- (oget lk "ts") consts/SKEW-MS)))
          nil
          (let [out (js/Object.assign
                     (js-obj)
                     (obj "v" 1 "t" "wlr" "lk" lk "seq" sq "ts" ts "bank" bank))]
            (unchecked-set out "bsig" bsig)
            out))))
    (catch :default _ nil)))

(defn release-shape
  "`wrl`. SEVEN keys — six preimage pairs plus `sig`.

  This kit checks what a release SAYS; it cannot check what it is ABOUT, because
  it never sees the lock — `lh` names an entry in a log this layer does not read.
  Binding the release to its lock (`wrl.to` = `lk.to`, `wrl.cur` = `lk.cur`,
  `lh` = that lock's entry hash) is the BANK's job and the bank has all three.
  A caller that treats a verified release as authorization without doing it is
  accepting a signature over somebody else's lock."
  [raw now-ms]
  (try
    (if-not (and (js-object? raw)
                 (identical? 7 (key-count raw))
                 (identical? 1 (oget raw "v"))
                 (identical? "wrl" (oget raw "t"))
                 (<= (byte-length raw) consts/MAX-ARTIFACT-BYTES))
      nil
      (let [cur (oget raw "cur")
            lh (oget raw "lh")
            to (oget raw "to")
            ts (oget raw "ts")
            sig (oget raw "sig")]
        (if-not (and (is-payable-currency cur)
                     (entry-hash? lh)
                     (pub? to)
                     (ts? ts (clock now-ms))
                     (sig? sig))
          nil
          (let [out (js/Object.assign (js-obj) (unsigned-release raw))]
            (unchecked-set out "sig" sig)
            out))))
    (catch :default _ nil)))

;; ---- build / verify -----------------------------------------------------------

(defn build-lock
  "Sign an instruction to LOCK. The signer IS the payer.

  opts: {cur, amt, to, seq, hash, ctx?, memo?, ttlMs?}
    seq   the payer's next sequence number for that bank — THE SAME SPACE a
          payment order draws from, not a second one. A lock and a payment are
          both this account moving its own money, and the bank consumes one slot
          per act; a wallet that handed slot 7 to a lock and then to an order
          would have one of them fail permanently.
    hash  the hashlock digest. `newHashlock()` produces a matching pair; keep
          `pre` secret until you claim with it, and never reuse it.
    ttlMs relative; default ten minutes. ADVISORY — a bank's fold never reads
          `exp`, because a verdict that depended on the reader's clock would let
          two replicas disagree. It is what a banker looks at before attesting a
          return, and what a UI counts down."
  [identity opts]
  (awaits [_ (js/Promise.resolve nil)]
    (let [cur (oget opts "cur")
          amt (oget opts "amt")
          to (oget opts "to")
          sq (oget opts "seq")
          h (oget opts "hash")
          from (oget identity "publicKeyB64")
          ttl-in (oget opts "ttlMs")
          ttl (if (identical? ttl-in js/undefined) consts/ORDER-TTL-MS ttl-in)]
      (when (is-neutral-unit cur)
        (fail! "the neutral unit is quote-only — a lock cannot be denominated in it"))
      (when-not (is-payable-currency cur) (fail! "bad currency id"))
      (when-not (amount? amt) (fail! "amt must be an integer in minor units, 1..2^50"))
      (when-not (pub? to) (fail! "to must be the beneficiary's identity public key"))
      (when-not (pub? from) (fail! "identity has no usable public key"))
      (when-not (seq-no? sq) (fail! "seq must be a positive integer"))
      (when-not (digest? h) (fail! "hash must be a canonical base64url sha256 digest"))
      (when-not (and (number? ttl) (js/Number.isInteger ttl) (> ttl 0) (<= ttl consts/MAX-TTL-MS))
        (fail! "ttlMs out of range"))
      (let [ts (js/Date.now)
            unsigned (obj "v" 1 "t" "wlk"
                          "id" (id-crypto/to-b64url (id-crypto/random-bytes 16))
                          "cur" cur "amt" amt "seq" sq "from" from "to" to
                          "hash" h
                          "ctx" (sanitize-ctx (oget opts "ctx"))
                          "memo" (sanitize-memo (oget opts "memo"))
                          "ts" ts "exp" (+ ts ttl))]
        (awaits [raw-sig (.signRaw ^js identity (id-crypto/utf8 (lock-preimage unsigned)))]
          (let [out (js/Object.assign (js-obj) unsigned)]
            (unchecked-set out "sig" (id-crypto/to-b64url raw-sig))
            out))))))

(defn verify-lock
  "Full verification; null = reject, never throws. Does NOT check liveness and
  does NOT check that you hold a preimage — a bank must be able to read a lock in
  order to hold it, and nobody but the claimant can open it.

  `verifyLock(e, null)` is the form a replicated fold must use."
  [raw now-ms]
  (-> (js/Promise.resolve nil)
      (.then (fn [_]
               (let [l (lock-shape raw now-ms)]
                 (if (nil? l)
                   nil
                   (awaits [ok (id-identity/verify-raw (oget l "from") (oget l "sig")
                                                       (id-crypto/utf8 (lock-preimage l)))]
                     (when ok l))))))
      (.catch (fn [_] nil))))

(defn build-lock-receipt
  "The banker side: co-sign one CLAIMED lock, so the ack that pins it has a
  preimage to cover and the beneficiary holds a receipt.

  opts: {seq}
    seq  the bank's own log entry reference for the CLAIM (a STRING — not wlk's
         numeric seq). The claim, not the lock: the lock is the promise and the
         claim is the money moving, and a receipt is for the latter.

  The lock is re-verified here, signature included, and the receipt embeds the
  REBUILT one — so a bank can never co-sign a shape it did not itself accept. A
  bank may only receipt its own paper."
  [identity lk opts]
  (awaits [_ (js/Promise.resolve nil)
           ;; the bank's OWN wall clock: signing is an act in the present
           lock (verify-lock lk js/undefined)]
    (let [opts (if (identical? opts js/undefined) (js-obj) opts)
          bank (oget identity "publicKeyB64")
          log-ref (oget opts "seq")
          ts (js/Date.now)]
      (when (nil? lock) (fail! "the lock does not verify — nothing to receipt"))
      (when-not (pub? bank) (fail! "identity has no usable public key"))
      (when-not (identical? (banker-of (oget lock "cur")) bank)
        (fail! "this identity is not the banker of that currency"))
      (when-not (log-ref? log-ref) (fail! "seq must be the bank's log entry reference"))
      (let [unsigned (obj "v" 1 "t" "wlr" "lk" lock "seq" log-ref "ts" ts "bank" bank)]
        (awaits [raw-sig (.signRaw ^js identity (id-crypto/utf8 (lock-receipt-preimage unsigned)))]
          (let [out (js/Object.assign (js-obj) unsigned)]
            (unchecked-set out "bsig" (id-crypto/to-b64url raw-sig))
            out))))))

(defn verify-lock-receipt
  "Full verification of a lock receipt; null = reject, never throws. Verifies the
  EMBEDDED LOCK's signature too — an unverified lock inside a valid bank
  signature would let a bank launder a forgery.

  `expectedBankPub` has verifySettlement's exact semantics and should be passed
  for the same reason: without it, a valid receipt by some OTHER bank is
  indistinguishable from the one you were waiting for."
  [raw expected-bank-pub now-ms]
  (-> (js/Promise.resolve nil)
      (.then (fn [_]
               (let [r (lock-receipt-shape raw now-ms)
                     bank (when (some? r) (oget r "bank"))]
                 (if (or (nil? r)
                         (not (or (identical? expected-bank-pub js/undefined)
                                  (nil? expected-bank-pub)
                                  (identical? expected-bank-pub bank))))
                   nil
                   (let [lk (oget r "lk")]
                     (awaits [lock-ok (id-identity/verify-raw
                                       (oget lk "from") (oget lk "sig")
                                       (id-crypto/utf8 (lock-preimage lk)))]
                       (if-not lock-ok
                         nil
                         (awaits [ok (id-identity/verify-raw
                                      bank (oget r "bsig")
                                      (id-crypto/utf8 (lock-receipt-preimage r)))]
                           (when ok r)))))))))
      (.catch (fn [_] nil))))

(defn build-release
  "The beneficiary side: hand a lock back to its payer without a preimage.

  opts: {cur, lh, ts?}
    lh  the LOCK ENTRY's hash in the bank's log.

  This is what keeps a dead banker from being a lost-funds event: a return needs
  either the bank attesting the clock or this, and this needs no bank at all.
  The signer IS the beneficiary, so `to` is not an argument — a release naming
  someone else would be giving away money that was never payable to you."
  [identity opts]
  (awaits [_ (js/Promise.resolve nil)]
    (let [cur (oget opts "cur")
          lh (oget opts "lh")
          to (oget identity "publicKeyB64")
          ts-in (oget opts "ts")
          ts (if (identical? ts-in js/undefined) (js/Date.now) ts-in)]
      (when (is-neutral-unit cur)
        (fail! "the neutral unit is quote-only — nothing can be locked in it"))
      (when-not (is-payable-currency cur) (fail! "bad currency id"))
      (when-not (entry-hash? lh) (fail! "lh must be the lock entry's log hash, a non-empty string"))
      (when-not (pub? to) (fail! "identity has no usable public key"))
      (when-not (and (number? ts) (js/Number.isInteger ts) (>= ts 0))
        (fail! "ts must be a non-negative integer epoch-ms"))
      (let [unsigned (obj "v" 1 "t" "wrl" "cur" cur "lh" lh "to" to "ts" ts)]
        (awaits [raw-sig (.signRaw ^js identity (id-crypto/utf8 (release-preimage unsigned)))]
          (let [out (js/Object.assign (js-obj) unsigned)]
            (unchecked-set out "sig" (id-crypto/to-b64url raw-sig))
            out))))))

(defn verify-release
  "Full verification of a release; null = reject, never throws.

  `expectedTo` is the CALLER's expectation — the beneficiary of the lock being
  released — and a bank MUST pass it, because this kit cannot see the lock. A
  release that verifies proves only that SOMEBODY signed away SOME lock; that it
  is the right somebody, and the right lock, is a comparison only the holder of
  the lock can make."
  [raw expected-to now-ms]
  (-> (js/Promise.resolve nil)
      (.then (fn [_]
               (let [r (release-shape raw now-ms)
                     to (when (some? r) (oget r "to"))]
                 (if (or (nil? r)
                         (not (or (identical? expected-to js/undefined)
                                  (nil? expected-to)
                                  (identical? expected-to to))))
                   nil
                   (awaits [ok (id-identity/verify-raw to (oget r "sig")
                                                       (id-crypto/utf8 (release-preimage r)))]
                     (when ok r))))))
      (.catch (fn [_] nil))))

static mirror of HEAD · about · clone: git clone https://git.ardegazu.ro/wallet-kit.git