@ocap/mpc-hsm 0.0.0-stage → 1.33.7

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 (74) hide show
  1. package/esm/bip39-english-wordlist.d.mts +11 -0
  2. package/esm/bip39-english-wordlist.mjs +31 -0
  3. package/esm/constants.d.mts +140 -0
  4. package/esm/constants.mjs +142 -0
  5. package/esm/dkg.d.mts +279 -0
  6. package/esm/dkg.mjs +903 -0
  7. package/esm/index.d.mts +17 -0
  8. package/esm/index.mjs +18 -0
  9. package/esm/mta.d.mts +63 -0
  10. package/esm/mta.mjs +275 -0
  11. package/esm/ocap-clear-signing.d.mts +125 -0
  12. package/esm/ocap-clear-signing.mjs +1170 -0
  13. package/esm/offline-ceremony.d.mts +127 -0
  14. package/esm/offline-ceremony.mjs +481 -0
  15. package/esm/ot.d.mts +193 -0
  16. package/esm/ot.mjs +726 -0
  17. package/esm/personal-vault.d.mts +1292 -0
  18. package/esm/personal-vault.mjs +3615 -0
  19. package/esm/personal.d.mts +10 -0
  20. package/esm/personal.mjs +11 -0
  21. package/esm/presign.d.mts +242 -0
  22. package/esm/presign.mjs +951 -0
  23. package/esm/rlp-eip1559.d.mts +75 -0
  24. package/esm/rlp-eip1559.mjs +293 -0
  25. package/esm/secp256k1-scalar.d.mts +141 -0
  26. package/esm/secp256k1-scalar.mjs +474 -0
  27. package/esm/sign.d.mts +113 -0
  28. package/esm/sign.mjs +225 -0
  29. package/esm/steel-mnemonic.d.mts +55 -0
  30. package/esm/steel-mnemonic.mjs +247 -0
  31. package/esm/tweak.d.mts +100 -0
  32. package/esm/tweak.mjs +168 -0
  33. package/esm/ves-backup.d.mts +296 -0
  34. package/esm/ves-backup.mjs +1025 -0
  35. package/esm/x402-agent-guard.d.mts +111 -0
  36. package/esm/x402-agent-guard.mjs +780 -0
  37. package/lib/bip39-english-wordlist.cjs +33 -0
  38. package/lib/bip39-english-wordlist.d.cts +11 -0
  39. package/lib/constants.cjs +264 -0
  40. package/lib/constants.d.cts +140 -0
  41. package/lib/dkg.cjs +910 -0
  42. package/lib/dkg.d.cts +279 -0
  43. package/lib/index.cjs +420 -0
  44. package/lib/index.d.cts +17 -0
  45. package/lib/mta.cjs +280 -0
  46. package/lib/mta.d.cts +63 -0
  47. package/lib/ocap-clear-signing.cjs +1176 -0
  48. package/lib/ocap-clear-signing.d.cts +125 -0
  49. package/lib/offline-ceremony.cjs +487 -0
  50. package/lib/offline-ceremony.d.cts +127 -0
  51. package/lib/ot.cjs +744 -0
  52. package/lib/ot.d.cts +193 -0
  53. package/lib/personal-vault.cjs +3725 -0
  54. package/lib/personal-vault.d.cts +1292 -0
  55. package/lib/personal.cjs +338 -0
  56. package/lib/personal.d.cts +10 -0
  57. package/lib/presign.cjs +954 -0
  58. package/lib/presign.d.cts +242 -0
  59. package/lib/rlp-eip1559.cjs +303 -0
  60. package/lib/rlp-eip1559.d.cts +75 -0
  61. package/lib/secp256k1-scalar.cjs +527 -0
  62. package/lib/secp256k1-scalar.d.cts +141 -0
  63. package/lib/sign.cjs +233 -0
  64. package/lib/sign.d.cts +113 -0
  65. package/lib/steel-mnemonic.cjs +253 -0
  66. package/lib/steel-mnemonic.d.cts +55 -0
  67. package/lib/tweak.cjs +178 -0
  68. package/lib/tweak.d.cts +100 -0
  69. package/lib/ves-backup.cjs +1053 -0
  70. package/lib/ves-backup.d.cts +296 -0
  71. package/lib/x402-agent-guard.cjs +788 -0
  72. package/lib/x402-agent-guard.d.cts +111 -0
  73. package/package.json +80 -4
  74. package/README.md +0 -3
@@ -0,0 +1,474 @@
1
+ import { MpcProtocolError, PEDERSEN_H_COMPRESSED_HEX, PEDERSEN_H_DST, PEDERSEN_H_MESSAGE, SECP256K1_N } from "./constants.mjs";
2
+ import { sha256 } from "@noble/hashes/sha2.js";
3
+ import { bytesToHex, hexToBytes } from "@noble/hashes/utils.js";
4
+ import { x25519 } from "@noble/curves/ed25519.js";
5
+ import { secp256k1, secp256k1_hasher } from "@noble/curves/secp256k1.js";
6
+ import { shake256 } from "@noble/hashes/sha3.js";
7
+
8
+ //#region src/secp256k1-scalar.ts
9
+ const Fn = secp256k1.Point.Fn;
10
+ const SECP256K1_G = secp256k1.Point.BASE;
11
+ const SECP256K1_ZERO = secp256k1.Point.ZERO;
12
+ SECP256K1_G.precompute(8);
13
+ const textEncoder = new TextEncoder();
14
+ function utf8Bytes(text) {
15
+ return textEncoder.encode(text);
16
+ }
17
+ function zeroizeBytes(...buffers) {
18
+ for (const buf of buffers) if (buf) buf.fill(0);
19
+ }
20
+ const MAX_GET_RANDOM_VALUES_CHUNK = 65536;
21
+ function constantTimeEqual(a, b) {
22
+ if (a.length !== b.length) return false;
23
+ let diff = 0;
24
+ for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
25
+ return diff === 0;
26
+ }
27
+ function defaultRandomBytes(length) {
28
+ if (!Number.isInteger(length) || length < 0) throw new MpcProtocolError("INVALID_PARAMETER", `Invalid random byte length: ${length}`);
29
+ const cryptoObj = globalThis.crypto;
30
+ if (!cryptoObj || typeof cryptoObj.getRandomValues !== "function") throw new MpcProtocolError("INVALID_PARAMETER", "WebCrypto getRandomValues is unavailable");
31
+ const out = new Uint8Array(length);
32
+ for (let offset = 0; offset < length; offset += MAX_GET_RANDOM_VALUES_CHUNK) {
33
+ const end = Math.min(offset + MAX_GET_RANDOM_VALUES_CHUNK, length);
34
+ cryptoObj.getRandomValues(out.subarray(offset, end));
35
+ }
36
+ return out;
37
+ }
38
+ /**
39
+ * RFC 9380 `secp256k1_XMD:SHA-256_SSWU_RO_` NUMS generator `H` for Pedersen commitments.
40
+ * Verified at initialization against the pinned 33-byte compressed constant (`H != O && H != G`).
41
+ */
42
+ function initPedersenGeneratorH() {
43
+ const derived = secp256k1_hasher.hashToCurve(utf8Bytes(PEDERSEN_H_MESSAGE), { DST: PEDERSEN_H_DST });
44
+ derived.assertValidity();
45
+ if (derived.is0() || derived.equals(SECP256K1_G)) throw new MpcProtocolError("INVALID_POINT", "Degenerate Pedersen generator H");
46
+ const derivedHex = bytesToHex(derived.toBytes(true));
47
+ if (derivedHex !== PEDERSEN_H_COMPRESSED_HEX) throw new MpcProtocolError("INVALID_POINT", `Pedersen generator H mismatch: expected ${PEDERSEN_H_COMPRESSED_HEX}, got ${derivedHex}`);
48
+ return derived;
49
+ }
50
+ const PEDERSEN_H = initPedersenGeneratorH();
51
+ PEDERSEN_H.precompute(8);
52
+ const PEDERSEN_H_COMP33 = PEDERSEN_H.toBytes(true);
53
+ const X25519_PROBE_SCALAR_32 = (() => {
54
+ const b = new Uint8Array(32);
55
+ b[0] = 9;
56
+ return b;
57
+ })();
58
+ const CURVE25519_P = (1n << 255n) - 19n;
59
+ /**
60
+ * Validates a 32-byte X25519 public key upfront, rejecting non-canonical encodings (`>= 2^255 - 19`)
61
+ * and all Curve25519 low-order torsion points, attributing `culpritSlot` on failure.
62
+ */
63
+ function assertValidX25519PublicKey(pubKey32, errorCode, culpritSlot) {
64
+ if (!(pubKey32 instanceof Uint8Array) || pubKey32.length !== 32) throw new MpcProtocolError(errorCode, "X25519 public key must be 32 bytes", culpritSlot);
65
+ let uLE = 0n;
66
+ for (let i = 31; i >= 0; i--) uLE = uLE << 8n | BigInt(pubKey32[i]);
67
+ if (uLE === 0n || uLE >= CURVE25519_P) throw new MpcProtocolError(errorCode, "Non-canonical or zero X25519 public key rejected", culpritSlot);
68
+ try {
69
+ const probe = x25519.getSharedSecret(X25519_PROBE_SCALAR_32, pubKey32);
70
+ let nonZero = 0;
71
+ for (let i = 0; i < 32; i++) nonZero |= probe[i];
72
+ zeroizeBytes(probe);
73
+ if (nonZero === 0) throw new Error("zero shared secret");
74
+ } catch {
75
+ throw new MpcProtocolError(errorCode, `Low-order or invalid X25519 public key${culpritSlot !== void 0 ? ` from slot ${culpritSlot}` : ""}`, culpritSlot);
76
+ }
77
+ }
78
+ function computeX25519SharedSecret(secretKey32, peerPublicKey32, errorCode, culpritSlot) {
79
+ assertValidX25519PublicKey(peerPublicKey32, errorCode, culpritSlot);
80
+ try {
81
+ const shared = x25519.getSharedSecret(secretKey32, peerPublicKey32);
82
+ let nonZero = 0;
83
+ for (let i = 0; i < 32; i++) nonZero |= shared[i];
84
+ if (nonZero === 0) {
85
+ zeroizeBytes(shared);
86
+ throw new Error("zero shared secret");
87
+ }
88
+ return shared;
89
+ } catch {
90
+ throw new MpcProtocolError(errorCode, `X25519 ECDH failed against peer${culpritSlot !== void 0 ? ` slot ${culpritSlot}` : ""}`, culpritSlot);
91
+ }
92
+ }
93
+ function u8(value) {
94
+ if (!Number.isInteger(value) || value < 0 || value > 255) throw new MpcProtocolError("INVALID_PARAMETER", `u8 out of range: ${value}`);
95
+ return Uint8Array.of(value);
96
+ }
97
+ function u16be(value) {
98
+ if (!Number.isInteger(value) || value < 0 || value > 65535) throw new MpcProtocolError("INVALID_PARAMETER", `u16be out of range: ${value}`);
99
+ const out = new Uint8Array(2);
100
+ out[0] = value >>> 8 & 255;
101
+ out[1] = value & 255;
102
+ return out;
103
+ }
104
+ function u32be(value) {
105
+ if (!Number.isInteger(value) || value < 0 || value > 4294967295) throw new MpcProtocolError("INVALID_PARAMETER", `u32be out of range: ${value}`);
106
+ const out = new Uint8Array(4);
107
+ out[0] = value >>> 24 & 255;
108
+ out[1] = value >>> 16 & 255;
109
+ out[2] = value >>> 8 & 255;
110
+ out[3] = value & 255;
111
+ return out;
112
+ }
113
+ function u64be(value) {
114
+ if (typeof value !== "bigint" || value < 0n || value > 18446744073709551615n) throw new MpcProtocolError("INVALID_PARAMETER", `u64be out of range: ${String(value)}`);
115
+ const out = new Uint8Array(8);
116
+ let rem = value;
117
+ for (let i = 7; i >= 0; i--) {
118
+ out[i] = Number(rem & 255n);
119
+ rem >>= 8n;
120
+ }
121
+ return out;
122
+ }
123
+ function concatBytes(...arrays) {
124
+ let total = 0;
125
+ for (const arr of arrays) total += arr.length;
126
+ const out = new Uint8Array(total);
127
+ let offset = 0;
128
+ for (const arr of arrays) {
129
+ out.set(arr, offset);
130
+ offset += arr.length;
131
+ }
132
+ return out;
133
+ }
134
+ function lengthPrefixedEncode(tag, parts) {
135
+ const tagBytes = utf8Bytes(tag);
136
+ let total = 4 + tagBytes.length + 4;
137
+ for (const part of parts) total += 4 + part.length;
138
+ const out = new Uint8Array(total);
139
+ const view = new DataView(out.buffer);
140
+ let offset = 0;
141
+ view.setUint32(offset, tagBytes.length, false);
142
+ offset += 4;
143
+ out.set(tagBytes, offset);
144
+ offset += tagBytes.length;
145
+ view.setUint32(offset, parts.length, false);
146
+ offset += 4;
147
+ for (const part of parts) {
148
+ view.setUint32(offset, part.length, false);
149
+ offset += 4;
150
+ out.set(part, offset);
151
+ offset += part.length;
152
+ }
153
+ return out;
154
+ }
155
+ function hashTranscriptSha256(tag, ...parts) {
156
+ return sha256(lengthPrefixedEncode(tag, parts));
157
+ }
158
+ function bytesToBigIntBE(bytes) {
159
+ let result = 0n;
160
+ for (let i = 0; i < bytes.length; i++) result = result << 8n | BigInt(bytes[i]);
161
+ return result;
162
+ }
163
+ function scalarToBytes32(scalar) {
164
+ if (typeof scalar !== "bigint" || scalar < 0n || scalar >= SECP256K1_N) throw new MpcProtocolError("INVALID_SCALAR", "Scalar out of [0, n - 1] range");
165
+ return Fn.toBytes(scalar);
166
+ }
167
+ function bytes32ToScalarStrict(bytes) {
168
+ if (!(bytes instanceof Uint8Array) || bytes.length !== 32) throw new MpcProtocolError("INVALID_SCALAR", `Expected 32-byte scalar, got ${bytes?.length}`);
169
+ const value = bytesToBigIntBE(bytes);
170
+ if (value >= SECP256K1_N) throw new MpcProtocolError("INVALID_SCALAR", "Scalar >= secp256k1 curve order n");
171
+ return value;
172
+ }
173
+ function bytes32ToScalarNonZero(bytes) {
174
+ const value = bytes32ToScalarStrict(bytes);
175
+ if (value === 0n) throw new MpcProtocolError("INVALID_SCALAR", "Scalar must be non-zero");
176
+ return value;
177
+ }
178
+ function assertScalarNonZero(scalar, label = "scalar") {
179
+ if (typeof scalar !== "bigint" || scalar <= 0n || scalar >= SECP256K1_N) throw new MpcProtocolError("INVALID_SCALAR", `${label} must satisfy 1 <= s < n`);
180
+ }
181
+ function assertScalarInField(scalar, label = "scalar") {
182
+ if (typeof scalar !== "bigint" || scalar < 0n || scalar >= SECP256K1_N) throw new MpcProtocolError("INVALID_SCALAR", `${label} must satisfy 0 <= s < n`);
183
+ }
184
+ function modN(a) {
185
+ return Fn.create(a);
186
+ }
187
+ function addModN(a, b) {
188
+ return Fn.add(Fn.create(a), Fn.create(b));
189
+ }
190
+ function subModN(a, b) {
191
+ return Fn.sub(Fn.create(a), Fn.create(b));
192
+ }
193
+ function mulModN(a, b) {
194
+ return Fn.mul(Fn.create(a), Fn.create(b));
195
+ }
196
+ function negModN(a) {
197
+ return Fn.neg(Fn.create(a));
198
+ }
199
+ function invModN(a) {
200
+ const reduced = Fn.create(a);
201
+ if (reduced === 0n) throw new MpcProtocolError("INVALID_SCALAR", "Cannot invert zero scalar modulo n");
202
+ return Fn.inv(reduced);
203
+ }
204
+ /**
205
+ * Unbiased rejection-sampled random scalar in `Z_n^* = [1, n - 1]`.
206
+ * Draws 32-byte blocks from CSPRNG and zeroizes each temporary buffer immediately.
207
+ */
208
+ function sampleScalarNonZero(rng = defaultRandomBytes) {
209
+ for (;;) {
210
+ const buf = rng(32);
211
+ if (buf.length !== 32) {
212
+ zeroizeBytes(buf);
213
+ throw new MpcProtocolError("INVALID_PARAMETER", "RNG must return exactly 32 bytes");
214
+ }
215
+ const candidate = bytesToBigIntBE(buf);
216
+ zeroizeBytes(buf);
217
+ if (candidate >= 1n && candidate < SECP256K1_N) return candidate;
218
+ }
219
+ }
220
+ /**
221
+ * Unbiased rejection-sampled hash-to-scalar `H_scalar(tag, ...parts) -> Z_n^*`.
222
+ * Streams 32-byte `SHAKE256` XOF blocks over injective length-prefixed framing until `1 <= u < n`.
223
+ */
224
+ function H_scalar(tag, ...parts) {
225
+ const xof = shake256.create({});
226
+ const framed = lengthPrefixedEncode(tag, parts);
227
+ xof.update(framed);
228
+ const block = new Uint8Array(32);
229
+ try {
230
+ for (;;) {
231
+ xof.xofInto(block);
232
+ const candidate = bytesToBigIntBE(block);
233
+ if (candidate >= 1n && candidate < SECP256K1_N) return candidate;
234
+ }
235
+ } finally {
236
+ zeroizeBytes(block);
237
+ xof.destroy();
238
+ }
239
+ }
240
+ function mulPoint(point, scalar) {
241
+ const s = Fn.create(scalar);
242
+ if (s === 0n || point.is0()) return SECP256K1_ZERO;
243
+ return point.multiply(s);
244
+ }
245
+ function mulBaseG(scalar) {
246
+ return mulPoint(SECP256K1_G, scalar);
247
+ }
248
+ function pedersenCommit(valueScalar, blindingScalar) {
249
+ return mulPoint(SECP256K1_G, valueScalar).add(mulPoint(PEDERSEN_H, blindingScalar));
250
+ }
251
+ function decodePointCompressed(bytes, allowIdentity = false) {
252
+ if (!(bytes instanceof Uint8Array)) throw new MpcProtocolError("INVALID_POINT", "Point bytes must be Uint8Array");
253
+ if (allowIdentity && bytes.length === 1 && bytes[0] === 0) return SECP256K1_ZERO;
254
+ if (bytes.length !== 33 || bytes[0] !== 2 && bytes[0] !== 3) throw new MpcProtocolError("INVALID_POINT", `Expected 33-byte compressed secp256k1 point, got ${bytes.length} bytes`);
255
+ let pt;
256
+ try {
257
+ pt = secp256k1.Point.fromBytes(bytes);
258
+ pt.assertValidity();
259
+ } catch (err) {
260
+ throw new MpcProtocolError("INVALID_POINT", `Invalid secp256k1 compressed point: ${err.message}`);
261
+ }
262
+ if (!allowIdentity && pt.is0()) throw new MpcProtocolError("INVALID_POINT", "Point at infinity is not allowed");
263
+ return pt;
264
+ }
265
+ function encodePointCompressed(point) {
266
+ if (point.is0()) throw new MpcProtocolError("INVALID_POINT", "Cannot compress point at infinity");
267
+ point.assertValidity();
268
+ return point.toBytes(true);
269
+ }
270
+ function normalizeHexBytes(value, expectedLength) {
271
+ let out;
272
+ if (value instanceof Uint8Array) out = new Uint8Array(value);
273
+ else if (typeof value === "string") {
274
+ const clean = value.startsWith("0x") || value.startsWith("0X") ? value.slice(2) : value;
275
+ if (clean.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(clean)) throw new MpcProtocolError("INVALID_PARAMETER", "Invalid hex string");
276
+ out = hexToBytes(clean);
277
+ } else throw new MpcProtocolError("INVALID_PARAMETER", "Expected Uint8Array or hex string");
278
+ if (expectedLength !== void 0 && out.length !== expectedLength) throw new MpcProtocolError("INVALID_PARAMETER", `Expected ${expectedLength} bytes, got ${out.length}`);
279
+ return out;
280
+ }
281
+ function normalizeSortedSubset(subset, t, nParties) {
282
+ if (!Array.isArray(subset) || subset.length === 0) throw new MpcProtocolError("PRESIG_INVALID_SUBSET", "Signing subset must be non-empty");
283
+ if (t !== void 0 && subset.length !== t) throw new MpcProtocolError("PRESIG_INVALID_SUBSET", `Signing subset must have size ${t}, got ${subset.length}`);
284
+ const sorted = [...subset].sort((a, b) => a - b);
285
+ for (let i = 0; i < sorted.length; i++) {
286
+ const slot = sorted[i];
287
+ if (!Number.isInteger(slot) || slot < 1 || nParties !== void 0 && slot > nParties) throw new MpcProtocolError("PRESIG_INVALID_SUBSET", `Invalid party slot ${slot} in subset`);
288
+ if (i > 0 && sorted[i - 1] === slot) throw new MpcProtocolError("PRESIG_INVALID_SUBSET", `Duplicate party slot ${slot} in subset`);
289
+ }
290
+ return sorted;
291
+ }
292
+ function sortedSubsetBytes(subset) {
293
+ const sorted = normalizeSortedSubset(subset);
294
+ const out = new Uint8Array(2 + sorted.length * 2);
295
+ out.set(u16be(sorted.length), 0);
296
+ for (let i = 0; i < sorted.length; i++) out.set(u16be(sorted[i]), 2 + i * 2);
297
+ return out;
298
+ }
299
+ function subsetsEqual(a, b) {
300
+ if (a.length !== b.length) return false;
301
+ const sa = [...a].sort((x, y) => x - y);
302
+ const sb = [...b].sort((x, y) => x - y);
303
+ for (let i = 0; i < sa.length; i++) if (sa[i] !== sb[i]) return false;
304
+ return true;
305
+ }
306
+ function enumerateCombinations(nParties, t) {
307
+ if (!Number.isInteger(nParties) || !Number.isInteger(t) || t < 1 || t > nParties) throw new MpcProtocolError("INVALID_PARAMETER", `Invalid combination (${nParties}, ${t})`);
308
+ const results = [];
309
+ const current = [];
310
+ const backtrack = (start) => {
311
+ if (current.length === t) {
312
+ results.push([...current]);
313
+ return;
314
+ }
315
+ const remainingNeeded = t - current.length;
316
+ for (let slot = start; slot <= nParties - remainingNeeded + 1; slot++) {
317
+ current.push(slot);
318
+ backtrack(slot + 1);
319
+ current.pop();
320
+ }
321
+ };
322
+ backtrack(1);
323
+ return results;
324
+ }
325
+ /**
326
+ * Computes Shamir Lagrange interpolation coefficient at 0 for `slot` within subset `subset`:
327
+ * `\lambda_{slot, S}(0) = \prod_{j \in S \setminus \{slot\}} (-j) * (slot - j)^{-1} mod n`.
328
+ */
329
+ function lagrangeCoefficientAtZero(slot, subset) {
330
+ const sorted = normalizeSortedSubset(subset);
331
+ if (!sorted.includes(slot)) throw new MpcProtocolError("PRESIG_INVALID_SUBSET", `Slot ${slot} is not in subset`);
332
+ let num = 1n;
333
+ let den = 1n;
334
+ const xI = BigInt(slot);
335
+ for (const other of sorted) {
336
+ if (other === slot) continue;
337
+ const xJ = BigInt(other);
338
+ num = mulModN(num, negModN(xJ));
339
+ den = mulModN(den, subModN(xI, xJ));
340
+ }
341
+ return mulModN(num, invModN(den));
342
+ }
343
+ function evaluatePolynomialModN(coeffs, x) {
344
+ let acc = 0n;
345
+ for (let i = coeffs.length - 1; i >= 0; i--) acc = addModN(mulModN(acc, x), coeffs[i]);
346
+ return acc;
347
+ }
348
+ function evaluateFeldmanCommitments(commitments, slotIndex) {
349
+ if (commitments.length === 0) throw new MpcProtocolError("INVALID_PARAMETER", "Empty Feldman commitment vector");
350
+ const x = BigInt(slotIndex);
351
+ let xPow = 1n;
352
+ let acc = SECP256K1_ZERO;
353
+ for (let l = 0; l < commitments.length; l++) {
354
+ acc = acc.add(mulPoint(commitments[l], xPow));
355
+ xPow = mulModN(xPow, x);
356
+ }
357
+ return acc;
358
+ }
359
+ /**
360
+ * Schnorr Proof of Knowledge of discrete logarithm `secret` in arbitrary prime-order base `basePoint`
361
+ * (`statementPoint = secret * basePoint`), Fiat-Shamir bound to `(dst, contextParts, basePoint, statementPoint, R)`.
362
+ */
363
+ function createSchnorrPokInBase(params) {
364
+ const { dst, basePoint, statementPoint, secretScalar, contextParts, rng } = params;
365
+ assertScalarNonZero(secretScalar, "Schnorr secretScalar");
366
+ if (basePoint.is0() || statementPoint.is0()) throw new MpcProtocolError("INVALID_POINT", "Schnorr PoK base/statement cannot be O");
367
+ const kNonce = sampleScalarNonZero(rng);
368
+ const noncePointComp33 = encodePointCompressed(mulPoint(basePoint, kNonce));
369
+ const baseComp33 = encodePointCompressed(basePoint);
370
+ const stmtComp33 = encodePointCompressed(statementPoint);
371
+ return {
372
+ noncePointComp33,
373
+ responseBytes32: scalarToBytes32(addModN(kNonce, mulModN(H_scalar(dst, ...contextParts, baseComp33, stmtComp33, noncePointComp33), secretScalar)))
374
+ };
375
+ }
376
+ function verifySchnorrPokInBase(params) {
377
+ try {
378
+ const { dst, basePoint, statementPoint, proof, contextParts } = params;
379
+ if (basePoint.is0() || statementPoint.is0()) return false;
380
+ const noncePoint = decodePointCompressed(proof.noncePointComp33, false);
381
+ const response = bytes32ToScalarStrict(proof.responseBytes32);
382
+ const baseComp33 = encodePointCompressed(basePoint);
383
+ const stmtComp33 = encodePointCompressed(statementPoint);
384
+ const challenge = H_scalar(dst, ...contextParts, baseComp33, stmtComp33, proof.noncePointComp33);
385
+ const lhs = mulPoint(basePoint, response);
386
+ const rhs = noncePoint.add(mulPoint(statementPoint, challenge));
387
+ return lhs.equals(rhs);
388
+ } catch {
389
+ return false;
390
+ }
391
+ }
392
+ function createPedersenPok(params) {
393
+ const { dst, commitmentPoint, valueScalar, blindingScalar, contextParts, rng } = params;
394
+ assertScalarNonZero(valueScalar, "Pedersen valueScalar");
395
+ assertScalarNonZero(blindingScalar, "Pedersen blindingScalar");
396
+ if (commitmentPoint.is0()) throw new MpcProtocolError("INVALID_POINT", "Pedersen commitment cannot be O");
397
+ const uVal = sampleScalarNonZero(rng);
398
+ const uBlind = sampleScalarNonZero(rng);
399
+ const noncePointComp33 = encodePointCompressed(pedersenCommit(uVal, uBlind));
400
+ const commComp33 = encodePointCompressed(commitmentPoint);
401
+ const challenge = H_scalar(dst, ...contextParts, commComp33, noncePointComp33);
402
+ const zVal = addModN(uVal, mulModN(challenge, valueScalar));
403
+ const zBlind = addModN(uBlind, mulModN(challenge, blindingScalar));
404
+ return {
405
+ noncePointComp33,
406
+ responseValueBytes32: scalarToBytes32(zVal),
407
+ responseBlindBytes32: scalarToBytes32(zBlind)
408
+ };
409
+ }
410
+ function verifyPedersenPok(params) {
411
+ try {
412
+ const { dst, commitmentPoint, proof, contextParts } = params;
413
+ if (commitmentPoint.is0()) return false;
414
+ const noncePoint = decodePointCompressed(proof.noncePointComp33, false);
415
+ const zVal = bytes32ToScalarStrict(proof.responseValueBytes32);
416
+ const zBlind = bytes32ToScalarStrict(proof.responseBlindBytes32);
417
+ const commComp33 = encodePointCompressed(commitmentPoint);
418
+ const challenge = H_scalar(dst, ...contextParts, commComp33, proof.noncePointComp33);
419
+ const lhs = pedersenCommit(zVal, zBlind);
420
+ const rhs = noncePoint.add(mulPoint(commitmentPoint, challenge));
421
+ return lhs.equals(rhs);
422
+ } catch {
423
+ return false;
424
+ }
425
+ }
426
+ function createLinearPedersenDleqProof(params) {
427
+ const { dst, baseR, pointK, commitmentCk, kScalar, rhoScalar, contextParts, rng } = params;
428
+ assertScalarNonZero(kScalar, "kScalar");
429
+ assertScalarNonZero(rhoScalar, "rhoScalar");
430
+ if (baseR.is0() || pointK.is0() || commitmentCk.is0()) throw new MpcProtocolError("INVALID_POINT", "Linear Pedersen DLEQ points cannot be O");
431
+ const uK = sampleScalarNonZero(rng);
432
+ const uRho = sampleScalarNonZero(rng);
433
+ const a1 = mulPoint(baseR, uK);
434
+ const a2 = pedersenCommit(uK, uRho);
435
+ const a1Comp33 = encodePointCompressed(a1);
436
+ const a2Comp33 = encodePointCompressed(a2);
437
+ const rComp33 = encodePointCompressed(baseR);
438
+ const ckComp33 = encodePointCompressed(commitmentCk);
439
+ const kComp33 = encodePointCompressed(pointK);
440
+ const challenge = H_scalar(dst, ...contextParts, rComp33, ckComp33, kComp33, a1Comp33, a2Comp33);
441
+ const zK = addModN(uK, mulModN(challenge, kScalar));
442
+ const zRho = addModN(uRho, mulModN(challenge, rhoScalar));
443
+ return {
444
+ a1Comp33,
445
+ a2Comp33,
446
+ zKBytes32: scalarToBytes32(zK),
447
+ zRhoBytes32: scalarToBytes32(zRho)
448
+ };
449
+ }
450
+ function verifyLinearPedersenDleqProof(params) {
451
+ try {
452
+ const { dst, baseR, pointK, commitmentCk, proof, contextParts } = params;
453
+ if (baseR.is0() || pointK.is0() || commitmentCk.is0()) return false;
454
+ const a1 = decodePointCompressed(proof.a1Comp33, false);
455
+ const a2 = decodePointCompressed(proof.a2Comp33, false);
456
+ const zK = bytes32ToScalarStrict(proof.zKBytes32);
457
+ const zRho = bytes32ToScalarStrict(proof.zRhoBytes32);
458
+ const rComp33 = encodePointCompressed(baseR);
459
+ const ckComp33 = encodePointCompressed(commitmentCk);
460
+ const kComp33 = encodePointCompressed(pointK);
461
+ const challenge = H_scalar(dst, ...contextParts, rComp33, ckComp33, kComp33, proof.a1Comp33, proof.a2Comp33);
462
+ const lhs1 = mulPoint(baseR, zK);
463
+ const rhs1 = a1.add(mulPoint(pointK, challenge));
464
+ if (!lhs1.equals(rhs1)) return false;
465
+ const lhs2 = pedersenCommit(zK, zRho);
466
+ const rhs2 = a2.add(mulPoint(commitmentCk, challenge));
467
+ return lhs2.equals(rhs2);
468
+ } catch {
469
+ return false;
470
+ }
471
+ }
472
+
473
+ //#endregion
474
+ export { Fn, H_scalar, PEDERSEN_H, PEDERSEN_H_COMP33, SECP256K1_G, SECP256K1_ZERO, addModN, assertScalarInField, assertScalarNonZero, assertValidX25519PublicKey, bytes32ToScalarNonZero, bytes32ToScalarStrict, bytesToBigIntBE, bytesToHex, computeX25519SharedSecret, concatBytes, constantTimeEqual, createLinearPedersenDleqProof, createPedersenPok, createSchnorrPokInBase, decodePointCompressed, defaultRandomBytes, encodePointCompressed, enumerateCombinations, evaluateFeldmanCommitments, evaluatePolynomialModN, hashTranscriptSha256, hexToBytes, invModN, lagrangeCoefficientAtZero, lengthPrefixedEncode, modN, mulBaseG, mulModN, mulPoint, negModN, normalizeHexBytes, normalizeSortedSubset, pedersenCommit, sampleScalarNonZero, scalarToBytes32, secp256k1, sortedSubsetBytes, subModN, subsetsEqual, u16be, u32be, u64be, u8, utf8Bytes, verifyLinearPedersenDleqProof, verifyPedersenPok, verifySchnorrPokInBase, zeroizeBytes };
package/esm/sign.d.mts ADDED
@@ -0,0 +1,113 @@
1
+ import { Secp256k1Point } from "./secp256k1-scalar.mjs";
2
+ import { DerivedChildKey, MpcChildDerivationSpec } from "./tweak.mjs";
3
+ import { PresignaturePublicVerification, PresignatureShareRecord, VolatilePresignaturePool } from "./presign.mjs";
4
+
5
+ //#region src/sign.d.ts
6
+
7
+ /**
8
+ * Internal-only symbol for deterministic unit-vector tests (e.g. `delta_rerand = 1n`).
9
+ * NOT exported from the `@ocap/mpc-hsm` package barrel (`src/index.ts`) and non-serializable over JSON/IPC.
10
+ */
11
+ declare const VECTOR_TEST_DELTA_RERAND_SYMBOL: unique symbol;
12
+ interface VectorTestRerandBag {
13
+ readonly [VECTOR_TEST_DELTA_RERAND_SYMBOL]?: bigint;
14
+ }
15
+ interface MpcOnlineSignRequest {
16
+ readonly rootId: string;
17
+ readonly presigId: Uint8Array | string;
18
+ readonly subset: ReadonlyArray<number>;
19
+ readonly msgDigest32: Uint8Array | string;
20
+ /**
21
+ * Authenticated derivation preimage (`untweaked | role-bound | rule-bound`).
22
+ * Online signing re-derives `(t_tweak, P_child)` from `(P_root, rootId, childDerivation)`,
23
+ * eliminating raw unauthenticated `tweakScalar` oracles and strictly enforcing the
24
+ * `"escape-canary"` hard-ban across all modes.
25
+ */
26
+ readonly childDerivation: MpcChildDerivationSpec;
27
+ }
28
+ interface MpcOnlineSignShare {
29
+ readonly slot: number;
30
+ readonly presigId32: Uint8Array;
31
+ readonly sShareBytes32: Uint8Array;
32
+ }
33
+ interface RerandomizedNonceResult {
34
+ readonly deltaRerand: bigint;
35
+ readonly rPrimePoint: Secp256k1Point;
36
+ readonly rPrimePointComp33: Uint8Array;
37
+ readonly rPrime: bigint;
38
+ readonly yPrimeParity: 0 | 1;
39
+ }
40
+ interface MpcAggregatedSignature {
41
+ readonly r: bigint;
42
+ readonly s: bigint;
43
+ readonly rBytes32: Uint8Array;
44
+ readonly sBytes32: Uint8Array;
45
+ readonly rHex: string;
46
+ readonly sHex: string;
47
+ readonly yParity: 0 | 1;
48
+ readonly v: 27 | 28;
49
+ readonly signature65Bytes: Uint8Array;
50
+ readonly signature65Hex: string;
51
+ readonly deltaRerand: bigint;
52
+ readonly rPrimePointComp33: Uint8Array;
53
+ readonly signerAddress: string;
54
+ }
55
+ declare function deriveGrothShoupRerandScalar(params: {
56
+ presigId32: Uint8Array;
57
+ subset: ReadonlyArray<number>;
58
+ rPointComp33: Uint8Array;
59
+ childPublicKeyComp33: Uint8Array;
60
+ msgDigest32: Uint8Array;
61
+ tweakScalar: bigint;
62
+ }): bigint;
63
+ declare function computeRerandomizedNoncePoint(rPointOrComp33: Secp256k1Point | Uint8Array, deltaRerand: bigint): RerandomizedNonceResult;
64
+ declare function verifyAndDeriveRequestChildKey(params: {
65
+ rootPublicKeyComp33: Uint8Array;
66
+ rootId: string;
67
+ childDerivation: MpcChildDerivationSpec;
68
+ }): DerivedChildKey;
69
+ /**
70
+ * Evaluates a Groth-Shoup partial signature share on an already-consumed `PresignatureShareRecord`
71
+ * and unconditionally zeroizes `(kShareBytes32, chiShareBytes32)` in `finally`.
72
+ */
73
+ declare function evaluateConsumedPresigShareWithRerand(params: {
74
+ consumedRecord: PresignatureShareRecord;
75
+ request: MpcOnlineSignRequest;
76
+ } & VectorTestRerandBag): {
77
+ share: MpcOnlineSignShare;
78
+ rerand: RerandomizedNonceResult;
79
+ };
80
+ /**
81
+ * Synchronously validates the request preimage (blocking `"escape-canary"` before pool touch),
82
+ * consumes `presigId` from `pool`, validates `request.subset === presig.subset`, computes `s_i`,
83
+ * and wipes `k_i` & `\chi_i` from RAM.
84
+ */
85
+ declare function createOnlineSignShare(params: {
86
+ pool: VolatilePresignaturePool;
87
+ request: MpcOnlineSignRequest;
88
+ }): {
89
+ share: MpcOnlineSignShare;
90
+ rerand: RerandomizedNonceResult;
91
+ };
92
+ /**
93
+ * Verifies a single party's partial signature share `s_i` (`design.md` §4.5(2)):
94
+ * `\delta_{rerand} * s_i * R == (m + r' * t_tweak) * K_i + r' * Z_i`.
95
+ * Attributes exact `culpritSlot = share.slot` on mismatch!
96
+ */
97
+ declare function verifyOnlineSignShare(params: {
98
+ share: MpcOnlineSignShare;
99
+ publicVerification: PresignaturePublicVerification;
100
+ request: MpcOnlineSignRequest;
101
+ } & VectorTestRerandBag): RerandomizedNonceResult;
102
+ /**
103
+ * Verifies all `t` partial signature shares, aggregates `s_raw = \sum_{i \in S} s_i mod n`,
104
+ * enforces EIP-2 low-S (`s_sig <= n / 2`, toggling `yParity ^= 1` when negated), and self-verifies
105
+ * `ecrecover(z, r', s_sig, yParity) === P_child`.
106
+ */
107
+ declare function aggregateOnlineSignature(params: {
108
+ shares: ReadonlyArray<MpcOnlineSignShare>;
109
+ publicVerification: PresignaturePublicVerification;
110
+ request: MpcOnlineSignRequest;
111
+ } & VectorTestRerandBag): MpcAggregatedSignature;
112
+ //#endregion
113
+ export { MpcAggregatedSignature, MpcOnlineSignRequest, MpcOnlineSignShare, RerandomizedNonceResult, VECTOR_TEST_DELTA_RERAND_SYMBOL, VectorTestRerandBag, aggregateOnlineSignature, computeRerandomizedNoncePoint, createOnlineSignShare, deriveGrothShoupRerandScalar, evaluateConsumedPresigShareWithRerand, verifyAndDeriveRequestChildKey, verifyOnlineSignShare };