@ocap/mpc-hsm 1.33.6 → 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.
- package/esm/bip39-english-wordlist.d.mts +11 -0
- package/esm/bip39-english-wordlist.mjs +31 -0
- package/esm/constants.d.mts +66 -2
- package/esm/constants.mjs +65 -1
- package/esm/dkg.mjs +2 -2
- package/esm/index.d.mts +11 -3
- package/esm/index.mjs +11 -3
- package/esm/ocap-clear-signing.d.mts +125 -0
- package/esm/ocap-clear-signing.mjs +1170 -0
- package/esm/offline-ceremony.d.mts +127 -0
- package/esm/offline-ceremony.mjs +481 -0
- package/esm/ot.d.mts +7 -1
- package/esm/ot.mjs +149 -16
- package/esm/personal-vault.d.mts +1292 -0
- package/esm/personal-vault.mjs +3615 -0
- package/esm/personal.d.mts +10 -0
- package/esm/personal.mjs +11 -0
- package/esm/presign.mjs +1 -1
- package/esm/rlp-eip1559.d.mts +75 -0
- package/esm/rlp-eip1559.mjs +293 -0
- package/esm/secp256k1-scalar.d.mts +1 -1
- package/esm/secp256k1-scalar.mjs +14 -5
- package/esm/steel-mnemonic.d.mts +55 -0
- package/esm/steel-mnemonic.mjs +247 -0
- package/esm/ves-backup.d.mts +296 -0
- package/esm/ves-backup.mjs +1025 -0
- package/esm/x402-agent-guard.d.mts +111 -0
- package/esm/x402-agent-guard.mjs +780 -0
- package/lib/bip39-english-wordlist.cjs +33 -0
- package/lib/bip39-english-wordlist.d.cts +11 -0
- package/lib/constants.cjs +128 -0
- package/lib/constants.d.cts +66 -2
- package/lib/dkg.cjs +2 -2
- package/lib/index.cjs +249 -0
- package/lib/index.d.cts +11 -3
- package/lib/ocap-clear-signing.cjs +1176 -0
- package/lib/ocap-clear-signing.d.cts +125 -0
- package/lib/offline-ceremony.cjs +487 -0
- package/lib/offline-ceremony.d.cts +127 -0
- package/lib/ot.cjs +150 -15
- package/lib/ot.d.cts +7 -1
- package/lib/personal-vault.cjs +3725 -0
- package/lib/personal-vault.d.cts +1292 -0
- package/lib/personal.cjs +338 -0
- package/lib/personal.d.cts +10 -0
- package/lib/presign.cjs +1 -1
- package/lib/rlp-eip1559.cjs +303 -0
- package/lib/rlp-eip1559.d.cts +75 -0
- package/lib/secp256k1-scalar.cjs +14 -5
- package/lib/steel-mnemonic.cjs +253 -0
- package/lib/steel-mnemonic.d.cts +55 -0
- package/lib/ves-backup.cjs +1053 -0
- package/lib/ves-backup.d.cts +296 -0
- package/lib/x402-agent-guard.cjs +788 -0
- package/lib/x402-agent-guard.d.cts +111 -0
- package/package.json +6 -1
|
@@ -0,0 +1,1025 @@
|
|
|
1
|
+
import { BSGS_M, DST_CANARY_CHALLENGE_V1, DST_CANARY_SHARD_POK_V1, DST_VES_BIT_OR_V1, DST_VES_CHUNK_LIN_V1, MAX_MPC_CLUSTER_NODES, MAX_RECOVERY_PACKAGE_BYTES, MPC_PROTOCOL_VERSION, MpcProtocolError, SECP256K1_N } from "./constants.mjs";
|
|
2
|
+
import { H_scalar, SECP256K1_G, SECP256K1_ZERO, addModN, bytes32ToScalarNonZero, bytes32ToScalarStrict, bytesToBigIntBE, bytesToHex, concatBytes, constantTimeEqual, createSchnorrPokInBase, decodePointCompressed, defaultRandomBytes, encodePointCompressed, evaluateFeldmanCommitments, hashTranscriptSha256, lengthPrefixedEncode, modN, mulBaseG, mulModN, mulPoint, normalizeHexBytes, sampleScalarNonZero, scalarToBytes32, u16be, u32be, u64be, u8, utf8Bytes, verifySchnorrPokInBase, zeroizeBytes } from "./secp256k1-scalar.mjs";
|
|
3
|
+
import { parseStrictEthAddress, pointToEthAddress } from "./tweak.mjs";
|
|
4
|
+
import { validateAndComputeDkgContext } from "./dkg.mjs";
|
|
5
|
+
import { guardianIndexToPlateLabel } from "./steel-mnemonic.mjs";
|
|
6
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
7
|
+
|
|
8
|
+
//#region src/ves-backup.ts
|
|
9
|
+
/**
|
|
10
|
+
* Direct Bit-ElGamal Verifiable Encrypted Secret Sharing (`design.md` §5.1):
|
|
11
|
+
* - Zero `PEDERSEN_H` blinding variable: every cold share bit `bit_{i,k,m,b} in {0, 1}` is encrypted
|
|
12
|
+
* directly under Guardian `k`'s secp256k1 public key `EK_k = sk_k * G`:
|
|
13
|
+
* `R_{i,k,m,b} = u * G`, `S_{i,k,m,b} = bit * G + u * EK_k`
|
|
14
|
+
* with a Cramer-Damgard-Schoenmakers (CDS) 1-of-2 Chaum-Pedersen DLEQ OR-proof (`e0 ^ e1 == e_128`).
|
|
15
|
+
* - Homomorphic 16-bit chunk derivation:
|
|
16
|
+
* `R^{(chunk)}_{i,k,m} = \sum_{b=0}^{15} 2^b R_{i,k,m,b}`,
|
|
17
|
+
* `S^{(chunk)}_{i,k,m} = \sum_{b=0}^{15} 2^b S_{i,k,m,b}`
|
|
18
|
+
* plus a single Chaum-Pedersen linear DLEQ proof `\pi^{lin}_{i,k}` proving `(R^{tot}_{i,k}, S^{tot}_{i,k} - G_{i,k})`
|
|
19
|
+
* has equal discrete log across `(G, EK_k)`, where `G_{i,k} = \sum_{l=0}^{t_c-1} k^l C_{i,l}`.
|
|
20
|
+
* - Unconditional BSGS (`M = 680`, `680^2 = 462,400 > 7 * 65535 = 458,745`) decoding of aggregated
|
|
21
|
+
* guardian chunks `[0, nParties * 65535]`, exact multi-limb integer sum reduced `mod n`, and
|
|
22
|
+
* verification against `Y_k` before zeroizing `sk_k`.
|
|
23
|
+
*/
|
|
24
|
+
const VES_DEALER_MAGIC = utf8Bytes("ARCVESD2");
|
|
25
|
+
const VES_PACKAGE_MAGIC = utf8Bytes("ARCVESP2");
|
|
26
|
+
const VES_CHUNKS_PER_SHARE = 16;
|
|
27
|
+
const VES_BITS_PER_CHUNK = 16;
|
|
28
|
+
const VES_BITS_PER_SHARE = 256;
|
|
29
|
+
const VES_MAX_LIMB_VALUE = 65535;
|
|
30
|
+
const VES_MAX_SUMMED_LIMB = MAX_MPC_CLUSTER_NODES * VES_MAX_LIMB_VALUE;
|
|
31
|
+
const VES_BIT_RECORD_BYTES = 162;
|
|
32
|
+
const VES_LINEAR_DLEQ_BYTES = 98;
|
|
33
|
+
const VES_GUARDIAN_BUNDLE_BYTES = 2 + VES_BITS_PER_SHARE * VES_BIT_RECORD_BYTES + VES_LINEAR_DLEQ_BYTES;
|
|
34
|
+
let cachedBsgsBabyStepTable = null;
|
|
35
|
+
const MAX_VERIFIED_DEALER_CACHE_SIZE = 256;
|
|
36
|
+
const verifiedDealerContributionDigests = /* @__PURE__ */ new Set();
|
|
37
|
+
function computeVerifiedDealerCacheKey(params) {
|
|
38
|
+
return bytesToHex(sha256(lengthPrefixedEncode("ARC-MPC-VES-VERIFIED-DEALER-CACHE-V1", [
|
|
39
|
+
params.ctxDkg32,
|
|
40
|
+
u16be(params.dealerSlot),
|
|
41
|
+
u16be(params.coldCommitmentsComp33.length),
|
|
42
|
+
...params.coldCommitmentsComp33,
|
|
43
|
+
u16be(params.guardianPublicKeysComp33.length),
|
|
44
|
+
...params.guardianPublicKeysComp33,
|
|
45
|
+
params.payload
|
|
46
|
+
])));
|
|
47
|
+
}
|
|
48
|
+
function recordVerifiedDealerCacheKey(cacheKey) {
|
|
49
|
+
if (verifiedDealerContributionDigests.size >= MAX_VERIFIED_DEALER_CACHE_SIZE) {
|
|
50
|
+
const oldest = verifiedDealerContributionDigests.values().next().value;
|
|
51
|
+
if (oldest !== void 0) verifiedDealerContributionDigests.delete(oldest);
|
|
52
|
+
}
|
|
53
|
+
verifiedDealerContributionDigests.add(cacheKey);
|
|
54
|
+
}
|
|
55
|
+
function getBsgsBabyStepTable() {
|
|
56
|
+
if (cachedBsgsBabyStepTable) return cachedBsgsBabyStepTable;
|
|
57
|
+
const map = /* @__PURE__ */ new Map();
|
|
58
|
+
map.set("00", 0);
|
|
59
|
+
let acc = SECP256K1_ZERO;
|
|
60
|
+
for (let r = 1; r < BSGS_M; r++) {
|
|
61
|
+
acc = acc.add(SECP256K1_G);
|
|
62
|
+
map.set(bytesToHex(encodePointCompressed(acc)), r);
|
|
63
|
+
}
|
|
64
|
+
cachedBsgsBabyStepTable = {
|
|
65
|
+
babyMap: map,
|
|
66
|
+
minusMG: acc.add(SECP256K1_G).negate()
|
|
67
|
+
};
|
|
68
|
+
return cachedBsgsBabyStepTable;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Solves `targetPoint == v * G` for `0 <= v <= maxBound` using Baby-Step Giant-Step (`M = 680`).
|
|
72
|
+
*/
|
|
73
|
+
function solveDiscreteLogBsgs(targetPoint, maxBound = VES_MAX_SUMMED_LIMB) {
|
|
74
|
+
if (!Number.isInteger(maxBound) || maxBound < 0 || maxBound >= BSGS_M * BSGS_M) throw new MpcProtocolError("INVALID_PARAMETER", `maxBound ${maxBound} exceeds BSGS capacity ${BSGS_M * BSGS_M - 1}`);
|
|
75
|
+
const { babyMap, minusMG } = getBsgsBabyStepTable();
|
|
76
|
+
let gamma = targetPoint;
|
|
77
|
+
for (let q = 0; q < BSGS_M; q++) {
|
|
78
|
+
const key = gamma.is0() ? "00" : bytesToHex(encodePointCompressed(gamma));
|
|
79
|
+
const r = babyMap.get(key);
|
|
80
|
+
if (r !== void 0) {
|
|
81
|
+
const value = q * BSGS_M + r;
|
|
82
|
+
if (value > maxBound) throw new MpcProtocolError("VES_BSGS_DECODE_FAILED", `Decoded BSGS limb ${value} exceeds allowed upper bound ${maxBound}`);
|
|
83
|
+
return value;
|
|
84
|
+
}
|
|
85
|
+
gamma = gamma.add(minusMG);
|
|
86
|
+
}
|
|
87
|
+
throw new MpcProtocolError("VES_BSGS_DECODE_FAILED", `BSGS failed to locate discrete log within [0, ${maxBound}]`);
|
|
88
|
+
}
|
|
89
|
+
function createBitElGamalWithCdsProof(params) {
|
|
90
|
+
const { ctxDkg32, dealerSlot, guardianIndex, chunkIndex, bitIndex, bitValue, ekPoint, ekComp33, rng } = params;
|
|
91
|
+
for (;;) {
|
|
92
|
+
const uScalar = sampleScalarNonZero(rng);
|
|
93
|
+
const rPoint = mulBaseG(uScalar);
|
|
94
|
+
const uEk = mulPoint(ekPoint, uScalar);
|
|
95
|
+
const sPoint = bitValue === 1 ? SECP256K1_G.add(uEk) : uEk;
|
|
96
|
+
if (rPoint.is0() || sPoint.is0()) continue;
|
|
97
|
+
const rComp33 = encodePointCompressed(rPoint);
|
|
98
|
+
const sComp33 = encodePointCompressed(sPoint);
|
|
99
|
+
const kReal = sampleScalarNonZero(rng);
|
|
100
|
+
const aReal = mulBaseG(kReal);
|
|
101
|
+
const bReal = mulPoint(ekPoint, kReal);
|
|
102
|
+
if (aReal.is0() || bReal.is0()) continue;
|
|
103
|
+
const eSim16 = rng(16);
|
|
104
|
+
if (eSim16.length !== 16) {
|
|
105
|
+
zeroizeBytes(eSim16);
|
|
106
|
+
throw new MpcProtocolError("INVALID_PARAMETER", "RNG must return 16 bytes for CDS challenge share");
|
|
107
|
+
}
|
|
108
|
+
const eSimScalar = bytesToBigIntBE(eSim16);
|
|
109
|
+
const zSim = sampleScalarNonZero(rng);
|
|
110
|
+
const ySim = bitValue === 0 ? sPoint.add(SECP256K1_G.negate()) : sPoint;
|
|
111
|
+
const aSim = mulBaseG(zSim).add(mulPoint(rPoint, eSimScalar).negate());
|
|
112
|
+
const bSim = mulPoint(ekPoint, zSim).add(mulPoint(ySim, eSimScalar).negate());
|
|
113
|
+
if (aSim.is0() || bSim.is0()) {
|
|
114
|
+
zeroizeBytes(eSim16);
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
const a0Comp33 = encodePointCompressed(bitValue === 0 ? aReal : aSim);
|
|
118
|
+
const b0Comp33 = encodePointCompressed(bitValue === 0 ? bReal : bSim);
|
|
119
|
+
const a1Comp33 = encodePointCompressed(bitValue === 0 ? aSim : aReal);
|
|
120
|
+
const b1Comp33 = encodePointCompressed(bitValue === 0 ? bSim : bReal);
|
|
121
|
+
const eFull32 = hashTranscriptSha256(DST_VES_BIT_OR_V1, ctxDkg32, u16be(dealerSlot), u16be(guardianIndex), u8(chunkIndex), u8(bitIndex), ekComp33, rComp33, sComp33, a0Comp33, b0Comp33, a1Comp33, b1Comp33);
|
|
122
|
+
const eReal16 = new Uint8Array(16);
|
|
123
|
+
for (let j = 0; j < 16; j++) eReal16[j] = eFull32[j] ^ eSim16[j];
|
|
124
|
+
const zReal = addModN(kReal, mulModN(bytesToBigIntBE(eReal16), uScalar));
|
|
125
|
+
const e0Bytes16 = bitValue === 0 ? eReal16 : eSim16;
|
|
126
|
+
const e1Bytes16 = bitValue === 0 ? eSim16 : eReal16;
|
|
127
|
+
const z0Bytes32 = scalarToBytes32(bitValue === 0 ? zReal : zSim);
|
|
128
|
+
const z1Bytes32 = scalarToBytes32(bitValue === 0 ? zSim : zReal);
|
|
129
|
+
const encodedRecord162 = new Uint8Array(VES_BIT_RECORD_BYTES);
|
|
130
|
+
encodedRecord162.set(rComp33, 0);
|
|
131
|
+
encodedRecord162.set(sComp33, 33);
|
|
132
|
+
encodedRecord162.set(e0Bytes16, 66);
|
|
133
|
+
encodedRecord162.set(e1Bytes16, 82);
|
|
134
|
+
encodedRecord162.set(z0Bytes32, 98);
|
|
135
|
+
encodedRecord162.set(z1Bytes32, 130);
|
|
136
|
+
return {
|
|
137
|
+
uScalar,
|
|
138
|
+
rPoint,
|
|
139
|
+
sPoint,
|
|
140
|
+
encodedRecord162
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
function verifyAndDecodeBitRecord(params) {
|
|
145
|
+
const { ctxDkg32, dealerSlot, guardianIndex, chunkIndex, bitIndex, ekPoint, ekComp33, record162, verifyProof } = params;
|
|
146
|
+
const rComp33 = record162.subarray(0, 33);
|
|
147
|
+
const sComp33 = record162.subarray(33, 66);
|
|
148
|
+
const rPoint = decodePointCompressed(rComp33, false);
|
|
149
|
+
const sPoint = decodePointCompressed(sComp33, false);
|
|
150
|
+
if (!verifyProof) return {
|
|
151
|
+
rPoint,
|
|
152
|
+
sPoint
|
|
153
|
+
};
|
|
154
|
+
const e0Bytes16 = record162.subarray(66, 82);
|
|
155
|
+
const e1Bytes16 = record162.subarray(82, 98);
|
|
156
|
+
const z0 = bytes32ToScalarStrict(record162.subarray(98, 130));
|
|
157
|
+
const z1 = bytes32ToScalarStrict(record162.subarray(130, 162));
|
|
158
|
+
const e0Scalar = bytesToBigIntBE(e0Bytes16);
|
|
159
|
+
const e1Scalar = bytesToBigIntBE(e1Bytes16);
|
|
160
|
+
const a0 = SECP256K1_G.multiplyUnsafe(z0).subtract(rPoint.multiplyUnsafe(e0Scalar));
|
|
161
|
+
const b0 = ekPoint.multiplyUnsafe(z0).subtract(sPoint.multiplyUnsafe(e0Scalar));
|
|
162
|
+
if (a0.is0() || b0.is0()) throw new MpcProtocolError("VES_BIT_PROOF_INVALID", "Degenerate branch-0 point in CDS bit OR-proof", dealerSlot);
|
|
163
|
+
const sMinusG = sPoint.subtract(SECP256K1_G);
|
|
164
|
+
const a1 = SECP256K1_G.multiplyUnsafe(z1).subtract(rPoint.multiplyUnsafe(e1Scalar));
|
|
165
|
+
const b1 = ekPoint.multiplyUnsafe(z1).subtract(sMinusG.multiplyUnsafe(e1Scalar));
|
|
166
|
+
if (a1.is0() || b1.is0()) throw new MpcProtocolError("VES_BIT_PROOF_INVALID", "Degenerate branch-1 point in CDS bit OR-proof", dealerSlot);
|
|
167
|
+
const eExpected32 = hashTranscriptSha256(DST_VES_BIT_OR_V1, ctxDkg32, u16be(dealerSlot), u16be(guardianIndex), u8(chunkIndex), u8(bitIndex), ekComp33, rComp33, sComp33, a0.toBytes(true), b0.toBytes(true), a1.toBytes(true), b1.toBytes(true));
|
|
168
|
+
const xor16 = new Uint8Array(16);
|
|
169
|
+
for (let j = 0; j < 16; j++) xor16[j] = e0Bytes16[j] ^ e1Bytes16[j];
|
|
170
|
+
if (!constantTimeEqual(xor16, eExpected32.subarray(0, 16))) throw new MpcProtocolError("VES_BIT_PROOF_INVALID", `CDS 1-of-2 bit OR-proof failed for dealer ${dealerSlot}, guardian ${guardianIndex}, chunk ${chunkIndex}, bit ${bitIndex}`, dealerSlot);
|
|
171
|
+
return {
|
|
172
|
+
rPoint,
|
|
173
|
+
sPoint
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
function createGuardianLinearDleqProof(params) {
|
|
177
|
+
const { ctxDkg32, dealerSlot, guardianIndex, coldCommitmentsComp33, ekPoint, ekComp33, gIkPoint, rTotPoint, dIkPoint, uTotScalar, rng } = params;
|
|
178
|
+
if (gIkPoint.is0() || rTotPoint.is0() || dIkPoint.is0()) throw new MpcProtocolError("VES_LINEAR_PROOF_INVALID", "Linear DLEQ statement point cannot be O", dealerSlot);
|
|
179
|
+
const wNonce = sampleScalarNonZero(rng);
|
|
180
|
+
const a1Comp33 = encodePointCompressed(mulBaseG(wNonce));
|
|
181
|
+
const a2Comp33 = encodePointCompressed(mulPoint(ekPoint, wNonce));
|
|
182
|
+
const gIkComp33 = encodePointCompressed(gIkPoint);
|
|
183
|
+
const rTotComp33 = encodePointCompressed(rTotPoint);
|
|
184
|
+
const dIkComp33 = encodePointCompressed(dIkPoint);
|
|
185
|
+
const zScalar = addModN(wNonce, mulModN(H_scalar(DST_VES_CHUNK_LIN_V1, ctxDkg32, u16be(dealerSlot), u16be(guardianIndex), ...coldCommitmentsComp33, ekComp33, gIkComp33, rTotComp33, dIkComp33, a1Comp33, a2Comp33), uTotScalar));
|
|
186
|
+
const out = new Uint8Array(VES_LINEAR_DLEQ_BYTES);
|
|
187
|
+
out.set(a1Comp33, 0);
|
|
188
|
+
out.set(a2Comp33, 33);
|
|
189
|
+
out.set(scalarToBytes32(zScalar), 66);
|
|
190
|
+
return out;
|
|
191
|
+
}
|
|
192
|
+
function verifyGuardianLinearDleqProof(params) {
|
|
193
|
+
const { ctxDkg32, dealerSlot, guardianIndex, coldCommitmentsComp33, ekPoint, ekComp33, gIkPoint, rTotPoint, dIkPoint, proof98 } = params;
|
|
194
|
+
if (gIkPoint.is0() || rTotPoint.is0() || dIkPoint.is0()) throw new MpcProtocolError("VES_LINEAR_PROOF_INVALID", "Degenerate linear DLEQ statement point", dealerSlot);
|
|
195
|
+
const a1Comp33 = proof98.subarray(0, 33);
|
|
196
|
+
const a2Comp33 = proof98.subarray(33, 66);
|
|
197
|
+
const a1 = decodePointCompressed(a1Comp33, false);
|
|
198
|
+
const a2 = decodePointCompressed(a2Comp33, false);
|
|
199
|
+
const zScalar = bytes32ToScalarStrict(proof98.subarray(66, 98));
|
|
200
|
+
const challenge = H_scalar(DST_VES_CHUNK_LIN_V1, ctxDkg32, u16be(dealerSlot), u16be(guardianIndex), ...coldCommitmentsComp33, ekComp33, encodePointCompressed(gIkPoint), encodePointCompressed(rTotPoint), encodePointCompressed(dIkPoint), a1Comp33, a2Comp33);
|
|
201
|
+
const lhs1 = mulBaseG(zScalar);
|
|
202
|
+
const rhs1 = a1.add(mulPoint(rTotPoint, challenge));
|
|
203
|
+
if (!lhs1.equals(rhs1)) throw new MpcProtocolError("VES_LINEAR_PROOF_INVALID", `Linear DLEQ base-G check failed for dealer ${dealerSlot}, guardian ${guardianIndex}`, dealerSlot);
|
|
204
|
+
const lhs2 = mulPoint(ekPoint, zScalar);
|
|
205
|
+
const rhs2 = a2.add(mulPoint(dIkPoint, challenge));
|
|
206
|
+
if (!lhs2.equals(rhs2)) throw new MpcProtocolError("VES_LINEAR_PROOF_INVALID", `Linear DLEQ base-EK check failed for dealer ${dealerSlot}, guardian ${guardianIndex}`, dealerSlot);
|
|
207
|
+
}
|
|
208
|
+
function parseDealerVesPayload(payload) {
|
|
209
|
+
if (!(payload instanceof Uint8Array) || payload.length < 14) throw new MpcProtocolError("VES_INVALID_PAYLOAD", "Dealer VES payload truncated");
|
|
210
|
+
if (!constantTimeEqual(payload.subarray(0, 8), VES_DEALER_MAGIC)) throw new MpcProtocolError("VES_INVALID_PAYLOAD", "Invalid dealer VES magic header");
|
|
211
|
+
const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
|
|
212
|
+
const dealerSlot = view.getUint16(8, false);
|
|
213
|
+
const tCold = view.getUint16(10, false);
|
|
214
|
+
const nCold = view.getUint16(12, false);
|
|
215
|
+
if (dealerSlot < 1 || dealerSlot > MAX_MPC_CLUSTER_NODES || tCold < 1 || tCold > nCold || nCold > MAX_MPC_CLUSTER_NODES) throw new MpcProtocolError("VES_INVALID_PAYLOAD", "Out-of-bounds dealer VES header fields", dealerSlot);
|
|
216
|
+
const expectedLen = 14 + tCold * 33 + nCold * VES_GUARDIAN_BUNDLE_BYTES;
|
|
217
|
+
if (payload.length !== expectedLen) throw new MpcProtocolError("VES_INVALID_PAYLOAD", `Dealer VES payload size mismatch: expected ${expectedLen}, got ${payload.length}`, dealerSlot);
|
|
218
|
+
let offset = 14;
|
|
219
|
+
const coldCommitmentsComp33 = [];
|
|
220
|
+
for (let l = 0; l < tCold; l++) {
|
|
221
|
+
coldCommitmentsComp33.push(payload.subarray(offset, offset + 33));
|
|
222
|
+
offset += 33;
|
|
223
|
+
}
|
|
224
|
+
const guardianBundles = [];
|
|
225
|
+
for (let k = 1; k <= nCold; k++) {
|
|
226
|
+
const rawBundleBytes = payload.subarray(offset, offset + VES_GUARDIAN_BUNDLE_BYTES);
|
|
227
|
+
const bundleGuardianIdx = new DataView(rawBundleBytes.buffer, rawBundleBytes.byteOffset, rawBundleBytes.byteLength).getUint16(0, false);
|
|
228
|
+
if (bundleGuardianIdx !== k) throw new MpcProtocolError("VES_INVALID_PAYLOAD", `Guardian bundle index mismatch: expected ${k}, got ${bundleGuardianIdx}`, dealerSlot);
|
|
229
|
+
guardianBundles.push({
|
|
230
|
+
guardianIndex: k,
|
|
231
|
+
rawBundleBytes
|
|
232
|
+
});
|
|
233
|
+
offset += VES_GUARDIAN_BUNDLE_BYTES;
|
|
234
|
+
}
|
|
235
|
+
return {
|
|
236
|
+
dealerSlot,
|
|
237
|
+
tCold,
|
|
238
|
+
nCold,
|
|
239
|
+
coldCommitmentsComp33,
|
|
240
|
+
guardianBundles
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
function decodeAndOptionallyVerifyGuardianBundle(params) {
|
|
244
|
+
const { ctxDkg32, dealerSlot, guardianIndex, coldCommitmentsComp33, coldPoints, ekPoint, ekComp33, rawBundleBytes, verifyProofs } = params;
|
|
245
|
+
const chunkR = new Array(VES_CHUNKS_PER_SHARE);
|
|
246
|
+
const chunkS = new Array(VES_CHUNKS_PER_SHARE);
|
|
247
|
+
let pos = 2;
|
|
248
|
+
for (let m = 0; m < VES_CHUNKS_PER_SHARE; m++) {
|
|
249
|
+
const rBits = new Array(VES_BITS_PER_CHUNK);
|
|
250
|
+
const sBits = new Array(VES_BITS_PER_CHUNK);
|
|
251
|
+
for (let b = 0; b < VES_BITS_PER_CHUNK; b++) {
|
|
252
|
+
const rec = rawBundleBytes.subarray(pos, pos + VES_BIT_RECORD_BYTES);
|
|
253
|
+
pos += VES_BIT_RECORD_BYTES;
|
|
254
|
+
const { rPoint, sPoint } = verifyAndDecodeBitRecord({
|
|
255
|
+
ctxDkg32,
|
|
256
|
+
dealerSlot,
|
|
257
|
+
guardianIndex,
|
|
258
|
+
chunkIndex: m,
|
|
259
|
+
bitIndex: b,
|
|
260
|
+
ekPoint,
|
|
261
|
+
ekComp33,
|
|
262
|
+
record162: rec,
|
|
263
|
+
verifyProof: verifyProofs
|
|
264
|
+
});
|
|
265
|
+
rBits[b] = rPoint;
|
|
266
|
+
sBits[b] = sPoint;
|
|
267
|
+
}
|
|
268
|
+
let rChunk = SECP256K1_ZERO;
|
|
269
|
+
let sChunk = SECP256K1_ZERO;
|
|
270
|
+
for (let b = VES_BITS_PER_CHUNK - 1; b >= 0; b--) {
|
|
271
|
+
rChunk = rChunk.double().add(rBits[b]);
|
|
272
|
+
sChunk = sChunk.double().add(sBits[b]);
|
|
273
|
+
}
|
|
274
|
+
chunkR[m] = rChunk;
|
|
275
|
+
chunkS[m] = sChunk;
|
|
276
|
+
}
|
|
277
|
+
if (verifyProofs) {
|
|
278
|
+
let rTot = SECP256K1_ZERO;
|
|
279
|
+
let sTot = SECP256K1_ZERO;
|
|
280
|
+
for (let m = VES_CHUNKS_PER_SHARE - 1; m >= 0; m--) {
|
|
281
|
+
for (let d = 0; d < 16; d++) {
|
|
282
|
+
rTot = rTot.double();
|
|
283
|
+
sTot = sTot.double();
|
|
284
|
+
}
|
|
285
|
+
rTot = rTot.add(chunkR[m]);
|
|
286
|
+
sTot = sTot.add(chunkS[m]);
|
|
287
|
+
}
|
|
288
|
+
const gIkPoint = evaluateFeldmanCommitments(coldPoints, guardianIndex);
|
|
289
|
+
const dIkPoint = sTot.add(gIkPoint.negate());
|
|
290
|
+
const proof98 = rawBundleBytes.subarray(pos, pos + VES_LINEAR_DLEQ_BYTES);
|
|
291
|
+
verifyGuardianLinearDleqProof({
|
|
292
|
+
ctxDkg32,
|
|
293
|
+
dealerSlot,
|
|
294
|
+
guardianIndex,
|
|
295
|
+
coldCommitmentsComp33,
|
|
296
|
+
ekPoint,
|
|
297
|
+
ekComp33,
|
|
298
|
+
gIkPoint,
|
|
299
|
+
rTotPoint: rTot,
|
|
300
|
+
dIkPoint,
|
|
301
|
+
proof98
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
return {
|
|
305
|
+
chunkR,
|
|
306
|
+
chunkS
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Creates dealer `i`'s Direct Bit-ElGamal VES contribution across all `k = 1..nCold` guardians.
|
|
311
|
+
*/
|
|
312
|
+
function createNodeColdVesContribution(input, options) {
|
|
313
|
+
const rng = options?.rng ?? defaultRandomBytes;
|
|
314
|
+
const { ctxDkg32, dealerSlot, coldCommitmentsComp33, guardianPublicKeysComp33, coldEvaluationsByGuardian } = input;
|
|
315
|
+
if (!(ctxDkg32 instanceof Uint8Array) || ctxDkg32.length !== 32) throw new MpcProtocolError("VES_INVALID_PAYLOAD", "ctxDkg32 must be 32 bytes");
|
|
316
|
+
if (!Number.isInteger(dealerSlot) || dealerSlot < 1 || dealerSlot > MAX_MPC_CLUSTER_NODES) throw new MpcProtocolError("VES_INVALID_PAYLOAD", `Invalid dealerSlot ${dealerSlot}`);
|
|
317
|
+
const tCold = coldCommitmentsComp33.length;
|
|
318
|
+
const nCold = guardianPublicKeysComp33.length;
|
|
319
|
+
if (tCold < 1 || tCold > nCold || nCold > MAX_MPC_CLUSTER_NODES) throw new MpcProtocolError("VES_INVALID_PAYLOAD", `Invalid cold threshold (${tCold}-of-${nCold})`);
|
|
320
|
+
if (coldEvaluationsByGuardian.length !== nCold) throw new MpcProtocolError("VES_INVALID_PAYLOAD", "coldEvaluationsByGuardian length mismatch");
|
|
321
|
+
const coldPoints = coldCommitmentsComp33.map((b) => decodePointCompressed(b, false));
|
|
322
|
+
const guardianBundleBuffers = [];
|
|
323
|
+
for (let idx = 0; idx < nCold; idx++) {
|
|
324
|
+
const k = idx + 1;
|
|
325
|
+
const evalEntry = coldEvaluationsByGuardian[idx];
|
|
326
|
+
if (evalEntry.guardianIndex !== k || !constantTimeEqual(evalEntry.guardianPublicKeyComp33, guardianPublicKeysComp33[idx])) throw new MpcProtocolError("VES_INVALID_PAYLOAD", `Guardian evaluation entry mismatch at index ${k}`);
|
|
327
|
+
const yScalar = evalEntry.evaluationScalar;
|
|
328
|
+
if (typeof yScalar !== "bigint" || yScalar < 1n || yScalar >= SECP256K1_N) throw new MpcProtocolError("VES_INVALID_PAYLOAD", `Invalid cold evaluation scalar for guardian ${k}`);
|
|
329
|
+
const gIkPoint = evaluateFeldmanCommitments(coldPoints, k);
|
|
330
|
+
if (!mulBaseG(yScalar).equals(gIkPoint)) throw new MpcProtocolError("VES_INVALID_PAYLOAD", `Dealer ${dealerSlot} cold evaluation y_{${dealerSlot},${k}} * G != Feldman G_{${dealerSlot},${k}}`);
|
|
331
|
+
const ekComp33 = guardianPublicKeysComp33[idx];
|
|
332
|
+
const ekPoint = decodePointCompressed(ekComp33, false);
|
|
333
|
+
ekPoint.precompute(8);
|
|
334
|
+
for (;;) {
|
|
335
|
+
const bundle = new Uint8Array(VES_GUARDIAN_BUNDLE_BYTES);
|
|
336
|
+
bundle.set(u16be(k), 0);
|
|
337
|
+
let pos = 2;
|
|
338
|
+
let uTot = 0n;
|
|
339
|
+
const chunkR = new Array(VES_CHUNKS_PER_SHARE);
|
|
340
|
+
const chunkS = new Array(VES_CHUNKS_PER_SHARE);
|
|
341
|
+
for (let m = 0; m < VES_CHUNKS_PER_SHARE; m++) {
|
|
342
|
+
const rBits = new Array(VES_BITS_PER_CHUNK);
|
|
343
|
+
const sBits = new Array(VES_BITS_PER_CHUNK);
|
|
344
|
+
for (let b = 0; b < VES_BITS_PER_CHUNK; b++) {
|
|
345
|
+
const bitShift = BigInt(16 * m + b);
|
|
346
|
+
const bitValue = Number(yScalar >> bitShift & 1n);
|
|
347
|
+
const bitRes = createBitElGamalWithCdsProof({
|
|
348
|
+
ctxDkg32,
|
|
349
|
+
dealerSlot,
|
|
350
|
+
guardianIndex: k,
|
|
351
|
+
chunkIndex: m,
|
|
352
|
+
bitIndex: b,
|
|
353
|
+
bitValue,
|
|
354
|
+
ekPoint,
|
|
355
|
+
ekComp33,
|
|
356
|
+
rng
|
|
357
|
+
});
|
|
358
|
+
bundle.set(bitRes.encodedRecord162, pos);
|
|
359
|
+
pos += VES_BIT_RECORD_BYTES;
|
|
360
|
+
rBits[b] = bitRes.rPoint;
|
|
361
|
+
sBits[b] = bitRes.sPoint;
|
|
362
|
+
const weight = 1n << bitShift;
|
|
363
|
+
uTot = addModN(uTot, mulModN(bitRes.uScalar, modN(weight)));
|
|
364
|
+
}
|
|
365
|
+
let rChunk = SECP256K1_ZERO;
|
|
366
|
+
let sChunk = SECP256K1_ZERO;
|
|
367
|
+
for (let b = VES_BITS_PER_CHUNK - 1; b >= 0; b--) {
|
|
368
|
+
rChunk = rChunk.double().add(rBits[b]);
|
|
369
|
+
sChunk = sChunk.double().add(sBits[b]);
|
|
370
|
+
}
|
|
371
|
+
chunkR[m] = rChunk;
|
|
372
|
+
chunkS[m] = sChunk;
|
|
373
|
+
}
|
|
374
|
+
if (uTot === 0n) continue;
|
|
375
|
+
let rTot = SECP256K1_ZERO;
|
|
376
|
+
let sTot = SECP256K1_ZERO;
|
|
377
|
+
for (let m = VES_CHUNKS_PER_SHARE - 1; m >= 0; m--) {
|
|
378
|
+
for (let d = 0; d < 16; d++) {
|
|
379
|
+
rTot = rTot.double();
|
|
380
|
+
sTot = sTot.double();
|
|
381
|
+
}
|
|
382
|
+
rTot = rTot.add(chunkR[m]);
|
|
383
|
+
sTot = sTot.add(chunkS[m]);
|
|
384
|
+
}
|
|
385
|
+
const dIkPoint = sTot.add(gIkPoint.negate());
|
|
386
|
+
if (rTot.is0() || dIkPoint.is0()) continue;
|
|
387
|
+
const linProof98 = createGuardianLinearDleqProof({
|
|
388
|
+
ctxDkg32,
|
|
389
|
+
dealerSlot,
|
|
390
|
+
guardianIndex: k,
|
|
391
|
+
coldCommitmentsComp33,
|
|
392
|
+
ekPoint,
|
|
393
|
+
ekComp33,
|
|
394
|
+
gIkPoint,
|
|
395
|
+
rTotPoint: rTot,
|
|
396
|
+
dIkPoint,
|
|
397
|
+
uTotScalar: uTot,
|
|
398
|
+
rng
|
|
399
|
+
});
|
|
400
|
+
bundle.set(linProof98, pos);
|
|
401
|
+
guardianBundleBuffers.push(bundle);
|
|
402
|
+
break;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
return concatBytes(VES_DEALER_MAGIC, u16be(dealerSlot), u16be(tCold), u16be(nCold), ...coldCommitmentsComp33, ...guardianBundleBuffers);
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Verifies dealer `i`'s Direct Bit-ElGamal VES contribution (all 256 CDS bit OR-proofs + linear DLEQ
|
|
409
|
+
* per guardian).
|
|
410
|
+
*/
|
|
411
|
+
function verifyNodeColdVesContribution(input) {
|
|
412
|
+
try {
|
|
413
|
+
const { ctxDkg32, dealerSlot, coldCommitmentsComp33, guardianPublicKeysComp33, payload } = input;
|
|
414
|
+
if (!(ctxDkg32 instanceof Uint8Array) || ctxDkg32.length !== 32) return false;
|
|
415
|
+
const parsed = parseDealerVesPayload(payload);
|
|
416
|
+
if (parsed.dealerSlot !== dealerSlot || parsed.tCold !== coldCommitmentsComp33.length || parsed.nCold !== guardianPublicKeysComp33.length) return false;
|
|
417
|
+
for (let l = 0; l < parsed.tCold; l++) if (!constantTimeEqual(parsed.coldCommitmentsComp33[l], coldCommitmentsComp33[l])) return false;
|
|
418
|
+
const cacheKey = computeVerifiedDealerCacheKey({
|
|
419
|
+
ctxDkg32,
|
|
420
|
+
dealerSlot,
|
|
421
|
+
coldCommitmentsComp33,
|
|
422
|
+
guardianPublicKeysComp33,
|
|
423
|
+
payload
|
|
424
|
+
});
|
|
425
|
+
if (verifiedDealerContributionDigests.has(cacheKey)) return true;
|
|
426
|
+
const coldPoints = coldCommitmentsComp33.map((b) => decodePointCompressed(b, false));
|
|
427
|
+
for (let idx = 0; idx < parsed.nCold; idx++) {
|
|
428
|
+
const ekComp33 = guardianPublicKeysComp33[idx];
|
|
429
|
+
const ekPoint = decodePointCompressed(ekComp33, false);
|
|
430
|
+
ekPoint.precompute(8);
|
|
431
|
+
decodeAndOptionallyVerifyGuardianBundle({
|
|
432
|
+
ctxDkg32,
|
|
433
|
+
dealerSlot,
|
|
434
|
+
guardianIndex: idx + 1,
|
|
435
|
+
coldCommitmentsComp33,
|
|
436
|
+
coldPoints,
|
|
437
|
+
ekPoint,
|
|
438
|
+
ekComp33,
|
|
439
|
+
rawBundleBytes: parsed.guardianBundles[idx].rawBundleBytes,
|
|
440
|
+
verifyProofs: true
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
recordVerifiedDealerCacheKey(cacheKey);
|
|
444
|
+
return true;
|
|
445
|
+
} catch {
|
|
446
|
+
return false;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
function parseRecoveryPackageBytes(recoveryPackageBytes) {
|
|
450
|
+
if (!(recoveryPackageBytes instanceof Uint8Array) || recoveryPackageBytes.length < 113 || recoveryPackageBytes.length >= MAX_RECOVERY_PACKAGE_BYTES) throw new MpcProtocolError("VES_PACKAGE_INVALID", `Recovery package size must satisfy 113 <= bytes < ${MAX_RECOVERY_PACKAGE_BYTES}, got ${recoveryPackageBytes?.length}`);
|
|
451
|
+
if (!constantTimeEqual(recoveryPackageBytes.subarray(0, 8), VES_PACKAGE_MAGIC)) throw new MpcProtocolError("VES_PACKAGE_INVALID", "Invalid recovery package magic header");
|
|
452
|
+
const view = new DataView(recoveryPackageBytes.buffer, recoveryPackageBytes.byteOffset, recoveryPackageBytes.byteLength);
|
|
453
|
+
const protocolVersion = view.getUint16(8, false);
|
|
454
|
+
const nParties = view.getUint16(10, false);
|
|
455
|
+
const tCold = view.getUint16(12, false);
|
|
456
|
+
const nCold = view.getUint16(14, false);
|
|
457
|
+
if (protocolVersion !== MPC_PROTOCOL_VERSION || nParties < 1 || nParties > MAX_MPC_CLUSTER_NODES || tCold < 1 || tCold > nCold || nCold > MAX_MPC_CLUSTER_NODES) throw new MpcProtocolError("VES_PACKAGE_INVALID", "Invalid recovery package dimensions or protocolVersion");
|
|
458
|
+
const singleDealerPayloadLen = 14 + tCold * 33 + nCold * VES_GUARDIAN_BUNDLE_BYTES;
|
|
459
|
+
const expectedTotalLen = 80 + (1 + tCold + nCold + nCold) * 33 + nParties * (6 + singleDealerPayloadLen);
|
|
460
|
+
if (recoveryPackageBytes.length !== expectedTotalLen) throw new MpcProtocolError("VES_PACKAGE_INVALID", `Recovery package byte length mismatch: expected ${expectedTotalLen}, got ${recoveryPackageBytes.length}`);
|
|
461
|
+
let offset = 16;
|
|
462
|
+
const ctxDkg32 = recoveryPackageBytes.subarray(offset, offset + 32);
|
|
463
|
+
offset += 32;
|
|
464
|
+
const hDkg32 = recoveryPackageBytes.subarray(offset, offset + 32);
|
|
465
|
+
offset += 32;
|
|
466
|
+
const rootPublicKeyComp33 = recoveryPackageBytes.subarray(offset, offset + 33);
|
|
467
|
+
offset += 33;
|
|
468
|
+
const aggColdCommitmentsComp33 = [];
|
|
469
|
+
for (let l = 0; l < tCold; l++) {
|
|
470
|
+
aggColdCommitmentsComp33.push(recoveryPackageBytes.subarray(offset, offset + 33));
|
|
471
|
+
offset += 33;
|
|
472
|
+
}
|
|
473
|
+
const guardianColdPublicSharesComp33 = [];
|
|
474
|
+
for (let k = 0; k < nCold; k++) {
|
|
475
|
+
guardianColdPublicSharesComp33.push(recoveryPackageBytes.subarray(offset, offset + 33));
|
|
476
|
+
offset += 33;
|
|
477
|
+
}
|
|
478
|
+
const guardianPublicKeysComp33 = [];
|
|
479
|
+
for (let k = 0; k < nCold; k++) {
|
|
480
|
+
guardianPublicKeysComp33.push(recoveryPackageBytes.subarray(offset, offset + 33));
|
|
481
|
+
offset += 33;
|
|
482
|
+
}
|
|
483
|
+
const dealerContributions = [];
|
|
484
|
+
for (let i = 1; i <= nParties; i++) {
|
|
485
|
+
const slot = view.getUint16(offset, false);
|
|
486
|
+
offset += 2;
|
|
487
|
+
const payloadLen = view.getUint32(offset, false);
|
|
488
|
+
offset += 4;
|
|
489
|
+
if (slot !== i || payloadLen !== singleDealerPayloadLen) throw new MpcProtocolError("VES_PACKAGE_INVALID", `Unexpected dealer entry at slot ${i}`);
|
|
490
|
+
const payload = recoveryPackageBytes.subarray(offset, offset + payloadLen);
|
|
491
|
+
offset += payloadLen;
|
|
492
|
+
const parsed = parseDealerVesPayload(payload);
|
|
493
|
+
if (parsed.dealerSlot !== i || parsed.tCold !== tCold || parsed.nCold !== nCold) throw new MpcProtocolError("VES_PACKAGE_INVALID", `Dealer ${i} header mismatch inside recovery package`);
|
|
494
|
+
dealerContributions.push({
|
|
495
|
+
dealerSlot: i,
|
|
496
|
+
payload,
|
|
497
|
+
parsed
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
return {
|
|
501
|
+
protocolVersion,
|
|
502
|
+
nParties,
|
|
503
|
+
tCold,
|
|
504
|
+
nCold,
|
|
505
|
+
ctxDkg32,
|
|
506
|
+
hDkg32,
|
|
507
|
+
rootPublicKeyComp33,
|
|
508
|
+
aggColdCommitmentsComp33,
|
|
509
|
+
guardianColdPublicSharesComp33,
|
|
510
|
+
guardianPublicKeysComp33,
|
|
511
|
+
dealerContributions
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* Aggregates all `nParties` verified dealer VES payloads into a canonical binary recovery package
|
|
516
|
+
* (`< MAX_RECOVERY_PACKAGE_BYTES = 2 MiB`) and returns `(recoveryPackageBytes, sha256(recoveryPackageBytes))`.
|
|
517
|
+
*/
|
|
518
|
+
function aggregateRecoveryPackage(input) {
|
|
519
|
+
const { ctxDkg32, hDkg32, rootPublicKeyComp33, aggColdCommitmentsComp33, guardianColdPublicSharesComp33, guardianPublicKeysComp33, dealerPayloads } = input;
|
|
520
|
+
if (ctxDkg32.length !== 32 || hDkg32.length !== 32 || rootPublicKeyComp33.length !== 33) throw new MpcProtocolError("VES_PACKAGE_INVALID", "Invalid ctxDkg32/hDkg32/rootPublicKeyComp33 byte length");
|
|
521
|
+
const nParties = dealerPayloads.length;
|
|
522
|
+
const tCold = aggColdCommitmentsComp33.length;
|
|
523
|
+
const nCold = guardianPublicKeysComp33.length;
|
|
524
|
+
if (nParties < 1 || nParties > MAX_MPC_CLUSTER_NODES || tCold < 1 || tCold > nCold || nCold > MAX_MPC_CLUSTER_NODES || guardianColdPublicSharesComp33.length !== nCold) throw new MpcProtocolError("VES_PACKAGE_INVALID", "Invalid recovery package dimensions");
|
|
525
|
+
const sortedDealers = [...dealerPayloads].sort((a, b) => a.dealerSlot - b.dealerSlot);
|
|
526
|
+
const dealerRecords = [];
|
|
527
|
+
for (let idx = 0; idx < nParties; idx++) {
|
|
528
|
+
const entry = sortedDealers[idx];
|
|
529
|
+
if (entry.dealerSlot !== idx + 1) throw new MpcProtocolError("VES_PACKAGE_INVALID", `Missing dealer slot ${idx + 1} in dealerPayloads`);
|
|
530
|
+
dealerRecords.push(u16be(entry.dealerSlot), u32be(entry.payload.length), entry.payload);
|
|
531
|
+
}
|
|
532
|
+
const recoveryPackageBytes = concatBytes(VES_PACKAGE_MAGIC, u16be(MPC_PROTOCOL_VERSION), u16be(nParties), u16be(tCold), u16be(nCold), ctxDkg32, hDkg32, rootPublicKeyComp33, ...aggColdCommitmentsComp33, ...guardianColdPublicSharesComp33, ...guardianPublicKeysComp33, ...dealerRecords);
|
|
533
|
+
if (recoveryPackageBytes.length >= MAX_RECOVERY_PACKAGE_BYTES) throw new MpcProtocolError("VES_PACKAGE_INVALID", `Serialized recovery package (${recoveryPackageBytes.length}B) exceeds < ${MAX_RECOVERY_PACKAGE_BYTES}B bound`);
|
|
534
|
+
return {
|
|
535
|
+
recoveryPackageBytes,
|
|
536
|
+
recoveryPackageHash32: sha256(recoveryPackageBytes)
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* Self-contained verification of a serialized Direct Bit-ElGamal recovery package:
|
|
541
|
+
* - Enforces `< MAX_RECOVERY_PACKAGE_BYTES` (`< 2 MiB`) and canonical byte layout.
|
|
542
|
+
* - Verifies `C^{cold}_0 == P_root`, distinct valid `EK_k`, and `Y_k == \sum_l k^l C^{cold}_l`.
|
|
543
|
+
* - Verifies EVERY dealer's 256-bit CDS OR-proofs + linear DLEQ `\pi^{lin}_{i,k}` and confirms
|
|
544
|
+
* `\sum_{i=1}^{nParties} C_{i,l} == C^{cold}_l` across all `l = 0..tCold-1`.
|
|
545
|
+
*/
|
|
546
|
+
function verifyRecoveryPackage(recoveryPackageBytes, expected) {
|
|
547
|
+
try {
|
|
548
|
+
const pkg = parseRecoveryPackageBytes(recoveryPackageBytes);
|
|
549
|
+
if (expected) {
|
|
550
|
+
if (!constantTimeEqual(pkg.ctxDkg32, expected.ctxDkg32) || !constantTimeEqual(pkg.rootPublicKeyComp33, expected.rootPublicKeyComp33) || pkg.aggColdCommitmentsComp33.length !== expected.aggColdCommitmentsComp33.length || pkg.guardianPublicKeysComp33.length !== expected.guardianPublicKeysComp33.length) return false;
|
|
551
|
+
for (let l = 0; l < pkg.tCold; l++) if (!constantTimeEqual(pkg.aggColdCommitmentsComp33[l], expected.aggColdCommitmentsComp33[l])) return false;
|
|
552
|
+
for (let k = 0; k < pkg.nCold; k++) if (!constantTimeEqual(pkg.guardianPublicKeysComp33[k], expected.guardianPublicKeysComp33[k])) return false;
|
|
553
|
+
}
|
|
554
|
+
const pRoot = decodePointCompressed(pkg.rootPublicKeyComp33, false);
|
|
555
|
+
const aggColdPoints = pkg.aggColdCommitmentsComp33.map((b) => decodePointCompressed(b, false));
|
|
556
|
+
if (!pRoot.equals(aggColdPoints[0])) return false;
|
|
557
|
+
const guardianEkPoints = [];
|
|
558
|
+
const seenEkHex = /* @__PURE__ */ new Set();
|
|
559
|
+
for (let k = 0; k < pkg.nCold; k++) {
|
|
560
|
+
const ekComp = pkg.guardianPublicKeysComp33[k];
|
|
561
|
+
const ekHex = bytesToHex(ekComp);
|
|
562
|
+
if (seenEkHex.has(ekHex)) return false;
|
|
563
|
+
seenEkHex.add(ekHex);
|
|
564
|
+
const ekPt = decodePointCompressed(ekComp, false);
|
|
565
|
+
ekPt.precompute(8);
|
|
566
|
+
guardianEkPoints.push(ekPt);
|
|
567
|
+
const expectedYk = evaluateFeldmanCommitments(aggColdPoints, k + 1);
|
|
568
|
+
const pkgYk = decodePointCompressed(pkg.guardianColdPublicSharesComp33[k], false);
|
|
569
|
+
if (expectedYk.is0() || !expectedYk.equals(pkgYk)) return false;
|
|
570
|
+
}
|
|
571
|
+
const summedColdCommitments = new Array(pkg.tCold).fill(SECP256K1_ZERO);
|
|
572
|
+
for (const dealer of pkg.dealerContributions) {
|
|
573
|
+
const dealerColdPoints = dealer.parsed.coldCommitmentsComp33.map((b) => decodePointCompressed(b, false));
|
|
574
|
+
for (let l = 0; l < pkg.tCold; l++) summedColdCommitments[l] = summedColdCommitments[l].add(dealerColdPoints[l]);
|
|
575
|
+
const cacheKey = computeVerifiedDealerCacheKey({
|
|
576
|
+
ctxDkg32: pkg.ctxDkg32,
|
|
577
|
+
dealerSlot: dealer.dealerSlot,
|
|
578
|
+
coldCommitmentsComp33: dealer.parsed.coldCommitmentsComp33,
|
|
579
|
+
guardianPublicKeysComp33: pkg.guardianPublicKeysComp33,
|
|
580
|
+
payload: dealer.payload
|
|
581
|
+
});
|
|
582
|
+
if (verifiedDealerContributionDigests.has(cacheKey)) continue;
|
|
583
|
+
for (let idx = 0; idx < pkg.nCold; idx++) decodeAndOptionallyVerifyGuardianBundle({
|
|
584
|
+
ctxDkg32: pkg.ctxDkg32,
|
|
585
|
+
dealerSlot: dealer.dealerSlot,
|
|
586
|
+
guardianIndex: idx + 1,
|
|
587
|
+
coldCommitmentsComp33: dealer.parsed.coldCommitmentsComp33,
|
|
588
|
+
coldPoints: dealerColdPoints,
|
|
589
|
+
ekPoint: guardianEkPoints[idx],
|
|
590
|
+
ekComp33: pkg.guardianPublicKeysComp33[idx],
|
|
591
|
+
rawBundleBytes: dealer.parsed.guardianBundles[idx].rawBundleBytes,
|
|
592
|
+
verifyProofs: true
|
|
593
|
+
});
|
|
594
|
+
recordVerifiedDealerCacheKey(cacheKey);
|
|
595
|
+
}
|
|
596
|
+
for (let l = 0; l < pkg.tCold; l++) if (!summedColdCommitments[l].equals(aggColdPoints[l])) return false;
|
|
597
|
+
return true;
|
|
598
|
+
} catch {
|
|
599
|
+
return false;
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
var DirectBitElGamalVesPlugin = class {
|
|
603
|
+
constructor(options) {
|
|
604
|
+
this.rng = options?.rng ?? defaultRandomBytes;
|
|
605
|
+
}
|
|
606
|
+
createDealerContribution(input) {
|
|
607
|
+
return createNodeColdVesContribution(input, { rng: this.rng });
|
|
608
|
+
}
|
|
609
|
+
verifyDealerContribution(input) {
|
|
610
|
+
return verifyNodeColdVesContribution(input);
|
|
611
|
+
}
|
|
612
|
+
aggregateRecoveryPackage(input) {
|
|
613
|
+
return aggregateRecoveryPackage(input);
|
|
614
|
+
}
|
|
615
|
+
verifyRecoveryPackage(recoveryPackageBytes, expected) {
|
|
616
|
+
return verifyRecoveryPackage(recoveryPackageBytes, expected);
|
|
617
|
+
}
|
|
618
|
+
};
|
|
619
|
+
/**
|
|
620
|
+
* Verifies the recovery package (unless `skipPackageProofVerification` is never set — always verified!),
|
|
621
|
+
* aggregates `(R^{agg}_{k,m}, S^{agg}_{k,m})` across all `nParties` dealers, solves each of the 16
|
|
622
|
+
* summed limbs in `[0, nParties * 65535]` via `BSGS_M = 680`, reduces `\sum_{m=0}^{15} Y_{k,m} 2^{16m} mod n`,
|
|
623
|
+
* asserts `g(k) * G == Y_k`, and wipes `guardianSecretKeyBytes32` in `finally` (`wipeSecretKeyInput` default `true`).
|
|
624
|
+
*/
|
|
625
|
+
function decryptGuardianColdShareBsgs(params) {
|
|
626
|
+
const { recoveryPackageBytes, guardianIndex, guardianSecretKeyBytes32, expectedManifest, wipeSecretKeyInput = true } = params;
|
|
627
|
+
let skScalar = 0n;
|
|
628
|
+
let shareScalar = 0n;
|
|
629
|
+
try {
|
|
630
|
+
if (!verifyRecoveryPackage(recoveryPackageBytes, expectedManifest)) throw new MpcProtocolError("VES_PACKAGE_INVALID", "Recovery package failed cryptographic verification");
|
|
631
|
+
const pkg = parseRecoveryPackageBytes(recoveryPackageBytes);
|
|
632
|
+
if (!Number.isInteger(guardianIndex) || guardianIndex < 1 || guardianIndex > pkg.nCold) throw new MpcProtocolError("INVALID_PARAMETER", `guardianIndex ${guardianIndex} out of 1..${pkg.nCold}`);
|
|
633
|
+
skScalar = bytes32ToScalarNonZero(guardianSecretKeyBytes32);
|
|
634
|
+
const derivedEkComp33 = encodePointCompressed(mulBaseG(skScalar));
|
|
635
|
+
const expectedEkComp33 = pkg.guardianPublicKeysComp33[guardianIndex - 1];
|
|
636
|
+
if (!constantTimeEqual(derivedEkComp33, expectedEkComp33)) throw new MpcProtocolError("VES_SHARE_MISMATCH", `Guardian secret key does not match guardianPublicKeysComp33[${guardianIndex - 1}]`);
|
|
637
|
+
const ekPoint = decodePointCompressed(expectedEkComp33, false);
|
|
638
|
+
const aggR = new Array(VES_CHUNKS_PER_SHARE).fill(SECP256K1_ZERO);
|
|
639
|
+
const aggS = new Array(VES_CHUNKS_PER_SHARE).fill(SECP256K1_ZERO);
|
|
640
|
+
for (const dealer of pkg.dealerContributions) {
|
|
641
|
+
const dealerColdPoints = dealer.parsed.coldCommitmentsComp33.map((b) => decodePointCompressed(b, false));
|
|
642
|
+
const { chunkR, chunkS } = decodeAndOptionallyVerifyGuardianBundle({
|
|
643
|
+
ctxDkg32: pkg.ctxDkg32,
|
|
644
|
+
dealerSlot: dealer.dealerSlot,
|
|
645
|
+
guardianIndex,
|
|
646
|
+
coldCommitmentsComp33: dealer.parsed.coldCommitmentsComp33,
|
|
647
|
+
coldPoints: dealerColdPoints,
|
|
648
|
+
ekPoint,
|
|
649
|
+
ekComp33: expectedEkComp33,
|
|
650
|
+
rawBundleBytes: dealer.parsed.guardianBundles[guardianIndex - 1].rawBundleBytes,
|
|
651
|
+
verifyProofs: false
|
|
652
|
+
});
|
|
653
|
+
for (let m = 0; m < VES_CHUNKS_PER_SHARE; m++) {
|
|
654
|
+
aggR[m] = aggR[m].add(chunkR[m]);
|
|
655
|
+
aggS[m] = aggS[m].add(chunkS[m]);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
const maxAllowedLimb = pkg.nParties * VES_MAX_LIMB_VALUE;
|
|
659
|
+
const decodedLimbs16 = new Array(VES_CHUNKS_PER_SHARE);
|
|
660
|
+
let exactIntegerSum = 0n;
|
|
661
|
+
for (let m = 0; m < VES_CHUNKS_PER_SHARE; m++) {
|
|
662
|
+
const limbVal = solveDiscreteLogBsgs(aggS[m].add(mulPoint(aggR[m], skScalar).negate()), maxAllowedLimb);
|
|
663
|
+
decodedLimbs16[m] = limbVal;
|
|
664
|
+
exactIntegerSum += BigInt(limbVal) << BigInt(16 * m);
|
|
665
|
+
}
|
|
666
|
+
shareScalar = modN(exactIntegerSum);
|
|
667
|
+
if (shareScalar === 0n) throw new MpcProtocolError("VES_SHARE_MISMATCH", "Decrypted guardian cold share reduced to zero");
|
|
668
|
+
const expectedYkComp33 = pkg.guardianColdPublicSharesComp33[guardianIndex - 1];
|
|
669
|
+
const expectedYk = decodePointCompressed(expectedYkComp33, false);
|
|
670
|
+
if (!mulBaseG(shareScalar).equals(expectedYk)) throw new MpcProtocolError("VES_SHARE_MISMATCH", `Decrypted guardian cold share g(${guardianIndex}) * G != Y_${guardianIndex}`);
|
|
671
|
+
return {
|
|
672
|
+
guardianIndex,
|
|
673
|
+
coldShareBytes32: scalarToBytes32(shareScalar),
|
|
674
|
+
coldPublicShareComp33: new Uint8Array(expectedYkComp33),
|
|
675
|
+
decodedLimbs16
|
|
676
|
+
};
|
|
677
|
+
} finally {
|
|
678
|
+
skScalar = 0n;
|
|
679
|
+
shareScalar = 0n;
|
|
680
|
+
if (wipeSecretKeyInput) zeroizeBytes(guardianSecretKeyBytes32);
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
/**
|
|
684
|
+
* Exports a deterministic, human-verifiable `PrintableManifestCard` pinning `ctxDkg`, `hDkg`,
|
|
685
|
+
* `rootPublicKey`, `escapeColdWallet`, `C^{cold}_{0..t_c-1}`, `Y_{1..n_c}`, `EK_{1..n_c}`, and
|
|
686
|
+
* `sha256(recoveryPackageBytes)` for air-gapped custodian and disaster-recovery verification.
|
|
687
|
+
*/
|
|
688
|
+
function exportPrintableManifestCard(params) {
|
|
689
|
+
const { clusterId, rootId, keyEpoch, t, nParties, tCold, nCold, ctxDkg32, hDkg32, rootPublicKeyComp33, escapeColdWallet, coldFeldmanCommitmentsComp33, guardianColdPublicSharesComp33, guardianPublicKeysComp33, recoveryPackageHash32 } = params;
|
|
690
|
+
if (typeof clusterId !== "string" || clusterId.trim().length === 0 || typeof rootId !== "string" || rootId.trim().length === 0 || typeof keyEpoch !== "bigint" || keyEpoch < 1n) throw new MpcProtocolError("INVALID_PARAMETER", "Invalid clusterId, rootId, or keyEpoch for manifest card");
|
|
691
|
+
if (!Number.isInteger(t) || !Number.isInteger(nParties) || t < 2 || t > nParties || nParties > MAX_MPC_CLUSTER_NODES || !Number.isInteger(tCold) || !Number.isInteger(nCold) || tCold < 1 || tCold > nCold || nCold > MAX_MPC_CLUSTER_NODES) throw new MpcProtocolError("INVALID_PARAMETER", "Invalid online or cold threshold dimensions for manifest card");
|
|
692
|
+
if (ctxDkg32.length !== 32 || hDkg32.length !== 32 || recoveryPackageHash32.length !== 32) throw new MpcProtocolError("INVALID_PARAMETER", "Manifest hashes must be 32 bytes");
|
|
693
|
+
const pRoot = decodePointCompressed(rootPublicKeyComp33, false);
|
|
694
|
+
const rootEthAddress = pointToEthAddress(pRoot).checksumAddress;
|
|
695
|
+
const normalizedEscape = parseStrictEthAddress(escapeColdWallet).checksumAddress;
|
|
696
|
+
if (coldFeldmanCommitmentsComp33.length !== tCold || guardianColdPublicSharesComp33.length !== nCold || guardianPublicKeysComp33.length !== nCold) throw new MpcProtocolError("INVALID_PARAMETER", "Cold commitment/guardian vector length mismatch");
|
|
697
|
+
const coldPoints = coldFeldmanCommitmentsComp33.map((c) => decodePointCompressed(c, false));
|
|
698
|
+
if (!coldPoints[0].equals(pRoot)) throw new MpcProtocolError("INVALID_PARAMETER", "Manifest C^{cold}_0 must equal rootPublicKey");
|
|
699
|
+
const seenEk = /* @__PURE__ */ new Set();
|
|
700
|
+
for (let k = 1; k <= nCold; k++) {
|
|
701
|
+
const ekHexKey = bytesToHex(decodePointCompressed(guardianPublicKeysComp33[k - 1], false).toBytes(true));
|
|
702
|
+
if (seenEk.has(ekHexKey)) throw new MpcProtocolError("INVALID_PARAMETER", "Duplicate guardian public key in manifest card");
|
|
703
|
+
seenEk.add(ekHexKey);
|
|
704
|
+
const expectedYk = evaluateFeldmanCommitments(coldPoints, k);
|
|
705
|
+
const givenYk = decodePointCompressed(guardianColdPublicSharesComp33[k - 1], false);
|
|
706
|
+
if (expectedYk.is0() || !expectedYk.equals(givenYk)) throw new MpcProtocolError("INVALID_PARAMETER", `Manifest Y_${k} does not match Feldman evaluation`);
|
|
707
|
+
}
|
|
708
|
+
const ctxDkgHex = `0x${bytesToHex(ctxDkg32)}`;
|
|
709
|
+
const hDkgHex = `0x${bytesToHex(hDkg32)}`;
|
|
710
|
+
const rootPublicKeyHex = `0x${bytesToHex(rootPublicKeyComp33)}`;
|
|
711
|
+
const recoveryPackageSha256Hex = `0x${bytesToHex(recoveryPackageHash32)}`;
|
|
712
|
+
const coldFeldmanCommitmentsHex = coldFeldmanCommitmentsComp33.map((c) => `0x${bytesToHex(decodePointCompressed(c, false).toBytes(true))}`);
|
|
713
|
+
const guardianColdPublicSharesHex = guardianColdPublicSharesComp33.map((y) => `0x${bytesToHex(decodePointCompressed(y, false).toBytes(true))}`);
|
|
714
|
+
const guardianPublicKeysHex = guardianPublicKeysComp33.map((ek) => `0x${bytesToHex(decodePointCompressed(ek, false).toBytes(true))}`);
|
|
715
|
+
const guardianLines = guardianColdPublicSharesHex.map((yHex, idx) => ` [${idx + 1}] ${guardianIndexToPlateLabel(idx + 1)}: EK=${guardianPublicKeysHex[idx]} | Y_${idx + 1}=${yHex}`);
|
|
716
|
+
const printableText = [
|
|
717
|
+
"=== ARC LOGICAL-HSM COLD RECOVERY MANIFEST CARD (V2) ===",
|
|
718
|
+
`Cluster / Root : ${clusterId} / ${rootId} (epoch ${keyEpoch.toString()})`,
|
|
719
|
+
`Quorums : Online ${t}-of-${nParties} | Cold Steel ${tCold}-of-${nCold} (24w BIP-39, ZERO passphrase)`,
|
|
720
|
+
`Root EOA : ${rootEthAddress} (${rootPublicKeyHex})`,
|
|
721
|
+
`Escape Wallet : ${normalizedEscape} [IMMUTABLE DESTINATION LOCK]`,
|
|
722
|
+
`ctx_dkg : ${ctxDkgHex}`,
|
|
723
|
+
`H_dkg : ${hDkgHex}`,
|
|
724
|
+
`VES Pkg SHA256 : ${recoveryPackageSha256Hex}`,
|
|
725
|
+
"Custodian Plates:",
|
|
726
|
+
...guardianLines,
|
|
727
|
+
"========================================================"
|
|
728
|
+
].join("\n");
|
|
729
|
+
return {
|
|
730
|
+
version: 2,
|
|
731
|
+
clusterId,
|
|
732
|
+
rootId,
|
|
733
|
+
keyEpoch: keyEpoch.toString(),
|
|
734
|
+
t,
|
|
735
|
+
nParties,
|
|
736
|
+
tCold,
|
|
737
|
+
nCold,
|
|
738
|
+
ctxDkgHex,
|
|
739
|
+
hDkgHex,
|
|
740
|
+
rootPublicKeyHex,
|
|
741
|
+
rootEthAddress,
|
|
742
|
+
escapeColdWallet: normalizedEscape,
|
|
743
|
+
coldFeldmanCommitmentsHex,
|
|
744
|
+
guardianColdPublicSharesHex,
|
|
745
|
+
guardianPublicKeysHex,
|
|
746
|
+
recoveryPackageSha256Hex,
|
|
747
|
+
printableText
|
|
748
|
+
};
|
|
749
|
+
}
|
|
750
|
+
/**
|
|
751
|
+
* Validates full internal & human-readable (`printableText`) self-consistency of a `PrintableManifestCard`:
|
|
752
|
+
* - Enforces version, integer bounds, EIP-55 `escapeColdWallet` & `rootEthAddress`, `C^{cold}_0 == P_root`,
|
|
753
|
+
* distinct `EK_k`, and `Y_k == \sum_l k^l C^{cold}_l`.
|
|
754
|
+
* - Recomputes canonical `printableText` via `exportPrintableManifestCard` and rejects any split-view
|
|
755
|
+
* mismatch between JSON fields (such as `escapeColdWallet`) and `printableText`.
|
|
756
|
+
*/
|
|
757
|
+
function validatePrintableManifestCard(manifest) {
|
|
758
|
+
if (!manifest || manifest.version !== 2 || typeof manifest.keyEpoch !== "string" || !/^[1-9]\d*$/.test(manifest.keyEpoch) || !Array.isArray(manifest.coldFeldmanCommitmentsHex) || !Array.isArray(manifest.guardianColdPublicSharesHex) || !Array.isArray(manifest.guardianPublicKeysHex) || typeof manifest.printableText !== "string") throw new MpcProtocolError("VES_PACKAGE_INVALID", "Malformed PrintableManifestCard structure");
|
|
759
|
+
let canonical;
|
|
760
|
+
try {
|
|
761
|
+
canonical = exportPrintableManifestCard({
|
|
762
|
+
clusterId: manifest.clusterId,
|
|
763
|
+
rootId: manifest.rootId,
|
|
764
|
+
keyEpoch: BigInt(manifest.keyEpoch),
|
|
765
|
+
t: manifest.t,
|
|
766
|
+
nParties: manifest.nParties,
|
|
767
|
+
tCold: manifest.tCold,
|
|
768
|
+
nCold: manifest.nCold,
|
|
769
|
+
ctxDkg32: normalizeHexBytes(manifest.ctxDkgHex, 32),
|
|
770
|
+
hDkg32: normalizeHexBytes(manifest.hDkgHex, 32),
|
|
771
|
+
rootPublicKeyComp33: normalizeHexBytes(manifest.rootPublicKeyHex, 33),
|
|
772
|
+
escapeColdWallet: manifest.escapeColdWallet,
|
|
773
|
+
coldFeldmanCommitmentsComp33: manifest.coldFeldmanCommitmentsHex.map((h) => normalizeHexBytes(h, 33)),
|
|
774
|
+
guardianColdPublicSharesComp33: manifest.guardianColdPublicSharesHex.map((h) => normalizeHexBytes(h, 33)),
|
|
775
|
+
guardianPublicKeysComp33: manifest.guardianPublicKeysHex.map((h) => normalizeHexBytes(h, 33)),
|
|
776
|
+
recoveryPackageHash32: normalizeHexBytes(manifest.recoveryPackageSha256Hex, 32)
|
|
777
|
+
});
|
|
778
|
+
} catch (err) {
|
|
779
|
+
throw new MpcProtocolError("VES_PACKAGE_INVALID", `Invalid PrintableManifestCard: ${err.message}`);
|
|
780
|
+
}
|
|
781
|
+
if (manifest.rootEthAddress !== canonical.rootEthAddress || manifest.escapeColdWallet !== canonical.escapeColdWallet || manifest.ctxDkgHex.toLowerCase() !== canonical.ctxDkgHex.toLowerCase() || manifest.hDkgHex.toLowerCase() !== canonical.hDkgHex.toLowerCase() || manifest.rootPublicKeyHex.toLowerCase() !== canonical.rootPublicKeyHex.toLowerCase() || manifest.recoveryPackageSha256Hex.toLowerCase() !== canonical.recoveryPackageSha256Hex.toLowerCase() || manifest.printableText !== canonical.printableText) throw new MpcProtocolError("VES_PACKAGE_INVALID", "PrintableManifestCard failed canonical or printableText consistency check (possible escapeColdWallet spoofing)");
|
|
782
|
+
}
|
|
783
|
+
function verifyManifestAgainstDkgConfig(manifest, config) {
|
|
784
|
+
try {
|
|
785
|
+
validatePrintableManifestCard(manifest);
|
|
786
|
+
const { ctxDkg32, normalizedEscapeColdWallet } = validateAndComputeDkgContext(config);
|
|
787
|
+
if (manifest.clusterId !== config.clusterId || manifest.rootId !== config.rootId || BigInt(manifest.keyEpoch) !== config.keyEpoch || manifest.t !== config.t || manifest.nParties !== config.nParties || manifest.tCold !== config.tCold || manifest.nCold !== config.nCold || manifest.escapeColdWallet !== normalizedEscapeColdWallet || !constantTimeEqual(normalizeHexBytes(manifest.ctxDkgHex, 32), ctxDkg32)) return false;
|
|
788
|
+
for (let k = 0; k < config.nCold; k++) if (!constantTimeEqual(normalizeHexBytes(manifest.guardianPublicKeysHex[k], 33), config.guardianPublicKeysComp33[k])) return false;
|
|
789
|
+
return true;
|
|
790
|
+
} catch {
|
|
791
|
+
return false;
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
function verifyManifestAgainstRecoveryPackage(manifest, recoveryPackageBytes) {
|
|
795
|
+
try {
|
|
796
|
+
validatePrintableManifestCard(manifest);
|
|
797
|
+
const expectedPkgHash32 = normalizeHexBytes(manifest.recoveryPackageSha256Hex, 32);
|
|
798
|
+
if (!constantTimeEqual(sha256(recoveryPackageBytes), expectedPkgHash32)) return false;
|
|
799
|
+
const pkg = parseRecoveryPackageBytes(recoveryPackageBytes);
|
|
800
|
+
if (pkg.nParties !== manifest.nParties || pkg.tCold !== manifest.tCold || pkg.nCold !== manifest.nCold || !constantTimeEqual(pkg.ctxDkg32, normalizeHexBytes(manifest.ctxDkgHex, 32)) || !constantTimeEqual(pkg.hDkg32, normalizeHexBytes(manifest.hDkgHex, 32))) return false;
|
|
801
|
+
for (let k = 0; k < pkg.nCold; k++) if (!constantTimeEqual(pkg.guardianColdPublicSharesComp33[k], normalizeHexBytes(manifest.guardianColdPublicSharesHex[k], 33))) return false;
|
|
802
|
+
return verifyRecoveryPackage(recoveryPackageBytes, {
|
|
803
|
+
ctxDkg32: normalizeHexBytes(manifest.ctxDkgHex, 32),
|
|
804
|
+
rootPublicKeyComp33: normalizeHexBytes(manifest.rootPublicKeyHex, 33),
|
|
805
|
+
aggColdCommitmentsComp33: manifest.coldFeldmanCommitmentsHex.map((h) => normalizeHexBytes(h, 33)),
|
|
806
|
+
guardianPublicKeysComp33: manifest.guardianPublicKeysHex.map((h) => normalizeHexBytes(h, 33))
|
|
807
|
+
});
|
|
808
|
+
} catch {
|
|
809
|
+
return false;
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
function computeCanaryChallengeDigest32(bundle) {
|
|
813
|
+
if (!bundle || bundle.version !== 2 || typeof bundle.rootId !== "string" || bundle.rootId.trim().length === 0 || typeof bundle.challengeId !== "string" || bundle.challengeId.trim().length === 0 || typeof bundle.keyEpoch !== "string" || !/^[1-9]\d*$/.test(bundle.keyEpoch)) throw new MpcProtocolError("CANARY_CERT_INVALID", "Malformed CanaryChallengeBundle");
|
|
814
|
+
const keyEpochBig = BigInt(bundle.keyEpoch);
|
|
815
|
+
if (!Number.isSafeInteger(bundle.issuedAtSec) || bundle.issuedAtSec < 0 || !Number.isSafeInteger(bundle.expiresAtSec) || bundle.expiresAtSec <= bundle.issuedAtSec || bundle.expiresAtSec - bundle.issuedAtSec > 900) throw new MpcProtocolError("CANARY_CERT_INVALID", "CanaryChallengeBundle TTL must satisfy 0 < ttl <= 900s");
|
|
816
|
+
const ctxDkg32 = normalizeHexBytes(bundle.ctxDkgHex, 32);
|
|
817
|
+
const hDkg32 = normalizeHexBytes(bundle.hDkgHex, 32);
|
|
818
|
+
const nonce32 = normalizeHexBytes(bundle.challengeNonceHex, 32);
|
|
819
|
+
if (!Number.isInteger(bundle.nCold) || bundle.nCold < 1 || bundle.nCold > MAX_MPC_CLUSTER_NODES || !Array.isArray(bundle.guardianColdPublicSharesHex) || bundle.guardianColdPublicSharesHex.length !== bundle.nCold) throw new MpcProtocolError("CANARY_CERT_INVALID", "Invalid guardianColdPublicSharesHex in CanaryChallengeBundle");
|
|
820
|
+
const yParts = bundle.guardianColdPublicSharesHex.map((h) => decodePointCompressed(normalizeHexBytes(h, 33), false).toBytes(true));
|
|
821
|
+
return hashTranscriptSha256(DST_CANARY_CHALLENGE_V1, utf8Bytes(bundle.rootId), u64be(keyEpochBig), ctxDkg32, hDkg32, utf8Bytes(bundle.challengeId), nonce32, u64be(BigInt(bundle.issuedAtSec)), u64be(BigInt(bundle.expiresAtSec)), u16be(bundle.nCold), ...yParts);
|
|
822
|
+
}
|
|
823
|
+
function assertChallengeBundleMatchesManifest(challengeBundle, manifestCard) {
|
|
824
|
+
validatePrintableManifestCard(manifestCard);
|
|
825
|
+
if (manifestCard.rootId !== challengeBundle.rootId || manifestCard.keyEpoch !== challengeBundle.keyEpoch || manifestCard.nCold !== challengeBundle.nCold || !Array.isArray(challengeBundle.guardianColdPublicSharesHex) || challengeBundle.guardianColdPublicSharesHex.length !== manifestCard.nCold || !constantTimeEqual(normalizeHexBytes(manifestCard.ctxDkgHex, 32), normalizeHexBytes(challengeBundle.ctxDkgHex, 32)) || !constantTimeEqual(normalizeHexBytes(manifestCard.hDkgHex, 32), normalizeHexBytes(challengeBundle.hDkgHex, 32))) throw new MpcProtocolError("CANARY_CERT_INVALID", "CanaryChallengeBundle metadata mismatch against pinned PrintableManifestCard");
|
|
826
|
+
for (let k = 0; k < manifestCard.nCold; k++) if (!constantTimeEqual(normalizeHexBytes(manifestCard.guardianColdPublicSharesHex[k], 33), normalizeHexBytes(challengeBundle.guardianColdPublicSharesHex[k], 33))) throw new MpcProtocolError("CANARY_CERT_INVALID", `CanaryChallengeBundle Y_${k + 1} mismatch against pinned PrintableManifestCard`);
|
|
827
|
+
}
|
|
828
|
+
function signCanaryChallengeApproval(params) {
|
|
829
|
+
const digest32 = computeCanaryChallengeDigest32(params.bundle);
|
|
830
|
+
const sk = bytes32ToScalarNonZero(params.rosterSigningSecretBytes32);
|
|
831
|
+
const pok = createSchnorrPokInBase({
|
|
832
|
+
dst: DST_CANARY_CHALLENGE_V1,
|
|
833
|
+
basePoint: SECP256K1_G,
|
|
834
|
+
statementPoint: mulBaseG(sk),
|
|
835
|
+
secretScalar: sk,
|
|
836
|
+
contextParts: [u16be(params.slot), digest32],
|
|
837
|
+
rng: params.rng
|
|
838
|
+
});
|
|
839
|
+
return {
|
|
840
|
+
slot: params.slot,
|
|
841
|
+
noncePointHex: `0x${bytesToHex(pok.noncePointComp33)}`,
|
|
842
|
+
responseHex: `0x${bytesToHex(pok.responseBytes32)}`
|
|
843
|
+
};
|
|
844
|
+
}
|
|
845
|
+
function verifyCanaryChallengeBundle(bundle, options) {
|
|
846
|
+
try {
|
|
847
|
+
const digest32 = computeCanaryChallengeDigest32(bundle);
|
|
848
|
+
if (options?.trustedNowSec !== void 0) {
|
|
849
|
+
if (!Number.isSafeInteger(options.trustedNowSec) || options.trustedNowSec < bundle.issuedAtSec || options.trustedNowSec >= bundle.expiresAtSec) return false;
|
|
850
|
+
}
|
|
851
|
+
const hasRosterMap = options?.rosterVerifyKeysComp33BySlot !== void 0;
|
|
852
|
+
const hasQuorumT = options?.requiredQuorumT !== void 0;
|
|
853
|
+
if (hasRosterMap !== hasQuorumT) return false;
|
|
854
|
+
if (hasRosterMap && hasQuorumT) {
|
|
855
|
+
const requiredT = options.requiredQuorumT;
|
|
856
|
+
const rosterMap = options.rosterVerifyKeysComp33BySlot;
|
|
857
|
+
if (!Number.isInteger(requiredT) || requiredT < 1 || requiredT > MAX_MPC_CLUSTER_NODES || rosterMap.size === 0) return false;
|
|
858
|
+
const approvals = bundle.peerApprovals ?? [];
|
|
859
|
+
if (!Array.isArray(approvals) || approvals.length < requiredT) return false;
|
|
860
|
+
const seenSlots = /* @__PURE__ */ new Set();
|
|
861
|
+
for (const app of approvals) {
|
|
862
|
+
if (!app || !Number.isInteger(app.slot) || app.slot < 1 || seenSlots.has(app.slot)) return false;
|
|
863
|
+
const pkComp33 = rosterMap.get(app.slot);
|
|
864
|
+
if (!pkComp33) return false;
|
|
865
|
+
if (!verifySchnorrPokInBase({
|
|
866
|
+
dst: DST_CANARY_CHALLENGE_V1,
|
|
867
|
+
basePoint: SECP256K1_G,
|
|
868
|
+
statementPoint: decodePointCompressed(pkComp33, false),
|
|
869
|
+
proof: {
|
|
870
|
+
noncePointComp33: normalizeHexBytes(app.noncePointHex, 33),
|
|
871
|
+
responseBytes32: normalizeHexBytes(app.responseHex, 32)
|
|
872
|
+
},
|
|
873
|
+
contextParts: [u16be(app.slot), digest32]
|
|
874
|
+
})) return false;
|
|
875
|
+
seenSlots.add(app.slot);
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
return true;
|
|
879
|
+
} catch {
|
|
880
|
+
return false;
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
/**
|
|
884
|
+
* Generates Custodian `k`'s Schnorr PoK `\pi^{cold}_k` over `(ctxDkg32, u16be(guardianIndex), challengeNonce32)`
|
|
885
|
+
* under cold share `g(k)` (`Y_k = g(k) * G`), proving physical steel-plate possession in zero knowledge
|
|
886
|
+
* WITHOUT revealing `g(k)` or reconstructing `x_root`.
|
|
887
|
+
*
|
|
888
|
+
* Strictly verifies `g(k) * G == Y_k` BEFORE generating the proof whenever `expectedColdPublicShare` is supplied.
|
|
889
|
+
*/
|
|
890
|
+
function createColdShardSchnorrPok(params) {
|
|
891
|
+
const { ctxDkg, guardianIndex, challengeNonce, coldShareBytes32, expectedColdPublicShare, rng, wipeColdShareInput = false } = params;
|
|
892
|
+
let gScalar = 0n;
|
|
893
|
+
try {
|
|
894
|
+
if (!Number.isInteger(guardianIndex) || guardianIndex < 1 || guardianIndex > MAX_MPC_CLUSTER_NODES) throw new MpcProtocolError("INVALID_PARAMETER", `Invalid guardianIndex: ${guardianIndex}`);
|
|
895
|
+
const ctxDkg32 = normalizeHexBytes(ctxDkg, 32);
|
|
896
|
+
const challengeNonce32 = normalizeHexBytes(challengeNonce, 32);
|
|
897
|
+
gScalar = bytes32ToScalarNonZero(coldShareBytes32);
|
|
898
|
+
const ykPoint = mulBaseG(gScalar);
|
|
899
|
+
if (expectedColdPublicShare !== void 0) {
|
|
900
|
+
const expectedYkPt = decodePointCompressed(normalizeHexBytes(expectedColdPublicShare, 33), false);
|
|
901
|
+
if (!ykPoint.equals(expectedYkPt)) throw new MpcProtocolError("VES_SHARE_MISMATCH", `Cold share scalar * G does not match expected Y_${guardianIndex}`);
|
|
902
|
+
}
|
|
903
|
+
const pok = createSchnorrPokInBase({
|
|
904
|
+
dst: DST_CANARY_SHARD_POK_V1,
|
|
905
|
+
basePoint: SECP256K1_G,
|
|
906
|
+
statementPoint: ykPoint,
|
|
907
|
+
secretScalar: gScalar,
|
|
908
|
+
contextParts: [
|
|
909
|
+
ctxDkg32,
|
|
910
|
+
u16be(guardianIndex),
|
|
911
|
+
challengeNonce32
|
|
912
|
+
],
|
|
913
|
+
rng
|
|
914
|
+
});
|
|
915
|
+
return {
|
|
916
|
+
guardianIndex,
|
|
917
|
+
coldPublicShareHex: `0x${bytesToHex(encodePointCompressed(ykPoint))}`,
|
|
918
|
+
noncePointHex: `0x${bytesToHex(pok.noncePointComp33)}`,
|
|
919
|
+
responseHex: `0x${bytesToHex(pok.responseBytes32)}`
|
|
920
|
+
};
|
|
921
|
+
} finally {
|
|
922
|
+
gScalar = 0n;
|
|
923
|
+
if (wipeColdShareInput) zeroizeBytes(coldShareBytes32);
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
function verifyColdShardSchnorrPok(params) {
|
|
927
|
+
try {
|
|
928
|
+
const { ctxDkg, challengeNonce, expectedColdPublicShare, shardProof } = params;
|
|
929
|
+
if (!shardProof || !Number.isInteger(shardProof.guardianIndex) || shardProof.guardianIndex < 1) return false;
|
|
930
|
+
const ctxDkg32 = normalizeHexBytes(ctxDkg, 32);
|
|
931
|
+
const challengeNonce32 = normalizeHexBytes(challengeNonce, 32);
|
|
932
|
+
const expectedYkComp33 = normalizeHexBytes(expectedColdPublicShare, 33);
|
|
933
|
+
if (!constantTimeEqual(expectedYkComp33, normalizeHexBytes(shardProof.coldPublicShareHex, 33))) return false;
|
|
934
|
+
return verifySchnorrPokInBase({
|
|
935
|
+
dst: DST_CANARY_SHARD_POK_V1,
|
|
936
|
+
basePoint: SECP256K1_G,
|
|
937
|
+
statementPoint: decodePointCompressed(expectedYkComp33, false),
|
|
938
|
+
proof: {
|
|
939
|
+
noncePointComp33: normalizeHexBytes(shardProof.noncePointHex, 33),
|
|
940
|
+
responseBytes32: normalizeHexBytes(shardProof.responseHex, 32)
|
|
941
|
+
},
|
|
942
|
+
contextParts: [
|
|
943
|
+
ctxDkg32,
|
|
944
|
+
u16be(shardProof.guardianIndex),
|
|
945
|
+
challengeNonce32
|
|
946
|
+
]
|
|
947
|
+
});
|
|
948
|
+
} catch {
|
|
949
|
+
return false;
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
function assembleCanaryActivationCert(params) {
|
|
953
|
+
const { clusterChallengeBundle, shardProofs, manifestCard } = params;
|
|
954
|
+
if (manifestCard) assertChallengeBundleMatchesManifest(clusterChallengeBundle, manifestCard);
|
|
955
|
+
const cert = {
|
|
956
|
+
version: 2,
|
|
957
|
+
clusterChallengeBundle,
|
|
958
|
+
shardProofs: [...shardProofs].sort((a, b) => a.guardianIndex - b.guardianIndex)
|
|
959
|
+
};
|
|
960
|
+
if (!verifyCanaryActivationCert(cert, {
|
|
961
|
+
ctxDkg: manifestCard ? manifestCard.ctxDkgHex : clusterChallengeBundle.ctxDkgHex,
|
|
962
|
+
hDkg: manifestCard ? manifestCard.hDkgHex : clusterChallengeBundle.hDkgHex,
|
|
963
|
+
rootId: manifestCard ? manifestCard.rootId : clusterChallengeBundle.rootId,
|
|
964
|
+
keyEpoch: BigInt(manifestCard ? manifestCard.keyEpoch : clusterChallengeBundle.keyEpoch),
|
|
965
|
+
nCold: manifestCard ? manifestCard.nCold : clusterChallengeBundle.nCold,
|
|
966
|
+
guardianColdPublicSharesComp33: manifestCard ? manifestCard.guardianColdPublicSharesHex : clusterChallengeBundle.guardianColdPublicSharesHex,
|
|
967
|
+
...manifestCard ? { coldFeldmanCommitmentsComp33: manifestCard.coldFeldmanCommitmentsHex } : {}
|
|
968
|
+
})) throw new MpcProtocolError("CANARY_CERT_INVALID", "Assembled CanaryActivationCert failed cryptographic verification");
|
|
969
|
+
return cert;
|
|
970
|
+
}
|
|
971
|
+
/**
|
|
972
|
+
* Verifies a self-verifying `CanaryActivationCert` (`design.md` §5.2):
|
|
973
|
+
* - Validates `clusterChallengeBundle` metadata, TTL (`<= 900s`), optional `trustedNowSec`, and
|
|
974
|
+
* optional `>= t` HSM roster approvals.
|
|
975
|
+
* - Requires ALL `nCold` (`3/3` default) distinct guardian Schnorr PoKs `\pi^{cold}_{1..nCold}`
|
|
976
|
+
* verified against `guardianColdPublicSharesComp33` (`Y_{1..nCold}`) and optional `coldFeldmanCommitmentsComp33`.
|
|
977
|
+
*/
|
|
978
|
+
function verifyCanaryActivationCert(cert, expected) {
|
|
979
|
+
try {
|
|
980
|
+
if (!cert || cert.version !== 2 || !cert.clusterChallengeBundle || !Array.isArray(cert.shardProofs)) return false;
|
|
981
|
+
const { clusterChallengeBundle: bundle, shardProofs } = cert;
|
|
982
|
+
if (!verifyCanaryChallengeBundle(bundle, {
|
|
983
|
+
rosterVerifyKeysComp33BySlot: expected.rosterVerifyKeysComp33BySlot,
|
|
984
|
+
requiredQuorumT: expected.requiredQuorumT,
|
|
985
|
+
trustedNowSec: expected.trustedNowSec
|
|
986
|
+
})) return false;
|
|
987
|
+
const expectedCtx32 = normalizeHexBytes(expected.ctxDkg, 32);
|
|
988
|
+
if (!constantTimeEqual(expectedCtx32, normalizeHexBytes(bundle.ctxDkgHex, 32))) return false;
|
|
989
|
+
if (expected.hDkg !== void 0) {
|
|
990
|
+
if (!constantTimeEqual(normalizeHexBytes(expected.hDkg, 32), normalizeHexBytes(bundle.hDkgHex, 32))) return false;
|
|
991
|
+
}
|
|
992
|
+
if (expected.rootId !== void 0 && bundle.rootId !== expected.rootId) return false;
|
|
993
|
+
if (expected.keyEpoch !== void 0 && BigInt(bundle.keyEpoch) !== expected.keyEpoch) return false;
|
|
994
|
+
const nCold = expected.nCold;
|
|
995
|
+
if (!Number.isInteger(nCold) || nCold < 1 || nCold > MAX_MPC_CLUSTER_NODES || bundle.nCold !== nCold || expected.guardianColdPublicSharesComp33.length !== nCold || bundle.guardianColdPublicSharesHex.length !== nCold || shardProofs.length !== nCold) return false;
|
|
996
|
+
const coldPoints = expected.coldFeldmanCommitmentsComp33?.map((c) => decodePointCompressed(normalizeHexBytes(c, 33), false));
|
|
997
|
+
for (let k = 1; k <= nCold; k++) {
|
|
998
|
+
const expectedYk33 = normalizeHexBytes(expected.guardianColdPublicSharesComp33[k - 1], 33);
|
|
999
|
+
if (!constantTimeEqual(expectedYk33, normalizeHexBytes(bundle.guardianColdPublicSharesHex[k - 1], 33))) return false;
|
|
1000
|
+
if (coldPoints) {
|
|
1001
|
+
const evalYk = evaluateFeldmanCommitments(coldPoints, k);
|
|
1002
|
+
if (evalYk.is0() || !evalYk.equals(decodePointCompressed(expectedYk33, false))) return false;
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
const challengeNonce32 = normalizeHexBytes(bundle.challengeNonceHex, 32);
|
|
1006
|
+
const seenGuardians = /* @__PURE__ */ new Set();
|
|
1007
|
+
for (const sp of shardProofs) {
|
|
1008
|
+
const k = sp.guardianIndex;
|
|
1009
|
+
if (!Number.isInteger(k) || k < 1 || k > nCold || seenGuardians.has(k)) return false;
|
|
1010
|
+
seenGuardians.add(k);
|
|
1011
|
+
if (!verifyColdShardSchnorrPok({
|
|
1012
|
+
ctxDkg: expectedCtx32,
|
|
1013
|
+
challengeNonce: challengeNonce32,
|
|
1014
|
+
expectedColdPublicShare: normalizeHexBytes(expected.guardianColdPublicSharesComp33[k - 1], 33),
|
|
1015
|
+
shardProof: sp
|
|
1016
|
+
})) return false;
|
|
1017
|
+
}
|
|
1018
|
+
return seenGuardians.size === nCold;
|
|
1019
|
+
} catch {
|
|
1020
|
+
return false;
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
//#endregion
|
|
1025
|
+
export { DirectBitElGamalVesPlugin, VES_BITS_PER_CHUNK, VES_BITS_PER_SHARE, VES_BIT_RECORD_BYTES, VES_CHUNKS_PER_SHARE, VES_GUARDIAN_BUNDLE_BYTES, VES_LINEAR_DLEQ_BYTES, VES_MAX_LIMB_VALUE, VES_MAX_SUMMED_LIMB, aggregateRecoveryPackage, assembleCanaryActivationCert, assertChallengeBundleMatchesManifest, computeCanaryChallengeDigest32, createColdShardSchnorrPok, createNodeColdVesContribution, decryptGuardianColdShareBsgs, exportPrintableManifestCard, parseRecoveryPackageBytes, signCanaryChallengeApproval, solveDiscreteLogBsgs, validatePrintableManifestCard, verifyCanaryActivationCert, verifyCanaryChallengeBundle, verifyColdShardSchnorrPok, verifyManifestAgainstDkgConfig, verifyManifestAgainstRecoveryPackage, verifyNodeColdVesContribution, verifyRecoveryPackage };
|