@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
package/esm/sign.mjs ADDED
@@ -0,0 +1,225 @@
1
+ import { DST_PRESIG_RERAND_V1, MpcProtocolError, SECP256K1_HALF_N, SECP256K1_N } from "./constants.mjs";
2
+ import { H_scalar, addModN, assertScalarNonZero, bytes32ToScalarNonZero, bytes32ToScalarStrict, bytesToBigIntBE, bytesToHex, concatBytes, constantTimeEqual, decodePointCompressed, encodePointCompressed, invModN, modN, mulModN, mulPoint, normalizeHexBytes, normalizeSortedSubset, scalarToBytes32, sortedSubsetBytes, subModN, subsetsEqual, zeroizeBytes } from "./secp256k1-scalar.mjs";
3
+ import { deriveRoleBoundChild, deriveRuleBoundChild, deriveUntweakedChild, ecrecoverEthAddress, pointToEthAddress } from "./tweak.mjs";
4
+
5
+ //#region src/sign.ts
6
+ /**
7
+ * Internal-only symbol for deterministic unit-vector tests (e.g. `delta_rerand = 1n`).
8
+ * NOT exported from the `@ocap/mpc-hsm` package barrel (`src/index.ts`) and non-serializable over JSON/IPC.
9
+ */
10
+ const VECTOR_TEST_DELTA_RERAND_SYMBOL = Symbol("ocap.mpc-hsm.vector-test-delta-rerand");
11
+ function deriveGrothShoupRerandScalar(params) {
12
+ const { presigId32, subset, rPointComp33, childPublicKeyComp33, msgDigest32, tweakScalar } = params;
13
+ if (presigId32.length !== 32 || msgDigest32.length !== 32) throw new MpcProtocolError("INVALID_PARAMETER", "presigId32 and msgDigest32 must be 32 bytes");
14
+ if (tweakScalar < 0n || tweakScalar >= SECP256K1_N) throw new MpcProtocolError("INVALID_SCALAR", "tweakScalar out of field range");
15
+ return H_scalar(DST_PRESIG_RERAND_V1, presigId32, sortedSubsetBytes(subset), rPointComp33, childPublicKeyComp33, msgDigest32, scalarToBytes32(tweakScalar));
16
+ }
17
+ function computeRerandomizedNoncePoint(rPointOrComp33, deltaRerand) {
18
+ assertScalarNonZero(deltaRerand, "deltaRerand");
19
+ const rPoint = rPointOrComp33 instanceof Uint8Array ? decodePointCompressed(rPointOrComp33, false) : rPointOrComp33;
20
+ if (rPoint.is0()) throw new MpcProtocolError("INVALID_POINT", "Presignature R cannot be infinity");
21
+ const rPrimePoint = mulPoint(rPoint, deltaRerand);
22
+ if (rPrimePoint.is0()) throw new MpcProtocolError("PRESIG_RERAND_BURN_RETRY", "Re-randomized R_prime hit infinity; burn presigId and retry with a fresh presignature");
23
+ const { x, y } = rPrimePoint.toAffine();
24
+ if (x >= SECP256K1_N || x % SECP256K1_N === 0n) throw new MpcProtocolError("PRESIG_RERAND_BURN_RETRY", "Re-randomized R_prime_x >= n or == 0; burn presigId and retry with a fresh presignature");
25
+ return {
26
+ deltaRerand,
27
+ rPrimePoint,
28
+ rPrimePointComp33: encodePointCompressed(rPrimePoint),
29
+ rPrime: x,
30
+ yPrimeParity: Number(y & 1n)
31
+ };
32
+ }
33
+ function verifyAndDeriveRequestChildKey(params) {
34
+ const { rootPublicKeyComp33, rootId, childDerivation } = params;
35
+ if (!childDerivation || typeof childDerivation !== "object") throw new MpcProtocolError("INVALID_PARAMETER", "Missing childDerivation in sign request");
36
+ let derived;
37
+ if (childDerivation.tweakMode === "untweaked") derived = deriveUntweakedChild(rootPublicKeyComp33);
38
+ else if (childDerivation.tweakMode === "role-bound") derived = deriveRoleBoundChild({
39
+ rootPublicKey: rootPublicKeyComp33,
40
+ rootId,
41
+ role: childDerivation.role,
42
+ ethChainId: childDerivation.ethChainId,
43
+ tweakLabel: childDerivation.tweakLabel
44
+ });
45
+ else if (childDerivation.tweakMode === "rule-bound") derived = deriveRuleBoundChild({
46
+ rootPublicKey: rootPublicKeyComp33,
47
+ rootId,
48
+ controllerDid: childDerivation.controllerDid,
49
+ ethChainId: childDerivation.ethChainId,
50
+ ruleHash: childDerivation.ruleHash
51
+ });
52
+ else throw new MpcProtocolError("INVALID_PARAMETER", "Unsupported childDerivation tweakMode");
53
+ if (!(childDerivation.childPublicKeyComp33 instanceof Uint8Array) || !constantTimeEqual(derived.childPublicKeyComp33, childDerivation.childPublicKeyComp33)) throw new MpcProtocolError("DEGENERATE_TWEAK", "childDerivation.childPublicKeyComp33 does not match canonically derived P_child");
54
+ return derived;
55
+ }
56
+ function validateRequestAgainstPublicPresig(request, pub) {
57
+ if (request.rootId !== pub.rootId) throw new MpcProtocolError("PRESIG_SUBSET_MISMATCH", `Sign request rootId ${request.rootId} != presig rootId ${pub.rootId}`);
58
+ if (!subsetsEqual(request.subset, pub.subset)) throw new MpcProtocolError("PRESIG_SUBSET_MISMATCH", `Sign request subset [${request.subset.join(",")}] != presig subset [${pub.subset.join(",")}]`);
59
+ if (!constantTimeEqual(normalizeHexBytes(request.presigId, 32), pub.presigId32)) throw new MpcProtocolError("PRESIG_SUBSET_MISMATCH", "presigId mismatch");
60
+ const msgDigest32 = normalizeHexBytes(request.msgDigest32, 32);
61
+ const derivedChild = verifyAndDeriveRequestChildKey({
62
+ rootPublicKeyComp33: pub.rootPublicKeyComp33,
63
+ rootId: pub.rootId,
64
+ childDerivation: request.childDerivation
65
+ });
66
+ return {
67
+ msgDigest32,
68
+ msgScalarModN: modN(bytesToBigIntBE(msgDigest32)),
69
+ derivedChild
70
+ };
71
+ }
72
+ /**
73
+ * Evaluates a Groth-Shoup partial signature share on an already-consumed `PresignatureShareRecord`
74
+ * and unconditionally zeroizes `(kShareBytes32, chiShareBytes32)` in `finally`.
75
+ */
76
+ function evaluateConsumedPresigShareWithRerand(params) {
77
+ const { consumedRecord, request } = params;
78
+ const vectorOverride = params[VECTOR_TEST_DELTA_RERAND_SYMBOL];
79
+ try {
80
+ const { msgDigest32, msgScalarModN, derivedChild } = validateRequestAgainstPublicPresig(request, consumedRecord.publicVerification);
81
+ const kI = bytes32ToScalarNonZero(consumedRecord.kShareBytes32);
82
+ const chiI = bytes32ToScalarNonZero(consumedRecord.chiShareBytes32);
83
+ const deltaRerand = vectorOverride ?? deriveGrothShoupRerandScalar({
84
+ presigId32: consumedRecord.publicVerification.presigId32,
85
+ subset: consumedRecord.publicVerification.subset,
86
+ rPointComp33: consumedRecord.publicVerification.rPointComp33,
87
+ childPublicKeyComp33: derivedChild.childPublicKeyComp33,
88
+ msgDigest32,
89
+ tweakScalar: derivedChild.tweakScalar
90
+ });
91
+ const rerand = computeRerandomizedNoncePoint(consumedRecord.publicVerification.rPointComp33, deltaRerand);
92
+ const inner = addModN(mulModN(kI, addModN(msgScalarModN, mulModN(rerand.rPrime, derivedChild.tweakScalar))), mulModN(rerand.rPrime, chiI));
93
+ const sI = mulModN(invModN(deltaRerand), inner);
94
+ return {
95
+ share: {
96
+ slot: consumedRecord.slot,
97
+ presigId32: new Uint8Array(consumedRecord.publicVerification.presigId32),
98
+ sShareBytes32: scalarToBytes32(sI)
99
+ },
100
+ rerand
101
+ };
102
+ } finally {
103
+ zeroizeBytes(consumedRecord.kShareBytes32, consumedRecord.chiShareBytes32);
104
+ }
105
+ }
106
+ /**
107
+ * Synchronously validates the request preimage (blocking `"escape-canary"` before pool touch),
108
+ * consumes `presigId` from `pool`, validates `request.subset === presig.subset`, computes `s_i`,
109
+ * and wipes `k_i` & `\chi_i` from RAM.
110
+ */
111
+ function createOnlineSignShare(params) {
112
+ const { pool, request } = params;
113
+ return evaluateConsumedPresigShareWithRerand({
114
+ consumedRecord: pool.consume({
115
+ rootId: request.rootId,
116
+ presigId: request.presigId,
117
+ requestedSubset: request.subset,
118
+ preValidateRecord: (rec) => {
119
+ validateRequestAgainstPublicPresig(request, rec.publicVerification);
120
+ }
121
+ }),
122
+ request
123
+ });
124
+ }
125
+ /**
126
+ * Verifies a single party's partial signature share `s_i` (`design.md` §4.5(2)):
127
+ * `\delta_{rerand} * s_i * R == (m + r' * t_tweak) * K_i + r' * Z_i`.
128
+ * Attributes exact `culpritSlot = share.slot` on mismatch!
129
+ */
130
+ function verifyOnlineSignShare(params) {
131
+ const { share, publicVerification, request } = params;
132
+ const vectorOverride = params[VECTOR_TEST_DELTA_RERAND_SYMBOL];
133
+ const { msgDigest32, msgScalarModN, derivedChild } = validateRequestAgainstPublicPresig(request, publicVerification);
134
+ if (!publicVerification.subset.includes(share.slot)) throw new MpcProtocolError("SIGN_SHARE_VERIFICATION_FAILED", `Unexpected sign share slot ${share.slot}`, share.slot);
135
+ if (!constantTimeEqual(share.presigId32, publicVerification.presigId32)) throw new MpcProtocolError("SIGN_SHARE_VERIFICATION_FAILED", `presigId mismatch in sign share from slot ${share.slot}`, share.slot);
136
+ let sI;
137
+ try {
138
+ sI = bytes32ToScalarStrict(share.sShareBytes32);
139
+ } catch {
140
+ throw new MpcProtocolError("SIGN_SHARE_VERIFICATION_FAILED", `Malformed s_${share.slot} scalar`, share.slot);
141
+ }
142
+ const deltaRerand = vectorOverride ?? deriveGrothShoupRerandScalar({
143
+ presigId32: publicVerification.presigId32,
144
+ subset: publicVerification.subset,
145
+ rPointComp33: publicVerification.rPointComp33,
146
+ childPublicKeyComp33: derivedChild.childPublicKeyComp33,
147
+ msgDigest32,
148
+ tweakScalar: derivedChild.tweakScalar
149
+ });
150
+ const rPoint = decodePointCompressed(publicVerification.rPointComp33, false);
151
+ const rerand = computeRerandomizedNoncePoint(rPoint, deltaRerand);
152
+ const kIComp33 = publicVerification.kPointsComp33BySlot.get(share.slot);
153
+ const zIComp33 = publicVerification.zPointsComp33BySlot.get(share.slot);
154
+ if (!kIComp33 || !zIComp33) throw new MpcProtocolError("SIGN_SHARE_VERIFICATION_FAILED", `Missing K_${share.slot} or Z_${share.slot}`, share.slot);
155
+ const kIPoint = decodePointCompressed(kIComp33, false);
156
+ const zIPoint = decodePointCompressed(zIComp33, false);
157
+ const lhs = mulPoint(rPoint, mulModN(deltaRerand, sI));
158
+ const rhs = mulPoint(kIPoint, addModN(msgScalarModN, mulModN(rerand.rPrime, derivedChild.tweakScalar))).add(mulPoint(zIPoint, rerand.rPrime));
159
+ if (!lhs.equals(rhs)) throw new MpcProtocolError("SIGN_SHARE_VERIFICATION_FAILED", `Identifiable abort: corrupted partial signature s_${share.slot}`, share.slot);
160
+ return rerand;
161
+ }
162
+ /**
163
+ * Verifies all `t` partial signature shares, aggregates `s_raw = \sum_{i \in S} s_i mod n`,
164
+ * enforces EIP-2 low-S (`s_sig <= n / 2`, toggling `yParity ^= 1` when negated), and self-verifies
165
+ * `ecrecover(z, r', s_sig, yParity) === P_child`.
166
+ */
167
+ function aggregateOnlineSignature(params) {
168
+ const { shares, publicVerification, request } = params;
169
+ const vectorOverride = params[VECTOR_TEST_DELTA_RERAND_SYMBOL];
170
+ const { msgDigest32, derivedChild } = validateRequestAgainstPublicPresig(request, publicVerification);
171
+ const pChild = derivedChild.childPoint;
172
+ const sorted = normalizeSortedSubset(publicVerification.subset);
173
+ if (shares.length !== sorted.length) throw new MpcProtocolError("SIGN_AGGREGATION_FAILED", `Expected ${sorted.length} partial shares, got ${shares.length}`);
174
+ const seenSlots = /* @__PURE__ */ new Set();
175
+ let sRaw = 0n;
176
+ let rerand = null;
177
+ for (const share of shares) {
178
+ if (seenSlots.has(share.slot)) throw new MpcProtocolError("SIGN_AGGREGATION_FAILED", `Duplicate sign share from slot ${share.slot}`, share.slot);
179
+ seenSlots.add(share.slot);
180
+ rerand = verifyOnlineSignShare({
181
+ share,
182
+ publicVerification,
183
+ request,
184
+ [VECTOR_TEST_DELTA_RERAND_SYMBOL]: vectorOverride
185
+ });
186
+ sRaw = addModN(sRaw, bytes32ToScalarStrict(share.sShareBytes32));
187
+ }
188
+ if (sRaw === 0n || !rerand) throw new MpcProtocolError("SIGN_AGGREGATION_FAILED", "Aggregated s_raw == 0");
189
+ let sSig = sRaw;
190
+ let yParity = rerand.yPrimeParity;
191
+ if (sRaw > SECP256K1_HALF_N) {
192
+ sSig = subModN(0n, sRaw);
193
+ yParity = yParity ^ 1;
194
+ }
195
+ const v = 27 + yParity;
196
+ const expectedAddr = pointToEthAddress(pChild);
197
+ const recovered = ecrecoverEthAddress({
198
+ msgDigest32,
199
+ r: rerand.rPrime,
200
+ s: sSig,
201
+ yParity
202
+ });
203
+ if (!recovered.recoveredPoint.equals(pChild) || recovered.checksumAddress !== expectedAddr.checksumAddress) throw new MpcProtocolError("SIGN_AGGREGATION_FAILED", "Internal invariant violation: ecrecover mismatch against P_child");
204
+ const rBytes32 = scalarToBytes32(rerand.rPrime);
205
+ const sBytes32 = scalarToBytes32(sSig);
206
+ const signature65Bytes = concatBytes(rBytes32, sBytes32, Uint8Array.of(v));
207
+ return {
208
+ r: rerand.rPrime,
209
+ s: sSig,
210
+ rBytes32,
211
+ sBytes32,
212
+ rHex: `0x${bytesToHex(rBytes32)}`,
213
+ sHex: `0x${bytesToHex(sBytes32)}`,
214
+ yParity,
215
+ v,
216
+ signature65Bytes,
217
+ signature65Hex: `0x${bytesToHex(signature65Bytes)}`,
218
+ deltaRerand: rerand.deltaRerand,
219
+ rPrimePointComp33: rerand.rPrimePointComp33,
220
+ signerAddress: expectedAddr.checksumAddress
221
+ };
222
+ }
223
+
224
+ //#endregion
225
+ export { VECTOR_TEST_DELTA_RERAND_SYMBOL, aggregateOnlineSignature, computeRerandomizedNoncePoint, createOnlineSignShare, deriveGrothShoupRerandScalar, evaluateConsumedPresigShareWithRerand, verifyAndDeriveRequestChildKey, verifyOnlineSignShare };
@@ -0,0 +1,55 @@
1
+ //#region src/steel-mnemonic.d.ts
2
+ /**
3
+ * Pure 3-Plate 24-Word Standard `BIP-39` Stainless-Steel Cold Backup (`design.md` §5.2):
4
+ * - ZERO human-memorized passphrases (`25th word`) anywhere in cold-backup encoding, decoding, or derivation.
5
+ * - Standard 256-bit entropy (`coldShareBytes32` in `[1, secp256k1.n - 1]`) + 8-bit `SHA-256` BIP-39 checksum
6
+ * -> 24 lowercase English BIP-39 words (`Plate A`, `Plate B`, `Plate C`).
7
+ * - Feldman index identification (`g(k) * G == Y_k`) and 24th-word 8-sibling `m/44'/60'/0'/0/0` decoy address
8
+ * enumeration for outgoing-nonce physical-burglar tripwires.
9
+ */
10
+ declare const BIP44_ETH_STANDARD_PATH: "m/44'/60'/0'/0/0";
11
+ declare function guardianIndexToPlateLabel(guardianIndex: number): string;
12
+ /**
13
+ * Encodes a 32-byte cold Shamir share (`1 <= scalar < secp256k1.n`) into 24 standard English BIP-39 words
14
+ * (`256` entropy bits + `8` SHA-256 checksum bits = `264` bits = `24 x 11` bits).
15
+ */
16
+ declare function encodeColdShareToBip39Words24(coldShareBytes32: Uint8Array): string[];
17
+ /**
18
+ * Decodes 24 standard English BIP-39 words into a validated 32-byte `secp256k1` scalar (`1 <= scalar < n`),
19
+ * verifying exact 24-word count (zero passphrases) and the 8-bit SHA-256 BIP-39 checksum.
20
+ */
21
+ declare function decodeBip39Words24ToColdShare(wordsInput: ReadonlyArray<string> | string): Uint8Array;
22
+ interface IdentifiedColdShare {
23
+ readonly guardianIndex: number;
24
+ readonly plateLabel: string;
25
+ readonly coldPublicShareComp33: Uint8Array;
26
+ }
27
+ /**
28
+ * Identifies which guardian index `k in 1..nCold` a physical 24-word cold share belongs to by
29
+ * evaluating the aggregated cold Feldman commitments `Y_k = \sum_{l=0}^{t_c-1} k^l C^{cold}_l`
30
+ * and checking `scalar * G == Y_k`. Fails closed if zero indices match (e.g. wrong 24th sibling word).
31
+ */
32
+ declare function identifyColdShareIndexViaFeldman(coldShareBytes32: Uint8Array, coldFeldmanCommitmentsComp33: ReadonlyArray<Uint8Array | string>, nCold: number): IdentifiedColdShare;
33
+ /**
34
+ * Derives the standard `m/44'/60'/0'/0/0` Ethereum EOA address (zero passphrase: salt = `"mnemonic"`)
35
+ * for a 24-word BIP-39 mnemonic so honeypot monitoring matches standard hardware/software wallets
36
+ * (`design.md` §5.2(2)).
37
+ */
38
+ declare function deriveBip44EthAddressFromWords24(wordsInput: ReadonlyArray<string> | string): string;
39
+ interface Bip39TwentyFourthSiblingEntry {
40
+ readonly tail3Bits: number;
41
+ readonly wordIndex: number;
42
+ readonly word24: string;
43
+ readonly words24: ReadonlyArray<string>;
44
+ readonly derivationPath: typeof BIP44_ETH_STANDARD_PATH;
45
+ readonly ethAddress: string;
46
+ readonly isValidColdScalar: boolean;
47
+ }
48
+ /**
49
+ * Given the first 23 standard BIP-39 words (`253` bits), enumerates all `2^3 = 8` checksum-valid
50
+ * 24th words (`3` entropy bits + `8` SHA-256 checksum bits) and derives each candidate's standard
51
+ * `m/44'/60'/0'/0/0` `0x...` Ethereum canary/honeypot address (`design.md` §5.2(2)).
52
+ */
53
+ declare function enumerateValid24thBip39Siblings(first23WordsInput: ReadonlyArray<string> | string): ReadonlyArray<Bip39TwentyFourthSiblingEntry>;
54
+ //#endregion
55
+ export { BIP44_ETH_STANDARD_PATH, Bip39TwentyFourthSiblingEntry, IdentifiedColdShare, decodeBip39Words24ToColdShare, deriveBip44EthAddressFromWords24, encodeColdShareToBip39Words24, enumerateValid24thBip39Siblings, guardianIndexToPlateLabel, identifyColdShareIndexViaFeldman };
@@ -0,0 +1,247 @@
1
+ import { MAX_MPC_CLUSTER_NODES, MpcProtocolError, SECP256K1_N } from "./constants.mjs";
2
+ import { addModN, bytes32ToScalarNonZero, bytesToBigIntBE, concatBytes, decodePointCompressed, encodePointCompressed, evaluateFeldmanCommitments, mulBaseG, normalizeHexBytes, scalarToBytes32, u32be, u8, utf8Bytes, zeroizeBytes } from "./secp256k1-scalar.mjs";
3
+ import { BIP39_ENGLISH_WORDLIST, BIP39_ENGLISH_WORD_TO_INDEX } from "./bip39-english-wordlist.mjs";
4
+ import { pointToEthAddress } from "./tweak.mjs";
5
+ import { sha256, sha512 } from "@noble/hashes/sha2.js";
6
+ import { hmac } from "@noble/hashes/hmac.js";
7
+ import { pbkdf2 } from "@noble/hashes/pbkdf2.js";
8
+
9
+ //#region src/steel-mnemonic.ts
10
+ /**
11
+ * Pure 3-Plate 24-Word Standard `BIP-39` Stainless-Steel Cold Backup (`design.md` §5.2):
12
+ * - ZERO human-memorized passphrases (`25th word`) anywhere in cold-backup encoding, decoding, or derivation.
13
+ * - Standard 256-bit entropy (`coldShareBytes32` in `[1, secp256k1.n - 1]`) + 8-bit `SHA-256` BIP-39 checksum
14
+ * -> 24 lowercase English BIP-39 words (`Plate A`, `Plate B`, `Plate C`).
15
+ * - Feldman index identification (`g(k) * G == Y_k`) and 24th-word 8-sibling `m/44'/60'/0'/0/0` decoy address
16
+ * enumeration for outgoing-nonce physical-burglar tripwires.
17
+ */
18
+ const BIP44_ETH_STANDARD_PATH = "m/44'/60'/0'/0/0";
19
+ const BIP44_ETH_INDICES = [
20
+ 2147483692,
21
+ 2147483708,
22
+ 2147483648,
23
+ 0,
24
+ 0
25
+ ];
26
+ const BIP39_WORD_RE = /^[a-z]+$/;
27
+ function guardianIndexToPlateLabel(guardianIndex) {
28
+ if (!Number.isInteger(guardianIndex) || guardianIndex < 1) throw new MpcProtocolError("INVALID_PARAMETER", `Invalid guardianIndex: ${guardianIndex}`);
29
+ if (guardianIndex <= 26) return `Plate ${String.fromCharCode(64 + guardianIndex)}`;
30
+ return `Plate #${guardianIndex}`;
31
+ }
32
+ function normalizeMnemonicWordList(wordsInput, expectedCount) {
33
+ let rawTokens;
34
+ if (typeof wordsInput === "string") {
35
+ const trimmed = wordsInput.trim();
36
+ if (trimmed.length === 0) throw new MpcProtocolError("BIP39_INVALID_MNEMONIC", "Mnemonic input is empty");
37
+ rawTokens = trimmed.split(/\s+/);
38
+ } else if (Array.isArray(wordsInput)) rawTokens = wordsInput.map((w) => {
39
+ if (typeof w !== "string") throw new MpcProtocolError("BIP39_INVALID_MNEMONIC", "Mnemonic words must be strings");
40
+ return w.trim();
41
+ });
42
+ else throw new MpcProtocolError("BIP39_INVALID_MNEMONIC", "Expected 24-word string or string array");
43
+ if (rawTokens.length !== expectedCount) throw new MpcProtocolError("BIP39_INVALID_MNEMONIC", `Expected exactly ${expectedCount} standard BIP-39 words (zero passphrases), got ${rawTokens.length}`);
44
+ return rawTokens.map((token, idx) => {
45
+ const lower = token.toLowerCase();
46
+ if (!BIP39_WORD_RE.test(lower) || !BIP39_ENGLISH_WORD_TO_INDEX.has(lower)) throw new MpcProtocolError("BIP39_INVALID_MNEMONIC", `Invalid BIP-39 English word at position ${idx + 1}: "${token}"`);
47
+ return lower;
48
+ });
49
+ }
50
+ /**
51
+ * Encodes a 32-byte cold Shamir share (`1 <= scalar < secp256k1.n`) into 24 standard English BIP-39 words
52
+ * (`256` entropy bits + `8` SHA-256 checksum bits = `264` bits = `24 x 11` bits).
53
+ */
54
+ function encodeColdShareToBip39Words24(coldShareBytes32) {
55
+ bytes32ToScalarNonZero(coldShareBytes32);
56
+ const digest32 = sha256(coldShareBytes32);
57
+ const words = new Array(24);
58
+ try {
59
+ const checksumByte = digest32[0];
60
+ for (let w = 0; w < 24; w++) {
61
+ let wordIndex = 0;
62
+ for (let bit = 0; bit < 11; bit++) {
63
+ const bitPos = w * 11 + bit;
64
+ let bitVal;
65
+ if (bitPos < 256) {
66
+ const byteIdx = bitPos >>> 3;
67
+ const shift = 7 - (bitPos & 7);
68
+ bitVal = coldShareBytes32[byteIdx] >>> shift & 1;
69
+ } else bitVal = checksumByte >>> 7 - (bitPos - 256) & 1;
70
+ wordIndex = wordIndex << 1 | bitVal;
71
+ }
72
+ words[w] = BIP39_ENGLISH_WORDLIST[wordIndex];
73
+ }
74
+ return words;
75
+ } finally {
76
+ zeroizeBytes(digest32);
77
+ }
78
+ }
79
+ /**
80
+ * Decodes 24 standard English BIP-39 words into a validated 32-byte `secp256k1` scalar (`1 <= scalar < n`),
81
+ * verifying exact 24-word count (zero passphrases) and the 8-bit SHA-256 BIP-39 checksum.
82
+ */
83
+ function decodeBip39Words24ToColdShare(wordsInput) {
84
+ const words = normalizeMnemonicWordList(wordsInput, 24);
85
+ const entropy32 = new Uint8Array(32);
86
+ let givenChecksum = 0;
87
+ for (let w = 0; w < 24; w++) {
88
+ const wordIndex = BIP39_ENGLISH_WORD_TO_INDEX.get(words[w]);
89
+ for (let bit = 0; bit < 11; bit++) {
90
+ const bitVal = wordIndex >>> 10 - bit & 1;
91
+ const bitPos = w * 11 + bit;
92
+ if (bitPos < 256) {
93
+ const byteIdx = bitPos >>> 3;
94
+ const shift = 7 - (bitPos & 7);
95
+ entropy32[byteIdx] |= bitVal << shift;
96
+ } else {
97
+ const chkShift = 7 - (bitPos - 256);
98
+ givenChecksum |= bitVal << chkShift;
99
+ }
100
+ }
101
+ }
102
+ const digest32 = sha256(entropy32);
103
+ const expectedChecksum = digest32[0];
104
+ zeroizeBytes(digest32);
105
+ if (givenChecksum !== expectedChecksum) {
106
+ zeroizeBytes(entropy32);
107
+ throw new MpcProtocolError("BIP39_CHECKSUM_MISMATCH", "24-word BIP-39 mnemonic failed 8-bit SHA-256 checksum verification");
108
+ }
109
+ const scalar = bytesToBigIntBE(entropy32);
110
+ if (scalar < 1n || scalar >= SECP256K1_N) {
111
+ zeroizeBytes(entropy32);
112
+ throw new MpcProtocolError("INVALID_SCALAR", "Decoded 24-word entropy is outside [1, secp256k1.n - 1]");
113
+ }
114
+ return entropy32;
115
+ }
116
+ /**
117
+ * Identifies which guardian index `k in 1..nCold` a physical 24-word cold share belongs to by
118
+ * evaluating the aggregated cold Feldman commitments `Y_k = \sum_{l=0}^{t_c-1} k^l C^{cold}_l`
119
+ * and checking `scalar * G == Y_k`. Fails closed if zero indices match (e.g. wrong 24th sibling word).
120
+ */
121
+ function identifyColdShareIndexViaFeldman(coldShareBytes32, coldFeldmanCommitmentsComp33, nCold) {
122
+ if (!Number.isInteger(nCold) || nCold < 1 || nCold > MAX_MPC_CLUSTER_NODES) throw new MpcProtocolError("INVALID_PARAMETER", `Invalid nCold: ${nCold}`);
123
+ if (!Array.isArray(coldFeldmanCommitmentsComp33) || coldFeldmanCommitmentsComp33.length === 0) throw new MpcProtocolError("INVALID_PARAMETER", "coldFeldmanCommitmentsComp33 must be non-empty");
124
+ const scalar = bytes32ToScalarNonZero(coldShareBytes32);
125
+ const coldPoints = coldFeldmanCommitmentsComp33.map((c) => decodePointCompressed(normalizeHexBytes(c, 33), false));
126
+ const candidatePub = mulBaseG(scalar);
127
+ let matchedIndex = null;
128
+ for (let k = 1; k <= nCold; k++) {
129
+ const yk = evaluateFeldmanCommitments(coldPoints, k);
130
+ if (!yk.is0() && candidatePub.equals(yk)) {
131
+ if (matchedIndex !== null) throw new MpcProtocolError("COLD_SHARE_UNKNOWN_INDEX", "Ambiguous Feldman cold share index match");
132
+ matchedIndex = k;
133
+ }
134
+ }
135
+ if (matchedIndex === null) throw new MpcProtocolError("COLD_SHARE_UNKNOWN_INDEX", `Cold share scalar * G does not match any guardian Feldman commitment Y_1..Y_${nCold}`);
136
+ return {
137
+ guardianIndex: matchedIndex,
138
+ plateLabel: guardianIndexToPlateLabel(matchedIndex),
139
+ coldPublicShareComp33: encodePointCompressed(candidatePub)
140
+ };
141
+ }
142
+ /**
143
+ * Derives the standard `m/44'/60'/0'/0/0` Ethereum EOA address (zero passphrase: salt = `"mnemonic"`)
144
+ * for a 24-word BIP-39 mnemonic so honeypot monitoring matches standard hardware/software wallets
145
+ * (`design.md` §5.2(2)).
146
+ */
147
+ function deriveBip44EthAddressFromWords24(wordsInput) {
148
+ const words = normalizeMnemonicWordList(wordsInput, 24);
149
+ const entropy32 = new Uint8Array(32);
150
+ let givenChecksum = 0;
151
+ for (let w = 0; w < 24; w++) {
152
+ const wordIndex = BIP39_ENGLISH_WORD_TO_INDEX.get(words[w]);
153
+ for (let bit = 0; bit < 11; bit++) {
154
+ const bitVal = wordIndex >>> 10 - bit & 1;
155
+ const bitPos = w * 11 + bit;
156
+ if (bitPos < 256) entropy32[bitPos >>> 3] |= bitVal << 7 - (bitPos & 7);
157
+ else givenChecksum |= bitVal << 7 - (bitPos - 256);
158
+ }
159
+ }
160
+ const chkDigest = sha256(entropy32);
161
+ const expectedChecksum = chkDigest[0];
162
+ zeroizeBytes(entropy32, chkDigest);
163
+ if (givenChecksum !== expectedChecksum) throw new MpcProtocolError("BIP39_CHECKSUM_MISMATCH", "Invalid 24-word BIP-39 checksum");
164
+ const sentenceBytes = utf8Bytes(words.join(" "));
165
+ const seed64 = pbkdf2(sha512, sentenceBytes, utf8Bytes("mnemonic"), {
166
+ c: 2048,
167
+ dkLen: 64
168
+ });
169
+ const masterI = hmac(sha512, utf8Bytes("Bitcoin seed"), seed64);
170
+ const chainCode32 = new Uint8Array(masterI.subarray(32, 64));
171
+ let keyScalar = bytesToBigIntBE(masterI.subarray(0, 32));
172
+ try {
173
+ if (keyScalar === 0n || keyScalar >= SECP256K1_N) throw new MpcProtocolError("INVALID_SCALAR", "Degenerate BIP-32 master key derived from mnemonic");
174
+ for (const childIndex of BIP44_ETH_INDICES) {
175
+ let data;
176
+ if (childIndex >= 2147483648) {
177
+ const keyBytes = scalarToBytes32(keyScalar);
178
+ data = concatBytes(u8(0), keyBytes, u32be(childIndex));
179
+ zeroizeBytes(keyBytes);
180
+ } else data = concatBytes(encodePointCompressed(mulBaseG(keyScalar)), u32be(childIndex));
181
+ const childI = hmac(sha512, chainCode32, data);
182
+ zeroizeBytes(data);
183
+ try {
184
+ const il = bytesToBigIntBE(childI.subarray(0, 32));
185
+ const nextKey = addModN(il, keyScalar);
186
+ if (il >= SECP256K1_N || nextKey === 0n) throw new MpcProtocolError("INVALID_SCALAR", "Degenerate BIP-32 child key derived along m/44h/60h/0h/0/0");
187
+ keyScalar = nextKey;
188
+ chainCode32.set(childI.subarray(32, 64));
189
+ } finally {
190
+ zeroizeBytes(childI);
191
+ }
192
+ }
193
+ return pointToEthAddress(mulBaseG(keyScalar)).checksumAddress;
194
+ } finally {
195
+ keyScalar = 0n;
196
+ zeroizeBytes(sentenceBytes, seed64, masterI, chainCode32);
197
+ }
198
+ }
199
+ /**
200
+ * Given the first 23 standard BIP-39 words (`253` bits), enumerates all `2^3 = 8` checksum-valid
201
+ * 24th words (`3` entropy bits + `8` SHA-256 checksum bits) and derives each candidate's standard
202
+ * `m/44'/60'/0'/0/0` `0x...` Ethereum canary/honeypot address (`design.md` §5.2(2)).
203
+ */
204
+ function enumerateValid24thBip39Siblings(first23WordsInput) {
205
+ const first23Words = normalizeMnemonicWordList(first23WordsInput, 23);
206
+ const baseEntropy32 = new Uint8Array(32);
207
+ for (let w = 0; w < 23; w++) {
208
+ const wordIndex = BIP39_ENGLISH_WORD_TO_INDEX.get(first23Words[w]);
209
+ for (let bit = 0; bit < 11; bit++) {
210
+ const bitVal = wordIndex >>> 10 - bit & 1;
211
+ const bitPos = w * 11 + bit;
212
+ baseEntropy32[bitPos >>> 3] |= bitVal << 7 - (bitPos & 7);
213
+ }
214
+ }
215
+ const results = [];
216
+ const candidateEntropy32 = new Uint8Array(32);
217
+ try {
218
+ for (let tail3 = 0; tail3 < 8; tail3++) {
219
+ candidateEntropy32.set(baseEntropy32);
220
+ candidateEntropy32[31] = baseEntropy32[31] & 248 | tail3;
221
+ const digest32 = sha256(candidateEntropy32);
222
+ const checksumByte = digest32[0];
223
+ zeroizeBytes(digest32);
224
+ const wordIndex = tail3 << 8 | checksumByte;
225
+ const word24 = BIP39_ENGLISH_WORDLIST[wordIndex];
226
+ const words24 = [...first23Words, word24];
227
+ const scalarVal = bytesToBigIntBE(candidateEntropy32);
228
+ const isValidColdScalar = scalarVal >= 1n && scalarVal < SECP256K1_N;
229
+ const ethAddress = deriveBip44EthAddressFromWords24(words24);
230
+ results.push({
231
+ tail3Bits: tail3,
232
+ wordIndex,
233
+ word24,
234
+ words24,
235
+ derivationPath: BIP44_ETH_STANDARD_PATH,
236
+ ethAddress,
237
+ isValidColdScalar
238
+ });
239
+ }
240
+ return results;
241
+ } finally {
242
+ zeroizeBytes(baseEntropy32, candidateEntropy32);
243
+ }
244
+ }
245
+
246
+ //#endregion
247
+ export { BIP44_ETH_STANDARD_PATH, decodeBip39Words24ToColdShare, deriveBip44EthAddressFromWords24, encodeColdShareToBip39Words24, enumerateValid24thBip39Siblings, guardianIndexToPlateLabel, identifyColdShareIndexViaFeldman };
@@ -0,0 +1,100 @@
1
+ import { Secp256k1Point } from "./secp256k1-scalar.mjs";
2
+
3
+ //#region src/tweak.d.ts
4
+ type MpcTweakMode = 'untweaked' | 'role-bound' | 'rule-bound';
5
+ type MpcChildDerivationSpec = {
6
+ readonly tweakMode: 'untweaked';
7
+ readonly childPublicKeyComp33: Uint8Array;
8
+ } | {
9
+ readonly tweakMode: 'role-bound';
10
+ readonly role: string;
11
+ readonly ethChainId: bigint;
12
+ readonly tweakLabel: string;
13
+ readonly childPublicKeyComp33: Uint8Array;
14
+ } | {
15
+ readonly tweakMode: 'rule-bound';
16
+ readonly controllerDid: string;
17
+ readonly ethChainId: bigint;
18
+ readonly ruleHash: Uint8Array | string;
19
+ readonly childPublicKeyComp33: Uint8Array;
20
+ };
21
+ interface DerivedChildKey {
22
+ readonly tweakMode: MpcTweakMode;
23
+ readonly tweakScalar: bigint;
24
+ readonly tweakBytes32: Uint8Array;
25
+ readonly tweakHex: string;
26
+ readonly childPoint: Secp256k1Point;
27
+ readonly childPublicKeyComp33: Uint8Array;
28
+ readonly ethAddress: string;
29
+ readonly ethAddressLower: string;
30
+ readonly derivationSpec: MpcChildDerivationSpec;
31
+ }
32
+ declare function toEip55ChecksumAddress(lowerHexWithoutPrefix: string): string;
33
+ /**
34
+ * Validates an Ethereum `0x` address (rejects non-hex, all-uppercase, bad EIP-55 mixed-case
35
+ * checksums, and the zero address `0x0000...0000`) and returns canonical EIP-55 + lowercase forms.
36
+ */
37
+ declare function parseStrictEthAddress(address: string): {
38
+ checksumAddress: string;
39
+ lowercaseAddress: string;
40
+ addressBytes20: Uint8Array;
41
+ };
42
+ declare function pointToEthAddress(pointOrComp33: Secp256k1Point | Uint8Array): {
43
+ checksumAddress: string;
44
+ lowercaseAddress: string;
45
+ };
46
+ declare function assertAllowedOnlineRole(role: string): void;
47
+ /**
48
+ * Applies a non-hardened additive scalar tweak `P_child = P_root + t_tweak * G`,
49
+ * strictly rejecting `t_tweak == 0`, `t_tweak >= n`, or `P_child == O`.
50
+ */
51
+ declare function applyAdditiveTweak(rootPublicKey: Secp256k1Point | Uint8Array, tweakScalar: bigint, tweakMode: Exclude<MpcTweakMode, 'untweaked'>, derivationMeta?: {
52
+ readonly kind: 'role-bound';
53
+ readonly role: string;
54
+ readonly ethChainId: bigint;
55
+ readonly tweakLabel: string;
56
+ } | {
57
+ readonly kind: 'rule-bound';
58
+ readonly controllerDid: string;
59
+ readonly ethChainId: bigint;
60
+ readonly ruleHashBytes32: Uint8Array;
61
+ }): DerivedChildKey;
62
+ declare function deriveUntweakedChild(rootPublicKey: Secp256k1Point | Uint8Array): DerivedChildKey;
63
+ /**
64
+ * `role-bound` EOA child derivation (`design.md` §4.2):
65
+ * `t_tweak = H_scalar("ARC-MPC-CHILD-TWEAK-V1", P_root^comp33, utf8(rootId), utf8(role), u64be(ethChainId), utf8(tweakLabel))`.
66
+ */
67
+ declare function deriveRoleBoundChild(params: {
68
+ rootPublicKey: Secp256k1Point | Uint8Array;
69
+ rootId: string;
70
+ role: string;
71
+ ethChainId: bigint;
72
+ tweakLabel: string;
73
+ }): DerivedChildKey;
74
+ /**
75
+ * `rule-bound` EOA child derivation (`design.md` §4.2):
76
+ * `t_tweak = H_scalar("ARC-MPC-RULE-TWEAK-V1", P_root^comp33, utf8(rootId), utf8(controllerDid), u64be(ethChainId), bytes32(ruleHash))`.
77
+ */
78
+ declare function deriveRuleBoundChild(params: {
79
+ rootPublicKey: Secp256k1Point | Uint8Array;
80
+ rootId: string;
81
+ controllerDid: string;
82
+ ethChainId: bigint;
83
+ ruleHash: Uint8Array | string;
84
+ }): DerivedChildKey;
85
+ /**
86
+ * Recovers the EIP-55 Ethereum address from a 32-byte digest and EIP-2 low-S `(r, s, yParity)`
87
+ * signature, matching Solidity `ecrecover` and Type-2 EIP-1559 transaction recovery.
88
+ */
89
+ declare function ecrecoverEthAddress(params: {
90
+ msgDigest32: Uint8Array;
91
+ r: bigint;
92
+ s: bigint;
93
+ yParity: 0 | 1;
94
+ }): {
95
+ recoveredPoint: Secp256k1Point;
96
+ checksumAddress: string;
97
+ lowercaseAddress: string;
98
+ };
99
+ //#endregion
100
+ export { DerivedChildKey, MpcChildDerivationSpec, MpcTweakMode, applyAdditiveTweak, assertAllowedOnlineRole, deriveRoleBoundChild, deriveRuleBoundChild, deriveUntweakedChild, ecrecoverEthAddress, parseStrictEthAddress, pointToEthAddress, toEip55ChecksumAddress };