@ocap/mpc-hsm 0.0.0-stage → 1.33.6

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.
package/lib/sign.cjs ADDED
@@ -0,0 +1,233 @@
1
+ const require_constants = require('./constants.cjs');
2
+ const require_secp256k1_scalar = require('./secp256k1-scalar.cjs');
3
+ const require_tweak = require('./tweak.cjs');
4
+ let _noble_hashes_utils_js = require("@noble/hashes/utils.js");
5
+
6
+ //#region src/sign.ts
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
+ const VECTOR_TEST_DELTA_RERAND_SYMBOL = Symbol("ocap.mpc-hsm.vector-test-delta-rerand");
12
+ function deriveGrothShoupRerandScalar(params) {
13
+ const { presigId32, subset, rPointComp33, childPublicKeyComp33, msgDigest32, tweakScalar } = params;
14
+ if (presigId32.length !== 32 || msgDigest32.length !== 32) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "presigId32 and msgDigest32 must be 32 bytes");
15
+ if (tweakScalar < 0n || tweakScalar >= require_constants.SECP256K1_N) throw new require_constants.MpcProtocolError("INVALID_SCALAR", "tweakScalar out of field range");
16
+ return require_secp256k1_scalar.H_scalar(require_constants.DST_PRESIG_RERAND_V1, presigId32, require_secp256k1_scalar.sortedSubsetBytes(subset), rPointComp33, childPublicKeyComp33, msgDigest32, require_secp256k1_scalar.scalarToBytes32(tweakScalar));
17
+ }
18
+ function computeRerandomizedNoncePoint(rPointOrComp33, deltaRerand) {
19
+ require_secp256k1_scalar.assertScalarNonZero(deltaRerand, "deltaRerand");
20
+ const rPoint = rPointOrComp33 instanceof Uint8Array ? require_secp256k1_scalar.decodePointCompressed(rPointOrComp33, false) : rPointOrComp33;
21
+ if (rPoint.is0()) throw new require_constants.MpcProtocolError("INVALID_POINT", "Presignature R cannot be infinity");
22
+ const rPrimePoint = require_secp256k1_scalar.mulPoint(rPoint, deltaRerand);
23
+ if (rPrimePoint.is0()) throw new require_constants.MpcProtocolError("PRESIG_RERAND_BURN_RETRY", "Re-randomized R_prime hit infinity; burn presigId and retry with a fresh presignature");
24
+ const { x, y } = rPrimePoint.toAffine();
25
+ if (x >= require_constants.SECP256K1_N || x % require_constants.SECP256K1_N === 0n) throw new require_constants.MpcProtocolError("PRESIG_RERAND_BURN_RETRY", "Re-randomized R_prime_x >= n or == 0; burn presigId and retry with a fresh presignature");
26
+ return {
27
+ deltaRerand,
28
+ rPrimePoint,
29
+ rPrimePointComp33: require_secp256k1_scalar.encodePointCompressed(rPrimePoint),
30
+ rPrime: x,
31
+ yPrimeParity: Number(y & 1n)
32
+ };
33
+ }
34
+ function verifyAndDeriveRequestChildKey(params) {
35
+ const { rootPublicKeyComp33, rootId, childDerivation } = params;
36
+ if (!childDerivation || typeof childDerivation !== "object") throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "Missing childDerivation in sign request");
37
+ let derived;
38
+ if (childDerivation.tweakMode === "untweaked") derived = require_tweak.deriveUntweakedChild(rootPublicKeyComp33);
39
+ else if (childDerivation.tweakMode === "role-bound") derived = require_tweak.deriveRoleBoundChild({
40
+ rootPublicKey: rootPublicKeyComp33,
41
+ rootId,
42
+ role: childDerivation.role,
43
+ ethChainId: childDerivation.ethChainId,
44
+ tweakLabel: childDerivation.tweakLabel
45
+ });
46
+ else if (childDerivation.tweakMode === "rule-bound") derived = require_tweak.deriveRuleBoundChild({
47
+ rootPublicKey: rootPublicKeyComp33,
48
+ rootId,
49
+ controllerDid: childDerivation.controllerDid,
50
+ ethChainId: childDerivation.ethChainId,
51
+ ruleHash: childDerivation.ruleHash
52
+ });
53
+ else throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "Unsupported childDerivation tweakMode");
54
+ if (!(childDerivation.childPublicKeyComp33 instanceof Uint8Array) || !require_secp256k1_scalar.constantTimeEqual(derived.childPublicKeyComp33, childDerivation.childPublicKeyComp33)) throw new require_constants.MpcProtocolError("DEGENERATE_TWEAK", "childDerivation.childPublicKeyComp33 does not match canonically derived P_child");
55
+ return derived;
56
+ }
57
+ function validateRequestAgainstPublicPresig(request, pub) {
58
+ if (request.rootId !== pub.rootId) throw new require_constants.MpcProtocolError("PRESIG_SUBSET_MISMATCH", `Sign request rootId ${request.rootId} != presig rootId ${pub.rootId}`);
59
+ if (!require_secp256k1_scalar.subsetsEqual(request.subset, pub.subset)) throw new require_constants.MpcProtocolError("PRESIG_SUBSET_MISMATCH", `Sign request subset [${request.subset.join(",")}] != presig subset [${pub.subset.join(",")}]`);
60
+ if (!require_secp256k1_scalar.constantTimeEqual(require_secp256k1_scalar.normalizeHexBytes(request.presigId, 32), pub.presigId32)) throw new require_constants.MpcProtocolError("PRESIG_SUBSET_MISMATCH", "presigId mismatch");
61
+ const msgDigest32 = require_secp256k1_scalar.normalizeHexBytes(request.msgDigest32, 32);
62
+ const derivedChild = verifyAndDeriveRequestChildKey({
63
+ rootPublicKeyComp33: pub.rootPublicKeyComp33,
64
+ rootId: pub.rootId,
65
+ childDerivation: request.childDerivation
66
+ });
67
+ return {
68
+ msgDigest32,
69
+ msgScalarModN: require_secp256k1_scalar.modN(require_secp256k1_scalar.bytesToBigIntBE(msgDigest32)),
70
+ derivedChild
71
+ };
72
+ }
73
+ /**
74
+ * Evaluates a Groth-Shoup partial signature share on an already-consumed `PresignatureShareRecord`
75
+ * and unconditionally zeroizes `(kShareBytes32, chiShareBytes32)` in `finally`.
76
+ */
77
+ function evaluateConsumedPresigShareWithRerand(params) {
78
+ const { consumedRecord, request } = params;
79
+ const vectorOverride = params[VECTOR_TEST_DELTA_RERAND_SYMBOL];
80
+ try {
81
+ const { msgDigest32, msgScalarModN, derivedChild } = validateRequestAgainstPublicPresig(request, consumedRecord.publicVerification);
82
+ const kI = require_secp256k1_scalar.bytes32ToScalarNonZero(consumedRecord.kShareBytes32);
83
+ const chiI = require_secp256k1_scalar.bytes32ToScalarNonZero(consumedRecord.chiShareBytes32);
84
+ const deltaRerand = vectorOverride ?? deriveGrothShoupRerandScalar({
85
+ presigId32: consumedRecord.publicVerification.presigId32,
86
+ subset: consumedRecord.publicVerification.subset,
87
+ rPointComp33: consumedRecord.publicVerification.rPointComp33,
88
+ childPublicKeyComp33: derivedChild.childPublicKeyComp33,
89
+ msgDigest32,
90
+ tweakScalar: derivedChild.tweakScalar
91
+ });
92
+ const rerand = computeRerandomizedNoncePoint(consumedRecord.publicVerification.rPointComp33, deltaRerand);
93
+ const inner = require_secp256k1_scalar.addModN(require_secp256k1_scalar.mulModN(kI, require_secp256k1_scalar.addModN(msgScalarModN, require_secp256k1_scalar.mulModN(rerand.rPrime, derivedChild.tweakScalar))), require_secp256k1_scalar.mulModN(rerand.rPrime, chiI));
94
+ const sI = require_secp256k1_scalar.mulModN(require_secp256k1_scalar.invModN(deltaRerand), inner);
95
+ return {
96
+ share: {
97
+ slot: consumedRecord.slot,
98
+ presigId32: new Uint8Array(consumedRecord.publicVerification.presigId32),
99
+ sShareBytes32: require_secp256k1_scalar.scalarToBytes32(sI)
100
+ },
101
+ rerand
102
+ };
103
+ } finally {
104
+ require_secp256k1_scalar.zeroizeBytes(consumedRecord.kShareBytes32, consumedRecord.chiShareBytes32);
105
+ }
106
+ }
107
+ /**
108
+ * Synchronously validates the request preimage (blocking `"escape-canary"` before pool touch),
109
+ * consumes `presigId` from `pool`, validates `request.subset === presig.subset`, computes `s_i`,
110
+ * and wipes `k_i` & `\chi_i` from RAM.
111
+ */
112
+ function createOnlineSignShare(params) {
113
+ const { pool, request } = params;
114
+ return evaluateConsumedPresigShareWithRerand({
115
+ consumedRecord: pool.consume({
116
+ rootId: request.rootId,
117
+ presigId: request.presigId,
118
+ requestedSubset: request.subset,
119
+ preValidateRecord: (rec) => {
120
+ validateRequestAgainstPublicPresig(request, rec.publicVerification);
121
+ }
122
+ }),
123
+ request
124
+ });
125
+ }
126
+ /**
127
+ * Verifies a single party's partial signature share `s_i` (`design.md` §4.5(2)):
128
+ * `\delta_{rerand} * s_i * R == (m + r' * t_tweak) * K_i + r' * Z_i`.
129
+ * Attributes exact `culpritSlot = share.slot` on mismatch!
130
+ */
131
+ function verifyOnlineSignShare(params) {
132
+ const { share, publicVerification, request } = params;
133
+ const vectorOverride = params[VECTOR_TEST_DELTA_RERAND_SYMBOL];
134
+ const { msgDigest32, msgScalarModN, derivedChild } = validateRequestAgainstPublicPresig(request, publicVerification);
135
+ if (!publicVerification.subset.includes(share.slot)) throw new require_constants.MpcProtocolError("SIGN_SHARE_VERIFICATION_FAILED", `Unexpected sign share slot ${share.slot}`, share.slot);
136
+ if (!require_secp256k1_scalar.constantTimeEqual(share.presigId32, publicVerification.presigId32)) throw new require_constants.MpcProtocolError("SIGN_SHARE_VERIFICATION_FAILED", `presigId mismatch in sign share from slot ${share.slot}`, share.slot);
137
+ let sI;
138
+ try {
139
+ sI = require_secp256k1_scalar.bytes32ToScalarStrict(share.sShareBytes32);
140
+ } catch {
141
+ throw new require_constants.MpcProtocolError("SIGN_SHARE_VERIFICATION_FAILED", `Malformed s_${share.slot} scalar`, share.slot);
142
+ }
143
+ const deltaRerand = vectorOverride ?? deriveGrothShoupRerandScalar({
144
+ presigId32: publicVerification.presigId32,
145
+ subset: publicVerification.subset,
146
+ rPointComp33: publicVerification.rPointComp33,
147
+ childPublicKeyComp33: derivedChild.childPublicKeyComp33,
148
+ msgDigest32,
149
+ tweakScalar: derivedChild.tweakScalar
150
+ });
151
+ const rPoint = require_secp256k1_scalar.decodePointCompressed(publicVerification.rPointComp33, false);
152
+ const rerand = computeRerandomizedNoncePoint(rPoint, deltaRerand);
153
+ const kIComp33 = publicVerification.kPointsComp33BySlot.get(share.slot);
154
+ const zIComp33 = publicVerification.zPointsComp33BySlot.get(share.slot);
155
+ if (!kIComp33 || !zIComp33) throw new require_constants.MpcProtocolError("SIGN_SHARE_VERIFICATION_FAILED", `Missing K_${share.slot} or Z_${share.slot}`, share.slot);
156
+ const kIPoint = require_secp256k1_scalar.decodePointCompressed(kIComp33, false);
157
+ const zIPoint = require_secp256k1_scalar.decodePointCompressed(zIComp33, false);
158
+ const lhs = require_secp256k1_scalar.mulPoint(rPoint, require_secp256k1_scalar.mulModN(deltaRerand, sI));
159
+ const rhs = require_secp256k1_scalar.mulPoint(kIPoint, require_secp256k1_scalar.addModN(msgScalarModN, require_secp256k1_scalar.mulModN(rerand.rPrime, derivedChild.tweakScalar))).add(require_secp256k1_scalar.mulPoint(zIPoint, rerand.rPrime));
160
+ if (!lhs.equals(rhs)) throw new require_constants.MpcProtocolError("SIGN_SHARE_VERIFICATION_FAILED", `Identifiable abort: corrupted partial signature s_${share.slot}`, share.slot);
161
+ return rerand;
162
+ }
163
+ /**
164
+ * Verifies all `t` partial signature shares, aggregates `s_raw = \sum_{i \in S} s_i mod n`,
165
+ * enforces EIP-2 low-S (`s_sig <= n / 2`, toggling `yParity ^= 1` when negated), and self-verifies
166
+ * `ecrecover(z, r', s_sig, yParity) === P_child`.
167
+ */
168
+ function aggregateOnlineSignature(params) {
169
+ const { shares, publicVerification, request } = params;
170
+ const vectorOverride = params[VECTOR_TEST_DELTA_RERAND_SYMBOL];
171
+ const { msgDigest32, derivedChild } = validateRequestAgainstPublicPresig(request, publicVerification);
172
+ const pChild = derivedChild.childPoint;
173
+ const sorted = require_secp256k1_scalar.normalizeSortedSubset(publicVerification.subset);
174
+ if (shares.length !== sorted.length) throw new require_constants.MpcProtocolError("SIGN_AGGREGATION_FAILED", `Expected ${sorted.length} partial shares, got ${shares.length}`);
175
+ const seenSlots = /* @__PURE__ */ new Set();
176
+ let sRaw = 0n;
177
+ let rerand = null;
178
+ for (const share of shares) {
179
+ if (seenSlots.has(share.slot)) throw new require_constants.MpcProtocolError("SIGN_AGGREGATION_FAILED", `Duplicate sign share from slot ${share.slot}`, share.slot);
180
+ seenSlots.add(share.slot);
181
+ rerand = verifyOnlineSignShare({
182
+ share,
183
+ publicVerification,
184
+ request,
185
+ [VECTOR_TEST_DELTA_RERAND_SYMBOL]: vectorOverride
186
+ });
187
+ sRaw = require_secp256k1_scalar.addModN(sRaw, require_secp256k1_scalar.bytes32ToScalarStrict(share.sShareBytes32));
188
+ }
189
+ if (sRaw === 0n || !rerand) throw new require_constants.MpcProtocolError("SIGN_AGGREGATION_FAILED", "Aggregated s_raw == 0");
190
+ let sSig = sRaw;
191
+ let yParity = rerand.yPrimeParity;
192
+ if (sRaw > require_constants.SECP256K1_HALF_N) {
193
+ sSig = require_secp256k1_scalar.subModN(0n, sRaw);
194
+ yParity = yParity ^ 1;
195
+ }
196
+ const v = 27 + yParity;
197
+ const expectedAddr = require_tweak.pointToEthAddress(pChild);
198
+ const recovered = require_tweak.ecrecoverEthAddress({
199
+ msgDigest32,
200
+ r: rerand.rPrime,
201
+ s: sSig,
202
+ yParity
203
+ });
204
+ if (!recovered.recoveredPoint.equals(pChild) || recovered.checksumAddress !== expectedAddr.checksumAddress) throw new require_constants.MpcProtocolError("SIGN_AGGREGATION_FAILED", "Internal invariant violation: ecrecover mismatch against P_child");
205
+ const rBytes32 = require_secp256k1_scalar.scalarToBytes32(rerand.rPrime);
206
+ const sBytes32 = require_secp256k1_scalar.scalarToBytes32(sSig);
207
+ const signature65Bytes = require_secp256k1_scalar.concatBytes(rBytes32, sBytes32, Uint8Array.of(v));
208
+ return {
209
+ r: rerand.rPrime,
210
+ s: sSig,
211
+ rBytes32,
212
+ sBytes32,
213
+ rHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(rBytes32)}`,
214
+ sHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(sBytes32)}`,
215
+ yParity,
216
+ v,
217
+ signature65Bytes,
218
+ signature65Hex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(signature65Bytes)}`,
219
+ deltaRerand: rerand.deltaRerand,
220
+ rPrimePointComp33: rerand.rPrimePointComp33,
221
+ signerAddress: expectedAddr.checksumAddress
222
+ };
223
+ }
224
+
225
+ //#endregion
226
+ exports.VECTOR_TEST_DELTA_RERAND_SYMBOL = VECTOR_TEST_DELTA_RERAND_SYMBOL;
227
+ exports.aggregateOnlineSignature = aggregateOnlineSignature;
228
+ exports.computeRerandomizedNoncePoint = computeRerandomizedNoncePoint;
229
+ exports.createOnlineSignShare = createOnlineSignShare;
230
+ exports.deriveGrothShoupRerandScalar = deriveGrothShoupRerandScalar;
231
+ exports.evaluateConsumedPresigShareWithRerand = evaluateConsumedPresigShareWithRerand;
232
+ exports.verifyAndDeriveRequestChildKey = verifyAndDeriveRequestChildKey;
233
+ exports.verifyOnlineSignShare = verifyOnlineSignShare;
package/lib/sign.d.cts ADDED
@@ -0,0 +1,113 @@
1
+ import { Secp256k1Point } from "./secp256k1-scalar.cjs";
2
+ import { DerivedChildKey, MpcChildDerivationSpec } from "./tweak.cjs";
3
+ import { PresignaturePublicVerification, PresignatureShareRecord, VolatilePresignaturePool } from "./presign.cjs";
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 };
package/lib/tweak.cjs ADDED
@@ -0,0 +1,178 @@
1
+ const require_constants = require('./constants.cjs');
2
+ const require_secp256k1_scalar = require('./secp256k1-scalar.cjs');
3
+ let _noble_hashes_sha3_js = require("@noble/hashes/sha3.js");
4
+ let _noble_hashes_utils_js = require("@noble/hashes/utils.js");
5
+ let _noble_curves_secp256k1_js = require("@noble/curves/secp256k1.js");
6
+
7
+ //#region src/tweak.ts
8
+ const ETH_ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
9
+ function toEip55ChecksumAddress(lowerHexWithoutPrefix) {
10
+ if (!/^[0-9a-f]{40}$/.test(lowerHexWithoutPrefix)) throw new require_constants.MpcProtocolError("INVALID_ETH_ADDRESS", "Expected 40 lowercase hex chars");
11
+ const digestHex = (0, _noble_hashes_utils_js.bytesToHex)((0, _noble_hashes_sha3_js.keccak_256)(require_secp256k1_scalar.utf8Bytes(lowerHexWithoutPrefix)));
12
+ let out = "0x";
13
+ for (let i = 0; i < 40; i++) {
14
+ const ch = lowerHexWithoutPrefix[i];
15
+ out += Number.parseInt(digestHex[i], 16) >= 8 ? ch.toUpperCase() : ch;
16
+ }
17
+ return out;
18
+ }
19
+ /**
20
+ * Validates an Ethereum `0x` address (rejects non-hex, all-uppercase, bad EIP-55 mixed-case
21
+ * checksums, and the zero address `0x0000...0000`) and returns canonical EIP-55 + lowercase forms.
22
+ */
23
+ function parseStrictEthAddress(address) {
24
+ if (typeof address !== "string" || !ETH_ADDRESS_RE.test(address)) throw new require_constants.MpcProtocolError("INVALID_ETH_ADDRESS", `Invalid Ethereum address format: ${String(address)}`);
25
+ const body = address.slice(2);
26
+ const lower = body.toLowerCase();
27
+ if (/^0+$/.test(lower)) throw new require_constants.MpcProtocolError("INVALID_ETH_ADDRESS", "Zero Ethereum address is forbidden");
28
+ const hasLower = /[a-f]/.test(body);
29
+ const hasUpper = /[A-F]/.test(body);
30
+ if (hasUpper && !hasLower) throw new require_constants.MpcProtocolError("INVALID_ETH_ADDRESS", "All-uppercase Ethereum address is invalid");
31
+ const checksumAddress = toEip55ChecksumAddress(lower);
32
+ if (hasUpper && hasLower && checksumAddress !== address) throw new require_constants.MpcProtocolError("INVALID_ETH_ADDRESS", "EIP-55 checksum mismatch");
33
+ return {
34
+ checksumAddress,
35
+ lowercaseAddress: `0x${lower}`,
36
+ addressBytes20: (0, _noble_hashes_utils_js.hexToBytes)(lower)
37
+ };
38
+ }
39
+ function pointToEthAddress(pointOrComp33) {
40
+ const pt = pointOrComp33 instanceof Uint8Array ? require_secp256k1_scalar.decodePointCompressed(pointOrComp33, false) : pointOrComp33;
41
+ if (pt.is0()) throw new require_constants.MpcProtocolError("INVALID_POINT", "Cannot derive Ethereum address from infinity");
42
+ pt.assertValidity();
43
+ const addrLower = (0, _noble_hashes_utils_js.bytesToHex)((0, _noble_hashes_sha3_js.keccak_256)(pt.toBytes(false).subarray(1, 65)).subarray(12, 32));
44
+ if (/^0+$/.test(addrLower)) throw new require_constants.MpcProtocolError("INVALID_ETH_ADDRESS", "Derived Ethereum address is zero");
45
+ return {
46
+ checksumAddress: toEip55ChecksumAddress(addrLower),
47
+ lowercaseAddress: `0x${addrLower}`
48
+ };
49
+ }
50
+ function assertAllowedOnlineRole(role) {
51
+ if (typeof role !== "string" || role.trim().length === 0) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "Role must be a non-empty string");
52
+ if (role === require_constants.FORBIDDEN_ONLINE_ROLE_ESCAPE_CANARY) throw new require_constants.MpcProtocolError("FORBIDDEN_ONLINE_ROLE", `Role "${require_constants.FORBIDDEN_ONLINE_ROLE_ESCAPE_CANARY}" is hard-banned in online MPC derivation and signing`);
53
+ }
54
+ /**
55
+ * Applies a non-hardened additive scalar tweak `P_child = P_root + t_tweak * G`,
56
+ * strictly rejecting `t_tweak == 0`, `t_tweak >= n`, or `P_child == O`.
57
+ */
58
+ function applyAdditiveTweak(rootPublicKey, tweakScalar, tweakMode, derivationMeta) {
59
+ const pRoot = rootPublicKey instanceof Uint8Array ? require_secp256k1_scalar.decodePointCompressed(rootPublicKey, false) : rootPublicKey;
60
+ if (pRoot.is0()) throw new require_constants.MpcProtocolError("INVALID_POINT", "Root public key cannot be O");
61
+ if (typeof tweakScalar !== "bigint" || tweakScalar <= 0n || tweakScalar >= require_constants.SECP256K1_N) throw new require_constants.MpcProtocolError("DEGENERATE_TWEAK", "Additive tweak scalar must satisfy 1 <= t_tweak < n");
62
+ const pChild = pRoot.add(require_secp256k1_scalar.mulBaseG(tweakScalar));
63
+ if (pChild.is0()) throw new require_constants.MpcProtocolError("DEGENERATE_TWEAK", "Derived child public key collapsed to point at infinity O");
64
+ const childPublicKeyComp33 = require_secp256k1_scalar.encodePointCompressed(pChild);
65
+ const tweakBytes32 = require_secp256k1_scalar.scalarToBytes32(tweakScalar);
66
+ const { checksumAddress, lowercaseAddress } = pointToEthAddress(pChild);
67
+ const derivationSpec = derivationMeta?.kind === "role-bound" ? {
68
+ tweakMode: "role-bound",
69
+ role: derivationMeta.role,
70
+ ethChainId: derivationMeta.ethChainId,
71
+ tweakLabel: derivationMeta.tweakLabel,
72
+ childPublicKeyComp33
73
+ } : derivationMeta?.kind === "rule-bound" ? {
74
+ tweakMode: "rule-bound",
75
+ controllerDid: derivationMeta.controllerDid,
76
+ ethChainId: derivationMeta.ethChainId,
77
+ ruleHash: derivationMeta.ruleHashBytes32,
78
+ childPublicKeyComp33
79
+ } : {
80
+ tweakMode: "untweaked",
81
+ childPublicKeyComp33
82
+ };
83
+ return {
84
+ tweakMode,
85
+ tweakScalar,
86
+ tweakBytes32,
87
+ tweakHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(tweakBytes32)}`,
88
+ childPoint: pChild,
89
+ childPublicKeyComp33,
90
+ ethAddress: checksumAddress,
91
+ ethAddressLower: lowercaseAddress,
92
+ derivationSpec
93
+ };
94
+ }
95
+ function deriveUntweakedChild(rootPublicKey) {
96
+ const pRoot = rootPublicKey instanceof Uint8Array ? require_secp256k1_scalar.decodePointCompressed(rootPublicKey, false) : rootPublicKey;
97
+ if (pRoot.is0()) throw new require_constants.MpcProtocolError("INVALID_POINT", "Root public key cannot be O");
98
+ const childPublicKeyComp33 = require_secp256k1_scalar.encodePointCompressed(pRoot);
99
+ const tweakBytes32 = new Uint8Array(32);
100
+ const { checksumAddress, lowercaseAddress } = pointToEthAddress(pRoot);
101
+ return {
102
+ tweakMode: "untweaked",
103
+ tweakScalar: 0n,
104
+ tweakBytes32,
105
+ tweakHex: `0x${(0, _noble_hashes_utils_js.bytesToHex)(tweakBytes32)}`,
106
+ childPoint: pRoot,
107
+ childPublicKeyComp33,
108
+ ethAddress: checksumAddress,
109
+ ethAddressLower: lowercaseAddress,
110
+ derivationSpec: {
111
+ tweakMode: "untweaked",
112
+ childPublicKeyComp33
113
+ }
114
+ };
115
+ }
116
+ /**
117
+ * `role-bound` EOA child derivation (`design.md` §4.2):
118
+ * `t_tweak = H_scalar("ARC-MPC-CHILD-TWEAK-V1", P_root^comp33, utf8(rootId), utf8(role), u64be(ethChainId), utf8(tweakLabel))`.
119
+ */
120
+ function deriveRoleBoundChild(params) {
121
+ const { rootPublicKey, rootId, role, ethChainId, tweakLabel } = params;
122
+ if (typeof rootId !== "string" || rootId.length === 0) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "rootId must be non-empty");
123
+ assertAllowedOnlineRole(role);
124
+ if (typeof tweakLabel !== "string" || tweakLabel.length === 0) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "tweakLabel must be non-empty");
125
+ const pRoot = rootPublicKey instanceof Uint8Array ? require_secp256k1_scalar.decodePointCompressed(rootPublicKey, false) : rootPublicKey;
126
+ return applyAdditiveTweak(pRoot, require_secp256k1_scalar.H_scalar(require_constants.DST_CHILD_TWEAK_V1, require_secp256k1_scalar.encodePointCompressed(pRoot), require_secp256k1_scalar.utf8Bytes(rootId), require_secp256k1_scalar.utf8Bytes(role), require_secp256k1_scalar.u64be(ethChainId), require_secp256k1_scalar.utf8Bytes(tweakLabel)), "role-bound", {
127
+ kind: "role-bound",
128
+ role,
129
+ ethChainId,
130
+ tweakLabel
131
+ });
132
+ }
133
+ /**
134
+ * `rule-bound` EOA child derivation (`design.md` §4.2):
135
+ * `t_tweak = H_scalar("ARC-MPC-RULE-TWEAK-V1", P_root^comp33, utf8(rootId), utf8(controllerDid), u64be(ethChainId), bytes32(ruleHash))`.
136
+ */
137
+ function deriveRuleBoundChild(params) {
138
+ const { rootPublicKey, rootId, controllerDid, ethChainId, ruleHash } = params;
139
+ if (typeof rootId !== "string" || rootId.length === 0) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "rootId must be non-empty");
140
+ if (typeof controllerDid !== "string" || controllerDid.length === 0) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "controllerDid must be non-empty");
141
+ const ruleHashBytes32 = require_secp256k1_scalar.normalizeHexBytes(ruleHash, 32);
142
+ const pRoot = rootPublicKey instanceof Uint8Array ? require_secp256k1_scalar.decodePointCompressed(rootPublicKey, false) : rootPublicKey;
143
+ return applyAdditiveTweak(pRoot, require_secp256k1_scalar.H_scalar(require_constants.DST_RULE_TWEAK_V1, require_secp256k1_scalar.encodePointCompressed(pRoot), require_secp256k1_scalar.utf8Bytes(rootId), require_secp256k1_scalar.utf8Bytes(controllerDid), require_secp256k1_scalar.u64be(ethChainId), ruleHashBytes32), "rule-bound", {
144
+ kind: "rule-bound",
145
+ controllerDid,
146
+ ethChainId,
147
+ ruleHashBytes32
148
+ });
149
+ }
150
+ /**
151
+ * Recovers the EIP-55 Ethereum address from a 32-byte digest and EIP-2 low-S `(r, s, yParity)`
152
+ * signature, matching Solidity `ecrecover` and Type-2 EIP-1559 transaction recovery.
153
+ */
154
+ function ecrecoverEthAddress(params) {
155
+ const { msgDigest32, r, s, yParity } = params;
156
+ if (!(msgDigest32 instanceof Uint8Array) || msgDigest32.length !== 32) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "msgDigest32 must be 32 bytes");
157
+ if (yParity !== 0 && yParity !== 1) throw new require_constants.MpcProtocolError("INVALID_PARAMETER", "yParity must be 0 or 1");
158
+ const sig = new _noble_curves_secp256k1_js.secp256k1.Signature(r, s, yParity);
159
+ if (sig.hasHighS()) throw new require_constants.MpcProtocolError("SIGN_AGGREGATION_FAILED", "High-S signature rejected by EIP-2");
160
+ const recoveredPoint = sig.recoverPublicKey(msgDigest32);
161
+ const { checksumAddress, lowercaseAddress } = pointToEthAddress(recoveredPoint);
162
+ return {
163
+ recoveredPoint,
164
+ checksumAddress,
165
+ lowercaseAddress
166
+ };
167
+ }
168
+
169
+ //#endregion
170
+ exports.applyAdditiveTweak = applyAdditiveTweak;
171
+ exports.assertAllowedOnlineRole = assertAllowedOnlineRole;
172
+ exports.deriveRoleBoundChild = deriveRoleBoundChild;
173
+ exports.deriveRuleBoundChild = deriveRuleBoundChild;
174
+ exports.deriveUntweakedChild = deriveUntweakedChild;
175
+ exports.ecrecoverEthAddress = ecrecoverEthAddress;
176
+ exports.parseStrictEthAddress = parseStrictEthAddress;
177
+ exports.pointToEthAddress = pointToEthAddress;
178
+ exports.toEip55ChecksumAddress = toEip55ChecksumAddress;
@@ -0,0 +1,100 @@
1
+ import { Secp256k1Point } from "./secp256k1-scalar.cjs";
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 };