@bsv/expo-wallet-toolbox 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/CHANGELOG.md +311 -0
  2. package/README.md +52 -1
  3. package/assets/sounds/vault-deposit.wav +0 -0
  4. package/assets/sounds/vault-withdraw.wav +0 -0
  5. package/core/config.tsx +21 -18
  6. package/core/context/VaultContext.tsx +8 -11
  7. package/core/context/WalletConnectionContext.tsx +137 -52
  8. package/core/context/WalletContext.tsx +413 -23
  9. package/core/hooks/useConfirmationSound.ts +14 -8
  10. package/core/i18n/translations.tsx +3368 -952
  11. package/core/index.ts +107 -14
  12. package/core/localpay/build.ts +674 -37
  13. package/core/localpay/codec.ts +68 -5
  14. package/core/localpay/pending.ts +240 -22
  15. package/core/localpay/settlementAck.ts +149 -0
  16. package/core/localpay/types.ts +14 -1
  17. package/core/localpay/verify.ts +118 -69
  18. package/core/mandala/abortGuard.ts +134 -0
  19. package/core/mandala/basketMigration.ts +166 -0
  20. package/core/mandala/bundle.ts +244 -0
  21. package/core/mandala/createRuntime.ts +2437 -0
  22. package/core/mandala/drain.ts +670 -0
  23. package/core/mandala/permissionModule.ts +642 -0
  24. package/core/mandala/resendTransfer.ts +175 -0
  25. package/core/mandala/runtime.ts +357 -0
  26. package/core/mandala/settlementStore.ts +412 -0
  27. package/core/mandala/types.ts +290 -0
  28. package/core/offline/cancelParked.ts +94 -1
  29. package/core/offline/payerHold.ts +152 -12
  30. package/core/offline/tokenFrames.ts +197 -0
  31. package/core/parsePeerPayURI.ts +70 -17
  32. package/core/pay/rails/address.ts +51 -3
  33. package/core/pay/rails/handle.ts +88 -9
  34. package/core/pay/rails/index.ts +16 -6
  35. package/core/pay/rails/nearby.ts +114 -4
  36. package/core/services/capWalletArgs.ts +8 -9
  37. package/core/services/externalOrigin.ts +39 -0
  38. package/core/services/vault/VaultKeyService.ts +912 -251
  39. package/core/services/vault/ceremony.ts +435 -367
  40. package/core/services/vault/ceremonyHost.ts +27 -21
  41. package/core/services/vault/devMock.ts +30 -7
  42. package/core/services/vault/driver.ts +95 -41
  43. package/core/services/vault/guard.ts +514 -56
  44. package/core/services/vault/hardwareLease.ts +22 -0
  45. package/core/services/vault/mockYubiKey.ts +258 -90
  46. package/core/services/vault/pivReset.ts +145 -0
  47. package/core/services/vault/r1comb.ts +976 -0
  48. package/core/services/vault/session.ts +93 -26
  49. package/core/services/vault/transfers.ts +2617 -747
  50. package/core/services/vault/types.ts +100 -43
  51. package/core/services/vault/vaultStore.ts +991 -74
  52. package/core/services/walletConnectionValidation.ts +293 -0
  53. package/core/services/walletServiceConfig.ts +19 -24
  54. package/core/storage/StorageExpoSQLite.ts +382 -56
  55. package/core/storage/dbImage.ts +48 -0
  56. package/core/storage/methods/findSql.ts +0 -54
  57. package/core/storage/methods/listOutputsSql.ts +7 -3
  58. package/core/storage/methods/offlineActions.ts +15 -0
  59. package/core/storage/methods/processOfflineActions.ts +263 -6
  60. package/core/storage/methods/walletBalanceSql.ts +16 -4
  61. package/core/storage/schema/createTables.ts +123 -0
  62. package/core/storage/sqlUpdateValue.ts +24 -0
  63. package/core/toolboxConfig.ts +240 -0
  64. package/core/walletRepair/runWalletCheck.ts +19 -2
  65. package/package.json +25 -24
  66. package/ui/components/QRScanner.tsx +1 -1
  67. package/ui/components/pay/AdmissionNotice.tsx +99 -0
  68. package/ui/components/pay/AssetPicker.tsx +184 -0
  69. package/ui/components/pay/AvailableBalance.tsx +33 -2
  70. package/ui/components/pay/HandleReceive.tsx +213 -50
  71. package/ui/components/pay/NearbyFlow.tsx +616 -69
  72. package/ui/components/pay/PayForm.tsx +73 -8
  73. package/ui/components/pay/PaymentSuccessOverlay.tsx +43 -2
  74. package/ui/components/pay/RecipientField.tsx +49 -4
  75. package/ui/components/pay/RequestHub.tsx +68 -8
  76. package/ui/components/pay/ResultBanner.tsx +41 -4
  77. package/ui/components/pay/UniversalSend.tsx +534 -30
  78. package/ui/components/pay/tokenSendCopy.ts +116 -0
  79. package/ui/components/pay/useRecipientInput.ts +36 -7
  80. package/ui/components/ui/PermissionSheet.tsx +65 -4
  81. package/ui/components/ui/Sheet.tsx +9 -2
  82. package/ui/components/vault/EnrollWizard.tsx +1432 -488
  83. package/ui/components/vault/KeyChooser.tsx +96 -0
  84. package/ui/components/vault/VaultCeremonySheet.tsx +107 -43
  85. package/ui/components/vault/vaultErrorCopy.ts +145 -0
  86. package/ui/components/wallet/ActivityRow.tsx +101 -17
  87. package/ui/components/wallet/AmountInput.tsx +77 -25
  88. package/ui/components/wallet/AssetAmount.tsx +95 -0
  89. package/ui/components/wallet/AssetSwitcherDropdown.tsx +261 -0
  90. package/ui/components/wallet/tokenEviction.ts +65 -0
  91. package/ui/hooks/useExportWalletData.ts +39 -0
  92. package/ui/hooks/useMandala.ts +303 -0
  93. package/ui/hooks/useVaultBalance.ts +105 -7
  94. package/ui/hooks/useVaultCoverage.ts +52 -0
  95. package/ui/importDatabases.ts +7 -3
  96. package/ui/index.ts +50 -7
  97. package/ui/screens/ConnectionsScreen.tsx +46 -29
  98. package/ui/screens/PairScreen.tsx +12 -12
  99. package/ui/screens/PayScreen.tsx +130 -10
  100. package/ui/screens/SettingsScreen.tsx +18 -9
  101. package/ui/screens/VaultScreen.tsx +925 -171
  102. package/ui/screens/VaultTransferScreen.tsx +376 -123
  103. package/ui/screens/WalletCheckScreen.tsx +10 -1
  104. package/ui/screens/WalletConfigScreen.tsx +42 -20
  105. package/ui/screens/WalletHomeScreen.tsx +417 -86
  106. package/ui/screens/homeBadges.ts +9 -1
  107. package/ui/screens/tokenRowTitle.ts +68 -0
  108. package/ui/tokenFormat.ts +108 -0
  109. package/ui/tokenSeen.ts +75 -0
  110. package/ui/tokenStatus.ts +79 -0
  111. package/assets/sounds/vault-close.wav +0 -0
  112. package/assets/sounds/vault-open.wav +0 -0
  113. package/core/services/vault/k1.ts +0 -75
  114. package/core/services/vault/sealing.ts +0 -84
  115. package/core/services/vault/vaultDerivation.ts +0 -152
  116. package/core/services/vault/vaultPassphrase.ts +0 -287
  117. package/ui/components/vault/PassphraseField.tsx +0 -306
  118. package/ui/components/vault/PhraseBackupSheet.tsx +0 -227
  119. package/ui/screens/VaultRecoverScreen.tsx +0 -226
@@ -0,0 +1,976 @@
1
+ /**
2
+ * R1C — the 1-of-N P-256 comb-verifier vault template (spec §2).
3
+ *
4
+ * Pure: no I/O, no React, no process.env; imports only @bsv/sdk and
5
+ * @noble/curves. Ported from docs/example-txs/spike/gen.mjs, gen2.mjs,
6
+ * unlock.mjs and unlock2.mjs. The fixed-base comb geometry is retained from
7
+ * the mined testnet fixture docs/example-txs/51c5…579a_0.hex; the mixed-add
8
+ * steps are completed here for the equality, inverse and infinity cases.
9
+ *
10
+ * Script numbers are BSV little-endian sign-magnitude; "minimal scriptnum" is
11
+ * what BigNumber.toSm('little') produces. Every constant is emitted minimally.
12
+ *
13
+ * SECURITY: nothing secret passes through this module — public keys, per-output
14
+ * salts, signatures the card already produced, and script bytes.
15
+ */
16
+ import { Hash, LockingScript, OP, PrivateKey, Script, Spend, Transaction, TransactionSignature, UnlockingScript, Utils } from '@bsv/sdk'
17
+ import { p256 } from '@noble/curves/nist.js'
18
+ import { VaultError } from './types'
19
+
20
+ // ───────────────────────── comb geometry and sizes (spec §2) ─────────────────────────
21
+ export const COMB_ROWS = 6
22
+ export const COMB_COLS = 43
23
+ /** Entries per base point = 2^(COMB_ROWS − 1). */
24
+ export const TABLE_SIZE = 32
25
+ /** OP_NUM2BIN width per coordinate in the canonical (hashed) serialisation. */
26
+ export const COORD_WIDTH = 33
27
+ export const SALT_BYTES = 32
28
+ /** Declared unlockingScriptLength; the measured hard maximum is 2,539 B including the salt. */
29
+ export const R1C_UNLOCK_LEN = 2560
30
+ export const R1C_MAX_KEYS = 5
31
+ /** BIP143 preimage length with subscript `ac` (2 B) and scope 0x41. */
32
+ export const R1C_PREIMAGE_LEN = 158
33
+ /** SIGHASH_ALL | SIGHASH_FORKID — the only scope the template supports. */
34
+ export const R1C_SIGHASH = 0x41
35
+
36
+ /** Exact hardened lock size for the salt-revealing witness template. */
37
+ export function R1C_LOCK_LEN(n: number): number {
38
+ if (n === 1) return 45199
39
+ if (Number.isInteger(n) && n >= 2 && n <= R1C_MAX_KEYS) return 45175 + 25 * n
40
+ throw new VaultError('template-invalid', `R1C_LOCK_LEN: N must be 1..${R1C_MAX_KEYS}, got ${String(n)}`)
41
+ }
42
+
43
+ // ───────────────────────── curve constants ─────────────────────────
44
+ const P256_CURVE = p256.Point.CURVE()
45
+ export const P256_P: bigint = P256_CURVE.p
46
+ export const P256_N: bigint = P256_CURVE.n
47
+ /** Largest canonical low-S P-256 signature scalar. */
48
+ export const P256_LOW_S_MAX: bigint = (P256_N - 1n) / 2n
49
+ /** secp256k1 group order — the OP_PUSH_TX leg only. */
50
+ export const SECP_N: bigint = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n
51
+ /** secp256k1 generator x — the OP_PUSH_TX signature's r (nonce k = 1). */
52
+ export const SECP_GX: bigint = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n
53
+ /** Public constants used by the two total OP_PUSH_TX signature branches. */
54
+ const PUSH_TX_C1 = 1n << 248n
55
+ const PUSH_TX_C2 = PUSH_TX_C1 + 1n
56
+ const RECODE_BITS = COMB_ROWS * COMB_COLS // 258 signed digits
57
+ /** 2^258 − 1: the recode constant at H2 (ANALYSIS.md §5.2). */
58
+ export const RECODE_CONST: bigint = (1n << BigInt(RECODE_BITS)) - 1n
59
+
60
+ // ───────────────────────── bigint / byte helpers ─────────────────────────
61
+ const mod = (a: bigint, m: bigint): bigint => ((a % m) + m) % m
62
+ function modpow(base: bigint, exp: bigint, m: bigint): bigint {
63
+ let r = 1n
64
+ let b = mod(base, m)
65
+ let e = exp
66
+ while (e > 0n) {
67
+ if ((e & 1n) === 1n) r = (r * b) % m
68
+ b = (b * b) % m
69
+ e >>= 1n
70
+ }
71
+ return r
72
+ }
73
+ /** Inverse modulo a prime. */
74
+ const modinv = (a: bigint, m: bigint): bigint => modpow(a, m - 2n, m)
75
+ const bytesOf = (h: string): number[] => Utils.toArray(h, 'hex') as number[]
76
+ const beToBig = (b: number[]): bigint => BigInt('0x' + (b.length > 0 ? Utils.toHex(b) : '0'))
77
+ const leToBig = (b: number[]): bigint => beToBig([...b].reverse())
78
+ const invalid = (message: string): VaultError => new VaultError('template-invalid', message)
79
+
80
+ /** Network recorded beside a Vault output and checked against wallet scope. */
81
+ export type VaultSaltChain = 'main' | 'test' | 'teratest'
82
+
83
+ /**
84
+ * Canonical `createHmac` data for a Vault output: the enrolled YubiKey serial
85
+ * numbers concatenated in commitment order with a one-byte count and a
86
+ * one-byte length before each ASCII serial. The framing keeps variable-length
87
+ * lists injective (`["1", "23"]` cannot collide with `["12", "3"]`).
88
+ */
89
+ export function vaultSaltHmacData(serials: readonly string[]): number[] {
90
+ if (serials.length < 1 || serials.length > R1C_MAX_KEYS) {
91
+ throw invalid(`Vault salt requires 1..${R1C_MAX_KEYS} YubiKey serials`)
92
+ }
93
+ const encoded: number[] = [serials.length]
94
+ for (const serial of serials) {
95
+ if (!/^[A-Za-z0-9._:-]{1,64}$/.test(serial)) {
96
+ throw invalid('Vault salt requires canonical YubiKey serials')
97
+ }
98
+ const bytes = Utils.toArray(serial, 'utf8') as number[]
99
+ encoded.push(bytes.length, ...bytes)
100
+ }
101
+ if (new Set(serials).size !== serials.length) {
102
+ throw invalid('Vault salt requires distinct YubiKey serials')
103
+ }
104
+ return encoded
105
+ }
106
+
107
+ // ───────────────────────── script-number encoding ─────────────────────────
108
+ /** Raw data push with the minimal push opcode (direct length, PUSHDATA1/2/4). */
109
+ export function pushData(data: number[]): number[] {
110
+ const d = [...data]
111
+ if (d.length === 0) return [OP.OP_0]
112
+ if (d.length <= 75) return [d.length, ...d]
113
+ if (d.length <= 0xff) return [OP.OP_PUSHDATA1, d.length, ...d]
114
+ if (d.length <= 0xffff) return [OP.OP_PUSHDATA2, d.length & 0xff, d.length >>> 8, ...d]
115
+ return [OP.OP_PUSHDATA4, d.length & 0xff, (d.length >>> 8) & 0xff, (d.length >>> 16) & 0xff, (d.length >>> 24) & 0xff, ...d]
116
+ }
117
+
118
+ /** Minimal script-number encoding (sign-magnitude little-endian) == BigNumber.toSm('little'). */
119
+ export function scriptNum(v: bigint): number[] {
120
+ if (v === 0n) return []
121
+ const neg = v < 0n
122
+ let m = neg ? -v : v
123
+ const b: number[] = []
124
+ while (m > 0n) {
125
+ b.push(Number(m & 0xffn))
126
+ m >>= 8n
127
+ }
128
+ if ((b[b.length - 1] & 0x80) !== 0) b.push(neg ? 0x80 : 0x00)
129
+ else if (neg) b[b.length - 1] |= 0x80
130
+ return b
131
+ }
132
+
133
+ /** Push a number as a minimally-encoded script number (OP_0, OP_1..OP_16, OP_1NEGATE, or a data push). */
134
+ export function encNum(v: bigint | number): number[] {
135
+ const n = BigInt(v)
136
+ if (n === 0n) return [OP.OP_0]
137
+ if (n >= 1n && n <= 16n) return [OP.OP_1 + Number(n) - 1]
138
+ if (n === -1n) return [OP.OP_1NEGATE]
139
+ return pushData(scriptNum(n))
140
+ }
141
+
142
+ // ───────────────────────── tiny assembler ─────────────────────────
143
+ // Tokens: OP_NAME | decimal integer (encNum) | <hex> (raw push) | {PARAM} | macro name.
144
+ const MACROS: Record<string, string> = {
145
+ // reduce top mod p; p lives on the altstack and is never consumed
146
+ MODP: 'OP_FROMALTSTACK OP_DUP OP_TOALTSTACK OP_MOD',
147
+ // BSV OP_MOD keeps the dividend's sign: normalise a negative remainder into [0, p)
148
+ NORM: 'OP_DUP 0 OP_LESSTHAN OP_IF OP_FROMALTSTACK OP_DUP OP_TOALTSTACK OP_ADD OP_ENDIF'
149
+ }
150
+ export type AsmParam = bigint | number | number[]
151
+ const OPCODES = OP as unknown as Record<string, number | undefined>
152
+
153
+ export function asm(text: string, params: Record<string, AsmParam> = {}): number[] {
154
+ const out: number[] = []
155
+ for (const tok of text.trim().split(/\s+/)) {
156
+ if (tok === '') continue
157
+ const macro = MACROS[tok]
158
+ if (macro !== undefined) {
159
+ out.push(...asm(macro, params))
160
+ continue
161
+ }
162
+ if (tok.startsWith('{') && tok.endsWith('}')) {
163
+ const v = params[tok.slice(1, -1)]
164
+ if (v === undefined) throw invalid(`asm: missing param ${tok}`)
165
+ out.push(...(typeof v === 'bigint' || typeof v === 'number' ? encNum(v) : pushData(v)))
166
+ continue
167
+ }
168
+ if (tok.startsWith('<') && tok.endsWith('>')) {
169
+ out.push(...pushData(bytesOf(tok.slice(1, -1))))
170
+ continue
171
+ }
172
+ if (/^-?\d+$/.test(tok)) {
173
+ out.push(...encNum(BigInt(tok)))
174
+ continue
175
+ }
176
+ const op = OPCODES[tok]
177
+ if (op === undefined) throw invalid(`asm: unknown opcode ${tok}`)
178
+ out.push(op)
179
+ }
180
+ return out
181
+ }
182
+
183
+ // ───────────────────────── public keys ─────────────────────────
184
+ /**
185
+ * 65-byte SEC1 (04‖X‖Y) or 33-byte compressed hex in → 33-byte compressed lowercase hex out.
186
+ * The card returns the 65-byte form; every comparison in the app uses the compressed form.
187
+ */
188
+ export function compressPubkey(sec1Hex: string): string {
189
+ if (typeof sec1Hex !== 'string' || !/^([0-9a-fA-F]{66}|[0-9a-fA-F]{130})$/.test(sec1Hex)) {
190
+ throw invalid('compressPubkey: expected 33- or 65-byte SEC1 hex')
191
+ }
192
+ const lower = sec1Hex.toLowerCase()
193
+ const prefix = lower.slice(0, 2)
194
+ if (lower.length === 66 && prefix !== '02' && prefix !== '03') throw invalid('compressPubkey: bad compressed prefix')
195
+ if (lower.length === 130 && prefix !== '04') throw invalid('compressPubkey: bad uncompressed prefix')
196
+ try {
197
+ const P = p256.Point.fromHex(lower)
198
+ P.assertValidity()
199
+ return P.toHex(true)
200
+ } catch {
201
+ throw invalid('compressPubkey: not a valid P-256 point')
202
+ }
203
+ }
204
+
205
+ // ───────────────────────── comb tables (spec §2.1) ─────────────────────────
206
+ export interface AffinePoint { x: bigint; y: bigint }
207
+ type P256Point = ReturnType<typeof p256.Point.fromHex>
208
+
209
+ /**
210
+ * Comb table scalar for entry j (0 <= j < 32):
211
+ * T_j = 2^(43·5) + Σ_{k<5} (bit_k(j) ? +1 : −1) · 2^(43k)
212
+ * The top digit is fixed +1 (the sign digit is applied in-script by negating y).
213
+ */
214
+ export function combTableScalar(j: number): bigint {
215
+ let s = 1n << BigInt(COMB_COLS * (COMB_ROWS - 1))
216
+ for (let k = 0; k < COMB_ROWS - 1; k++) s += (((j >> k) & 1) !== 0 ? 1n : -1n) << BigInt(COMB_COLS * k)
217
+ return s
218
+ }
219
+
220
+ function tableOf(base: P256Point): AffinePoint[] {
221
+ const pts: AffinePoint[] = []
222
+ for (let j = 0; j < TABLE_SIZE; j++) {
223
+ const a = base.multiply(mod(combTableScalar(j), P256_N)).toAffine()
224
+ pts.push({ x: a.x, y: a.y })
225
+ }
226
+ return pts
227
+ }
228
+
229
+ let gTableCache: AffinePoint[] | null = null
230
+ const copyTable = (table: readonly AffinePoint[]): AffinePoint[] => table.map(({ x, y }) => ({ x, y }))
231
+ /** table(G) — computed once on first use (32 scalar multiplications), then constant. */
232
+ export function gTable(): AffinePoint[] {
233
+ if (gTableCache === null) gTableCache = tableOf(p256.Point.BASE)
234
+ // Never expose the cache itself: callers may freely mutate the returned table
235
+ // without changing future locks or commitments.
236
+ return copyTable(gTableCache)
237
+ }
238
+
239
+ const TABLE_CACHE_MAX = 8
240
+ const qTableCache = new Map<string, AffinePoint[]>()
241
+ /** table(Q): 32 affine points T_j·Q. Memoised per compressed pubkey (Map, FIFO, max 8). Never persisted. */
242
+ export function combTable(pubkeyHex33: string): AffinePoint[] {
243
+ const key = compressPubkey(pubkeyHex33)
244
+ const hit = qTableCache.get(key)
245
+ if (hit !== undefined) return copyTable(hit)
246
+ const table = tableOf(p256.Point.fromHex(key))
247
+ if (qTableCache.size >= TABLE_CACHE_MAX) {
248
+ const oldest = qTableCache.keys().next().value
249
+ if (oldest !== undefined) qTableCache.delete(oldest)
250
+ }
251
+ qTableCache.set(key, table)
252
+ return copyTable(table)
253
+ }
254
+
255
+ // ───────────────────────── commitment (spec §2.2) ─────────────────────────
256
+ /** OP_NUM2BIN(v, 33) for a non-negative v: minimal LE scriptnum zero-padded to 33 bytes. */
257
+ export function le33(v: bigint): number[] {
258
+ if (v < 0n) throw invalid('le33: negative coordinate')
259
+ const b = scriptNum(v)
260
+ if (b.length > COORD_WIDTH) throw invalid('le33: value does not fit in 33 bytes')
261
+ while (b.length < COORD_WIDTH) b.push(0)
262
+ return b
263
+ }
264
+
265
+ /** le33(x_0) ‖ le33(y_0) ‖ … ‖ le33(y_31) — 2,112 bytes; injective over integer values. */
266
+ export function canonicalTableBytes(pubkeyHex33: string): number[] {
267
+ const out: number[] = []
268
+ for (const { x, y } of combTable(pubkeyHex33)) out.push(...le33(x), ...le33(y))
269
+ return out
270
+ }
271
+
272
+ function saltBytes(saltHex64: string): number[] {
273
+ if (typeof saltHex64 !== 'string' || !/^[0-9a-fA-F]{64}$/.test(saltHex64)) {
274
+ throw invalid(`salt must be ${SALT_BYTES} bytes as 64 hex chars`)
275
+ }
276
+ return bytesOf(saltHex64)
277
+ }
278
+
279
+ /** hash160(salt ‖ canonicalTableBytes(Q)) as 40 lowercase hex chars — the value baked into the lock. */
280
+ export function commitment(pubkeyHex33: string, saltHex64: string): string {
281
+ return Utils.toHex(Hash.hash160([...saltBytes(saltHex64), ...canonicalTableBytes(pubkeyHex33)]))
282
+ }
283
+
284
+ // ───────────────────────── scalar recoding (spec §2.4, ANALYSIS.md §5.2) ─────────────────────────
285
+ /** u' = ((u odd ? u : u + n) + 2^258 − 1) / 2 — exactly the H2 arithmetic. u' < 2^258 and bit 257 is always set. */
286
+ export function recode(u: bigint): bigint {
287
+ let v = mod(u, P256_N)
288
+ if (v % 2n === 0n) v += P256_N
289
+ return (v + RECODE_CONST) / 2n
290
+ }
291
+
292
+ // ───────────────────────── header H0–H5 (spec §2.3, gen2.mjs emitHeader2) ─────────────────────────
293
+ /** 64 Q coordinates pushed by the unlocker. */
294
+ const K_Q = 2 * TABLE_SIZE
295
+
296
+ /**
297
+ * H0–H3: identical for every lock. Stack in (unlock):
298
+ * [r u2' u1' Q0..Q63 s sInv preimage salt]. The preimage and salt are
299
+ * staged on alt in that order, then n is placed above them. Stack out:
300
+ * [r u2' u1' Q0..Q63] alt [preimage salt n].
301
+ */
302
+ let headerBeforeSaltCache: number[] | null = null
303
+ function emitHeaderBeforeSalt(): number[] {
304
+ if (headerBeforeSaltCache !== null) return headerBeforeSaltCache
305
+ const out: number[] = []
306
+ // Canonical witness shape: reject extra bottom pushes as well as missing fields.
307
+ out.push(...asm('OP_DEPTH {DEPTH} OP_NUMEQUALVERIFY', { DEPTH: 3 + K_Q + 4 }))
308
+ // H0: bind withdrawals to transaction version 1 at consensus level, then
309
+ // e = unsigned-LE(hash256(preimage)); preimage -> alt. OP_PUSH_TX later binds
310
+ // this exact preimage to the transaction being evaluated.
311
+ out.push(...asm(`
312
+ OP_OVER 4 OP_SPLIT OP_DROP <01000000> OP_EQUALVERIFY
313
+ OP_OVER OP_HASH256 <00> OP_CAT OP_BIN2NUM
314
+ 2 OP_ROLL OP_TOALTSTACK OP_SWAP OP_TOALTSTACK
315
+ `))
316
+ // H1: n -> alt; enforce canonical r, low-S s and sInv before any modular
317
+ // arithmetic; s*sInv == 1; u1 = e*sInv; u2 = r*sInv. The r checks are
318
+ // consensus-critical: without 1 <= r < p and r != n, CRT can give r one
319
+ // residue modulo n for scalar multiplication and another modulo p for the
320
+ // final affine-x check, permitting a signature-free spend.
321
+ // [.. s sInv u1]: u1(0) sInv(1) s(2) Q63(3) .. Q0(2+K) u1'(3+K) u2'(4+K) r(5+K)
322
+ out.push(...asm(`
323
+ {N} OP_TOALTSTACK
324
+ 2 OP_PICK 1 {HALFP1} OP_WITHIN OP_VERIFY
325
+ OP_OVER 1 OP_FROMALTSTACK OP_DUP OP_TOALTSTACK OP_WITHIN OP_VERIFY
326
+ {RDEPTH} OP_PICK OP_DUP 1 {P} OP_WITHIN OP_VERIFY
327
+ OP_FROMALTSTACK OP_DUP OP_TOALTSTACK OP_NUMNOTEQUAL OP_VERIFY
328
+ 2 OP_PICK 2 OP_PICK OP_MUL MODP 1 OP_NUMEQUALVERIFY
329
+ OP_OVER OP_MUL MODP
330
+ {RDEPTH} OP_PICK 2 OP_PICK OP_MUL MODP
331
+ 2 OP_ROLL OP_DROP 2 OP_ROLL OP_DROP
332
+ `, { N: P256_N, HALFP1: P256_LOW_S_MAX + 1n, P: P256_P, RDEPTH: K_Q + 5 }))
333
+ // H2: recode u2 then u1 -> [.. Q63 u1' u2']
334
+ const one = 'OP_DUP 2 OP_MOD OP_NOTIF {N} OP_ADD OP_ENDIF {C} OP_ADD 2 OP_DIV OP_SWAP'
335
+ out.push(...asm(`${one} ${one}`, { N: P256_N, C: RECODE_CONST }))
336
+ // H3: computed u2' == pushed u2' (depth K+3), then computed u1' == pushed u1' (depth K+1) -> [r u2' u1' Q..]
337
+ out.push(...asm('{DU2} OP_PICK OP_NUMEQUALVERIFY {DU1} OP_PICK OP_NUMEQUALVERIFY', { DU2: K_Q + 3, DU1: K_Q + 1 }))
338
+ headerBeforeSaltCache = out
339
+ return out
340
+ }
341
+
342
+ /** H4: recover and consume the witness salt, then hash160(salt || canonical table). */
343
+ let headerAfterSaltCache: number[] | null = null
344
+ function emitHeaderAfterSalt(): number[] {
345
+ if (headerAfterSaltCache !== null) return headerAfterSaltCache
346
+ // alt enters [preimage salt n]. Preserve n above preimage for emitPreloop,
347
+ // while returning salt to the main stack for its exact byte-length check.
348
+ const out: number[] = [...asm('OP_FROMALTSTACK OP_FROMALTSTACK OP_SWAP OP_TOALTSTACK OP_SIZE {SALT_BYTES} OP_NUMEQUALVERIFY', { SALT_BYTES })]
349
+ for (let m = 0; m < K_Q; m++) out.push(...asm('{D} OP_PICK {W} OP_NUM2BIN OP_CAT', { D: K_Q - m, W: COORD_WIDTH }))
350
+ out.push(OP.OP_HASH160)
351
+ headerAfterSaltCache = out
352
+ return out
353
+ }
354
+
355
+ /** H0–H4. The salt is supplied by the unlocking script and never appears here. */
356
+ function emitHeaderPrefix(): number[] {
357
+ return [...emitHeaderBeforeSalt(), ...emitHeaderAfterSalt()]
358
+ }
359
+
360
+ /** H5: H must equal one of the N baked 20-byte commitments. 22 B (N = 1) or 25N − 2 B (N >= 2). */
361
+ function emitH5(commitments: number[][]): number[] {
362
+ const out: number[] = []
363
+ if (commitments.length === 1) {
364
+ out.push(...asm('{C} OP_EQUALVERIFY', { C: commitments[0] }))
365
+ return out
366
+ }
367
+ for (let i = 0; i < commitments.length - 1; i++) out.push(...asm('OP_DUP {C} OP_EQUAL OP_SWAP', { C: commitments[i] }))
368
+ out.push(...asm('{C} OP_EQUAL', { C: commitments[commitments.length - 1] }))
369
+ for (let i = 0; i < commitments.length - 1; i++) out.push(OP.OP_BOOLOR)
370
+ out.push(OP.OP_VERIFY)
371
+ return out
372
+ }
373
+
374
+ // ───────────────────────── hardened suffix: G table, pre-loop, complete comb loop, tail ─────────────────────────
375
+ function emitGTable(): number[] {
376
+ const out: number[] = []
377
+ for (const { x, y } of gTable()) out.push(...encNum(x), ...encNum(y))
378
+ return out
379
+ }
380
+
381
+ /** Push p; swap altstack top n -> p; accumulator := Jacobian infinity (1, 1, 0). */
382
+ function emitPreloop(): number[] {
383
+ return asm('{P} OP_FROMALTSTACK OP_DROP OP_TOALTSTACK 1 1 0', { P: P256_P })
384
+ }
385
+
386
+ // Jacobian doubling, a = -3 (dbl-2001-b): M = 3(X-Z^2)(X+Z^2), S = 4XY^2,
387
+ // X3 = M^2 - 2S, Y3 = M(S - X3) - 8Y^4, Z3 = 2YZ. Only X3, Y3, Z3 are reduced.
388
+ const DOUBLE = `
389
+ OP_DUP OP_DUP OP_MUL
390
+ 3 OP_PICK OP_OVER OP_SUB
391
+ 4 OP_PICK 2 OP_ROLL OP_ADD
392
+ 1 OP_ROLL 1 OP_ROLL
393
+ OP_MUL 3 OP_MUL
394
+ 2 OP_PICK OP_DUP OP_MUL
395
+ 4 OP_ROLL OP_OVER OP_MUL 4 OP_MUL
396
+ 2 OP_PICK OP_DUP OP_MUL
397
+ OP_OVER OP_2MUL
398
+ 1 OP_ROLL 1 OP_ROLL
399
+ OP_SUB MODP NORM
400
+ 1 OP_ROLL OP_OVER OP_SUB
401
+ 3 OP_ROLL 1 OP_ROLL OP_MUL
402
+ 2 OP_ROLL OP_DUP OP_MUL 8 OP_MUL
403
+ 1 OP_ROLL 1 OP_ROLL OP_SUB MODP NORM
404
+ 3 OP_ROLL 3 OP_ROLL OP_MUL OP_2MUL MODP NORM
405
+ 2 OP_ROLL 2 OP_ROLL 2 OP_ROLL
406
+ `
407
+
408
+ // Digit extraction + table lookup + conditional negation. Stack in: [.. X Y Z]; out: [.. X Y Z x y].
409
+ // Row 0 bit = sign digit; rows 1..4 are XNOR'd against it to form the 5-bit table index j.
410
+ const DIGITS_AND_LOOKUP = `
411
+ {DEPTH0} OP_PICK {SHIFT0} OP_RSHIFTNUM 2 OP_MOD
412
+ {DEPTH1} OP_PICK {SHIFT1} OP_RSHIFTNUM 2 OP_MOD OP_OVER OP_NUMEQUAL OP_2MUL
413
+ {DEPTH2} OP_PICK {SHIFT2} OP_RSHIFTNUM 2 OP_MOD 2 OP_PICK OP_NUMEQUAL OP_ADD OP_2MUL
414
+ {DEPTH2} OP_PICK {SHIFT3} OP_RSHIFTNUM 2 OP_MOD 2 OP_PICK OP_NUMEQUAL OP_ADD OP_2MUL
415
+ {DEPTH2} OP_PICK {SHIFT4} OP_RSHIFTNUM 2 OP_MOD 2 OP_PICK OP_NUMEQUAL OP_ADD OP_2MUL
416
+ {DEPTH2} OP_PICK {SHIFT5} OP_RSHIFTNUM 2 OP_MOD 2 OP_PICK OP_NUMEQUAL OP_ADD
417
+ OP_DUP OP_2MUL {BASE} OP_SWAP OP_SUB OP_PICK
418
+ OP_OVER OP_2MUL {BASE} OP_SWAP OP_SUB OP_PICK
419
+ 2 OP_ROLL OP_DROP 2 OP_ROLL
420
+ OP_NOTIF OP_FROMALTSTACK OP_DUP OP_TOALTSTACK OP_SWAP OP_SUB OP_ENDIF
421
+ `
422
+
423
+ // Mixed Jacobian + affine addition: U2 = xZ^2, S2 = yZ^3, H = U2 - X, R = S2 - Y,
424
+ // X3 = R^2 - H^3 - 2XH^2, Y3 = R(XH^2 - X3) - YH^3, Z3 = ZH. Only X3, Y3, Z3 are reduced.
425
+ const MADD = `
426
+ 2 OP_PICK OP_DUP OP_MUL
427
+ 2 OP_ROLL OP_OVER OP_MUL
428
+ 3 OP_PICK 2 OP_ROLL OP_MUL
429
+ 2 OP_ROLL 1 OP_ROLL OP_MUL
430
+ 1 OP_ROLL 4 OP_PICK OP_SUB
431
+ 1 OP_ROLL 3 OP_PICK OP_SUB
432
+ OP_OVER OP_DUP OP_MUL
433
+ 2 OP_PICK OP_OVER OP_MUL
434
+ 6 OP_ROLL 2 OP_ROLL OP_MUL
435
+ 2 OP_PICK OP_DUP OP_MUL
436
+ OP_OVER OP_2MUL
437
+ 1 OP_ROLL 3 OP_PICK OP_SUB
438
+ 1 OP_ROLL OP_SUB MODP NORM
439
+ 1 OP_ROLL OP_OVER OP_SUB
440
+ 3 OP_ROLL 1 OP_ROLL OP_MUL
441
+ 5 OP_ROLL 3 OP_ROLL OP_MUL
442
+ 1 OP_ROLL 1 OP_ROLL OP_SUB MODP NORM
443
+ 3 OP_ROLL 3 OP_ROLL OP_MUL MODP NORM
444
+ 2 OP_ROLL 2 OP_ROLL 2 OP_ROLL
445
+ `
446
+
447
+ // Complete wrapper for mixed addition. The fast formula above is undefined
448
+ // when the accumulator is infinity or H = 0. Handle those cases explicitly:
449
+ // infinity + P = P; P + P = DOUBLE(P); P + (-P) = infinity. This is required
450
+ // for availability for every valid key/signature, rather than relying on the
451
+ // exceptional relations being improbable.
452
+ const COMPLETE_MADD = `
453
+ 2 OP_PICK 0 OP_NUMEQUAL
454
+ OP_IF
455
+ OP_TOALTSTACK OP_TOALTSTACK OP_DROP OP_DROP OP_DROP
456
+ OP_FROMALTSTACK OP_FROMALTSTACK 1
457
+ OP_ELSE
458
+ 2 OP_PICK OP_DUP OP_MUL MODP
459
+ 2 OP_PICK OP_MUL
460
+ 5 OP_PICK OP_SUB MODP NORM
461
+ 0 OP_NUMEQUAL
462
+ OP_IF
463
+ 2 OP_PICK OP_DUP OP_MUL MODP
464
+ 3 OP_PICK OP_MUL
465
+ 1 OP_PICK OP_MUL
466
+ 4 OP_PICK OP_SUB MODP NORM
467
+ 0 OP_NUMEQUAL
468
+ OP_IF
469
+ OP_2DROP
470
+ ${DOUBLE}
471
+ OP_ELSE
472
+ OP_2DROP OP_2DROP OP_DROP 1 1 0
473
+ OP_ENDIF
474
+ OP_ELSE
475
+ ${MADD}
476
+ OP_ENDIF
477
+ OP_ENDIF
478
+ `
479
+
480
+ /** Complete Jacobian-plus-affine addition fragment; p must be the altstack top. */
481
+ export function completeMixedAddScript(): number[] {
482
+ return asm(COMPLETE_MADD)
483
+ }
484
+
485
+ /** Stack layout beneath the accumulator: [r u2' u1' C[0..K-1]] with K = 128 table coordinates (Q[0..63] then G[0..63]). */
486
+ const K_CONSTS = 2 * 2 * TABLE_SIZE // 128
487
+ const BELOW = 3 + K_CONSTS // 131 items under the accumulator (X Y Z)
488
+ // With [.. X Y Z] on top (BELOW + 3 items): stack index 1 (= u2') is at depth 132, index 2 (= u1') at 131.
489
+ const scalarDepth = (half: 0 | 1): number => BELOW + 1 - half
490
+ // C[m] sits at depth 132 − m once [.. X Y Z sign j] is on top; half 0 -> C[0..63] (= Q), half 1 -> C[64..127] (= G).
491
+ const tableBase = (half: 0 | 1): number => BELOW + 1 - 2 * TABLE_SIZE * half
492
+ /** Shift for column c, row k: bit position 43k + 42 − c of the recoded scalar = 257 − c − 43k. */
493
+ export const shiftFor = (c: number, k: number): number => COMB_COLS * (COMB_ROWS - 1 - k) + (COMB_COLS - 1 - c)
494
+
495
+ function emitAdd(half: 0 | 1, c: number): number[] {
496
+ const params: Record<string, AsmParam> = {
497
+ DEPTH0: scalarDepth(half), DEPTH1: scalarDepth(half) + 1, DEPTH2: scalarDepth(half) + 2, BASE: tableBase(half)
498
+ }
499
+ for (let k = 0; k < COMB_ROWS; k++) params[`SHIFT${k}`] = shiftFor(c, k)
500
+ return [...asm(DIGITS_AND_LOOKUP, params), ...completeMixedAddScript()]
501
+ }
502
+
503
+ /** 43 columns, Horner: acc = 2·acc + d2(c)·TQ[j2] + d1(c)·TG[j1], with complete mixed additions. */
504
+ function emitCombLoop(): number[] {
505
+ const out: number[] = []
506
+ for (let c = 0; c < COMB_COLS; c++) {
507
+ out.push(...asm(DOUBLE))
508
+ out.push(...emitAdd(0, c)) // index-1 scalar (u2') with C[0..63] (Q)
509
+ out.push(...emitAdd(1, c)) // index-2 scalar (u1') with C[64..127] (G)
510
+ }
511
+ return out
512
+ }
513
+
514
+ /** DER INTEGER for a non-negative bigint: minimal big-endian with a 0x00 pad if the top bit is set. */
515
+ function derIntBytes(v: bigint): number[] {
516
+ let h = v.toString(16)
517
+ if (h.length % 2 === 1) h = '0' + h
518
+ const b = bytesOf(h)
519
+ if ((b[0] & 0x80) !== 0) b.unshift(0)
520
+ return [0x02, b.length, ...b]
521
+ }
522
+
523
+ /**
524
+ * An OP_PUSH_TX dummy key d·G on secp256k1 for the public constant C,
525
+ * d = C·Gx⁻¹ mod n_k1. With nonce k = 1 the corresponding signature is
526
+ * (r, s) = (Gx, e + C mod n_k1). Nothing about these keys is secret.
527
+ */
528
+ const pushTxPubKeyCache = new Map<bigint, number[]>()
529
+ function pushTxPubKey(constant: bigint): number[] {
530
+ let key = pushTxPubKeyCache.get(constant)
531
+ if (!key) {
532
+ const d = mod(constant * modinv(SECP_GX, SECP_N), SECP_N)
533
+ key = new PrivateKey(d.toString(16).padStart(64, '0'), 16).toPublicKey().encode(true) as number[]
534
+ pushTxPubKeyCache.set(constant, key)
535
+ }
536
+ return key.slice()
537
+ }
538
+
539
+ /**
540
+ * Tail: Z != 0 and X == r·Z² (mod p); clear the stack; total OP_PUSH_TX with
541
+ * k = 1 on secp256k1 (ANALYSIS.md §6).
542
+ *
543
+ * Ordinarily C1 = 2^248 and dummy key d1 produce s = e + C1 (mod n). For the
544
+ * single digest where that scalar is zero, the script selects C2 = C1 + 1 and
545
+ * dummy key d2, which produces s = 1. Two distinct constants cannot both be
546
+ * zero for one e, so the covenant signature is defined for every digest; no
547
+ * probabilistic transaction-sequence retry is part of spend availability.
548
+ */
549
+ function emitTail(): number[] {
550
+ // r (item index 0) with [.. X Y Z Z^2] on top (BELOW + 4 items) is at depth BELOW + 3 = 134
551
+ const rCheck = asm(`
552
+ OP_DUP 0 OP_NUMEQUAL OP_NOTIF
553
+ OP_DUP OP_DUP OP_MUL MODP
554
+ {RDEPTH} OP_PICK OP_OVER OP_MUL MODP
555
+ 4 OP_PICK OP_NUMEQUAL
556
+ OP_ELSE 0 OP_ENDIF OP_VERIFY
557
+ OP_FROMALTSTACK OP_DROP
558
+ `, { RDEPTH: BELOW + 3 })
559
+ // stack now holds BELOW + 4 items (r u2' u1' C[] X Y Z Z^2): drop them all
560
+ const leftover = BELOW + 4
561
+ const clear: number[] = [
562
+ ...new Array<number>(Math.floor(leftover / 2)).fill(OP.OP_2DROP),
563
+ ...(leftover % 2 === 1 ? [OP.OP_DROP] : [])
564
+ ]
565
+ // e_k1 = BE(hash256(preimage)); normally s = lowS((e_k1 + C1) mod n_k1).
566
+ // If that is zero, use C2 and its public key, for which s is exactly 1.
567
+ const rev31 = new Array<string>(31).fill('OP_SWAP OP_CAT').join(' ')
568
+ const pushTx = asm(`
569
+ OP_FROMALTSTACK {SIGHASH} OP_TOALTSTACK OP_HASH256
570
+ ${new Array<string>(31).fill('1 OP_SPLIT').join(' ')}
571
+ ${rev31}
572
+ <00> OP_CAT OP_BIN2NUM
573
+ 0 31 OP_NUM2BIN 1 OP_CAT OP_ADD
574
+ {NK} OP_TUCK 2 OP_DIV OP_OVER OP_LESSTHAN
575
+ OP_IF OP_OVER OP_MOD OP_OVER 2 OP_DIV OP_OVER OP_LESSTHAN OP_IF OP_SUB OP_ELSE OP_NIP OP_ENDIF
576
+ OP_ELSE OP_NIP OP_ENDIF
577
+ OP_DUP OP_0NOTEQUAL
578
+ OP_IF {PUBKEY1} OP_SWAP
579
+ OP_ELSE OP_DROP {PUBKEY2} 1 OP_ENDIF
580
+ ${new Array<string>(31).fill('OP_SIZE OP_0NOTEQUAL OP_SPLIT').join(' ')}
581
+ ${rev31}
582
+ OP_SIZE OP_SWAP OP_CAT
583
+ {DERPREFIX} OP_SWAP OP_CAT
584
+ OP_SIZE OP_SWAP OP_CAT
585
+ <30> OP_SWAP OP_CAT
586
+ OP_FROMALTSTACK OP_CAT
587
+ OP_SWAP OP_CODESEPARATOR OP_CHECKSIG
588
+ `, {
589
+ SIGHASH: [R1C_SIGHASH], NK: SECP_N,
590
+ DERPREFIX: [...derIntBytes(SECP_GX), 0x02], // 02 20 <Gx> 02 (s INTEGER tag appended)
591
+ PUBKEY1: pushTxPubKey(PUSH_TX_C1),
592
+ PUBKEY2: pushTxPubKey(PUSH_TX_C2)
593
+ })
594
+ return [...rCheck, ...clear, ...pushTx]
595
+ }
596
+
597
+ let sharedSuffixCache: number[] | null = null
598
+ /** G table + pre-loop + complete comb loop + total covenant tail: 44,388 B. Computed once. */
599
+ export function sharedSuffix(): number[] {
600
+ if (sharedSuffixCache === null) sharedSuffixCache = [...emitGTable(), ...emitPreloop(), ...emitCombLoop(), ...emitTail()]
601
+ return sharedSuffixCache.slice()
602
+ }
603
+
604
+ // ───────────────────────── public: buildLock / bakedCommitments (spec §2.3) ─────────────────────────
605
+ function parseCommitments(commitments: unknown): number[][] {
606
+ if (!Array.isArray(commitments) || commitments.length < 1 || commitments.length > R1C_MAX_KEYS) {
607
+ throw invalid(`buildLock: commitments must be 1..${R1C_MAX_KEYS} hash160 hex strings`)
608
+ }
609
+ const lower: string[] = commitments.map(c => {
610
+ if (typeof c !== 'string' || !/^[0-9a-fA-F]{40}$/.test(c)) throw invalid('buildLock: commitment must be 40 hex chars')
611
+ return c.toLowerCase()
612
+ })
613
+ if (new Set(lower).size !== lower.length) throw invalid('buildLock: duplicate commitment')
614
+ return lower.map(bytesOf)
615
+ }
616
+
617
+ /** N in 1..5 salted table commitments. saltHex64 is validated but never emitted into the lock. */
618
+ export function buildLock(a: { commitments: string[]; saltHex64: string }): LockingScript {
619
+ const cs = parseCommitments(a.commitments)
620
+ saltBytes(a.saltHex64)
621
+ const bytes = [...emitHeaderPrefix(), ...emitH5(cs), ...sharedSuffix()]
622
+ const expected = R1C_LOCK_LEN(cs.length)
623
+ if (bytes.length !== expected) throw invalid(`buildLock: emitted ${bytes.length} bytes, expected ${expected}`)
624
+ return new LockingScript(Script.fromBinary(bytes).chunks)
625
+ }
626
+
627
+ /**
628
+ * Parse and validate a lock built by buildLock. The H5 skeleton and whole
629
+ * salt-free template must be byte-identical to a rebuilt lock.
630
+ */
631
+ function parseBakedLock(lock: Script): { commitments: string[] } {
632
+ const bin = lock.toBinary()
633
+ let n = -1
634
+ for (let k = 1; k <= R1C_MAX_KEYS; k++) if (bin.length === R1C_LOCK_LEN(k)) n = k
635
+ if (n < 0) throw invalid(`bakedCommitments: ${bin.length} bytes is not an R1C lock length`)
636
+ const prefix = emitHeaderPrefix()
637
+ const suffix = sharedSuffix()
638
+ const h5 = bin.slice(prefix.length, bin.length - suffix.length)
639
+ const cs: number[][] = []
640
+ if (n === 1) {
641
+ cs.push(h5.slice(1, 21))
642
+ } else {
643
+ for (let i = 0; i < n - 1; i++) cs.push(h5.slice(24 * i + 2, 24 * i + 22))
644
+ cs.push(h5.slice(24 * (n - 1) + 1, 24 * (n - 1) + 21))
645
+ }
646
+ const rebuilt = [...prefix, ...emitH5(cs), ...suffix]
647
+ if (rebuilt.length !== bin.length || rebuilt.some((b, i) => b !== bin[i])) {
648
+ throw invalid('bakedCommitments: not an R1C lock')
649
+ }
650
+ return { commitments: cs.map(c => Utils.toHex(c)) }
651
+ }
652
+
653
+ /** Commitments baked into an exact current R1C lock, in order. */
654
+ export function bakedCommitments(lock: Script): string[] {
655
+ return parseBakedLock(lock).commitments
656
+ }
657
+
658
+ // ───────────────────────── sighash preimage and signer digest (spec §2.5) ─────────────────────────
659
+ /** OP_CODESEPARATOR OP_CHECKSIG ⇒ the scriptCode the lock's CHECKSIG hashes is the single byte `ac`. */
660
+ const SUBSCRIPT = Script.fromHex('ac')
661
+
662
+ function requirePreimage(preimage: number[], where: string): void {
663
+ if (!Array.isArray(preimage) || preimage.length !== R1C_PREIMAGE_LEN) {
664
+ throw invalid(`${where}: preimage must be ${R1C_PREIMAGE_LEN} bytes`)
665
+ }
666
+ const version = new Utils.Reader(preimage.slice(0, 4)).readUInt32LE()
667
+ if (version !== 1) throw invalid(`${where}: vault withdrawals require transaction version 1; this preimage carries version ${version}`)
668
+ }
669
+
670
+ /** Version-1 BIP143 preimage, subscript `ac`, scope 0x41, for input `inputIndex` of `tx` whose source output carried `sourceSatoshis`. */
671
+ export function sighashPreimage(tx: Transaction, inputIndex: number, sourceSatoshis: number): number[] {
672
+ const input = tx.inputs[inputIndex]
673
+ if (input === undefined) throw invalid(`sighashPreimage: input ${inputIndex} does not exist`)
674
+ const sourceTXID = input.sourceTXID ?? input.sourceTransaction?.id('hex')
675
+ if (sourceTXID === undefined) throw invalid('sighashPreimage: input needs sourceTXID or sourceTransaction')
676
+ if (!Number.isSafeInteger(sourceSatoshis) || sourceSatoshis < 0) throw invalid('sighashPreimage: sourceSatoshis must be a non-negative integer')
677
+ const preimage = TransactionSignature.format({
678
+ sourceTXID,
679
+ sourceOutputIndex: input.sourceOutputIndex,
680
+ sourceSatoshis,
681
+ transactionVersion: tx.version,
682
+ otherInputs: tx.inputs.filter((_, i) => i !== inputIndex),
683
+ outputs: tx.outputs,
684
+ inputIndex,
685
+ subscript: SUBSCRIPT,
686
+ inputSequence: input.sequence ?? 0xffffffff,
687
+ lockTime: tx.lockTime,
688
+ scope: R1C_SIGHASH
689
+ })
690
+ requirePreimage(preimage, 'sighashPreimage')
691
+ return preimage
692
+ }
693
+
694
+ /** reverse(hash256(preimage)) as 64 lowercase hex — the raw digest the P-256 signer signs (the script reads e little-endian). */
695
+ export function signerDigest(preimage: number[]): string {
696
+ requirePreimage(preimage, 'signerDigest')
697
+ return Utils.toHex([...Hash.hash256(preimage)].reverse())
698
+ }
699
+
700
+ // ───────────────────────── OP_PUSH_TX model (ANALYSIS.md §6) ─────────────────────────
701
+ /**
702
+ * The nonzero s the tail assembles. It uses lowS((BE(hash256(preimage)) +
703
+ * C1) mod n_k1), except that the zero case selects C2 and therefore s = 1.
704
+ * In both branches r is fixed at Gx (nonce k = 1).
705
+ */
706
+ export function pushTxSignatureS(preimage: number[]): bigint {
707
+ const e = beToBig(Hash.hash256(preimage))
708
+ const first = mod(e + PUSH_TX_C1, SECP_N)
709
+ const t = first === 0n ? mod(e + PUSH_TX_C2, SECP_N) : first
710
+ return t > (SECP_N - 1n) / 2n ? SECP_N - t : t
711
+ }
712
+
713
+ /**
714
+ * Pre-sign check for the fixed OP_PUSH_TX signature. The byte-reversal loop
715
+ * uses OP_SIZE rather than parsing arbitrary suffix bytes as script numbers,
716
+ * so every positive low-S encoding is accepted. The two-key covenant branch
717
+ * makes s nonzero for every digest; `ok` is retained for caller compatibility.
718
+ */
719
+ export function pushTxDerCheck(preimage: number[]): { ok: boolean; s: bigint } {
720
+ requirePreimage(preimage, 'pushTxDerCheck')
721
+ const s = pushTxSignatureS(preimage)
722
+ return { ok: true, s }
723
+ }
724
+
725
+ // ───────────────────────── DER ─────────────────────────
726
+ /** Strict DER `SEQUENCE { INTEGER r, INTEGER s }` → (r, s), both in [1, n−1]. Short-form lengths only (max 72 B). */
727
+ export function decodeDerSignature(der: number[]): { r: bigint; s: bigint } {
728
+ const fail = (why: string): never => { throw invalid(`decodeDerSignature: ${why}`) }
729
+ if (!Array.isArray(der) || der.length < 8 || der.length > 72) fail('length')
730
+ if (der[0] !== 0x30) fail('not a SEQUENCE')
731
+ if (der[1] !== der.length - 2) fail('bad SEQUENCE length')
732
+ let pos = 2
733
+ const readInt = (): bigint => {
734
+ if (der[pos] !== 0x02) fail('expected INTEGER')
735
+ const len = der[pos + 1]
736
+ if (len === undefined || len === 0 || len > 33 || pos + 2 + len > der.length) fail('bad INTEGER length')
737
+ const body = der.slice(pos + 2, pos + 2 + len)
738
+ if ((body[0] & 0x80) !== 0) fail('negative INTEGER')
739
+ if (len > 1 && body[0] === 0x00 && (body[1] & 0x80) === 0) fail('non-minimal INTEGER')
740
+ pos += 2 + len
741
+ return beToBig(body)
742
+ }
743
+ const r = readInt()
744
+ const s = readInt()
745
+ if (pos !== der.length) fail('trailing bytes')
746
+ if (r === 0n || r >= P256_N || s === 0n || s >= P256_N) fail('scalar out of range')
747
+ return { r, s }
748
+ }
749
+
750
+ // ───────────────────────── strict verification flags ─────────────────────────
751
+ /**
752
+ * Explicit @bsv/sdk Spend flags. With flags given, every rule is flag-driven and ignores the transaction
753
+ * version: MINIMALDATA (minimal pushes and script numbers),
754
+ * UTXO_AFTER_CHRONICLE (post-Genesis limits off, OP_RSHIFTNUM/OP_2MUL live), SIGHASH_FORKID + STRICTENC
755
+ * (strict DER, defined hash type, FORKID required), and CLEANSTACK + SIGPUSHONLY + LOW_S to rule out
756
+ * otherwise-valid witness encodings. Vault withdrawals are version 1 as an additional network-policy guard.
757
+ */
758
+ export const R1C_VERIFY_FLAGS: readonly string[] = [
759
+ 'MINIMALDATA',
760
+ 'UTXO_AFTER_CHRONICLE',
761
+ 'SIGHASH_FORKID',
762
+ 'STRICTENC',
763
+ 'CLEANSTACK',
764
+ 'SIGPUSHONLY',
765
+ 'LOW_S'
766
+ ]
767
+
768
+ // ───────────────────────── fullR / buildUnlock (spec §2.4) ─────────────────────────
769
+ /**
770
+ * R = u1·G + u2·Q for e = LE(hash256(preimage)), u1 = e·s⁻¹, u2 = rSig·s⁻¹ (mod n).
771
+ * Returns the FULL affine x (in [0, p)), or null if R is the point at infinity. Throws on s ≡ 0.
772
+ */
773
+ export function fullR(a: { preimage: number[]; rSig: bigint; s: bigint; pubkeyHex33: string }): bigint | null {
774
+ requirePreimage(a.preimage, 'fullR')
775
+ const Q = p256.Point.fromHex(compressPubkey(a.pubkeyHex33))
776
+ const s = mod(a.s, P256_N)
777
+ if (s === 0n) throw invalid('fullR: s ≡ 0 (mod n)')
778
+ const e = leToBig(Hash.hash256(a.preimage))
779
+ const sInv = modinv(s, P256_N)
780
+ const u1 = mod(e * sInv, P256_N)
781
+ const u2 = mod(a.rSig * sInv, P256_N)
782
+ const R = (u1 === 0n ? p256.Point.ZERO : p256.Point.BASE.multiply(u1)).add(u2 === 0n ? p256.Point.ZERO : Q.multiply(u2))
783
+ if (R.is0()) return null
784
+ return R.toAffine().x
785
+ }
786
+
787
+ /**
788
+ * The 71-push unlocking script: r, u2', u1', 64 coords of table(Q), s, s⁻¹,
789
+ * preimage, and the 32-byte salt (spec §2.4).
790
+ * Refuses: wrong preimage length, preimage version ≠ 1,
791
+ * bad key / DER, R = O. It does NOT verify the signature against Q: the interpreter is the arbiter
792
+ * (Plan 2 runs verifyVaultInput on every input before signAction).
793
+ */
794
+ export function buildUnlock(a: { preimage: number[]; derSig: number[]; pubkeyHex33: string; saltHex64: string }): UnlockingScript {
795
+ const { preimage } = a
796
+ requirePreimage(preimage, 'buildUnlock')
797
+ const key = compressPubkey(a.pubkeyHex33)
798
+ const decoded = decodeDerSignature(a.derSig)
799
+ const rSig = decoded.r
800
+ // (r, n-s) verifies whenever (r, s) does and has the same R.x. Normalising
801
+ // here lets hardware return either valid form while the consensus script has
802
+ // one canonical scalar representation.
803
+ const s = decoded.s > P256_LOW_S_MAX ? P256_N - decoded.s : decoded.s
804
+ const Rx = fullR({ preimage, rSig, s, pubkeyHex33: key })
805
+ if (Rx === null) throw invalid('buildUnlock: R is the point at infinity')
806
+ const e = leToBig(Hash.hash256(preimage))
807
+ const sInv = modinv(s, P256_N)
808
+ const u1 = mod(e * sInv, P256_N)
809
+ const u2 = mod(Rx * sInv, P256_N) // the lock derives u2 from the PUSHED r (≡ rSig mod n), so recode that
810
+ const bytes: number[] = [...encNum(Rx), ...encNum(recode(u2)), ...encNum(recode(u1))]
811
+ for (const { x, y } of combTable(key)) bytes.push(...encNum(x), ...encNum(y))
812
+ bytes.push(...encNum(s), ...encNum(sInv), ...pushData(preimage), ...pushData(saltBytes(a.saltHex64)))
813
+ if (bytes.length > R1C_UNLOCK_LEN) throw invalid(`buildUnlock: ${bytes.length} bytes exceeds R1C_UNLOCK_LEN`)
814
+ return new UnlockingScript(Script.fromBinary(bytes).chunks)
815
+ }
816
+
817
+ // ───────────────────────── strict local verification ─────────────────────────
818
+ /** Run @bsv/sdk Spend with R1C_VERIFY_FLAGS for one input. Returns true or throws the interpreter's error. */
819
+ export function verifyVaultInput(a: {
820
+ tx: Transaction
821
+ inputIndex: number
822
+ sourceSatoshis: number
823
+ lockingScript: LockingScript
824
+ unlockingScript: UnlockingScript
825
+ }): true {
826
+ const { tx, inputIndex } = a
827
+ const input = tx.inputs[inputIndex]
828
+ if (input === undefined) throw invalid(`verifyVaultInput: input ${inputIndex} does not exist`)
829
+ const sourceTXID = input.sourceTXID ?? input.sourceTransaction?.id('hex')
830
+ if (sourceTXID === undefined) throw invalid('verifyVaultInput: input needs sourceTXID or sourceTransaction')
831
+ const spend = new Spend({
832
+ sourceTXID,
833
+ sourceOutputIndex: input.sourceOutputIndex,
834
+ sourceSatoshis: a.sourceSatoshis,
835
+ lockingScript: a.lockingScript,
836
+ transactionVersion: tx.version,
837
+ otherInputs: tx.inputs.filter((_, i) => i !== inputIndex),
838
+ outputs: tx.outputs,
839
+ inputIndex,
840
+ unlockingScript: a.unlockingScript,
841
+ inputSequence: input.sequence ?? 0xffffffff,
842
+ lockTime: tx.lockTime,
843
+ verifyFlags: [...R1C_VERIFY_FLAGS]
844
+ })
845
+ if (spend.validate() !== true) throw invalid('verifyVaultInput: script evaluated to false')
846
+ return true
847
+ }
848
+
849
+ // ───────────────────────── self-describing customInstructions v6 ─────────────────────────
850
+ export interface VaultInstructionKey {
851
+ serial: string
852
+ slot: number
853
+ pubkey: string
854
+ nickname: string
855
+ enrolledAt: number
856
+ }
857
+
858
+ /** Recoverable key metadata in the exact commitment order of this output. */
859
+ export interface VaultInstructionsV6 {
860
+ v: 6
861
+ type: 'R1C'
862
+ /** Wallet createHmac result; revealed by the unlocking script and committed through H5. */
863
+ salt: string
864
+ /** Canonical positive decimal wallet key index (`"1"`, `"2"`, ...). */
865
+ saltKeyId: string
866
+ /** Network scope of the output. */
867
+ chain: VaultSaltChain
868
+ vaultId: string
869
+ revision: number
870
+ createdAt: number
871
+ keys: VaultInstructionKey[]
872
+ }
873
+ export type VaultInstructions = VaultInstructionsV6
874
+
875
+ const MAX_CUSTOM_INSTRUCTIONS_CHARS = 4096
876
+ const exactFields = (v: Record<string, unknown>, fields: readonly string[]): boolean => {
877
+ const actual = Object.keys(v)
878
+ return actual.length === fields.length && fields.every(field => Object.prototype.hasOwnProperty.call(v, field))
879
+ }
880
+ const positiveSafeInteger = (v: unknown): v is number => Number.isSafeInteger(v) && (v as number) > 0
881
+
882
+ /**
883
+ * Parse exact v6 output recovery metadata. Older and extended shapes fail
884
+ * closed: future code must explicitly version any semantic change.
885
+ */
886
+ export function decodeVaultInstructions(ci?: string): VaultInstructionsV6 | null {
887
+ if (typeof ci !== 'string' || ci.length === 0 || ci.length > MAX_CUSTOM_INSTRUCTIONS_CHARS) return null
888
+ let parsed: unknown
889
+ try {
890
+ parsed = JSON.parse(ci)
891
+ } catch {
892
+ return null
893
+ }
894
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return null
895
+ const p = parsed as Record<string, unknown>
896
+ if (!exactFields(p, ['v', 'type', 'salt', 'saltKeyId', 'chain', 'vaultId', 'revision', 'createdAt', 'keys'])) return null
897
+ if (p.v !== 6 || p.type !== 'R1C') return null
898
+ if (typeof p.salt !== 'string' || !/^[0-9a-f]{64}$/.test(p.salt)) return null
899
+ if (typeof p.vaultId !== 'string' || !/^[0-9a-f]{64}$/.test(p.vaultId)) return null
900
+ if (
901
+ typeof p.saltKeyId !== 'string' ||
902
+ !/^[1-9][0-9]{0,15}$/.test(p.saltKeyId)
903
+ ) return null
904
+ if (p.chain !== 'main' && p.chain !== 'test' && p.chain !== 'teratest') return null
905
+ const saltIndex = Number(p.saltKeyId)
906
+ if (!positiveSafeInteger(saltIndex)) return null
907
+ if (!positiveSafeInteger(p.revision) || !positiveSafeInteger(p.createdAt)) return null
908
+ if (!Array.isArray(p.keys) || p.keys.length < 1 || p.keys.length > R1C_MAX_KEYS) return null
909
+ const keys: VaultInstructionKey[] = []
910
+ for (const raw of p.keys) {
911
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return null
912
+ const k = raw as Record<string, unknown>
913
+ if (!exactFields(k, ['serial', 'slot', 'pubkey', 'nickname', 'enrolledAt'])) return null
914
+ if (typeof k.serial !== 'string' || !/^[A-Za-z0-9._:-]{1,64}$/.test(k.serial)) return null
915
+ if (k.slot !== 0x82) return null
916
+ if (typeof k.pubkey !== 'string' || !/^0[23][0-9a-f]{64}$/.test(k.pubkey)) return null
917
+ if (
918
+ typeof k.nickname !== 'string' || k.nickname.length < 1 || k.nickname.length > 64 ||
919
+ k.nickname !== k.nickname.trim() || /[\u0000-\u001f\u007f]/.test(k.nickname)
920
+ ) return null
921
+ if (!positiveSafeInteger(k.enrolledAt)) return null
922
+ try {
923
+ if (compressPubkey(k.pubkey) !== k.pubkey) return null
924
+ } catch {
925
+ return null
926
+ }
927
+ keys.push({
928
+ serial: k.serial,
929
+ slot: k.slot,
930
+ pubkey: k.pubkey,
931
+ nickname: k.nickname,
932
+ enrolledAt: k.enrolledAt
933
+ })
934
+ }
935
+ if (new Set(keys.map(k => k.serial)).size !== keys.length) return null
936
+ if (new Set(keys.map(k => k.pubkey)).size !== keys.length) return null
937
+ try {
938
+ vaultSaltHmacData(keys.map(k => k.serial))
939
+ } catch {
940
+ return null
941
+ }
942
+ return {
943
+ v: 6,
944
+ type: 'R1C',
945
+ salt: p.salt,
946
+ saltKeyId: p.saltKeyId,
947
+ chain: p.chain,
948
+ vaultId: p.vaultId,
949
+ revision: p.revision,
950
+ createdAt: p.createdAt,
951
+ keys
952
+ }
953
+ }
954
+
955
+ /** Serialise only the canonical v6 fields, after applying the decoder's validation. */
956
+ export function encodeVaultInstructions(i: VaultInstructionsV6): string {
957
+ const s = JSON.stringify({
958
+ v: 6,
959
+ type: 'R1C',
960
+ salt: i.salt,
961
+ saltKeyId: i.saltKeyId,
962
+ chain: i.chain,
963
+ vaultId: i.vaultId,
964
+ revision: i.revision,
965
+ createdAt: i.createdAt,
966
+ keys: i.keys.map(k => ({
967
+ serial: k.serial,
968
+ slot: k.slot,
969
+ pubkey: k.pubkey,
970
+ nickname: k.nickname,
971
+ enrolledAt: k.enrolledAt
972
+ }))
973
+ })
974
+ if (decodeVaultInstructions(s) === null) throw invalid('encodeVaultInstructions: record would not decode as canonical v6 vault metadata')
975
+ return s
976
+ }