@ocap/mpc-hsm 0.0.0-stage → 1.33.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/esm/bip39-english-wordlist.d.mts +11 -0
- package/esm/bip39-english-wordlist.mjs +31 -0
- package/esm/constants.d.mts +140 -0
- package/esm/constants.mjs +142 -0
- package/esm/dkg.d.mts +279 -0
- package/esm/dkg.mjs +903 -0
- package/esm/index.d.mts +17 -0
- package/esm/index.mjs +18 -0
- package/esm/mta.d.mts +63 -0
- package/esm/mta.mjs +275 -0
- 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 +193 -0
- package/esm/ot.mjs +726 -0
- 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.d.mts +242 -0
- package/esm/presign.mjs +951 -0
- package/esm/rlp-eip1559.d.mts +75 -0
- package/esm/rlp-eip1559.mjs +293 -0
- package/esm/secp256k1-scalar.d.mts +141 -0
- package/esm/secp256k1-scalar.mjs +474 -0
- package/esm/sign.d.mts +113 -0
- package/esm/sign.mjs +225 -0
- package/esm/steel-mnemonic.d.mts +55 -0
- package/esm/steel-mnemonic.mjs +247 -0
- package/esm/tweak.d.mts +100 -0
- package/esm/tweak.mjs +168 -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 +264 -0
- package/lib/constants.d.cts +140 -0
- package/lib/dkg.cjs +910 -0
- package/lib/dkg.d.cts +279 -0
- package/lib/index.cjs +420 -0
- package/lib/index.d.cts +17 -0
- package/lib/mta.cjs +280 -0
- package/lib/mta.d.cts +63 -0
- 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 +744 -0
- package/lib/ot.d.cts +193 -0
- 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 +954 -0
- package/lib/presign.d.cts +242 -0
- package/lib/rlp-eip1559.cjs +303 -0
- package/lib/rlp-eip1559.d.cts +75 -0
- package/lib/secp256k1-scalar.cjs +527 -0
- package/lib/secp256k1-scalar.d.cts +141 -0
- package/lib/sign.cjs +233 -0
- package/lib/sign.d.cts +113 -0
- package/lib/steel-mnemonic.cjs +253 -0
- package/lib/steel-mnemonic.d.cts +55 -0
- package/lib/tweak.cjs +178 -0
- package/lib/tweak.d.cts +100 -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 +80 -4
- package/README.md +0 -3
|
@@ -0,0 +1,3615 @@
|
|
|
1
|
+
import { CLOUD_SYNC_SEALED_BLOB_BYTES, DST_PERSONAL_ANNOUNCE_TICKET_V1, DST_PERSONAL_BASEOT_CTX_V1, DST_PERSONAL_BLIND_OCAP_VELOCITY_TAG_V1, DST_PERSONAL_BLIND_SLOT_TAG_V1, DST_PERSONAL_BLIND_VAULT_TAG_V1, DST_PERSONAL_BLIND_VELOCITY_TAG_V1, DST_PERSONAL_BLOB_AAD_V1, DST_PERSONAL_BLOB_MAGIC, DST_PERSONAL_CHALLENGE_ANNOUNCE_V1, DST_PERSONAL_CHALLENGE_ENTITLEMENT_APPLY_V1, DST_PERSONAL_CHALLENGE_PAIR_RESPLIT_V1, DST_PERSONAL_CHALLENGE_PRESIGN_INIT_V1, DST_PERSONAL_CHALLENGE_RESEAL_KID_V1, DST_PERSONAL_CHALLENGE_REVOKE_SLOT_V1, DST_PERSONAL_CHALLENGE_SEAL_ENROLL_V1, DST_PERSONAL_CHALLENGE_SESSION_LOCK_V1, DST_PERSONAL_CHALLENGE_SESSION_OPEN_V1, DST_PERSONAL_CHALLENGE_SIGN_V1, DST_PERSONAL_CHALLENGE_VETO_V1, DST_PERSONAL_CLEAR_PREVIEW_V1, DST_PERSONAL_CLOUD_BLOB_V1, DST_PERSONAL_CLOUD_SYNC_V1, DST_PERSONAL_CLUSTER_HDKG_V1, DST_PERSONAL_COLD_MANIFEST_V1, DST_PERSONAL_DEVICE_AAD_V1, DST_PERSONAL_DEVICE_ENV_V1, DST_PERSONAL_ENTITLEMENT_TICKET_V1, DST_PERSONAL_FIREWALL_ATTESTATION_V1, DST_PERSONAL_GUARDIAN_QUORUM_V1, DST_PERSONAL_PAIR_POP_V1, DST_PERSONAL_PAIR_SHARE_AAD_V1, DST_PERSONAL_PAIR_SHARE_BOX_V1, DST_PERSONAL_POLICY_V1, DST_PERSONAL_PWD_CLIENT_HKDF_V1, DST_PERSONAL_PWD_HSM_HKDF_V1, DST_PERSONAL_ROLE_QUORUM_V1, DST_PERSONAL_SEAL_ENROLL_ACTOR_POK_V1, DST_PERSONAL_SEAL_KEY_V1, DST_PERSONAL_SEAL_SALT_V1, DST_PERSONAL_SIMULATED_DELTA_V1, DST_PERSONAL_TRANSPORT_AAD_V1, DST_PERSONAL_TRANSPORT_BOX_V1, HSM_SEALED_BLOB_BYTES, MAX_PERSONAL_CALL_DEPTH, MAX_PERSONAL_FIREWALL_ATTESTATION_TTL_SECONDS, MAX_PERSONAL_TX_DATA_BYTES, MpcProtocolError, SECP256K1_HALF_N, SECP256K1_N } from "./constants.mjs";
|
|
2
|
+
import { SECP256K1_G, addModN, assertScalarNonZero, assertValidX25519PublicKey, bytes32ToScalarNonZero, bytesToBigIntBE, bytesToHex, computeX25519SharedSecret, concatBytes, constantTimeEqual, createSchnorrPokInBase, decodePointCompressed, defaultRandomBytes, encodePointCompressed, evaluatePolynomialModN, hashTranscriptSha256, hexToBytes, invModN, lagrangeCoefficientAtZero, lengthPrefixedEncode, mulBaseG, mulModN, mulPoint, negModN, normalizeHexBytes, sampleScalarNonZero, scalarToBytes32, secp256k1, subModN, u16be, u32be, u64be, u8, utf8Bytes, verifySchnorrPokInBase, zeroizeBytes } from "./secp256k1-scalar.mjs";
|
|
3
|
+
import { deriveRoleBoundChild, deriveRuleBoundChild, deriveUntweakedChild, parseStrictEthAddress, pointToEthAddress, toEip55ChecksumAddress } from "./tweak.mjs";
|
|
4
|
+
import { baseOtReceiverStep2, baseOtSenderStep1, baseOtSenderStep3, wipeBaseOtReceiverState, wipeBaseOtSenderState } from "./ot.mjs";
|
|
5
|
+
import { PresignPartySession, VolatilePresignaturePool } from "./presign.mjs";
|
|
6
|
+
import { aggregateOnlineSignature, createOnlineSignShare } from "./sign.mjs";
|
|
7
|
+
import { decodeBip39Words24ToColdShare, deriveBip44EthAddressFromWords24, encodeColdShareToBip39Words24, guardianIndexToPlateLabel, identifyColdShareIndexViaFeldman } from "./steel-mnemonic.mjs";
|
|
8
|
+
import { EIP1559_TX_TYPE_BYTE, ERC20_TRANSFER_SELECTOR_HEX, decodeAndRecoverSignedEip1559Tx, decodeErc20TransferCalldata, encodeErc20TransferCalldata, encodeSignedEip1559Tx, encodeUnsignedEip1559Tx, rlpDecode } from "./rlp-eip1559.mjs";
|
|
9
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
10
|
+
import { ed25519, x25519 } from "@noble/curves/ed25519.js";
|
|
11
|
+
import { keccak_256 } from "@noble/hashes/sha3.js";
|
|
12
|
+
import { hkdf } from "@noble/hashes/hkdf.js";
|
|
13
|
+
import { hmac } from "@noble/hashes/hmac.js";
|
|
14
|
+
import { pbkdf2 } from "@noble/hashes/pbkdf2.js";
|
|
15
|
+
import { p256 } from "@noble/curves/nist.js";
|
|
16
|
+
import { scrypt } from "@noble/hashes/scrypt.js";
|
|
17
|
+
|
|
18
|
+
//#region src/personal-vault.ts
|
|
19
|
+
const textDecoder = new TextDecoder("utf-8", { fatal: true });
|
|
20
|
+
function utf8DecodeStrict(bytes, errorCode = "INVALID_PARAMETER") {
|
|
21
|
+
try {
|
|
22
|
+
return textDecoder.decode(bytes);
|
|
23
|
+
} catch {
|
|
24
|
+
throw new MpcProtocolError(errorCode, "Invalid UTF-8 byte sequence");
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
const BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
28
|
+
const BASE64URL_LOOKUP = (() => {
|
|
29
|
+
const table = new Int16Array(128).fill(-1);
|
|
30
|
+
for (let i = 0; i < 64; i++) table[BASE64URL_ALPHABET.charCodeAt(i)] = i;
|
|
31
|
+
return table;
|
|
32
|
+
})();
|
|
33
|
+
function base64UrlEncodeBytes(bytes) {
|
|
34
|
+
let out = "";
|
|
35
|
+
let i = 0;
|
|
36
|
+
for (; i + 2 < bytes.length; i += 3) {
|
|
37
|
+
const n = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
|
|
38
|
+
out += BASE64URL_ALPHABET[n >>> 18 & 63] + BASE64URL_ALPHABET[n >>> 12 & 63] + BASE64URL_ALPHABET[n >>> 6 & 63] + BASE64URL_ALPHABET[n & 63];
|
|
39
|
+
}
|
|
40
|
+
const rem = bytes.length - i;
|
|
41
|
+
if (rem === 1) {
|
|
42
|
+
const n = bytes[i] << 4;
|
|
43
|
+
out += BASE64URL_ALPHABET[n >>> 6 & 63] + BASE64URL_ALPHABET[n & 63];
|
|
44
|
+
} else if (rem === 2) {
|
|
45
|
+
const n = bytes[i] << 10 | bytes[i + 1] << 2;
|
|
46
|
+
out += BASE64URL_ALPHABET[n >>> 12 & 63] + BASE64URL_ALPHABET[n >>> 6 & 63] + BASE64URL_ALPHABET[n & 63];
|
|
47
|
+
}
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
function base64UrlDecodeBytes(encoded, errorCode = "PERSONAL_ACTOR_SIGNATURE_INVALID") {
|
|
51
|
+
if (typeof encoded !== "string") throw new MpcProtocolError(errorCode, "Expected base64url string");
|
|
52
|
+
const len = encoded.length;
|
|
53
|
+
if (len % 4 === 1) throw new MpcProtocolError(errorCode, "Invalid base64url length");
|
|
54
|
+
const vals = new Uint8Array(len);
|
|
55
|
+
for (let i$1 = 0; i$1 < len; i$1++) {
|
|
56
|
+
const code = encoded.charCodeAt(i$1);
|
|
57
|
+
if (code >= 128 || BASE64URL_LOOKUP[code] < 0) throw new MpcProtocolError(errorCode, "Invalid character in base64url string");
|
|
58
|
+
vals[i$1] = BASE64URL_LOOKUP[code];
|
|
59
|
+
}
|
|
60
|
+
const rem = len % 4;
|
|
61
|
+
if (rem === 2 && (vals[len - 1] & 15) !== 0) throw new MpcProtocolError(errorCode, "Non-canonical trailing bits in base64url string");
|
|
62
|
+
if (rem === 3 && (vals[len - 1] & 3) !== 0) throw new MpcProtocolError(errorCode, "Non-canonical trailing bits in base64url string");
|
|
63
|
+
const outLen = Math.floor(len * 3 / 4);
|
|
64
|
+
const out = new Uint8Array(outLen);
|
|
65
|
+
let outIdx = 0;
|
|
66
|
+
let i = 0;
|
|
67
|
+
for (; i + 3 < len; i += 4) {
|
|
68
|
+
const n = vals[i] << 18 | vals[i + 1] << 12 | vals[i + 2] << 6 | vals[i + 3];
|
|
69
|
+
out[outIdx++] = n >>> 16 & 255;
|
|
70
|
+
out[outIdx++] = n >>> 8 & 255;
|
|
71
|
+
out[outIdx++] = n & 255;
|
|
72
|
+
}
|
|
73
|
+
if (rem === 2) out[outIdx++] = (vals[i] << 2 | vals[i + 1] >>> 4) & 255;
|
|
74
|
+
else if (rem === 3) {
|
|
75
|
+
const n = vals[i] << 10 | vals[i + 1] << 4 | vals[i + 2] >>> 2;
|
|
76
|
+
out[outIdx++] = n >>> 8 & 255;
|
|
77
|
+
out[outIdx++] = n & 255;
|
|
78
|
+
}
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
function toArrayBuffer(bytes) {
|
|
82
|
+
return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
|
83
|
+
}
|
|
84
|
+
function getSubtleCrypto() {
|
|
85
|
+
const subtle = globalThis.crypto?.subtle;
|
|
86
|
+
if (!subtle) throw new MpcProtocolError("INVALID_PARAMETER", "WebCrypto SubtleCrypto is unavailable");
|
|
87
|
+
return subtle;
|
|
88
|
+
}
|
|
89
|
+
async function aes256GcmEncryptDetached(params) {
|
|
90
|
+
const { key32, iv12, plaintext, aad } = params;
|
|
91
|
+
if (!(key32 instanceof Uint8Array) || key32.length !== 32) throw new MpcProtocolError("INVALID_PARAMETER", "AES-256-GCM key32 must be 32 bytes");
|
|
92
|
+
if (!(iv12 instanceof Uint8Array) || iv12.length !== 12) throw new MpcProtocolError("INVALID_PARAMETER", "AES-256-GCM iv12 must be 12 bytes");
|
|
93
|
+
const subtle = getSubtleCrypto();
|
|
94
|
+
const cryptoKey = await subtle.importKey("raw", toArrayBuffer(key32), { name: "AES-GCM" }, false, ["encrypt"]);
|
|
95
|
+
const combinedBuf = await subtle.encrypt({
|
|
96
|
+
name: "AES-GCM",
|
|
97
|
+
iv: toArrayBuffer(iv12),
|
|
98
|
+
additionalData: toArrayBuffer(aad),
|
|
99
|
+
tagLength: 128
|
|
100
|
+
}, cryptoKey, toArrayBuffer(plaintext));
|
|
101
|
+
const combined = new Uint8Array(combinedBuf);
|
|
102
|
+
return {
|
|
103
|
+
ciphertext: combined.slice(0, plaintext.length),
|
|
104
|
+
tag16: combined.slice(plaintext.length, plaintext.length + 16)
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
async function aes256GcmDecryptDetached(params) {
|
|
108
|
+
const { key32, iv12, ciphertext, tag16, aad, authFailureCode = "PERSONAL_ENVELOPE_AUTH_FAILED" } = params;
|
|
109
|
+
if (!(key32 instanceof Uint8Array) || key32.length !== 32) throw new MpcProtocolError("INVALID_PARAMETER", "AES-256-GCM key32 must be 32 bytes");
|
|
110
|
+
if (!(iv12 instanceof Uint8Array) || iv12.length !== 12 || !(tag16 instanceof Uint8Array) || tag16.length !== 16) throw new MpcProtocolError(authFailureCode, "Invalid AES-256-GCM IV or authentication tag length");
|
|
111
|
+
const subtle = getSubtleCrypto();
|
|
112
|
+
const cryptoKey = await subtle.importKey("raw", toArrayBuffer(key32), { name: "AES-GCM" }, false, ["decrypt"]);
|
|
113
|
+
const combined = concatBytes(ciphertext, tag16);
|
|
114
|
+
try {
|
|
115
|
+
const plainBuf = await subtle.decrypt({
|
|
116
|
+
name: "AES-GCM",
|
|
117
|
+
iv: toArrayBuffer(iv12),
|
|
118
|
+
additionalData: toArrayBuffer(aad),
|
|
119
|
+
tagLength: 128
|
|
120
|
+
}, cryptoKey, toArrayBuffer(combined));
|
|
121
|
+
return new Uint8Array(plainBuf);
|
|
122
|
+
} catch {
|
|
123
|
+
throw new MpcProtocolError(authFailureCode, "AES-256-GCM authentication failed");
|
|
124
|
+
} finally {
|
|
125
|
+
zeroizeBytes(combined);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
function readU16BE(bytes, offset) {
|
|
129
|
+
return (bytes[offset] << 8 | bytes[offset + 1]) >>> 0;
|
|
130
|
+
}
|
|
131
|
+
function readU64BE(bytes, offset) {
|
|
132
|
+
let acc = 0n;
|
|
133
|
+
for (let i = 0; i < 8; i++) acc = acc << 8n | BigInt(bytes[offset + i]);
|
|
134
|
+
return acc;
|
|
135
|
+
}
|
|
136
|
+
const MAX_UINT64 = (1n << 64n) - 1n;
|
|
137
|
+
const MAX_UINT128 = (1n << 128n) - 1n;
|
|
138
|
+
const MAX_UINT256 = (1n << 256n) - 1n;
|
|
139
|
+
const PERSONAL_MAX_VELOCITY_UINT128 = MAX_UINT128;
|
|
140
|
+
const UNLIMITED_APPROVE_THRESHOLD = 1n << 255n;
|
|
141
|
+
function assertPrintableIdentifierAscii(id, maxBytes, label, errorCode = "PERSONAL_BLOB_MALFORMED") {
|
|
142
|
+
if (typeof id !== "string" || id.length === 0 || id.length > maxBytes) throw new MpcProtocolError(errorCode, `${label} must be 1..${maxBytes} printable ASCII characters`);
|
|
143
|
+
for (let i = 0; i < id.length; i++) {
|
|
144
|
+
const code = id.charCodeAt(i);
|
|
145
|
+
if (code < 33 || code > 126) throw new MpcProtocolError(errorCode, `${label} contains non-printable or whitespace ASCII character`);
|
|
146
|
+
}
|
|
147
|
+
return utf8Bytes(id);
|
|
148
|
+
}
|
|
149
|
+
function decodeZeroPaddedIdentifierAscii(blob, lenOffset, maxLen, label) {
|
|
150
|
+
const declaredLen = blob[lenOffset];
|
|
151
|
+
if (declaredLen < 1 || declaredLen > maxLen) throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", `Invalid ${label} length ${declaredLen} in blob header`);
|
|
152
|
+
const fieldStart = lenOffset + 1;
|
|
153
|
+
const fieldEnd = fieldStart + maxLen;
|
|
154
|
+
for (let i = fieldStart; i < fieldStart + declaredLen; i++) {
|
|
155
|
+
const b = blob[i];
|
|
156
|
+
if (b < 33 || b > 126) throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", `Invalid ASCII byte 0x${b.toString(16)} in ${label}`);
|
|
157
|
+
}
|
|
158
|
+
for (let i = fieldStart + declaredLen; i < fieldEnd; i++) if (blob[i] !== 0) throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", `Non-zero trailing padding in ${label}`);
|
|
159
|
+
return utf8DecodeStrict(blob.subarray(fieldStart, fieldStart + declaredLen), "PERSONAL_BLOB_MALFORMED");
|
|
160
|
+
}
|
|
161
|
+
const ACTOR_KIND_AND_ALG_BYTE = {
|
|
162
|
+
"human-p256": 1,
|
|
163
|
+
"agent-ed25519": 2,
|
|
164
|
+
"agent-p256": 3
|
|
165
|
+
};
|
|
166
|
+
const HSM_SEALED_BLOB_VERSION = 1;
|
|
167
|
+
const HSM_SEALED_BLOB_HEADER_BYTES = 319;
|
|
168
|
+
const HSM_SEALED_BLOB_HEADER_MAC_OFFSET = 319;
|
|
169
|
+
const HSM_SEALED_BLOB_HEADER_WITH_MAC_BYTES = 351;
|
|
170
|
+
const HSM_SEALED_BLOB_IV_OFFSET = 351;
|
|
171
|
+
const HSM_SEALED_BLOB_TAG_OFFSET = 363;
|
|
172
|
+
const HSM_SEALED_BLOB_CIPHERTEXT_OFFSET = 379;
|
|
173
|
+
const HSM_SEALED_BLOB_CIPHERTEXT_BYTES = 3717;
|
|
174
|
+
const HSM_SEALED_BLOB_MAX_POLICY_UTF8_BYTES = 3642;
|
|
175
|
+
const HSM_BLOB_MAGIC_BYTES_8 = utf8Bytes(DST_PERSONAL_BLOB_MAGIC);
|
|
176
|
+
function actorKindAndAlgToByte(kind) {
|
|
177
|
+
const b = ACTOR_KIND_AND_ALG_BYTE[kind];
|
|
178
|
+
if (b === void 0) throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", `Unsupported actorKindAndAlg: ${String(kind)}`);
|
|
179
|
+
return b;
|
|
180
|
+
}
|
|
181
|
+
function byteToActorKindAndAlg(byte) {
|
|
182
|
+
if (byte === 1) return "human-p256";
|
|
183
|
+
if (byte === 2) return "agent-ed25519";
|
|
184
|
+
if (byte === 3) return "agent-p256";
|
|
185
|
+
throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", `Unknown actorKindAndAlg byte: 0x${byte.toString(16)}`);
|
|
186
|
+
}
|
|
187
|
+
function isAgentActorKind(kind) {
|
|
188
|
+
return kind === "agent-ed25519" || kind === "agent-p256";
|
|
189
|
+
}
|
|
190
|
+
function validateEd25519PublicKeyNonTorsion32(pubKey32, errorCode = "PERSONAL_BLOB_MALFORMED") {
|
|
191
|
+
if (!(pubKey32 instanceof Uint8Array) || pubKey32.length !== 32) throw new MpcProtocolError(errorCode, "Ed25519 public key must be 32 bytes");
|
|
192
|
+
let pt;
|
|
193
|
+
try {
|
|
194
|
+
pt = ed25519.Point.fromBytes(pubKey32, false);
|
|
195
|
+
pt.assertValidity();
|
|
196
|
+
} catch {
|
|
197
|
+
throw new MpcProtocolError(errorCode, "Invalid Ed25519 public key encoding");
|
|
198
|
+
}
|
|
199
|
+
if (pt.is0() || pt.clearCofactor().is0()) throw new MpcProtocolError(errorCode, "Low-order torsion or identity Ed25519 public key rejected");
|
|
200
|
+
}
|
|
201
|
+
function validateP256UncompressedPublicKey65(pubKey65, errorCode = "PERSONAL_BLOB_MALFORMED") {
|
|
202
|
+
if (!(pubKey65 instanceof Uint8Array) || pubKey65.length !== 65 || pubKey65[0] !== 4) throw new MpcProtocolError(errorCode, "Expected 65-byte uncompressed (0x04) P-256 public key");
|
|
203
|
+
try {
|
|
204
|
+
const pt = p256.Point.fromBytes(pubKey65);
|
|
205
|
+
pt.assertValidity();
|
|
206
|
+
if (pt.is0()) throw new Error("P-256 infinity");
|
|
207
|
+
} catch {
|
|
208
|
+
throw new MpcProtocolError(errorCode, "Invalid off-curve P-256 public key");
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Normalizes an actor public key (`33B` compressed or `65B` uncompressed P-256 for `0x01`/`0x03`,
|
|
213
|
+
* or `32B` Ed25519 / `65B` zero-padded Ed25519 for `0x02`) into canonical `65`-byte padded format.
|
|
214
|
+
*/
|
|
215
|
+
function normalizeActorPublicKeyToPadded65(actorKindAndAlg, pubKeyInput, errorCode = "PERSONAL_BLOB_MALFORMED") {
|
|
216
|
+
actorKindAndAlgToByte(actorKindAndAlg);
|
|
217
|
+
const raw = normalizeHexBytes(pubKeyInput);
|
|
218
|
+
if (actorKindAndAlg === "human-p256" || actorKindAndAlg === "agent-p256") {
|
|
219
|
+
if (raw.length !== 33 && raw.length !== 65) throw new MpcProtocolError(errorCode, "P-256 public key must be 33 (compressed) or 65 (uncompressed) bytes");
|
|
220
|
+
try {
|
|
221
|
+
const pt = p256.Point.fromBytes(raw);
|
|
222
|
+
pt.assertValidity();
|
|
223
|
+
if (pt.is0()) throw new Error("P-256 infinity");
|
|
224
|
+
return pt.toBytes(false);
|
|
225
|
+
} catch {
|
|
226
|
+
throw new MpcProtocolError(errorCode, "Invalid P-256 actor public key");
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
if (raw.length === 32) {
|
|
230
|
+
validateEd25519PublicKeyNonTorsion32(raw, errorCode);
|
|
231
|
+
const out = new Uint8Array(65);
|
|
232
|
+
out.set(raw, 0);
|
|
233
|
+
return out;
|
|
234
|
+
}
|
|
235
|
+
if (raw.length === 65) {
|
|
236
|
+
for (let i = 32; i < 65; i++) if (raw[i] !== 0) throw new MpcProtocolError(errorCode, "Non-zero trailing padding in 65-byte Ed25519 actor public key");
|
|
237
|
+
validateEd25519PublicKeyNonTorsion32(raw.subarray(0, 32), errorCode);
|
|
238
|
+
return new Uint8Array(raw);
|
|
239
|
+
}
|
|
240
|
+
throw new MpcProtocolError(errorCode, "Ed25519 public key must be 32 bytes (or 65 zero-padded bytes)");
|
|
241
|
+
}
|
|
242
|
+
function validateActorPublicKeyPadded65(actorKindAndAlg, actorPubKeyPadded65, errorCode = "PERSONAL_BLOB_MALFORMED") {
|
|
243
|
+
if (!(actorPubKeyPadded65 instanceof Uint8Array) || actorPubKeyPadded65.length !== 65) throw new MpcProtocolError(errorCode, "actorPubKeyPadded65 must be exactly 65 bytes");
|
|
244
|
+
if (actorKindAndAlg === "human-p256" || actorKindAndAlg === "agent-p256") {
|
|
245
|
+
validateP256UncompressedPublicKey65(actorPubKeyPadded65, errorCode);
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
for (let i = 32; i < 65; i++) if (actorPubKeyPadded65[i] !== 0) throw new MpcProtocolError(errorCode, "Non-zero trailing padding in Ed25519 actorPubKeyPadded65[32..64]");
|
|
249
|
+
validateEd25519PublicKeyNonTorsion32(actorPubKeyPadded65.subarray(0, 32), errorCode);
|
|
250
|
+
}
|
|
251
|
+
function canonicalizePersonalBlobAadBytes(aad) {
|
|
252
|
+
if (aad === void 0) return lengthPrefixedEncode(DST_PERSONAL_BLOB_AAD_V1, [u8(0)]);
|
|
253
|
+
if (aad instanceof Uint8Array) return lengthPrefixedEncode(DST_PERSONAL_BLOB_AAD_V1, [u8(1), aad]);
|
|
254
|
+
if (typeof aad === "string") return lengthPrefixedEncode(DST_PERSONAL_BLOB_AAD_V1, [u8(2), utf8Bytes(aad)]);
|
|
255
|
+
if (typeof aad === "object" && aad !== null && !Array.isArray(aad)) {
|
|
256
|
+
const sortedKeys = Object.keys(aad).sort();
|
|
257
|
+
const parts = [u8(3), u32be(sortedKeys.length)];
|
|
258
|
+
for (const k of sortedKeys) {
|
|
259
|
+
const val = aad[k];
|
|
260
|
+
if (typeof val !== "string") throw new MpcProtocolError("INVALID_PARAMETER", `AAD map key "${k}" must have a string value`);
|
|
261
|
+
parts.push(utf8Bytes(k), utf8Bytes(val));
|
|
262
|
+
}
|
|
263
|
+
return lengthPrefixedEncode(DST_PERSONAL_BLOB_AAD_V1, parts);
|
|
264
|
+
}
|
|
265
|
+
throw new MpcProtocolError("INVALID_PARAMETER", "Unsupported PersonalBlobAadInput type");
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Encodes the canonical `319`-byte `HsmSealedBlob` header (`[0..318]`, `design.md` §4.1).
|
|
269
|
+
*/
|
|
270
|
+
function encodeHsmSealedBlobHeader319(params) {
|
|
271
|
+
const kidBytes = assertPrintableIdentifierAscii(params.kid, 32, "kid");
|
|
272
|
+
const vaultIdBytes = assertPrintableIdentifierAscii(params.vaultId, 64, "vaultId");
|
|
273
|
+
const slotIdBytes = assertPrintableIdentifierAscii(params.slotId, 64, "slotId");
|
|
274
|
+
let pRootComp33;
|
|
275
|
+
try {
|
|
276
|
+
pRootComp33 = encodePointCompressed(decodePointCompressed(normalizeHexBytes(params.rootPublicKeyComp33, 33), false));
|
|
277
|
+
} catch {
|
|
278
|
+
throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", "Invalid secp256k1 rootPublicKeyComp33 in header");
|
|
279
|
+
}
|
|
280
|
+
if (typeof params.policyEpoch !== "bigint" || params.policyEpoch < 1n || params.policyEpoch > MAX_UINT64) throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", "policyEpoch must satisfy 1 <= policyEpoch <= 2^64-1");
|
|
281
|
+
const actorKindByte = actorKindAndAlgToByte(params.actorKindAndAlg);
|
|
282
|
+
const actorPubKey65 = normalizeActorPublicKeyToPadded65(params.actorKindAndAlg, params.actorPublicKey, "PERSONAL_BLOB_MALFORMED");
|
|
283
|
+
if (typeof params.slotExpiresAtSec !== "bigint" || params.slotExpiresAtSec < 0n || params.slotExpiresAtSec > MAX_UINT64) throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", "Invalid slotExpiresAtSec uint64");
|
|
284
|
+
if (isAgentActorKind(params.actorKindAndAlg) && params.slotExpiresAtSec <= 0n) throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", `Agent actor slot (${params.actorKindAndAlg}) requires mandatory slotExpiresAtSec > 0n`);
|
|
285
|
+
let policyHashBytes32;
|
|
286
|
+
try {
|
|
287
|
+
policyHashBytes32 = normalizeHexBytes(params.policyHash32, 32);
|
|
288
|
+
} catch {
|
|
289
|
+
throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", "policyHash32 must be 32 bytes");
|
|
290
|
+
}
|
|
291
|
+
const header = new Uint8Array(HSM_SEALED_BLOB_HEADER_BYTES);
|
|
292
|
+
header.set(HSM_BLOB_MAGIC_BYTES_8, 0);
|
|
293
|
+
header[8] = HSM_SEALED_BLOB_VERSION;
|
|
294
|
+
header[9] = kidBytes.length;
|
|
295
|
+
header.set(kidBytes, 10);
|
|
296
|
+
header[42] = vaultIdBytes.length;
|
|
297
|
+
header.set(vaultIdBytes, 43);
|
|
298
|
+
header[107] = slotIdBytes.length;
|
|
299
|
+
header.set(slotIdBytes, 108);
|
|
300
|
+
header.set(pRootComp33, 172);
|
|
301
|
+
header.set(u64be(params.policyEpoch), 205);
|
|
302
|
+
header[213] = actorKindByte;
|
|
303
|
+
header.set(actorPubKey65, 214);
|
|
304
|
+
header.set(u64be(params.slotExpiresAtSec), 279);
|
|
305
|
+
header.set(policyHashBytes32, 287);
|
|
306
|
+
return header;
|
|
307
|
+
}
|
|
308
|
+
function decodeHsmSealedBlobHeader319(headerBytes) {
|
|
309
|
+
if (!(headerBytes instanceof Uint8Array) || headerBytes.length !== HSM_SEALED_BLOB_HEADER_BYTES) throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", `Expected ${HSM_SEALED_BLOB_HEADER_BYTES}-byte header, got ${headerBytes?.length}`);
|
|
310
|
+
if (!constantTimeEqual(headerBytes.subarray(0, 8), HSM_BLOB_MAGIC_BYTES_8)) throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", "Invalid HsmSealedBlob magic bytes");
|
|
311
|
+
const version = headerBytes[8];
|
|
312
|
+
if (version !== HSM_SEALED_BLOB_VERSION) throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", `Unsupported HsmSealedBlob version: ${version}`);
|
|
313
|
+
const kid = decodeZeroPaddedIdentifierAscii(headerBytes, 9, 32, "kid");
|
|
314
|
+
const vaultId = decodeZeroPaddedIdentifierAscii(headerBytes, 42, 64, "vaultId");
|
|
315
|
+
const slotId = decodeZeroPaddedIdentifierAscii(headerBytes, 107, 64, "slotId");
|
|
316
|
+
const rootPublicKeyComp33 = headerBytes.slice(172, 205);
|
|
317
|
+
try {
|
|
318
|
+
decodePointCompressed(rootPublicKeyComp33, false);
|
|
319
|
+
} catch {
|
|
320
|
+
throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", "Invalid secp256k1 rootPublicKeyComp33 in blob header");
|
|
321
|
+
}
|
|
322
|
+
const policyEpoch = readU64BE(headerBytes, 205);
|
|
323
|
+
if (policyEpoch < 1n) throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", "policyEpoch in blob header must be >= 1n");
|
|
324
|
+
const actorKindAndAlg = byteToActorKindAndAlg(headerBytes[213]);
|
|
325
|
+
const actorPubKeyPadded65 = headerBytes.slice(214, 279);
|
|
326
|
+
validateActorPublicKeyPadded65(actorKindAndAlg, actorPubKeyPadded65, "PERSONAL_BLOB_MALFORMED");
|
|
327
|
+
const slotExpiresAtSec = readU64BE(headerBytes, 279);
|
|
328
|
+
if (isAgentActorKind(actorKindAndAlg) && slotExpiresAtSec <= 0n) throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", "Agent slot header missing mandatory slotExpiresAtSec > 0n");
|
|
329
|
+
return {
|
|
330
|
+
version: 1,
|
|
331
|
+
kid,
|
|
332
|
+
vaultId,
|
|
333
|
+
slotId,
|
|
334
|
+
rootPublicKeyComp33,
|
|
335
|
+
policyEpoch,
|
|
336
|
+
actorKindAndAlg,
|
|
337
|
+
actorPubKeyPadded65,
|
|
338
|
+
slotExpiresAtSec,
|
|
339
|
+
policyHash32: headerBytes.slice(287, 319)
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Parses and validates a fixed `4,096`-byte `HsmSealedBlob` (`design.md` §4.1).
|
|
344
|
+
*/
|
|
345
|
+
function parseHsmSealedBlobHeader(blobBytes) {
|
|
346
|
+
if (!(blobBytes instanceof Uint8Array) || blobBytes.length !== HSM_SEALED_BLOB_BYTES) throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", `HsmSealedBlob must be exactly ${HSM_SEALED_BLOB_BYTES} bytes, got ${blobBytes?.length}`);
|
|
347
|
+
const header319 = blobBytes.slice(0, HSM_SEALED_BLOB_HEADER_BYTES);
|
|
348
|
+
return {
|
|
349
|
+
header: decodeHsmSealedBlobHeader319(header319),
|
|
350
|
+
header319,
|
|
351
|
+
headerMac32: blobBytes.slice(HSM_SEALED_BLOB_HEADER_MAC_OFFSET, HSM_SEALED_BLOB_HEADER_WITH_MAC_BYTES),
|
|
352
|
+
authenticatedPrefix351: blobBytes.slice(0, HSM_SEALED_BLOB_HEADER_WITH_MAC_BYTES),
|
|
353
|
+
aesGcmIv12: blobBytes.slice(HSM_SEALED_BLOB_IV_OFFSET, HSM_SEALED_BLOB_TAG_OFFSET),
|
|
354
|
+
aesGcmTag16: blobBytes.slice(HSM_SEALED_BLOB_TAG_OFFSET, HSM_SEALED_BLOB_CIPHERTEXT_OFFSET),
|
|
355
|
+
ciphertext3717: blobBytes.slice(HSM_SEALED_BLOB_CIPHERTEXT_OFFSET, HSM_SEALED_BLOB_BYTES)
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
function assertPersonalSlotNotExpired(header, nowSec) {
|
|
359
|
+
if (isAgentActorKind(header.actorKindAndAlg) && header.slotExpiresAtSec <= 0n) throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", "Agent slot requires slotExpiresAtSec > 0n");
|
|
360
|
+
if (header.slotExpiresAtSec > 0n && nowSec >= header.slotExpiresAtSec) throw new MpcProtocolError("PERSONAL_SLOT_EXPIRED", "Actor slot has expired");
|
|
361
|
+
}
|
|
362
|
+
function computeHsmSealedBlobHeaderMac32(params) {
|
|
363
|
+
if (!(params.headerMacKey32 instanceof Uint8Array) || params.headerMacKey32.length !== 32) throw new MpcProtocolError("INVALID_PARAMETER", "headerMacKey32 must be 32 bytes");
|
|
364
|
+
if (!(params.header319 instanceof Uint8Array) || params.header319.length !== HSM_SEALED_BLOB_HEADER_BYTES) throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", "header319 must be 319 bytes");
|
|
365
|
+
const canonicalAad = canonicalizePersonalBlobAadBytes(params.aad);
|
|
366
|
+
return hmac(sha256, params.headerMacKey32, concatBytes(params.header319, canonicalAad));
|
|
367
|
+
}
|
|
368
|
+
function deriveHsmPersonalSealKey32(params) {
|
|
369
|
+
if (params.hsmWrappingKey32.length !== 32 || params.kUnsealSecret32.length !== 32) throw new MpcProtocolError("INVALID_PARAMETER", "hsmWrappingKey32 and kUnsealSecret32 must be 32 bytes");
|
|
370
|
+
const ikm64 = concatBytes(params.hsmWrappingKey32, params.kUnsealSecret32);
|
|
371
|
+
const salt32 = sha256(lengthPrefixedEncode(DST_PERSONAL_SEAL_SALT_V1, [utf8Bytes(params.vaultId), utf8Bytes(params.slotId)]));
|
|
372
|
+
try {
|
|
373
|
+
return hkdf(sha256, ikm64, salt32, utf8Bytes(DST_PERSONAL_SEAL_KEY_V1), 32);
|
|
374
|
+
} finally {
|
|
375
|
+
zeroizeBytes(ikm64, salt32);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
function encodeHsmSealedBlobInnerPlaintext3717(params) {
|
|
379
|
+
const sHsm = bytes32ToScalarNonZero(params.sHsmBytes32);
|
|
380
|
+
const pRoot = decodePointCompressed(params.rootPublicKeyComp33, false);
|
|
381
|
+
const xActor = decodePointCompressed(params.xActorComp33, false);
|
|
382
|
+
if (xActor.equals(pRoot)) throw new MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Degenerate X_actor == P_root forbidden");
|
|
383
|
+
if (!xActor.add(mulBaseG(sHsm)).equals(pRoot)) throw new MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "X_actor + s_hsm * G != P_root");
|
|
384
|
+
if (params.canonicalPolicyUtf8.length < 1 || params.canonicalPolicyUtf8.length > HSM_SEALED_BLOB_MAX_POLICY_UTF8_BYTES) throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", `Policy UTF-8 length must be 1..${HSM_SEALED_BLOB_MAX_POLICY_UTF8_BYTES}`);
|
|
385
|
+
if (!constantTimeEqual(sha256(lengthPrefixedEncode(DST_PERSONAL_POLICY_V1, [params.canonicalPolicyUtf8])), params.expectedPolicyHash32)) throw new MpcProtocolError("PERSONAL_BLOB_TAMPERED", "Policy hash mismatch against header");
|
|
386
|
+
const out = new Uint8Array(HSM_SEALED_BLOB_CIPHERTEXT_BYTES);
|
|
387
|
+
out.set(params.sHsmBytes32, 0);
|
|
388
|
+
out.set(encodePointCompressed(xActor), 32);
|
|
389
|
+
out.set(u64be(params.sealedAtSec), 65);
|
|
390
|
+
out.set(u16be(params.canonicalPolicyUtf8.length), 73);
|
|
391
|
+
out.set(params.canonicalPolicyUtf8, 75);
|
|
392
|
+
return out;
|
|
393
|
+
}
|
|
394
|
+
function decodeHsmSealedBlobInnerPlaintext3717(params) {
|
|
395
|
+
const { plaintext3717, rootPublicKeyComp33, expectedPolicyHash32 } = params;
|
|
396
|
+
if (!(plaintext3717 instanceof Uint8Array) || plaintext3717.length !== HSM_SEALED_BLOB_CIPHERTEXT_BYTES) throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", "Inner plaintext must be 3717 bytes");
|
|
397
|
+
const sHsmBytes32 = plaintext3717.slice(0, 32);
|
|
398
|
+
const xActorComp33 = plaintext3717.slice(32, 65);
|
|
399
|
+
try {
|
|
400
|
+
const sHsm = bytes32ToScalarNonZero(sHsmBytes32);
|
|
401
|
+
const pRoot = decodePointCompressed(rootPublicKeyComp33, false);
|
|
402
|
+
const xActor = decodePointCompressed(xActorComp33, false);
|
|
403
|
+
if (xActor.equals(pRoot) || !xActor.add(mulBaseG(sHsm)).equals(pRoot)) throw new MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Invalid unsealed additive split against P_root");
|
|
404
|
+
const sealedAtSec = readU64BE(plaintext3717, 65);
|
|
405
|
+
const policyJsonLen = readU16BE(plaintext3717, 73);
|
|
406
|
+
if (policyJsonLen < 1 || policyJsonLen > HSM_SEALED_BLOB_MAX_POLICY_UTF8_BYTES) throw new MpcProtocolError("PERSONAL_BLOB_TAMPERED", `Invalid policyJsonLen ${policyJsonLen} in unsealed blob`);
|
|
407
|
+
const padStart = 75 + policyJsonLen;
|
|
408
|
+
for (let i = padStart; i < HSM_SEALED_BLOB_CIPHERTEXT_BYTES; i++) if (plaintext3717[i] !== 0) throw new MpcProtocolError("PERSONAL_BLOB_TAMPERED", "Non-zero padding byte detected in unsealed blob");
|
|
409
|
+
const canonicalPolicyUtf8 = plaintext3717.slice(75, padStart);
|
|
410
|
+
if (!constantTimeEqual(sha256(lengthPrefixedEncode(DST_PERSONAL_POLICY_V1, [canonicalPolicyUtf8])), expectedPolicyHash32)) throw new MpcProtocolError("PERSONAL_BLOB_TAMPERED", "Unsealed policy hash mismatch");
|
|
411
|
+
return {
|
|
412
|
+
sHsmBytes32,
|
|
413
|
+
xActorComp33,
|
|
414
|
+
sealedAtSec,
|
|
415
|
+
canonicalPolicyUtf8,
|
|
416
|
+
canonicalPolicyJson: utf8DecodeStrict(canonicalPolicyUtf8, "PERSONAL_BLOB_TAMPERED")
|
|
417
|
+
};
|
|
418
|
+
} catch (err) {
|
|
419
|
+
zeroizeBytes(sHsmBytes32);
|
|
420
|
+
throw err;
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
function deriveBlindVaultTag32(blindTagKey32, vaultId, rootPublicKeyComp33) {
|
|
424
|
+
if (blindTagKey32.length !== 32) throw new MpcProtocolError("INVALID_PARAMETER", "blindTagKey32 must be 32 bytes");
|
|
425
|
+
const pRoot = encodePointCompressed(decodePointCompressed(rootPublicKeyComp33, false));
|
|
426
|
+
return hmac(sha256, blindTagKey32, lengthPrefixedEncode(DST_PERSONAL_BLIND_VAULT_TAG_V1, [utf8Bytes(vaultId), pRoot]));
|
|
427
|
+
}
|
|
428
|
+
function deriveBlindSlotTag32(blindTagKey32, vaultId, slotId, rootPublicKeyComp33) {
|
|
429
|
+
if (blindTagKey32.length !== 32) throw new MpcProtocolError("INVALID_PARAMETER", "blindTagKey32 must be 32 bytes");
|
|
430
|
+
const pRoot = encodePointCompressed(decodePointCompressed(rootPublicKeyComp33, false));
|
|
431
|
+
return hmac(sha256, blindTagKey32, lengthPrefixedEncode(DST_PERSONAL_BLIND_SLOT_TAG_V1, [
|
|
432
|
+
utf8Bytes(vaultId),
|
|
433
|
+
utf8Bytes(slotId),
|
|
434
|
+
pRoot
|
|
435
|
+
]));
|
|
436
|
+
}
|
|
437
|
+
function deriveBlindVelocityTag32(blindTagKey32, vaultId, rootPublicKeyComp33, chainId, assetKeyLower) {
|
|
438
|
+
if (blindTagKey32.length !== 32) throw new MpcProtocolError("INVALID_PARAMETER", "blindTagKey32 must be 32 bytes");
|
|
439
|
+
const pRoot = encodePointCompressed(decodePointCompressed(rootPublicKeyComp33, false));
|
|
440
|
+
return hmac(sha256, blindTagKey32, lengthPrefixedEncode(DST_PERSONAL_BLIND_VELOCITY_TAG_V1, [
|
|
441
|
+
utf8Bytes(vaultId),
|
|
442
|
+
pRoot,
|
|
443
|
+
u64be(chainId),
|
|
444
|
+
utf8Bytes(assetKeyLower.toLowerCase())
|
|
445
|
+
]));
|
|
446
|
+
}
|
|
447
|
+
function deriveBlindOcapVelocityTag32(blindTagKey32, vaultId, rootPublicKeyComp33, ocapChainId, assetIdentifier) {
|
|
448
|
+
if (blindTagKey32.length !== 32) throw new MpcProtocolError("INVALID_PARAMETER", "blindTagKey32 must be 32 bytes");
|
|
449
|
+
const chainBytes = assertPrintableIdentifierAscii(ocapChainId, 64, "ocapChainId", "INVALID_PARAMETER");
|
|
450
|
+
const assetBytes = assertPrintableIdentifierAscii(assetIdentifier, 64, "assetIdentifier", "INVALID_PARAMETER");
|
|
451
|
+
const pRoot = encodePointCompressed(decodePointCompressed(rootPublicKeyComp33, false));
|
|
452
|
+
return hmac(sha256, blindTagKey32, lengthPrefixedEncode(DST_PERSONAL_BLIND_OCAP_VELOCITY_TAG_V1, [
|
|
453
|
+
utf8Bytes(vaultId),
|
|
454
|
+
pRoot,
|
|
455
|
+
chainBytes,
|
|
456
|
+
assetBytes
|
|
457
|
+
]));
|
|
458
|
+
}
|
|
459
|
+
const INV_TWO_MOD_N = invModN(2n);
|
|
460
|
+
function additiveToShamirSlot1Share(sActor32) {
|
|
461
|
+
return scalarToBytes32(mulModN(INV_TWO_MOD_N, bytes32ToScalarNonZero(sActor32)));
|
|
462
|
+
}
|
|
463
|
+
function additiveToShamirSlot2Share(sHsm32) {
|
|
464
|
+
return scalarToBytes32(negModN(bytes32ToScalarNonZero(sHsm32)));
|
|
465
|
+
}
|
|
466
|
+
function verifyPersonalAdditiveSplitMatchesRoot(params) {
|
|
467
|
+
const sActor = bytes32ToScalarNonZero(params.sActor32);
|
|
468
|
+
const sHsm = bytes32ToScalarNonZero(params.sHsm32);
|
|
469
|
+
if (addModN(sActor, sHsm) === 0n) throw new MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "s_actor + s_hsm collapsed to 0 mod n");
|
|
470
|
+
const pRoot = decodePointCompressed(normalizeHexBytes(params.rootPublicKeyComp33, 33), false);
|
|
471
|
+
const xActor = mulBaseG(sActor);
|
|
472
|
+
const xHsm = mulBaseG(sHsm);
|
|
473
|
+
if (xActor.is0() || xHsm.is0() || xActor.equals(pRoot)) throw new MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Degenerate additive split point");
|
|
474
|
+
if (!xActor.add(xHsm).equals(pRoot)) throw new MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "s_actor * G + s_hsm * G != P_root");
|
|
475
|
+
const xActorEncoded = encodePointCompressed(xActor);
|
|
476
|
+
if (params.xActorComp33 !== void 0) {
|
|
477
|
+
if (!constantTimeEqual(xActorEncoded, normalizeHexBytes(params.xActorComp33, 33))) throw new MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "X_actor mismatch against s_actor * G");
|
|
478
|
+
}
|
|
479
|
+
return {
|
|
480
|
+
xActorComp33: xActorEncoded,
|
|
481
|
+
xHsmComp33: encodePointCompressed(xHsm)
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
function buildPersonalVaultClusterInfo(params) {
|
|
485
|
+
assertPrintableIdentifierAscii(params.vaultId, 64, "vaultId", "INVALID_PARAMETER");
|
|
486
|
+
assertPrintableIdentifierAscii(params.slotId, 64, "slotId", "INVALID_PARAMETER");
|
|
487
|
+
if (typeof params.policyEpoch !== "bigint" || params.policyEpoch < 1n || params.policyEpoch > MAX_UINT64) throw new MpcProtocolError("INVALID_PARAMETER", "policyEpoch must satisfy 1 <= policyEpoch <= 2^64-1");
|
|
488
|
+
const pRoot = decodePointCompressed(normalizeHexBytes(params.rootPublicKeyComp33, 33), false);
|
|
489
|
+
const xActor = decodePointCompressed(normalizeHexBytes(params.xActorComp33, 33), false);
|
|
490
|
+
if (xActor.equals(pRoot)) throw new MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "X_actor cannot equal P_root (s_hsm == 0)");
|
|
491
|
+
const x1Point = mulPoint(xActor, INV_TWO_MOD_N);
|
|
492
|
+
const x2Point = xActor.subtract(pRoot);
|
|
493
|
+
if (x1Point.is0() || x2Point.is0()) throw new MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Degenerate Shamir public share derived from X_actor");
|
|
494
|
+
const pRootComp33 = encodePointCompressed(pRoot);
|
|
495
|
+
const xActorEncoded = encodePointCompressed(xActor);
|
|
496
|
+
const hDkg32 = hashTranscriptSha256(DST_PERSONAL_CLUSTER_HDKG_V1, utf8Bytes(params.vaultId), utf8Bytes(params.slotId), u64be(params.policyEpoch), pRootComp33, xActorEncoded);
|
|
497
|
+
return {
|
|
498
|
+
rootId: params.vaultId,
|
|
499
|
+
keyEpoch: params.policyEpoch,
|
|
500
|
+
t: 2,
|
|
501
|
+
nParties: 2,
|
|
502
|
+
hDkg32,
|
|
503
|
+
rootPublicKeyComp33: pRootComp33,
|
|
504
|
+
publicSharesComp33BySlot: new Map([[1, encodePointCompressed(x1Point)], [2, encodePointCompressed(x2Point)]])
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
function derivePersonalWakePasswordKeys(params) {
|
|
508
|
+
if (typeof params.password !== "string") throw new MpcProtocolError("INVALID_PARAMETER", "Wake password must be a string");
|
|
509
|
+
const normalized = params.password.normalize("NFKC");
|
|
510
|
+
if (normalized.length === 0 || normalized.length > 512) throw new MpcProtocolError("INVALID_PARAMETER", "Wake password must be 1..512 characters after NFKC");
|
|
511
|
+
const salt32 = normalizeHexBytes(params.vaultSalt32, 32);
|
|
512
|
+
const pwdBytes = utf8Bytes(normalized);
|
|
513
|
+
const kdfMode = params.kdf ?? "pbkdf2-sha256";
|
|
514
|
+
let masterKey64 = null;
|
|
515
|
+
try {
|
|
516
|
+
if (kdfMode === "pbkdf2-sha256") {
|
|
517
|
+
const iterations = params.pbkdf2Iterations ?? 21e4;
|
|
518
|
+
if (!Number.isInteger(iterations) || iterations < 1e3 || iterations > 5e6) throw new MpcProtocolError("INVALID_PARAMETER", "pbkdf2Iterations must be in [1000, 5000000]");
|
|
519
|
+
masterKey64 = pbkdf2(sha256, pwdBytes, salt32, {
|
|
520
|
+
c: iterations,
|
|
521
|
+
dkLen: 64
|
|
522
|
+
});
|
|
523
|
+
} else if (kdfMode === "scrypt") {
|
|
524
|
+
const opts = params.scryptOpts ?? {
|
|
525
|
+
N: 16384,
|
|
526
|
+
r: 8,
|
|
527
|
+
p: 1
|
|
528
|
+
};
|
|
529
|
+
if (!Number.isInteger(opts.N) || opts.N < 1024 || (opts.N & opts.N - 1) !== 0) throw new MpcProtocolError("INVALID_PARAMETER", "scrypt N must be a power of 2 >= 1024");
|
|
530
|
+
masterKey64 = scrypt(pwdBytes, salt32, {
|
|
531
|
+
N: opts.N,
|
|
532
|
+
r: opts.r,
|
|
533
|
+
p: opts.p,
|
|
534
|
+
dkLen: 64
|
|
535
|
+
});
|
|
536
|
+
} else throw new MpcProtocolError("INVALID_PARAMETER", `Unsupported KDF mode: ${String(kdfMode)}`);
|
|
537
|
+
return {
|
|
538
|
+
kPwdClient32: hkdf(sha256, masterKey64, salt32, utf8Bytes(DST_PERSONAL_PWD_CLIENT_HKDF_V1), 32),
|
|
539
|
+
kPwdHsm32: hkdf(sha256, masterKey64, salt32, utf8Bytes(DST_PERSONAL_PWD_HSM_HKDF_V1), 32)
|
|
540
|
+
};
|
|
541
|
+
} finally {
|
|
542
|
+
zeroizeBytes(pwdBytes, masterKey64);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
function buildDeviceEnvelopeAad(vaultId, slotId, rootPublicKeyComp33, xActorComp33) {
|
|
546
|
+
return lengthPrefixedEncode(DST_PERSONAL_DEVICE_AAD_V1, [
|
|
547
|
+
utf8Bytes(vaultId),
|
|
548
|
+
utf8Bytes(slotId),
|
|
549
|
+
rootPublicKeyComp33,
|
|
550
|
+
xActorComp33
|
|
551
|
+
]);
|
|
552
|
+
}
|
|
553
|
+
function deriveDeviceEnvelopeKey32(kHw32, kPwdClient32, deviceSalt32) {
|
|
554
|
+
if (kHw32.length !== 32 || kPwdClient32.length !== 32 || deviceSalt32.length !== 32) throw new MpcProtocolError("INVALID_PARAMETER", "kHw32, kPwdClient32, and deviceSalt32 must each be 32 bytes");
|
|
555
|
+
const ikm64 = concatBytes(kHw32, kPwdClient32);
|
|
556
|
+
try {
|
|
557
|
+
return hkdf(sha256, ikm64, deviceSalt32, utf8Bytes(DST_PERSONAL_DEVICE_ENV_V1), 32);
|
|
558
|
+
} finally {
|
|
559
|
+
zeroizeBytes(ikm64);
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
async function sealDeviceShareEnvelope(params) {
|
|
563
|
+
const rng = params.rng ?? defaultRandomBytes;
|
|
564
|
+
assertPrintableIdentifierAscii(params.vaultId, 64, "vaultId", "INVALID_PARAMETER");
|
|
565
|
+
assertPrintableIdentifierAscii(params.slotId, 64, "slotId", "INVALID_PARAMETER");
|
|
566
|
+
const sActor = bytes32ToScalarNonZero(params.sActorBytes32);
|
|
567
|
+
const pRoot = decodePointCompressed(normalizeHexBytes(params.rootPublicKeyComp33, 33), false);
|
|
568
|
+
const xActor = mulBaseG(sActor);
|
|
569
|
+
if (xActor.is0() || xActor.equals(pRoot)) throw new MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Degenerate s_actor share in sealDeviceShareEnvelope");
|
|
570
|
+
const pRootComp33 = encodePointCompressed(pRoot);
|
|
571
|
+
const xActorComp33 = encodePointCompressed(xActor);
|
|
572
|
+
const deviceSalt32 = params.deviceSalt32 ? normalizeHexBytes(params.deviceSalt32, 32) : rng(32);
|
|
573
|
+
const iv12 = rng(12);
|
|
574
|
+
const envKey32 = deriveDeviceEnvelopeKey32(params.kHw32, params.kPwdClient32, deviceSalt32);
|
|
575
|
+
const aad = buildDeviceEnvelopeAad(params.vaultId, params.slotId, pRootComp33, xActorComp33);
|
|
576
|
+
try {
|
|
577
|
+
const { ciphertext, tag16 } = await aes256GcmEncryptDetached({
|
|
578
|
+
key32: envKey32,
|
|
579
|
+
iv12,
|
|
580
|
+
plaintext: params.sActorBytes32,
|
|
581
|
+
aad
|
|
582
|
+
});
|
|
583
|
+
return {
|
|
584
|
+
version: 1,
|
|
585
|
+
vaultId: params.vaultId,
|
|
586
|
+
slotId: params.slotId,
|
|
587
|
+
rootPublicKeyHex: `0x${bytesToHex(pRootComp33)}`,
|
|
588
|
+
xActorPublicKeyHex: `0x${bytesToHex(xActorComp33)}`,
|
|
589
|
+
deviceSaltHex: `0x${bytesToHex(deviceSalt32)}`,
|
|
590
|
+
ivHex: `0x${bytesToHex(iv12)}`,
|
|
591
|
+
tagHex: `0x${bytesToHex(tag16)}`,
|
|
592
|
+
ciphertextHex: `0x${bytesToHex(ciphertext)}`
|
|
593
|
+
};
|
|
594
|
+
} finally {
|
|
595
|
+
zeroizeBytes(envKey32);
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
async function unsealDeviceShareEnvelope(params) {
|
|
599
|
+
const { envelope } = params;
|
|
600
|
+
if (!envelope || envelope.version !== 1) throw new MpcProtocolError("PERSONAL_ENVELOPE_AUTH_FAILED", "Invalid DeviceShareEnvelope version");
|
|
601
|
+
let pRootComp33;
|
|
602
|
+
let xActorComp33;
|
|
603
|
+
let deviceSalt32;
|
|
604
|
+
let iv12;
|
|
605
|
+
let tag16;
|
|
606
|
+
let ciphertext;
|
|
607
|
+
try {
|
|
608
|
+
pRootComp33 = encodePointCompressed(decodePointCompressed(normalizeHexBytes(envelope.rootPublicKeyHex, 33), false));
|
|
609
|
+
xActorComp33 = encodePointCompressed(decodePointCompressed(normalizeHexBytes(envelope.xActorPublicKeyHex, 33), false));
|
|
610
|
+
deviceSalt32 = normalizeHexBytes(envelope.deviceSaltHex, 32);
|
|
611
|
+
iv12 = normalizeHexBytes(envelope.ivHex, 12);
|
|
612
|
+
tag16 = normalizeHexBytes(envelope.tagHex, 16);
|
|
613
|
+
ciphertext = normalizeHexBytes(envelope.ciphertextHex, 32);
|
|
614
|
+
} catch {
|
|
615
|
+
throw new MpcProtocolError("PERSONAL_ENVELOPE_AUTH_FAILED", "Malformed DeviceShareEnvelope fields");
|
|
616
|
+
}
|
|
617
|
+
const envKey32 = deriveDeviceEnvelopeKey32(params.kHw32, params.kPwdClient32, deviceSalt32);
|
|
618
|
+
const aad = buildDeviceEnvelopeAad(envelope.vaultId, envelope.slotId, pRootComp33, xActorComp33);
|
|
619
|
+
try {
|
|
620
|
+
const sActorBytes32 = await aes256GcmDecryptDetached({
|
|
621
|
+
key32: envKey32,
|
|
622
|
+
iv12,
|
|
623
|
+
ciphertext,
|
|
624
|
+
tag16,
|
|
625
|
+
aad,
|
|
626
|
+
authFailureCode: "PERSONAL_ENVELOPE_AUTH_FAILED"
|
|
627
|
+
});
|
|
628
|
+
const derivedX = encodePointCompressed(mulBaseG(bytes32ToScalarNonZero(sActorBytes32)));
|
|
629
|
+
if (!constantTimeEqual(derivedX, xActorComp33) || constantTimeEqual(derivedX, pRootComp33)) {
|
|
630
|
+
zeroizeBytes(sActorBytes32);
|
|
631
|
+
throw new MpcProtocolError("PERSONAL_ENVELOPE_AUTH_FAILED", "Unsealed s_actor does not match X_actor");
|
|
632
|
+
}
|
|
633
|
+
return {
|
|
634
|
+
sActorBytes32,
|
|
635
|
+
xActorComp33,
|
|
636
|
+
rootPublicKeyComp33: pRootComp33
|
|
637
|
+
};
|
|
638
|
+
} finally {
|
|
639
|
+
zeroizeBytes(envKey32);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
/**
|
|
643
|
+
* Double-wraps a `4,096B` `HsmSealedBlob` into a `4,140B` `CloudSyncBlob` (`design.md` §4.4):
|
|
644
|
+
* `syncSalt16 [0..15] || iv12 [16..27] || tag16 [28..43] || ciphertext [44..4139]`.
|
|
645
|
+
*/
|
|
646
|
+
async function wrapSealedBlobForCloudSync(params) {
|
|
647
|
+
const rng = params.rng ?? defaultRandomBytes;
|
|
648
|
+
parseHsmSealedBlobHeader(params.sealedBlob4096);
|
|
649
|
+
if (!(params.syncSecret32 instanceof Uint8Array) || params.syncSecret32.length !== 32) throw new MpcProtocolError("INVALID_PARAMETER", "syncSecret32 must be 32 bytes");
|
|
650
|
+
if (typeof params.recordId !== "string" || params.recordId.length === 0 || params.recordId.length > 256) throw new MpcProtocolError("INVALID_PARAMETER", "recordId must be 1..256 characters");
|
|
651
|
+
const syncSalt16 = rng(16);
|
|
652
|
+
const iv12 = rng(12);
|
|
653
|
+
const kSync32 = hkdf(sha256, params.syncSecret32, syncSalt16, utf8Bytes(DST_PERSONAL_CLOUD_SYNC_V1), 32);
|
|
654
|
+
const aad = lengthPrefixedEncode(DST_PERSONAL_CLOUD_BLOB_V1, [utf8Bytes(params.recordId)]);
|
|
655
|
+
try {
|
|
656
|
+
const { ciphertext, tag16 } = await aes256GcmEncryptDetached({
|
|
657
|
+
key32: kSync32,
|
|
658
|
+
iv12,
|
|
659
|
+
plaintext: params.sealedBlob4096,
|
|
660
|
+
aad
|
|
661
|
+
});
|
|
662
|
+
const out = concatBytes(syncSalt16, iv12, tag16, ciphertext);
|
|
663
|
+
if (out.length !== CLOUD_SYNC_SEALED_BLOB_BYTES) throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", "CloudSyncBlob output length invariant failed");
|
|
664
|
+
return out;
|
|
665
|
+
} finally {
|
|
666
|
+
zeroizeBytes(kSync32);
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
async function unwrapSealedBlobFromCloudSync(params) {
|
|
670
|
+
const { cloudBlob4140, syncSecret32, recordId } = params;
|
|
671
|
+
if (!(cloudBlob4140 instanceof Uint8Array) || cloudBlob4140.length !== CLOUD_SYNC_SEALED_BLOB_BYTES) throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", `CloudSyncBlob must be exactly ${CLOUD_SYNC_SEALED_BLOB_BYTES} bytes`);
|
|
672
|
+
if (!(syncSecret32 instanceof Uint8Array) || syncSecret32.length !== 32) throw new MpcProtocolError("INVALID_PARAMETER", "syncSecret32 must be 32 bytes");
|
|
673
|
+
if (typeof recordId !== "string" || recordId.length === 0 || recordId.length > 256) throw new MpcProtocolError("INVALID_PARAMETER", "recordId must be 1..256 characters");
|
|
674
|
+
const syncSalt16 = cloudBlob4140.subarray(0, 16);
|
|
675
|
+
const iv12 = cloudBlob4140.subarray(16, 28);
|
|
676
|
+
const tag16 = cloudBlob4140.subarray(28, 44);
|
|
677
|
+
const ciphertext4096 = cloudBlob4140.subarray(44, CLOUD_SYNC_SEALED_BLOB_BYTES);
|
|
678
|
+
const kSync32 = hkdf(sha256, syncSecret32, syncSalt16, utf8Bytes(DST_PERSONAL_CLOUD_SYNC_V1), 32);
|
|
679
|
+
const aad = lengthPrefixedEncode(DST_PERSONAL_CLOUD_BLOB_V1, [utf8Bytes(recordId)]);
|
|
680
|
+
try {
|
|
681
|
+
const plainBlob = await aes256GcmDecryptDetached({
|
|
682
|
+
key32: kSync32,
|
|
683
|
+
iv12,
|
|
684
|
+
ciphertext: ciphertext4096,
|
|
685
|
+
tag16,
|
|
686
|
+
aad,
|
|
687
|
+
authFailureCode: "PERSONAL_BLOB_TAMPERED"
|
|
688
|
+
});
|
|
689
|
+
parseHsmSealedBlobHeader(plainBlob);
|
|
690
|
+
return plainBlob;
|
|
691
|
+
} finally {
|
|
692
|
+
zeroizeBytes(kSync32);
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
function buildTransportBoxAad(vaultId, slotId, challengeNonce32, headerMac32) {
|
|
696
|
+
return lengthPrefixedEncode(DST_PERSONAL_TRANSPORT_AAD_V1, [
|
|
697
|
+
utf8Bytes(vaultId),
|
|
698
|
+
utf8Bytes(slotId),
|
|
699
|
+
challengeNonce32,
|
|
700
|
+
headerMac32
|
|
701
|
+
]);
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* Seals inbound sensitive material (`kUnsealSecret32`, `sHsm1`, or resplit `delta`) to the HSM's
|
|
705
|
+
* X25519 transport public key (`epkX25519_32 || iv12 || tag16 || ciphertext`, `design.md` §4.4).
|
|
706
|
+
*/
|
|
707
|
+
async function sealHsmInboundTransportBox(params) {
|
|
708
|
+
const rng = params.rng ?? defaultRandomBytes;
|
|
709
|
+
assertPrintableIdentifierAscii(params.vaultId, 64, "vaultId", "INVALID_PARAMETER");
|
|
710
|
+
assertPrintableIdentifierAscii(params.slotId, 64, "slotId", "INVALID_PARAMETER");
|
|
711
|
+
const hsmPub32 = normalizeHexBytes(params.hsmTransportPub32, 32);
|
|
712
|
+
assertValidX25519PublicKey(hsmPub32, "INVALID_POINT");
|
|
713
|
+
const challengeNonce32 = normalizeHexBytes(params.challengeNonce32, 32);
|
|
714
|
+
const headerMac32 = normalizeHexBytes(params.headerMac32, 32);
|
|
715
|
+
const esk32 = rng(32);
|
|
716
|
+
let shared32 = null;
|
|
717
|
+
let boxKey32 = null;
|
|
718
|
+
try {
|
|
719
|
+
const epk32 = x25519.getPublicKey(esk32);
|
|
720
|
+
shared32 = computeX25519SharedSecret(esk32, hsmPub32, "INVALID_POINT");
|
|
721
|
+
boxKey32 = hkdf(sha256, shared32, concatBytes(epk32, hsmPub32), utf8Bytes(DST_PERSONAL_TRANSPORT_BOX_V1), 32);
|
|
722
|
+
const iv12 = rng(12);
|
|
723
|
+
const aad = buildTransportBoxAad(params.vaultId, params.slotId, challengeNonce32, headerMac32);
|
|
724
|
+
const { ciphertext, tag16 } = await aes256GcmEncryptDetached({
|
|
725
|
+
key32: boxKey32,
|
|
726
|
+
iv12,
|
|
727
|
+
plaintext: params.plaintext,
|
|
728
|
+
aad
|
|
729
|
+
});
|
|
730
|
+
return concatBytes(epk32, iv12, tag16, ciphertext);
|
|
731
|
+
} finally {
|
|
732
|
+
zeroizeBytes(esk32, shared32, boxKey32);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
async function openHsmInboundTransportBox(params) {
|
|
736
|
+
if (!(params.hsmTransportSecretKey32 instanceof Uint8Array) || params.hsmTransportSecretKey32.length !== 32) throw new MpcProtocolError("INVALID_PARAMETER", "hsmTransportSecretKey32 must be 32 bytes");
|
|
737
|
+
const box = normalizeHexBytes(params.boxBytes);
|
|
738
|
+
if (box.length < 60) throw new MpcProtocolError("PERSONAL_ENVELOPE_AUTH_FAILED", "HsmInboundTransportBox truncated (< 60 bytes)");
|
|
739
|
+
const challengeNonce32 = normalizeHexBytes(params.challengeNonce32, 32);
|
|
740
|
+
const headerMac32 = normalizeHexBytes(params.headerMac32, 32);
|
|
741
|
+
const epk32 = box.subarray(0, 32);
|
|
742
|
+
const iv12 = box.subarray(32, 44);
|
|
743
|
+
const tag16 = box.subarray(44, 60);
|
|
744
|
+
const ciphertext = box.subarray(60);
|
|
745
|
+
assertValidX25519PublicKey(epk32, "PERSONAL_ENVELOPE_AUTH_FAILED");
|
|
746
|
+
const hsmPub32 = x25519.getPublicKey(params.hsmTransportSecretKey32);
|
|
747
|
+
let shared32 = null;
|
|
748
|
+
let boxKey32 = null;
|
|
749
|
+
try {
|
|
750
|
+
shared32 = computeX25519SharedSecret(params.hsmTransportSecretKey32, epk32, "PERSONAL_ENVELOPE_AUTH_FAILED");
|
|
751
|
+
boxKey32 = hkdf(sha256, shared32, concatBytes(epk32, hsmPub32), utf8Bytes(DST_PERSONAL_TRANSPORT_BOX_V1), 32);
|
|
752
|
+
const aad = buildTransportBoxAad(params.vaultId, params.slotId, challengeNonce32, headerMac32);
|
|
753
|
+
return await aes256GcmDecryptDetached({
|
|
754
|
+
key32: boxKey32,
|
|
755
|
+
iv12,
|
|
756
|
+
ciphertext,
|
|
757
|
+
tag16,
|
|
758
|
+
aad,
|
|
759
|
+
authFailureCode: "PERSONAL_ENVELOPE_AUTH_FAILED"
|
|
760
|
+
});
|
|
761
|
+
} finally {
|
|
762
|
+
zeroizeBytes(shared32, boxKey32);
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
function signPersonalActorChallenge(params) {
|
|
766
|
+
if (!(params.actorSecretKey32 instanceof Uint8Array) || params.actorSecretKey32.length !== 32) throw new MpcProtocolError("INVALID_PARAMETER", "actorSecretKey32 must be 32 bytes");
|
|
767
|
+
const digest32 = normalizeHexBytes(params.challengeDigest32, 32);
|
|
768
|
+
if (params.mode === "raw-p256") {
|
|
769
|
+
const format = params.p256Format ?? "compact";
|
|
770
|
+
return {
|
|
771
|
+
mode: "raw-p256",
|
|
772
|
+
signatureBytes: p256.sign(digest32, params.actorSecretKey32, {
|
|
773
|
+
prehash: true,
|
|
774
|
+
lowS: true,
|
|
775
|
+
format
|
|
776
|
+
})
|
|
777
|
+
};
|
|
778
|
+
}
|
|
779
|
+
if (params.mode === "ed25519") return {
|
|
780
|
+
mode: "ed25519",
|
|
781
|
+
signatureBytes: ed25519.sign(digest32, params.actorSecretKey32)
|
|
782
|
+
};
|
|
783
|
+
throw new MpcProtocolError("INVALID_PARAMETER", `Unsupported sign mode: ${String(params.mode)}`);
|
|
784
|
+
}
|
|
785
|
+
function verifyP256Sha256SignatureFlexible(sigBytes, messageBytes, pubKey65) {
|
|
786
|
+
if (sigBytes.length >= 8 && sigBytes.length <= 73 && sigBytes[0] === 48 && sigBytes[1] === sigBytes.length - 2 && sigBytes[2] === 2) try {
|
|
787
|
+
if (p256.verify(sigBytes, messageBytes, pubKey65, {
|
|
788
|
+
prehash: true,
|
|
789
|
+
lowS: false,
|
|
790
|
+
format: "der"
|
|
791
|
+
})) return true;
|
|
792
|
+
} catch {}
|
|
793
|
+
if (sigBytes.length === 64) try {
|
|
794
|
+
return p256.verify(sigBytes, messageBytes, pubKey65, {
|
|
795
|
+
prehash: true,
|
|
796
|
+
lowS: false,
|
|
797
|
+
format: "compact"
|
|
798
|
+
});
|
|
799
|
+
} catch {
|
|
800
|
+
return false;
|
|
801
|
+
}
|
|
802
|
+
return false;
|
|
803
|
+
}
|
|
804
|
+
const WEBAUTHN_FLAG_UP = 1;
|
|
805
|
+
const WEBAUTHN_FLAG_UV = 4;
|
|
806
|
+
const WEBAUTHN_FLAG_BE = 8;
|
|
807
|
+
const WEBAUTHN_FLAG_BS = 16;
|
|
808
|
+
function verifyPersonalActorSignature(params) {
|
|
809
|
+
const digest32 = normalizeHexBytes(params.challengeDigest32, 32);
|
|
810
|
+
const padded65 = normalizeActorPublicKeyToPadded65(params.actorKindAndAlg, params.actorPublicKey, "PERSONAL_ACTOR_SIGNATURE_INVALID");
|
|
811
|
+
const { signature } = params;
|
|
812
|
+
if (!signature || typeof signature !== "object") throw new MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Missing actor signature");
|
|
813
|
+
if (signature.mode === "ed25519") {
|
|
814
|
+
if (params.actorKindAndAlg !== "agent-ed25519") throw new MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Ed25519 signature rejected for P-256 slot");
|
|
815
|
+
let sig64;
|
|
816
|
+
try {
|
|
817
|
+
sig64 = normalizeHexBytes(signature.signatureBytes, 64);
|
|
818
|
+
} catch {
|
|
819
|
+
throw new MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Ed25519 signature must be 64 bytes");
|
|
820
|
+
}
|
|
821
|
+
const pub32 = padded65.subarray(0, 32);
|
|
822
|
+
let ok = false;
|
|
823
|
+
try {
|
|
824
|
+
ok = ed25519.verify(sig64, digest32, pub32, { zip215: false });
|
|
825
|
+
} catch {
|
|
826
|
+
ok = false;
|
|
827
|
+
}
|
|
828
|
+
if (!ok) throw new MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Invalid Ed25519 actor signature");
|
|
829
|
+
return;
|
|
830
|
+
}
|
|
831
|
+
if (params.actorKindAndAlg !== "human-p256" && params.actorKindAndAlg !== "agent-p256") throw new MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "P-256 signature rejected for Ed25519 slot");
|
|
832
|
+
if (signature.mode === "raw-p256") {
|
|
833
|
+
let sigBytes;
|
|
834
|
+
try {
|
|
835
|
+
sigBytes = normalizeHexBytes(signature.signatureBytes);
|
|
836
|
+
} catch {
|
|
837
|
+
throw new MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Malformed raw P-256 signature bytes");
|
|
838
|
+
}
|
|
839
|
+
if (!verifyP256Sha256SignatureFlexible(sigBytes, digest32, padded65)) throw new MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Invalid raw P-256 actor signature");
|
|
840
|
+
return;
|
|
841
|
+
}
|
|
842
|
+
if (signature.mode === "webauthn-p256") {
|
|
843
|
+
if (!params.webauthnPolicy || !params.webauthnPolicy.expectedRpId) throw new MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "WebAuthn verification requires expectedRpId and expectedOrigin policy");
|
|
844
|
+
let authData;
|
|
845
|
+
let sigBytes;
|
|
846
|
+
try {
|
|
847
|
+
authData = normalizeHexBytes(signature.authenticatorData);
|
|
848
|
+
sigBytes = normalizeHexBytes(signature.signatureBytes);
|
|
849
|
+
} catch {
|
|
850
|
+
throw new MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Malformed WebAuthn binary fields");
|
|
851
|
+
}
|
|
852
|
+
if (authData.length < 37 || authData.length > 2048) throw new MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "WebAuthn authenticatorData must be 37..2048 bytes");
|
|
853
|
+
const expectedRpIdHash32 = sha256(utf8Bytes(params.webauthnPolicy.expectedRpId));
|
|
854
|
+
if (!constantTimeEqual(authData.subarray(0, 32), expectedRpIdHash32)) throw new MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "WebAuthn rpIdHash mismatch");
|
|
855
|
+
const flags = authData[32];
|
|
856
|
+
if ((flags & WEBAUTHN_FLAG_UP) === 0 || (flags & WEBAUTHN_FLAG_UV) === 0) throw new MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "WebAuthn UP (0x01) and UV (0x04) flags required");
|
|
857
|
+
if ((flags & WEBAUTHN_FLAG_BE) === 0 && (flags & WEBAUTHN_FLAG_BS) !== 0) throw new MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Invalid WebAuthn BE=0 / BS=1 flag state");
|
|
858
|
+
const clientDataBytes = typeof signature.clientDataJSON === "string" ? utf8Bytes(signature.clientDataJSON) : signature.clientDataJSON instanceof Uint8Array ? signature.clientDataJSON : null;
|
|
859
|
+
if (!clientDataBytes || clientDataBytes.length < 20 || clientDataBytes.length > 4096) throw new MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Invalid WebAuthn clientDataJSON length");
|
|
860
|
+
const clientDataStr = utf8DecodeStrict(clientDataBytes, "PERSONAL_ACTOR_SIGNATURE_INVALID");
|
|
861
|
+
let parsedClientData;
|
|
862
|
+
try {
|
|
863
|
+
const rawJson = JSON.parse(clientDataStr);
|
|
864
|
+
if (!rawJson || typeof rawJson !== "object" || Array.isArray(rawJson)) throw new Error("not object");
|
|
865
|
+
parsedClientData = rawJson;
|
|
866
|
+
} catch {
|
|
867
|
+
throw new MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Malformed WebAuthn clientDataJSON");
|
|
868
|
+
}
|
|
869
|
+
if (parsedClientData.type !== "webauthn.get") throw new MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "WebAuthn type must be \"webauthn.get\"");
|
|
870
|
+
if (parsedClientData.crossOrigin === true || parsedClientData.crossOrigin !== void 0 && parsedClientData.crossOrigin !== false) throw new MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Cross-origin WebAuthn assertions are forbidden");
|
|
871
|
+
const allowedOrigins = Array.isArray(params.webauthnPolicy.expectedOrigin) ? params.webauthnPolicy.expectedOrigin : [params.webauthnPolicy.expectedOrigin];
|
|
872
|
+
if (typeof parsedClientData.origin !== "string" || !allowedOrigins.includes(parsedClientData.origin)) throw new MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "WebAuthn origin mismatch");
|
|
873
|
+
if (typeof parsedClientData.challenge !== "string") throw new MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Missing WebAuthn challenge");
|
|
874
|
+
if (!constantTimeEqual(base64UrlDecodeBytes(parsedClientData.challenge, "PERSONAL_ACTOR_SIGNATURE_INVALID"), digest32) || base64UrlEncodeBytes(digest32) !== parsedClientData.challenge) throw new MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "WebAuthn challenge mismatch");
|
|
875
|
+
const signedData = concatBytes(authData, sha256(clientDataBytes));
|
|
876
|
+
if (!verifyP256Sha256SignatureFlexible(sigBytes, signedData, padded65)) throw new MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Invalid WebAuthn P-256 signature");
|
|
877
|
+
return;
|
|
878
|
+
}
|
|
879
|
+
throw new MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Unsupported PersonalActorSignature mode");
|
|
880
|
+
}
|
|
881
|
+
/**
|
|
882
|
+
* Generates a Schnorr Proof of Knowledge of `s_actor` for `X_actor = s_actor * G` bound to
|
|
883
|
+
* `(vaultId, slotId, challengeNonce32)` (`LOW-2` rogue-key defense on `seal-enroll`).
|
|
884
|
+
*/
|
|
885
|
+
function createPersonalSealEnrollActorPok(params) {
|
|
886
|
+
assertPrintableIdentifierAscii(params.vaultId, 64, "vaultId", "INVALID_PARAMETER");
|
|
887
|
+
assertPrintableIdentifierAscii(params.slotId, 64, "slotId", "INVALID_PARAMETER");
|
|
888
|
+
const challengeNonce32 = normalizeHexBytes(params.challengeNonce32, 32);
|
|
889
|
+
let sActorScalar = 0n;
|
|
890
|
+
try {
|
|
891
|
+
sActorScalar = bytes32ToScalarNonZero(params.sActorBytes32);
|
|
892
|
+
const derivedXActor = mulBaseG(sActorScalar);
|
|
893
|
+
if (params.xActorComp33 !== void 0) {
|
|
894
|
+
const expectedX = decodePointCompressed(normalizeHexBytes(params.xActorComp33, 33), false);
|
|
895
|
+
if (!derivedXActor.equals(expectedX)) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "sActorBytes32 * G does not match xActorComp33");
|
|
896
|
+
}
|
|
897
|
+
return createSchnorrPokInBase({
|
|
898
|
+
dst: DST_PERSONAL_SEAL_ENROLL_ACTOR_POK_V1,
|
|
899
|
+
basePoint: SECP256K1_G,
|
|
900
|
+
statementPoint: derivedXActor,
|
|
901
|
+
secretScalar: sActorScalar,
|
|
902
|
+
contextParts: [
|
|
903
|
+
utf8Bytes(params.vaultId),
|
|
904
|
+
utf8Bytes(params.slotId),
|
|
905
|
+
challengeNonce32
|
|
906
|
+
],
|
|
907
|
+
rng: params.rng
|
|
908
|
+
});
|
|
909
|
+
} finally {
|
|
910
|
+
sActorScalar = 0n;
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
function verifyPersonalSealEnrollActorPok(params) {
|
|
914
|
+
if (!params.actorSharePok || typeof params.actorSharePok !== "object" || Array.isArray(params.actorSharePok)) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "Missing seal-enroll actorSharePok Schnorr PoK");
|
|
915
|
+
let noncePointComp33;
|
|
916
|
+
let responseBytes32;
|
|
917
|
+
let statementPoint;
|
|
918
|
+
let challengeNonce32;
|
|
919
|
+
try {
|
|
920
|
+
noncePointComp33 = normalizeHexBytes(params.actorSharePok.noncePointComp33, 33);
|
|
921
|
+
responseBytes32 = normalizeHexBytes(params.actorSharePok.responseBytes32, 32);
|
|
922
|
+
statementPoint = decodePointCompressed(normalizeHexBytes(params.xActorComp33, 33), false);
|
|
923
|
+
challengeNonce32 = normalizeHexBytes(params.challengeNonce32, 32);
|
|
924
|
+
} catch {
|
|
925
|
+
throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "Malformed seal-enroll actorSharePok fields");
|
|
926
|
+
}
|
|
927
|
+
if (!verifySchnorrPokInBase({
|
|
928
|
+
dst: DST_PERSONAL_SEAL_ENROLL_ACTOR_POK_V1,
|
|
929
|
+
basePoint: SECP256K1_G,
|
|
930
|
+
statementPoint,
|
|
931
|
+
proof: {
|
|
932
|
+
noncePointComp33,
|
|
933
|
+
responseBytes32
|
|
934
|
+
},
|
|
935
|
+
contextParts: [
|
|
936
|
+
utf8Bytes(params.vaultId),
|
|
937
|
+
utf8Bytes(params.slotId),
|
|
938
|
+
challengeNonce32
|
|
939
|
+
]
|
|
940
|
+
})) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "Invalid Schnorr PoK for X_actor = s_actor * G on seal-enroll");
|
|
941
|
+
}
|
|
942
|
+
function buildPersonalSealEnrollChallengeDigest32(params) {
|
|
943
|
+
decodeHsmSealedBlobHeader319(params.header319);
|
|
944
|
+
return hashTranscriptSha256(DST_PERSONAL_CHALLENGE_SEAL_ENROLL_V1, utf8Bytes(params.vaultId), utf8Bytes(params.slotId), normalizeHexBytes(params.challengeNonce32, 32), params.header319);
|
|
945
|
+
}
|
|
946
|
+
function buildPersonalPresignInitChallengeDigest32(params) {
|
|
947
|
+
return hashTranscriptSha256(DST_PERSONAL_CHALLENGE_PRESIGN_INIT_V1, utf8Bytes(params.vaultId), utf8Bytes(params.slotId), normalizeHexBytes(params.challengeNonce32, 32), normalizeHexBytes(params.headerMac32, 32), normalizeHexBytes(params.sessionNonce32, 32));
|
|
948
|
+
}
|
|
949
|
+
function buildPersonalSignChallengeDigest32(params) {
|
|
950
|
+
return hashTranscriptSha256(DST_PERSONAL_CHALLENGE_SIGN_V1, utf8Bytes(params.vaultId), utf8Bytes(params.slotId), normalizeHexBytes(params.challengeNonce32, 32), normalizeHexBytes(params.headerMac32, 32), normalizeHexBytes(params.presigId32, 32), normalizeHexBytes(params.clearSigningPreviewHash32, 32), normalizeHexBytes(params.signingDigest32, 32));
|
|
951
|
+
}
|
|
952
|
+
function buildPersonalPairResplitChallengeDigest32(params) {
|
|
953
|
+
validateActorPublicKeyPadded65(params.targetActorKindAndAlg, params.targetActorPubKeyPadded65);
|
|
954
|
+
return hashTranscriptSha256(DST_PERSONAL_CHALLENGE_PAIR_RESPLIT_V1, utf8Bytes(params.vaultId), utf8Bytes(params.sourceSlotId), normalizeHexBytes(params.challengeNonce32, 32), normalizeHexBytes(params.sourceHeaderMac32, 32), utf8Bytes(params.targetSlotId), u8(actorKindAndAlgToByte(params.targetActorKindAndAlg)), params.targetActorPubKeyPadded65, normalizeHexBytes(params.xActor2Comp33, 33), u64be(params.targetSlotExpiresAtSec), normalizeHexBytes(params.targetPairNonce32, 32));
|
|
955
|
+
}
|
|
956
|
+
function buildPersonalAnnounceChallengeDigest32(params) {
|
|
957
|
+
return hashTranscriptSha256(DST_PERSONAL_CHALLENGE_ANNOUNCE_V1, utf8Bytes(params.vaultId), utf8Bytes(params.slotId), normalizeHexBytes(params.challengeNonce32, 32), normalizeHexBytes(params.headerMac32, 32), normalizeHexBytes(params.clearSigningPreviewHash32, 32), normalizeHexBytes(params.signingDigest32, 32));
|
|
958
|
+
}
|
|
959
|
+
function buildPersonalVetoChallengeDigest32(params) {
|
|
960
|
+
return hashTranscriptSha256(DST_PERSONAL_CHALLENGE_VETO_V1, utf8Bytes(params.vaultId), utf8Bytes(params.slotId), normalizeHexBytes(params.challengeNonce32, 32), normalizeHexBytes(params.headerMac32, 32), utf8Bytes(params.reason));
|
|
961
|
+
}
|
|
962
|
+
function buildPersonalRevokeSlotChallengeDigest32(params) {
|
|
963
|
+
assertPrintableIdentifierAscii(params.targetSlotId, 64, "targetSlotId", "INVALID_PARAMETER");
|
|
964
|
+
return hashTranscriptSha256(DST_PERSONAL_CHALLENGE_REVOKE_SLOT_V1, utf8Bytes(params.vaultId), utf8Bytes(params.slotId), normalizeHexBytes(params.challengeNonce32, 32), normalizeHexBytes(params.headerMac32, 32), utf8Bytes(params.targetSlotId));
|
|
965
|
+
}
|
|
966
|
+
function buildPersonalSessionOpenChallengeDigest32(params) {
|
|
967
|
+
return hashTranscriptSha256(DST_PERSONAL_CHALLENGE_SESSION_OPEN_V1, utf8Bytes(params.vaultId), utf8Bytes(params.slotId), normalizeHexBytes(params.challengeNonce32, 32), normalizeHexBytes(params.headerMac32, 32), u32be(params.ttlSeconds));
|
|
968
|
+
}
|
|
969
|
+
function buildPersonalSessionLockChallengeDigest32(params) {
|
|
970
|
+
return hashTranscriptSha256(DST_PERSONAL_CHALLENGE_SESSION_LOCK_V1, utf8Bytes(params.vaultId), utf8Bytes(params.slotId), normalizeHexBytes(params.challengeNonce32, 32), normalizeHexBytes(params.headerMac32, 32), utf8Bytes(params.sessionLeaseId));
|
|
971
|
+
}
|
|
972
|
+
function buildPersonalResealKidChallengeDigest32(params) {
|
|
973
|
+
assertPrintableIdentifierAscii(params.targetKid, 32, "targetKid", "INVALID_PARAMETER");
|
|
974
|
+
return hashTranscriptSha256(DST_PERSONAL_CHALLENGE_RESEAL_KID_V1, utf8Bytes(params.vaultId), utf8Bytes(params.slotId), normalizeHexBytes(params.challengeNonce32, 32), normalizeHexBytes(params.oldHeaderMac32, 32), utf8Bytes(params.targetKid));
|
|
975
|
+
}
|
|
976
|
+
function buildPersonalEntitlementApplyChallengeDigest32(params) {
|
|
977
|
+
return hashTranscriptSha256(DST_PERSONAL_CHALLENGE_ENTITLEMENT_APPLY_V1, utf8Bytes(params.vaultId), utf8Bytes(params.slotId), normalizeHexBytes(params.challengeNonce32, 32), normalizeHexBytes(params.headerMac32, 32), normalizeHexBytes(params.entitlementTicketHash32, 32));
|
|
978
|
+
}
|
|
979
|
+
function computePersonalActorChallengeDigest32(payload) {
|
|
980
|
+
switch (payload.action) {
|
|
981
|
+
case "seal-enroll": return buildPersonalSealEnrollChallengeDigest32(payload);
|
|
982
|
+
case "presign-init": return buildPersonalPresignInitChallengeDigest32(payload);
|
|
983
|
+
case "sign": return buildPersonalSignChallengeDigest32(payload);
|
|
984
|
+
case "pair-resplit": return buildPersonalPairResplitChallengeDigest32(payload);
|
|
985
|
+
case "announce": return buildPersonalAnnounceChallengeDigest32(payload);
|
|
986
|
+
case "veto": return buildPersonalVetoChallengeDigest32(payload);
|
|
987
|
+
case "revoke-slot": return buildPersonalRevokeSlotChallengeDigest32(payload);
|
|
988
|
+
case "session-open": return buildPersonalSessionOpenChallengeDigest32(payload);
|
|
989
|
+
case "session-lock": return buildPersonalSessionLockChallengeDigest32(payload);
|
|
990
|
+
case "reseal-kid": return buildPersonalResealKidChallengeDigest32(payload);
|
|
991
|
+
case "entitlement-apply": return buildPersonalEntitlementApplyChallengeDigest32(payload);
|
|
992
|
+
default: throw new MpcProtocolError("INVALID_PARAMETER", "Unsupported personal challenge action");
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
const ERC20_APPROVE_SELECTOR_HEX = "095ea7b3";
|
|
996
|
+
const EIP7702_SET_CODE_TX_TYPE = 4;
|
|
997
|
+
const EIP7702_AUTH_MAGIC = 5;
|
|
998
|
+
function selectorHexFromSignature(sig) {
|
|
999
|
+
return `0x${bytesToHex(keccak_256(utf8Bytes(sig)).subarray(0, 4))}`;
|
|
1000
|
+
}
|
|
1001
|
+
const HARD_BANNED_PERSONAL_EVM_SELECTORS = new Set([
|
|
1002
|
+
selectorHexFromSignature("transferFrom(address,address,uint256)"),
|
|
1003
|
+
selectorHexFromSignature("safeTransferFrom(address,address,uint256)"),
|
|
1004
|
+
selectorHexFromSignature("safeTransferFrom(address,address,uint256,bytes)"),
|
|
1005
|
+
selectorHexFromSignature("multicall(bytes[])"),
|
|
1006
|
+
selectorHexFromSignature("multicall(uint256,bytes[])"),
|
|
1007
|
+
selectorHexFromSignature("multicall(bytes32,bytes[])"),
|
|
1008
|
+
selectorHexFromSignature("execute(address,uint256,bytes)")
|
|
1009
|
+
]);
|
|
1010
|
+
function encodeErc20ApproveCalldata(spenderAddress, allowanceAmount) {
|
|
1011
|
+
const parsedSpender = parseStrictEthAddress(spenderAddress);
|
|
1012
|
+
if (typeof allowanceAmount !== "bigint" || allowanceAmount < 0n || allowanceAmount > MAX_UINT256) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "ERC-20 approve allowanceAmount must satisfy 0 <= amount <= 2^256 - 1");
|
|
1013
|
+
const out = new Uint8Array(68);
|
|
1014
|
+
out.set(normalizeHexBytes(ERC20_APPROVE_SELECTOR_HEX, 4), 0);
|
|
1015
|
+
out.set(parsedSpender.addressBytes20, 16);
|
|
1016
|
+
let rem = allowanceAmount;
|
|
1017
|
+
for (let i = 67; i >= 36; i--) {
|
|
1018
|
+
out[i] = Number(rem & 255n);
|
|
1019
|
+
rem >>= 8n;
|
|
1020
|
+
}
|
|
1021
|
+
return out;
|
|
1022
|
+
}
|
|
1023
|
+
function decodeErc20ApproveCalldata(calldata) {
|
|
1024
|
+
const bytes = normalizeHexBytes(calldata);
|
|
1025
|
+
if (bytes.length !== 68 || bytesToHex(bytes.subarray(0, 4)) !== ERC20_APPROVE_SELECTOR_HEX) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Expected 68-byte ERC-20 approve(address,uint256) calldata");
|
|
1026
|
+
for (let i = 4; i < 16; i++) if (bytes[i] !== 0) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Non-zero padding in ABI-encoded ERC-20 spender word");
|
|
1027
|
+
const addrLower = bytesToHex(bytes.subarray(16, 36));
|
|
1028
|
+
if (/^0+$/.test(addrLower)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Zero spender in ERC-20 approve calldata");
|
|
1029
|
+
const allowanceAmount = bytesToBigIntBE(bytes.subarray(36, 68));
|
|
1030
|
+
return {
|
|
1031
|
+
spenderChecksumAddress: toEip55ChecksumAddress(addrLower),
|
|
1032
|
+
allowanceAmount,
|
|
1033
|
+
isUnlimitedApprove: allowanceAmount >= UNLIMITED_APPROVE_THRESHOLD
|
|
1034
|
+
};
|
|
1035
|
+
}
|
|
1036
|
+
/**
|
|
1037
|
+
* Hard-bans `0x04` EIP-7702 `SetCode` transactions, `0x05` EIP-7702 authorization magic payloads,
|
|
1038
|
+
* and raw `32`-byte blind message digests (`design.md` §2 Lens 4).
|
|
1039
|
+
*/
|
|
1040
|
+
function assertNoEip7702Bytes(rawPayload) {
|
|
1041
|
+
const bytes = normalizeHexBytes(rawPayload);
|
|
1042
|
+
if (bytes.length === 0) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Empty transaction payload");
|
|
1043
|
+
const firstByte = bytes[0];
|
|
1044
|
+
if (firstByte === EIP7702_SET_CODE_TX_TYPE || firstByte === EIP7702_AUTH_MAGIC) throw new MpcProtocolError("PERSONAL_EIP7702_FORBIDDEN", `EIP-7702 envelope byte 0x0${firstByte.toString(16)} is strictly forbidden on MPC-secured EOAs`);
|
|
1045
|
+
if (firstByte !== EIP1559_TX_TYPE_BYTE) {
|
|
1046
|
+
if (bytes.length === 32) throw new MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "Opaque 32-byte blind digest signing is strictly forbidden");
|
|
1047
|
+
throw new MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", `Only EIP-1559 Type 0x02 clear-signed transactions are permitted (got prefix 0x${firstByte.toString(16).padStart(2, "0")})`);
|
|
1048
|
+
}
|
|
1049
|
+
return bytes;
|
|
1050
|
+
}
|
|
1051
|
+
function parseStrictNonNegativeBigInt(val, max, label, errorCode = "PERSONAL_POLICY_VIOLATION") {
|
|
1052
|
+
let out;
|
|
1053
|
+
if (typeof val === "bigint") out = val;
|
|
1054
|
+
else if (typeof val === "number") {
|
|
1055
|
+
if (!Number.isSafeInteger(val) || val < 0) throw new MpcProtocolError(errorCode, `${label} must be a non-negative safe integer`);
|
|
1056
|
+
out = BigInt(val);
|
|
1057
|
+
} else if (typeof val === "string" && /^(?:0|[1-9][0-9]*)$/.test(val)) out = BigInt(val);
|
|
1058
|
+
else throw new MpcProtocolError(errorCode, `Invalid canonical integer for ${label}: ${String(val)}`);
|
|
1059
|
+
if (out < 0n || out > max) throw new MpcProtocolError(errorCode, `${label} exceeds range [0, ${max}]`);
|
|
1060
|
+
return out;
|
|
1061
|
+
}
|
|
1062
|
+
function normalizeSelector4Lower(sel) {
|
|
1063
|
+
if (typeof sel !== "string" || !/^0x[0-9a-fA-F]{8}$/.test(sel)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Invalid 4-byte selector: ${String(sel)}`);
|
|
1064
|
+
const lower = sel.toLowerCase();
|
|
1065
|
+
if (HARD_BANNED_PERSONAL_EVM_SELECTORS.has(lower)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Selector ${lower} is hard-banned and cannot be allowlisted`);
|
|
1066
|
+
return lower;
|
|
1067
|
+
}
|
|
1068
|
+
function validateAndNormalizeQuorumMember(member) {
|
|
1069
|
+
assertPrintableIdentifierAscii(member.memberId, 64, "memberId", "PERSONAL_POLICY_VIOLATION");
|
|
1070
|
+
const rawPub = normalizeHexBytes(member.publicKeyHex);
|
|
1071
|
+
if (member.alg === "p256") {
|
|
1072
|
+
if (rawPub.length !== 33 && rawPub.length !== 65) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Quorum p256 publicKey must be 33 or 65 bytes");
|
|
1073
|
+
const pt = p256.Point.fromBytes(rawPub);
|
|
1074
|
+
pt.assertValidity();
|
|
1075
|
+
if (pt.is0()) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Degenerate p256 quorum public key");
|
|
1076
|
+
return {
|
|
1077
|
+
memberId: member.memberId,
|
|
1078
|
+
alg: "p256",
|
|
1079
|
+
publicKeyHex: `0x${bytesToHex(pt.toBytes(false))}`
|
|
1080
|
+
};
|
|
1081
|
+
}
|
|
1082
|
+
if (member.alg === "ed25519") {
|
|
1083
|
+
validateEd25519PublicKeyNonTorsion32(rawPub, "PERSONAL_POLICY_VIOLATION");
|
|
1084
|
+
return {
|
|
1085
|
+
memberId: member.memberId,
|
|
1086
|
+
alg: "ed25519",
|
|
1087
|
+
publicKeyHex: `0x${bytesToHex(rawPub)}`
|
|
1088
|
+
};
|
|
1089
|
+
}
|
|
1090
|
+
if (member.alg === "secp256k1") {
|
|
1091
|
+
const pt = decodePointCompressed(rawPub, false);
|
|
1092
|
+
return {
|
|
1093
|
+
memberId: member.memberId,
|
|
1094
|
+
alg: "secp256k1",
|
|
1095
|
+
publicKeyHex: `0x${bytesToHex(encodePointCompressed(pt))}`
|
|
1096
|
+
};
|
|
1097
|
+
}
|
|
1098
|
+
throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Unsupported quorum alg: ${String(member.alg)}`);
|
|
1099
|
+
}
|
|
1100
|
+
function normalizeRosterMembers(threshold, members, label) {
|
|
1101
|
+
if (!Array.isArray(members) || members.length === 0 || members.length > 32) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `${label} must have 1..32 members`);
|
|
1102
|
+
if (!Number.isInteger(threshold) || threshold < 1 || threshold > members.length) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Invalid threshold ${threshold} for ${label}`);
|
|
1103
|
+
const normalized = members.map((m) => validateAndNormalizeQuorumMember(m));
|
|
1104
|
+
normalized.sort((a, b) => a.memberId.localeCompare(b.memberId));
|
|
1105
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
1106
|
+
const seenKeys = /* @__PURE__ */ new Set();
|
|
1107
|
+
for (const m of normalized) {
|
|
1108
|
+
if (seenIds.has(m.memberId) || seenKeys.has(`${m.alg}:${m.publicKeyHex}`)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Duplicate memberId or publicKey in ${label}`);
|
|
1109
|
+
seenIds.add(m.memberId);
|
|
1110
|
+
seenKeys.add(`${m.alg}:${m.publicKeyHex}`);
|
|
1111
|
+
}
|
|
1112
|
+
return normalized;
|
|
1113
|
+
}
|
|
1114
|
+
function deterministicJsonStringify(value) {
|
|
1115
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
1116
|
+
if (Array.isArray(value)) return `[${value.map((v) => deterministicJsonStringify(v)).join(",")}]`;
|
|
1117
|
+
const obj = value;
|
|
1118
|
+
return `{${Object.keys(obj).filter((k) => obj[k] !== void 0).sort().map((k) => `${JSON.stringify(k)}:${deterministicJsonStringify(obj[k])}`).join(",")}}`;
|
|
1119
|
+
}
|
|
1120
|
+
const OCAP_BASE58_BODY_RE = /^z[1-9A-HJ-NP-Za-km-z]{24,60}$/;
|
|
1121
|
+
const OCAP_TX_TYPE_RE = /^fg:t:[a-z0-9_]{1,64}$/;
|
|
1122
|
+
function normalizeOcapAddressOrEth(raw, label, errorCode = "PERSONAL_POLICY_VIOLATION") {
|
|
1123
|
+
if (typeof raw !== "string" || raw.length === 0 || raw.length > 96) throw new MpcProtocolError(errorCode, `Invalid ${label} address`);
|
|
1124
|
+
const stripped = raw.replace(/^did:[a-z0-9]+:/, "");
|
|
1125
|
+
if (stripped.startsWith("0x") || stripped.startsWith("0X")) return parseStrictEthAddress(stripped).checksumAddress;
|
|
1126
|
+
if (!OCAP_BASE58_BODY_RE.test(stripped)) throw new MpcProtocolError(errorCode, `Invalid OCAP base58btc or EIP-55 address for ${label}`);
|
|
1127
|
+
return stripped;
|
|
1128
|
+
}
|
|
1129
|
+
function normalizeCanonicalOcapTokenKey(raw, label, errorCode = "PERSONAL_POLICY_VIOLATION") {
|
|
1130
|
+
const norm = normalizeOcapAddressOrEth(raw, label, errorCode);
|
|
1131
|
+
return norm.startsWith("0x") || norm.startsWith("0X") ? norm.toLowerCase() : norm;
|
|
1132
|
+
}
|
|
1133
|
+
function canonicalizePersonalVaultPolicy(policy) {
|
|
1134
|
+
if (!policy || policy.version !== 1) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "PersonalVaultPolicy version must be 1");
|
|
1135
|
+
assertPrintableIdentifierAscii(policy.vaultId, 64, "vaultId", "PERSONAL_POLICY_VIOLATION");
|
|
1136
|
+
if (!Array.isArray(policy.allowedChainIds)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "allowedChainIds must be an array");
|
|
1137
|
+
const ocapChainSet = /* @__PURE__ */ new Set();
|
|
1138
|
+
for (const rawOcapChain of policy.allowedOcapChainIds ?? []) {
|
|
1139
|
+
assertPrintableIdentifierAscii(rawOcapChain, 64, "allowedOcapChainIds[]", "PERSONAL_POLICY_VIOLATION");
|
|
1140
|
+
ocapChainSet.add(rawOcapChain);
|
|
1141
|
+
}
|
|
1142
|
+
const allowedOcapChainIds = [...ocapChainSet].sort();
|
|
1143
|
+
if (policy.allowedChainIds.length === 0 && allowedOcapChainIds.length === 0) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "allowedChainIds or allowedOcapChainIds must be non-empty");
|
|
1144
|
+
const chainSet = /* @__PURE__ */ new Set();
|
|
1145
|
+
for (const rawChain of policy.allowedChainIds) {
|
|
1146
|
+
const cid = parseStrictNonNegativeBigInt(rawChain, MAX_UINT64, "chainId");
|
|
1147
|
+
if (cid < 1n) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "chainId must be >= 1");
|
|
1148
|
+
chainSet.add(cid.toString(10));
|
|
1149
|
+
}
|
|
1150
|
+
const allowedChainIds = [...chainSet].sort((a, b) => BigInt(a) < BigInt(b) ? -1 : BigInt(a) > BigInt(b) ? 1 : 0);
|
|
1151
|
+
const ocapTxTypeSet = /* @__PURE__ */ new Set();
|
|
1152
|
+
for (const txType of policy.allowedOcapTxTypes ?? []) {
|
|
1153
|
+
if (typeof txType !== "string" || !OCAP_TX_TYPE_RE.test(txType)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Invalid allowedOcapTxTypes entry: ${String(txType)}`);
|
|
1154
|
+
ocapTxTypeSet.add(txType);
|
|
1155
|
+
}
|
|
1156
|
+
const allowedOcapTxTypes = [...ocapTxTypeSet].sort();
|
|
1157
|
+
const payeeSet = /* @__PURE__ */ new Set();
|
|
1158
|
+
for (const p of policy.allowedPayees ?? []) payeeSet.add(parseStrictEthAddress(p).checksumAddress);
|
|
1159
|
+
const allowedPayees = [...payeeSet].sort();
|
|
1160
|
+
const ocapPayeeSet = /* @__PURE__ */ new Set();
|
|
1161
|
+
for (const p of policy.allowedOcapPayees ?? []) ocapPayeeSet.add(normalizeOcapAddressOrEth(p, "allowedOcapPayees[]"));
|
|
1162
|
+
const allowedOcapPayees = [...ocapPayeeSet].sort();
|
|
1163
|
+
const allowedContracts = (policy.allowedContracts ?? []).map((rule) => {
|
|
1164
|
+
const cid = parseStrictNonNegativeBigInt(rule.chainId, MAX_UINT64, "contract.chainId");
|
|
1165
|
+
if (cid < 1n) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "contract.chainId must be >= 1");
|
|
1166
|
+
const checksumAddr = parseStrictEthAddress(rule.address).checksumAddress;
|
|
1167
|
+
const selSet = /* @__PURE__ */ new Set();
|
|
1168
|
+
for (const s of rule.selectors) selSet.add(normalizeSelector4Lower(s));
|
|
1169
|
+
if (selSet.size === 0) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "allowedContracts selectors must be non-empty");
|
|
1170
|
+
const maxVal = rule.maxValueWei === void 0 ? 0n : parseStrictNonNegativeBigInt(rule.maxValueWei, MAX_UINT128, "maxValueWei");
|
|
1171
|
+
return {
|
|
1172
|
+
chainId: cid.toString(10),
|
|
1173
|
+
address: checksumAddr,
|
|
1174
|
+
selectors: [...selSet].sort(),
|
|
1175
|
+
maxValueWei: maxVal.toString(10)
|
|
1176
|
+
};
|
|
1177
|
+
}).sort((a, b) => `${a.chainId}:${a.address}`.localeCompare(`${b.chainId}:${b.address}`));
|
|
1178
|
+
const seenAssetKeys = /* @__PURE__ */ new Set();
|
|
1179
|
+
const assetLimits = (policy.assetLimits ?? []).map((lim) => {
|
|
1180
|
+
const cid = parseStrictNonNegativeBigInt(lim.chainId, MAX_UINT64, "assetLimit.chainId");
|
|
1181
|
+
if (cid < 1n) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "assetLimit.chainId must be >= 1");
|
|
1182
|
+
const normalizedAsset = lim.asset === "native" ? "native" : parseStrictEthAddress(lim.asset).lowercaseAddress;
|
|
1183
|
+
const key = `${cid.toString(10)}:${normalizedAsset}`;
|
|
1184
|
+
if (seenAssetKeys.has(key)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Duplicate assetLimit entry for ${key}`);
|
|
1185
|
+
seenAssetKeys.add(key);
|
|
1186
|
+
const l0PerTx = parseStrictNonNegativeBigInt(lim.l0MaxPerTxAmount, MAX_UINT128, "l0MaxPerTxAmount");
|
|
1187
|
+
const l0Roll = parseStrictNonNegativeBigInt(lim.l0MaxRolling24hAmount, MAX_UINT128, "l0MaxRolling24hAmount");
|
|
1188
|
+
if (l0Roll < l0PerTx) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "l0MaxRolling24hAmount must be >= l0MaxPerTxAmount");
|
|
1189
|
+
const l1Max = lim.l1MaxPerTxAmount !== void 0 ? parseStrictNonNegativeBigInt(lim.l1MaxPerTxAmount, MAX_UINT128, "l1MaxPerTxAmount") : void 0;
|
|
1190
|
+
const l2Max = lim.l2MaxPerTxAmount !== void 0 ? parseStrictNonNegativeBigInt(lim.l2MaxPerTxAmount, MAX_UINT128, "l2MaxPerTxAmount") : void 0;
|
|
1191
|
+
if (l1Max !== void 0 && l1Max < l0PerTx) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "l1MaxPerTxAmount must be >= l0MaxPerTxAmount");
|
|
1192
|
+
if (l2Max !== void 0 && l1Max !== void 0 && l2Max < l1Max) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "l2MaxPerTxAmount must be >= l1MaxPerTxAmount");
|
|
1193
|
+
if (l2Max !== void 0 && l1Max === void 0 && l2Max < l0PerTx) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "l2MaxPerTxAmount must be >= l0MaxPerTxAmount");
|
|
1194
|
+
return {
|
|
1195
|
+
chainId: cid.toString(10),
|
|
1196
|
+
asset: normalizedAsset,
|
|
1197
|
+
l0MaxPerTxAmount: l0PerTx.toString(10),
|
|
1198
|
+
l0MaxRolling24hAmount: l0Roll.toString(10),
|
|
1199
|
+
...l1Max !== void 0 ? { l1MaxPerTxAmount: l1Max.toString(10) } : {},
|
|
1200
|
+
...l2Max !== void 0 ? { l2MaxPerTxAmount: l2Max.toString(10) } : {}
|
|
1201
|
+
};
|
|
1202
|
+
}).sort((a, b) => `${a.chainId}:${a.asset}`.localeCompare(`${b.chainId}:${b.asset}`));
|
|
1203
|
+
if (!Number.isInteger(policy.timelockDelaySec) || policy.timelockDelaySec < 1 || policy.timelockDelaySec > 2592e3) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "timelockDelaySec must be 1..2592000");
|
|
1204
|
+
const roleRosters = {};
|
|
1205
|
+
if (policy.roleRosters) for (const roleKey of Object.keys(policy.roleRosters).sort()) {
|
|
1206
|
+
const r = policy.roleRosters[roleKey];
|
|
1207
|
+
assertPrintableIdentifierAscii(r.role, 64, "roleRoster.role", "PERSONAL_POLICY_VIOLATION");
|
|
1208
|
+
if (r.role !== roleKey) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `roleRosters key "${roleKey}" != role "${r.role}"`);
|
|
1209
|
+
roleRosters[roleKey] = {
|
|
1210
|
+
role: r.role,
|
|
1211
|
+
threshold: r.threshold,
|
|
1212
|
+
members: normalizeRosterMembers(r.threshold, r.members, `roleRosters[${roleKey}]`)
|
|
1213
|
+
};
|
|
1214
|
+
}
|
|
1215
|
+
if (policy.defaultRoleForL2 !== void 0 && !roleRosters[policy.defaultRoleForL2]) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "defaultRoleForL2 must reference a defined roleRoster");
|
|
1216
|
+
if (policy.defaultRoleForL3 !== void 0 && !roleRosters[policy.defaultRoleForL3]) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "defaultRoleForL3 must reference a defined roleRoster");
|
|
1217
|
+
if (Object.keys(roleRosters).length > 1 && policy.defaultRoleForL2 === void 0 && policy.defaultRoleForL3 === void 0) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "defaultRoleForL2 must be explicitly specified when roleRosters defines multiple roles");
|
|
1218
|
+
const guardianRoster = policy.guardianRoster ? {
|
|
1219
|
+
threshold: policy.guardianRoster.threshold,
|
|
1220
|
+
members: normalizeRosterMembers(policy.guardianRoster.threshold, policy.guardianRoster.members, "guardianRoster")
|
|
1221
|
+
} : void 0;
|
|
1222
|
+
const emergencyExitAddress = policy.emergencyExitAddress !== void 0 ? parseStrictEthAddress(policy.emergencyExitAddress).checksumAddress : void 0;
|
|
1223
|
+
const emergencyExitOcapAddress = policy.emergencyExitOcapAddress !== void 0 ? normalizeOcapAddressOrEth(policy.emergencyExitOcapAddress, "emergencyExitOcapAddress") : void 0;
|
|
1224
|
+
const seenOcapAssetKeys = /* @__PURE__ */ new Set();
|
|
1225
|
+
const ocapAssetLimits = (policy.ocapAssetLimits ?? []).map((lim) => {
|
|
1226
|
+
assertPrintableIdentifierAscii(lim.chainId, 64, "ocapAssetLimit.chainId", "PERSONAL_POLICY_VIOLATION");
|
|
1227
|
+
const normalizedAsset = lim.asset === "native" ? "native" : normalizeCanonicalOcapTokenKey(lim.asset, "ocapAssetLimit.asset");
|
|
1228
|
+
const key = `${lim.chainId}:${normalizedAsset}`;
|
|
1229
|
+
if (seenOcapAssetKeys.has(key)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Duplicate ocapAssetLimit entry for ${key}`);
|
|
1230
|
+
seenOcapAssetKeys.add(key);
|
|
1231
|
+
const l0PerTx = parseStrictNonNegativeBigInt(lim.l0MaxPerTxAmount, MAX_UINT128, "ocap.l0MaxPerTxAmount");
|
|
1232
|
+
const l0Roll = parseStrictNonNegativeBigInt(lim.l0MaxRolling24hAmount, MAX_UINT128, "ocap.l0MaxRolling24hAmount");
|
|
1233
|
+
if (l0Roll < l0PerTx) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "l0MaxRolling24hAmount must be >= l0MaxPerTxAmount");
|
|
1234
|
+
const l1Max = lim.l1MaxPerTxAmount !== void 0 ? parseStrictNonNegativeBigInt(lim.l1MaxPerTxAmount, MAX_UINT128, "ocap.l1MaxPerTxAmount") : void 0;
|
|
1235
|
+
const l2Max = lim.l2MaxPerTxAmount !== void 0 ? parseStrictNonNegativeBigInt(lim.l2MaxPerTxAmount, MAX_UINT128, "ocap.l2MaxPerTxAmount") : void 0;
|
|
1236
|
+
if (l1Max !== void 0 && l1Max < l0PerTx) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "l1MaxPerTxAmount must be >= l0MaxPerTxAmount");
|
|
1237
|
+
if (l2Max !== void 0 && l1Max !== void 0 && l2Max < l1Max) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "l2MaxPerTxAmount must be >= l1MaxPerTxAmount");
|
|
1238
|
+
if (l2Max !== void 0 && l1Max === void 0 && l2Max < l0PerTx) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "l2MaxPerTxAmount must be >= l0MaxPerTxAmount");
|
|
1239
|
+
return {
|
|
1240
|
+
chainId: lim.chainId,
|
|
1241
|
+
asset: normalizedAsset,
|
|
1242
|
+
l0MaxPerTxAmount: l0PerTx.toString(10),
|
|
1243
|
+
l0MaxRolling24hAmount: l0Roll.toString(10),
|
|
1244
|
+
...l1Max !== void 0 ? { l1MaxPerTxAmount: l1Max.toString(10) } : {},
|
|
1245
|
+
...l2Max !== void 0 ? { l2MaxPerTxAmount: l2Max.toString(10) } : {}
|
|
1246
|
+
};
|
|
1247
|
+
}).sort((a, b) => `${a.chainId}:${a.asset}`.localeCompare(`${b.chainId}:${b.asset}`));
|
|
1248
|
+
const ocapPrimaryTokenByChainId = {};
|
|
1249
|
+
if (policy.ocapPrimaryTokenByChainId) {
|
|
1250
|
+
assertPlainSimulationRecord(policy.ocapPrimaryTokenByChainId, "ocapPrimaryTokenByChainId");
|
|
1251
|
+
for (const chainKey of Object.keys(policy.ocapPrimaryTokenByChainId).sort()) {
|
|
1252
|
+
assertPrintableIdentifierAscii(chainKey, 64, "ocapPrimaryTokenByChainId.key", "PERSONAL_POLICY_VIOLATION");
|
|
1253
|
+
const rawTok = policy.ocapPrimaryTokenByChainId[chainKey];
|
|
1254
|
+
ocapPrimaryTokenByChainId[chainKey] = normalizeCanonicalOcapTokenKey(rawTok, `ocapPrimaryTokenByChainId[${chainKey}]`);
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
const ocapGasConfigByChainId = {};
|
|
1258
|
+
if (policy.ocapGasConfigByChainId !== void 0) {
|
|
1259
|
+
assertPlainSimulationRecord(policy.ocapGasConfigByChainId, "ocapGasConfigByChainId");
|
|
1260
|
+
for (const chainKey of Object.keys(policy.ocapGasConfigByChainId).sort()) {
|
|
1261
|
+
assertPrintableIdentifierAscii(chainKey, 64, "ocapGasConfigByChainId.key", "PERSONAL_POLICY_VIOLATION");
|
|
1262
|
+
const rawCfg = policy.ocapGasConfigByChainId[chainKey];
|
|
1263
|
+
assertPlainSimulationRecord(rawCfg, `ocapGasConfigByChainId[${chainKey}]`);
|
|
1264
|
+
const price = parseStrictNonNegativeBigInt(rawCfg.price, MAX_UINT128, `ocapGasConfig[${chainKey}].price`);
|
|
1265
|
+
const dataStorage = rawCfg.dataStorage !== void 0 ? parseStrictNonNegativeBigInt(rawCfg.dataStorage, MAX_UINT64, `ocapGasConfig[${chainKey}].dataStorage`) : price > 0n ? 0n : 1n;
|
|
1266
|
+
const createState = rawCfg.createState !== void 0 ? parseStrictNonNegativeBigInt(rawCfg.createState, MAX_UINT64, `ocapGasConfig[${chainKey}].createState`) : price > 0n ? 0n : 1n;
|
|
1267
|
+
const updateState = rawCfg.updateState !== void 0 ? parseStrictNonNegativeBigInt(rawCfg.updateState, MAX_UINT64, `ocapGasConfig[${chainKey}].updateState`) : price > 0n ? 0n : 1n;
|
|
1268
|
+
if (price > 0n && (dataStorage < 1n || createState < 1n || updateState < 1n)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `ocapGasConfigByChainId[${chainKey}] with price > 0 requires positive dataStorage, createState, and updateState`);
|
|
1269
|
+
let txFeeBaseUnitsByType;
|
|
1270
|
+
if (rawCfg.txFeeBaseUnitsByType !== void 0) {
|
|
1271
|
+
assertPlainSimulationRecord(rawCfg.txFeeBaseUnitsByType, `ocapGasConfig[${chainKey}].txFeeBaseUnitsByType`);
|
|
1272
|
+
txFeeBaseUnitsByType = {};
|
|
1273
|
+
for (const feeKey of Object.keys(rawCfg.txFeeBaseUnitsByType).sort()) {
|
|
1274
|
+
assertPrintableIdentifierAscii(feeKey, 64, "txFeeBaseUnitsByType.key", "PERSONAL_POLICY_VIOLATION");
|
|
1275
|
+
const feeVal = parseStrictNonNegativeBigInt(rawCfg.txFeeBaseUnitsByType[feeKey], MAX_UINT128, `txFeeBaseUnitsByType[${feeKey}]`);
|
|
1276
|
+
txFeeBaseUnitsByType[feeKey] = feeVal.toString(10);
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
let signedEnvelopeOverheadBytes;
|
|
1280
|
+
if (rawCfg.signedEnvelopeOverheadBytes !== void 0) {
|
|
1281
|
+
if (!Number.isSafeInteger(rawCfg.signedEnvelopeOverheadBytes) || rawCfg.signedEnvelopeOverheadBytes < 72 || rawCfg.signedEnvelopeOverheadBytes > 4096) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `ocapGasConfig[${chainKey}].signedEnvelopeOverheadBytes must be an integer in 72..4096`);
|
|
1282
|
+
signedEnvelopeOverheadBytes = rawCfg.signedEnvelopeOverheadBytes;
|
|
1283
|
+
}
|
|
1284
|
+
ocapGasConfigByChainId[chainKey] = {
|
|
1285
|
+
price: price.toString(10),
|
|
1286
|
+
dataStorage: dataStorage.toString(10),
|
|
1287
|
+
createState: createState.toString(10),
|
|
1288
|
+
updateState: updateState.toString(10),
|
|
1289
|
+
...txFeeBaseUnitsByType && Object.keys(txFeeBaseUnitsByType).length > 0 ? { txFeeBaseUnitsByType } : {},
|
|
1290
|
+
...signedEnvelopeOverheadBytes !== void 0 ? { signedEnvelopeOverheadBytes } : {}
|
|
1291
|
+
};
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
for (const allowedChain of allowedOcapChainIds) if (!ocapGasConfigByChainId[allowedChain]) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `allowedOcapChainIds entry "${allowedChain}" requires an explicit trusted ocapGasConfigByChainId["${allowedChain}"] bound`);
|
|
1295
|
+
const issuerSet = /* @__PURE__ */ new Set();
|
|
1296
|
+
for (const hexKey of policy.entitlementIssuerPublicKeysHex ?? []) {
|
|
1297
|
+
const pub32 = normalizeHexBytes(hexKey, 32);
|
|
1298
|
+
validateEd25519PublicKeyNonTorsion32(pub32, "PERSONAL_POLICY_VIOLATION");
|
|
1299
|
+
issuerSet.add(`0x${bytesToHex(pub32)}`);
|
|
1300
|
+
}
|
|
1301
|
+
const entitlementIssuerPublicKeysHex = [...issuerSet].sort();
|
|
1302
|
+
if (policy.requireEntitlement && entitlementIssuerPublicKeysHex.length === 0) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "requireEntitlement=true requires at least one entitlementIssuerPublicKeysHex");
|
|
1303
|
+
const firewallVerifierSet = /* @__PURE__ */ new Set();
|
|
1304
|
+
for (const hexKey of policy.firewallVerifierPublicKeysHex ?? []) {
|
|
1305
|
+
const pub32 = normalizeHexBytes(hexKey, 32);
|
|
1306
|
+
validateEd25519PublicKeyNonTorsion32(pub32, "PERSONAL_POLICY_VIOLATION");
|
|
1307
|
+
firewallVerifierSet.add(`0x${bytesToHex(pub32)}`);
|
|
1308
|
+
}
|
|
1309
|
+
const firewallVerifierPublicKeysHex = [...firewallVerifierSet].sort();
|
|
1310
|
+
if (policy.requireFirewallAttestation && firewallVerifierPublicKeysHex.length === 0) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "requireFirewallAttestation=true requires at least one firewallVerifierPublicKeysHex");
|
|
1311
|
+
const canonicalPolicy = {
|
|
1312
|
+
version: 1,
|
|
1313
|
+
vaultId: policy.vaultId,
|
|
1314
|
+
allowedChainIds,
|
|
1315
|
+
...allowedOcapChainIds.length > 0 ? { allowedOcapChainIds } : {},
|
|
1316
|
+
...allowedOcapTxTypes.length > 0 ? { allowedOcapTxTypes } : {},
|
|
1317
|
+
allowedPayees,
|
|
1318
|
+
...allowedOcapPayees.length > 0 ? { allowedOcapPayees } : {},
|
|
1319
|
+
enforcePayeeAllowlistInL0: Boolean(policy.enforcePayeeAllowlistInL0),
|
|
1320
|
+
allowedContracts,
|
|
1321
|
+
assetLimits,
|
|
1322
|
+
...ocapAssetLimits.length > 0 ? { ocapAssetLimits } : {},
|
|
1323
|
+
...Object.keys(ocapPrimaryTokenByChainId).length > 0 ? { ocapPrimaryTokenByChainId } : {},
|
|
1324
|
+
...Object.keys(ocapGasConfigByChainId).length > 0 ? { ocapGasConfigByChainId } : {},
|
|
1325
|
+
timelockDelaySec: policy.timelockDelaySec,
|
|
1326
|
+
allowUnlimitedApproveByQuorum: Boolean(policy.allowUnlimitedApproveByQuorum),
|
|
1327
|
+
...policy.allowArcblockJwt ? { allowArcblockJwt: true } : {},
|
|
1328
|
+
...policy.allowDelegationTokenByQuorum ? { allowDelegationTokenByQuorum: true } : {},
|
|
1329
|
+
...policy.defaultRoleForL2 !== void 0 ? { defaultRoleForL2: policy.defaultRoleForL2 } : {},
|
|
1330
|
+
...policy.defaultRoleForL3 !== void 0 ? { defaultRoleForL3: policy.defaultRoleForL3 } : {},
|
|
1331
|
+
roleRosters,
|
|
1332
|
+
...guardianRoster !== void 0 ? { guardianRoster } : {},
|
|
1333
|
+
...emergencyExitAddress !== void 0 ? { emergencyExitAddress } : {},
|
|
1334
|
+
...emergencyExitOcapAddress !== void 0 ? { emergencyExitOcapAddress } : {},
|
|
1335
|
+
requireEntitlement: Boolean(policy.requireEntitlement),
|
|
1336
|
+
entitlementIssuerPublicKeysHex,
|
|
1337
|
+
...policy.requireFirewallAttestation ? { requireFirewallAttestation: true } : {},
|
|
1338
|
+
...firewallVerifierPublicKeysHex.length > 0 ? { firewallVerifierPublicKeysHex } : {}
|
|
1339
|
+
};
|
|
1340
|
+
const canonicalPolicyJson = deterministicJsonStringify(canonicalPolicy);
|
|
1341
|
+
const canonicalPolicyUtf8 = utf8Bytes(canonicalPolicyJson);
|
|
1342
|
+
if (canonicalPolicyUtf8.length > HSM_SEALED_BLOB_MAX_POLICY_UTF8_BYTES) throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", `Canonical PersonalVaultPolicy (${canonicalPolicyUtf8.length}B) exceeds ${HSM_SEALED_BLOB_MAX_POLICY_UTF8_BYTES}B limit`);
|
|
1343
|
+
return {
|
|
1344
|
+
canonicalPolicy,
|
|
1345
|
+
canonicalPolicyJson,
|
|
1346
|
+
canonicalPolicyUtf8,
|
|
1347
|
+
policyHash32: sha256(lengthPrefixedEncode(DST_PERSONAL_POLICY_V1, [canonicalPolicyUtf8]))
|
|
1348
|
+
};
|
|
1349
|
+
}
|
|
1350
|
+
function computePersonalPolicyHash32(policy) {
|
|
1351
|
+
if (typeof policy === "string") return canonicalizePersonalVaultPolicy(JSON.parse(policy)).policyHash32;
|
|
1352
|
+
return canonicalizePersonalVaultPolicy(policy).policyHash32;
|
|
1353
|
+
}
|
|
1354
|
+
function decodeRawUnsignedEip1559Bytes(rawBytes) {
|
|
1355
|
+
assertNoEip7702Bytes(rawBytes);
|
|
1356
|
+
const decoded = rlpDecode(rawBytes.subarray(1));
|
|
1357
|
+
if (!Array.isArray(decoded) || decoded.length !== 9) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Unsigned EIP-1559 RLP list must have 9 elements");
|
|
1358
|
+
for (let i = 0; i < 9; i++) if (i === 8) {
|
|
1359
|
+
if (!Array.isArray(decoded[8])) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "accessList must be an RLP list");
|
|
1360
|
+
} else if (!(decoded[i] instanceof Uint8Array)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `Field ${i} must be an RLP byte string`);
|
|
1361
|
+
const parseCanonicalUint = (b, label) => {
|
|
1362
|
+
if (b.length > 32 || b.length > 0 && b[0] === 0) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `Non-canonical RLP integer in ${label}`);
|
|
1363
|
+
return bytesToBigIntBE(b);
|
|
1364
|
+
};
|
|
1365
|
+
const toBytes = decoded[5];
|
|
1366
|
+
if (toBytes.length === 0) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Contract creation transactions are forbidden");
|
|
1367
|
+
if (toBytes.length !== 20) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Destination address must be 20 bytes");
|
|
1368
|
+
const toHex = bytesToHex(toBytes);
|
|
1369
|
+
if (/^0+$/.test(toHex)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Zero destination address is forbidden");
|
|
1370
|
+
const accessList = decoded[8].map((entry) => {
|
|
1371
|
+
if (!Array.isArray(entry) || entry.length !== 2 || !(entry[0] instanceof Uint8Array) || !Array.isArray(entry[1])) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Invalid accessList item");
|
|
1372
|
+
if (entry[0].length !== 20) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Invalid accessList address length");
|
|
1373
|
+
return {
|
|
1374
|
+
address: toEip55ChecksumAddress(bytesToHex(entry[0])),
|
|
1375
|
+
storageKeys: entry[1].map((sk) => {
|
|
1376
|
+
if (!(sk instanceof Uint8Array) || sk.length !== 32) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Invalid accessList storageKey");
|
|
1377
|
+
return new Uint8Array(sk);
|
|
1378
|
+
})
|
|
1379
|
+
};
|
|
1380
|
+
});
|
|
1381
|
+
const fields = {
|
|
1382
|
+
chainId: parseCanonicalUint(decoded[0], "chainId"),
|
|
1383
|
+
nonce: parseCanonicalUint(decoded[1], "nonce"),
|
|
1384
|
+
maxPriorityFeePerGasWei: parseCanonicalUint(decoded[2], "maxPriorityFeePerGasWei"),
|
|
1385
|
+
maxFeePerGasWei: parseCanonicalUint(decoded[3], "maxFeePerGasWei"),
|
|
1386
|
+
gasLimit: parseCanonicalUint(decoded[4], "gasLimit"),
|
|
1387
|
+
to: toEip55ChecksumAddress(toHex),
|
|
1388
|
+
valueWei: parseCanonicalUint(decoded[6], "valueWei"),
|
|
1389
|
+
data: new Uint8Array(decoded[7]),
|
|
1390
|
+
accessList
|
|
1391
|
+
};
|
|
1392
|
+
if (!constantTimeEqual(rawBytes, encodeUnsignedEip1559Tx(fields).unsignedPayloadBytes)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Non-canonical unsigned EIP-1559 RLP encoding");
|
|
1393
|
+
return fields;
|
|
1394
|
+
}
|
|
1395
|
+
function decodeAndVerifyPersonalEip1559Tx(params) {
|
|
1396
|
+
let txFields;
|
|
1397
|
+
if (params.txOrRawBytes instanceof Uint8Array || typeof params.txOrRawBytes === "string") txFields = decodeRawUnsignedEip1559Bytes(assertNoEip7702Bytes(params.txOrRawBytes));
|
|
1398
|
+
else {
|
|
1399
|
+
txFields = params.txOrRawBytes;
|
|
1400
|
+
if (!txFields || typeof txFields !== "object") throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Missing EIP-1559 transaction fields");
|
|
1401
|
+
if (typeof txFields.to !== "string" || txFields.to.trim() === "" || txFields.to === "0x") throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Contract creation transactions are forbidden");
|
|
1402
|
+
}
|
|
1403
|
+
const encoded = encodeUnsignedEip1559Tx(txFields);
|
|
1404
|
+
const dataBytes = txFields.data === void 0 || txFields.data === "0x" || txFields.data === "" ? new Uint8Array(0) : normalizeHexBytes(txFields.data);
|
|
1405
|
+
if (dataBytes.length > MAX_PERSONAL_TX_DATA_BYTES) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Transaction calldata (${dataBytes.length}B) exceeds MAX_PERSONAL_TX_DATA_BYTES (${MAX_PERSONAL_TX_DATA_BYTES}B)`);
|
|
1406
|
+
if (dataBytes.length > 0 && dataBytes.length < 4) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Truncated 1..3 byte EVM function selector is forbidden");
|
|
1407
|
+
const canonicalPolicy = params.policy ? "enforcePayeeAllowlistInL0" in params.policy && Array.isArray(params.policy.allowedChainIds) && params.policy.allowedChainIds.every((c) => typeof c === "string") ? params.policy : canonicalizePersonalVaultPolicy(params.policy).canonicalPolicy : void 0;
|
|
1408
|
+
if (canonicalPolicy && !canonicalPolicy.allowedChainIds.includes(txFields.chainId.toString(10))) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `ChainId ${txFields.chainId} is not allowlisted by policy`);
|
|
1409
|
+
const maxGasFeeWei = txFields.gasLimit * txFields.maxFeePerGasWei;
|
|
1410
|
+
if (maxGasFeeWei > MAX_UINT256) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "maxGasFeeWei (gasLimit * maxFeePerGasWei) overflows uint256");
|
|
1411
|
+
if (dataBytes.length === 0) {
|
|
1412
|
+
if (txFields.valueWei + maxGasFeeWei > MAX_UINT256) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "valueWei + maxGasFeeWei overflows uint256");
|
|
1413
|
+
return {
|
|
1414
|
+
txFields,
|
|
1415
|
+
unsignedPayloadBytes: encoded.unsignedPayloadBytes,
|
|
1416
|
+
signingDigest32: encoded.signingDigest32,
|
|
1417
|
+
signingDigestHex: encoded.signingDigestHex,
|
|
1418
|
+
toChecksumAddress: encoded.toChecksumAddress,
|
|
1419
|
+
callKind: "native-transfer",
|
|
1420
|
+
selector4Lower: "0x",
|
|
1421
|
+
velocityAssetKey: "native",
|
|
1422
|
+
velocityAmount: txFields.valueWei,
|
|
1423
|
+
maxGasFeeWei,
|
|
1424
|
+
payeeOrSpenderChecksumAddress: encoded.toChecksumAddress,
|
|
1425
|
+
isUnlimitedApprove: false,
|
|
1426
|
+
callDepth: MAX_PERSONAL_CALL_DEPTH
|
|
1427
|
+
};
|
|
1428
|
+
}
|
|
1429
|
+
const selector4Hex = bytesToHex(dataBytes.subarray(0, 4)).toLowerCase();
|
|
1430
|
+
const selector4Lower = `0x${selector4Hex}`;
|
|
1431
|
+
if (HARD_BANNED_PERSONAL_EVM_SELECTORS.has(selector4Lower)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Dangerous EVM selector ${selector4Lower} is hard-banned on MPC-secured EOAs`);
|
|
1432
|
+
if (selector4Hex === ERC20_TRANSFER_SELECTOR_HEX) {
|
|
1433
|
+
if (txFields.valueWei !== 0n) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "ERC-20 transfer must have valueWei === 0n");
|
|
1434
|
+
const decodedTransfer = decodeErc20TransferCalldata(dataBytes);
|
|
1435
|
+
return {
|
|
1436
|
+
txFields,
|
|
1437
|
+
unsignedPayloadBytes: encoded.unsignedPayloadBytes,
|
|
1438
|
+
signingDigest32: encoded.signingDigest32,
|
|
1439
|
+
signingDigestHex: encoded.signingDigestHex,
|
|
1440
|
+
toChecksumAddress: encoded.toChecksumAddress,
|
|
1441
|
+
callKind: "erc20-transfer",
|
|
1442
|
+
selector4Lower,
|
|
1443
|
+
velocityAssetKey: encoded.toChecksumAddress.toLowerCase(),
|
|
1444
|
+
velocityAmount: decodedTransfer.tokenAmount,
|
|
1445
|
+
maxGasFeeWei,
|
|
1446
|
+
payeeOrSpenderChecksumAddress: decodedTransfer.recipientChecksumAddress,
|
|
1447
|
+
isUnlimitedApprove: false,
|
|
1448
|
+
callDepth: MAX_PERSONAL_CALL_DEPTH
|
|
1449
|
+
};
|
|
1450
|
+
}
|
|
1451
|
+
if (selector4Hex === ERC20_APPROVE_SELECTOR_HEX) {
|
|
1452
|
+
if (txFields.valueWei !== 0n) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "ERC-20 approve must have valueWei === 0n");
|
|
1453
|
+
const decodedApprove = decodeErc20ApproveCalldata(dataBytes);
|
|
1454
|
+
if (decodedApprove.isUnlimitedApprove && (!params.allowPolicyBlindCustomCalldata || canonicalPolicy)) {
|
|
1455
|
+
if (!(Boolean(canonicalPolicy?.allowUnlimitedApproveByQuorum) && Boolean(params.hasL2OrL3QuorumProof))) throw new MpcProtocolError("PERSONAL_UNLIMITED_APPROVE_FORBIDDEN", "ERC-20 approve >= 2^255 is forbidden without allowUnlimitedApproveByQuorum + L2/L3 quorum proof");
|
|
1456
|
+
}
|
|
1457
|
+
return {
|
|
1458
|
+
txFields,
|
|
1459
|
+
unsignedPayloadBytes: encoded.unsignedPayloadBytes,
|
|
1460
|
+
signingDigest32: encoded.signingDigest32,
|
|
1461
|
+
signingDigestHex: encoded.signingDigestHex,
|
|
1462
|
+
toChecksumAddress: encoded.toChecksumAddress,
|
|
1463
|
+
callKind: "erc20-approve",
|
|
1464
|
+
selector4Lower,
|
|
1465
|
+
velocityAssetKey: encoded.toChecksumAddress.toLowerCase(),
|
|
1466
|
+
velocityAmount: decodedApprove.allowanceAmount,
|
|
1467
|
+
maxGasFeeWei,
|
|
1468
|
+
payeeOrSpenderChecksumAddress: decodedApprove.spenderChecksumAddress,
|
|
1469
|
+
isUnlimitedApprove: decodedApprove.isUnlimitedApprove,
|
|
1470
|
+
callDepth: MAX_PERSONAL_CALL_DEPTH
|
|
1471
|
+
};
|
|
1472
|
+
}
|
|
1473
|
+
if (canonicalPolicy) {
|
|
1474
|
+
const matchingContract = canonicalPolicy.allowedContracts.find((c) => c.chainId === txFields.chainId.toString(10) && c.address === encoded.toChecksumAddress && c.selectors.includes(selector4Lower));
|
|
1475
|
+
if (!matchingContract) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Contract call (${txFields.chainId}, ${encoded.toChecksumAddress}, ${selector4Lower}) is not allowlisted`);
|
|
1476
|
+
if (txFields.valueWei > BigInt(matchingContract.maxValueWei)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Contract call valueWei (${txFields.valueWei}) exceeds rule maxValueWei (${matchingContract.maxValueWei})`);
|
|
1477
|
+
} else if (!params.allowPolicyBlindCustomCalldata) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Custom calldata selector ${selector4Lower} requires an explicit PersonalVaultPolicy allowlist`);
|
|
1478
|
+
if (txFields.valueWei + maxGasFeeWei > MAX_UINT256) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "valueWei + maxGasFeeWei overflows uint256");
|
|
1479
|
+
return {
|
|
1480
|
+
txFields,
|
|
1481
|
+
unsignedPayloadBytes: encoded.unsignedPayloadBytes,
|
|
1482
|
+
signingDigest32: encoded.signingDigest32,
|
|
1483
|
+
signingDigestHex: encoded.signingDigestHex,
|
|
1484
|
+
toChecksumAddress: encoded.toChecksumAddress,
|
|
1485
|
+
callKind: "allowlisted-contract-call",
|
|
1486
|
+
selector4Lower,
|
|
1487
|
+
velocityAssetKey: "native",
|
|
1488
|
+
velocityAmount: txFields.valueWei,
|
|
1489
|
+
maxGasFeeWei,
|
|
1490
|
+
payeeOrSpenderChecksumAddress: encoded.toChecksumAddress,
|
|
1491
|
+
isUnlimitedApprove: false,
|
|
1492
|
+
callDepth: MAX_PERSONAL_CALL_DEPTH
|
|
1493
|
+
};
|
|
1494
|
+
}
|
|
1495
|
+
function buildPersonalClearSigningPreview(params) {
|
|
1496
|
+
const fromChecksum = parseStrictEthAddress(params.fromAddress).checksumAddress;
|
|
1497
|
+
const { verifiedTx } = params;
|
|
1498
|
+
const { txFields } = verifiedTx;
|
|
1499
|
+
const maxGasFeeWei = txFields.gasLimit * txFields.maxFeePerGasWei;
|
|
1500
|
+
let summaryText;
|
|
1501
|
+
if (verifiedTx.callKind === "native-transfer") summaryText = `Pay ${verifiedTx.velocityAmount.toString(10)} wei native on chain ${txFields.chainId.toString(10)} to ${verifiedTx.payeeOrSpenderChecksumAddress}`;
|
|
1502
|
+
else if (verifiedTx.callKind === "erc20-transfer") summaryText = `Transfer ${verifiedTx.velocityAmount.toString(10)} units of token ${verifiedTx.toChecksumAddress} on chain ${txFields.chainId.toString(10)} to ${verifiedTx.payeeOrSpenderChecksumAddress}`;
|
|
1503
|
+
else if (verifiedTx.callKind === "erc20-approve") summaryText = `Approve spender ${verifiedTx.payeeOrSpenderChecksumAddress} for ${verifiedTx.velocityAmount.toString(10)} units of token ${verifiedTx.toChecksumAddress} on chain ${txFields.chainId.toString(10)}`;
|
|
1504
|
+
else summaryText = `Call ${verifiedTx.selector4Lower} on ${verifiedTx.toChecksumAddress} (value ${txFields.valueWei.toString(10)} wei) on chain ${txFields.chainId.toString(10)}`;
|
|
1505
|
+
return {
|
|
1506
|
+
version: 1,
|
|
1507
|
+
chainId: txFields.chainId.toString(10),
|
|
1508
|
+
fromAddress: fromChecksum,
|
|
1509
|
+
toAddress: verifiedTx.toChecksumAddress,
|
|
1510
|
+
callKind: verifiedTx.callKind,
|
|
1511
|
+
selector: verifiedTx.selector4Lower,
|
|
1512
|
+
payeeOrSpenderAddress: verifiedTx.payeeOrSpenderChecksumAddress,
|
|
1513
|
+
assetIdentifier: verifiedTx.velocityAssetKey,
|
|
1514
|
+
outflowAmount: verifiedTx.velocityAmount.toString(10),
|
|
1515
|
+
maxGasFeeWei: maxGasFeeWei.toString(10),
|
|
1516
|
+
nonce: txFields.nonce.toString(10),
|
|
1517
|
+
signingDigestHex: verifiedTx.signingDigestHex,
|
|
1518
|
+
summaryText
|
|
1519
|
+
};
|
|
1520
|
+
}
|
|
1521
|
+
function computePersonalClearSigningPreviewHash32(preview) {
|
|
1522
|
+
return sha256(lengthPrefixedEncode(DST_PERSONAL_CLEAR_PREVIEW_V1, [utf8Bytes(deterministicJsonStringify(preview))]));
|
|
1523
|
+
}
|
|
1524
|
+
const FORBIDDEN_SIMULATION_KEYS = new Set([
|
|
1525
|
+
"__proto__",
|
|
1526
|
+
"constructor",
|
|
1527
|
+
"prototype"
|
|
1528
|
+
]);
|
|
1529
|
+
function assertPlainSimulationRecord(value, label) {
|
|
1530
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `${label} must be a plain object`);
|
|
1531
|
+
const proto = Object.getPrototypeOf(value);
|
|
1532
|
+
if (proto !== null && proto !== Object.prototype) throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `${label} must be a plain object`);
|
|
1533
|
+
for (const key of Object.getOwnPropertyNames(value)) if (FORBIDDEN_SIMULATION_KEYS.has(key)) throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Forbidden property "${key}" in ${label}`);
|
|
1534
|
+
return value;
|
|
1535
|
+
}
|
|
1536
|
+
function assertNonNegativeSimulationBigInt(value, label) {
|
|
1537
|
+
if (typeof value !== "bigint" || value < 0n || value > MAX_UINT256) throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `${label} must be a non-negative bigint within uint256`);
|
|
1538
|
+
return value;
|
|
1539
|
+
}
|
|
1540
|
+
function assertSignedSimulationBigInt(value, label) {
|
|
1541
|
+
if (typeof value !== "bigint" || value < -MAX_UINT256 || value > MAX_UINT256) throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `${label} must be a signed bigint within [-2^256+1, 2^256-1]`);
|
|
1542
|
+
return value;
|
|
1543
|
+
}
|
|
1544
|
+
function assertOptionalSimulationStringArray(value, label) {
|
|
1545
|
+
if (value === void 0) return void 0;
|
|
1546
|
+
if (!Array.isArray(value)) throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `${label} must be an array of strings`);
|
|
1547
|
+
for (let i = 0; i < value.length; i++) if (typeof value[i] !== "string" || value[i].length === 0) throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `${label}[${i}] must be a non-empty string`);
|
|
1548
|
+
return value;
|
|
1549
|
+
}
|
|
1550
|
+
function normalizeSimulationTokenAddress(tokenAddr, label) {
|
|
1551
|
+
if (typeof tokenAddr !== "string" || tokenAddr.length === 0 || tokenAddr.length > 128) throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Invalid token address in ${label}`);
|
|
1552
|
+
const stripped = tokenAddr.replace(/^did:[a-z0-9]+:/, "");
|
|
1553
|
+
if (stripped.startsWith("0x") || stripped.startsWith("0X")) {
|
|
1554
|
+
const colonIdx = stripped.indexOf(":");
|
|
1555
|
+
if (colonIdx !== -1) {
|
|
1556
|
+
const addrPart = stripped.slice(0, colonIdx);
|
|
1557
|
+
const idPart = stripped.slice(colonIdx + 1);
|
|
1558
|
+
if (!/^(?:0|[1-9][0-9]{0,77}|batch)$/.test(idPart)) throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Invalid ERC-1155 tokenId in ${label}`);
|
|
1559
|
+
try {
|
|
1560
|
+
return `${parseStrictEthAddress(addrPart).lowercaseAddress}:${idPart}`;
|
|
1561
|
+
} catch {
|
|
1562
|
+
throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Invalid EVM ERC-1155 contract in ${label}`);
|
|
1563
|
+
}
|
|
1564
|
+
}
|
|
1565
|
+
try {
|
|
1566
|
+
return parseStrictEthAddress(stripped).lowercaseAddress;
|
|
1567
|
+
} catch {
|
|
1568
|
+
throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Invalid EVM token address in ${label}`);
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
if (!OCAP_BASE58_BODY_RE.test(stripped)) throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Invalid token address in ${label}`);
|
|
1572
|
+
return stripped;
|
|
1573
|
+
}
|
|
1574
|
+
function normalizeMaxTokenOutflowsCaps(maxTokenOutflows) {
|
|
1575
|
+
const allowedTokenMax = /* @__PURE__ */ new Map();
|
|
1576
|
+
if (maxTokenOutflows === void 0) return allowedTokenMax;
|
|
1577
|
+
const rawMaxMap = assertPlainSimulationRecord(maxTokenOutflows, "postConditions.maxTokenOutflows");
|
|
1578
|
+
for (const tokenAddr of Object.keys(rawMaxMap)) {
|
|
1579
|
+
const cap = assertNonNegativeSimulationBigInt(rawMaxMap[tokenAddr], `maxTokenOutflows[${tokenAddr}]`);
|
|
1580
|
+
const tokenLower = normalizeSimulationTokenAddress(tokenAddr, "postConditions.maxTokenOutflows");
|
|
1581
|
+
const existingCap = allowedTokenMax.get(tokenLower);
|
|
1582
|
+
if (existingCap !== void 0 && existingCap !== cap) throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Conflicting duplicate token entry in maxTokenOutflows for ${tokenLower}`);
|
|
1583
|
+
allowedTokenMax.set(tokenLower, cap);
|
|
1584
|
+
}
|
|
1585
|
+
return allowedTokenMax;
|
|
1586
|
+
}
|
|
1587
|
+
function verifyPersonalSimulationBalanceDelta(params) {
|
|
1588
|
+
if (!params || typeof params !== "object") throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", "Missing postConditions or simulatedDelta");
|
|
1589
|
+
const { postConditions, simulatedDelta } = params;
|
|
1590
|
+
assertPlainSimulationRecord(postConditions, "postConditions");
|
|
1591
|
+
assertPlainSimulationRecord(simulatedDelta, "simulatedDelta");
|
|
1592
|
+
if (typeof postConditions.strictZeroUnlistedOutflow !== "boolean") throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", "postConditions.strictZeroUnlistedOutflow must be a boolean");
|
|
1593
|
+
if (simulatedDelta.simulationReverted !== void 0 && typeof simulatedDelta.simulationReverted !== "boolean") throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", "simulatedDelta.simulationReverted must be a boolean when provided");
|
|
1594
|
+
if (simulatedDelta.simulationReverted) throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", "Dry-run transaction simulation reverted");
|
|
1595
|
+
const maxNativeOutflowWei = assertNonNegativeSimulationBigInt(postConditions.maxNativeOutflowWei, "postConditions.maxNativeOutflowWei");
|
|
1596
|
+
const minNativeInflowWei = postConditions.minNativeInflowWei !== void 0 ? assertNonNegativeSimulationBigInt(postConditions.minNativeInflowWei, "postConditions.minNativeInflowWei") : void 0;
|
|
1597
|
+
const nativeDeltaWei = assertSignedSimulationBigInt(simulatedDelta.nativeDeltaWei, "simulatedDelta.nativeDeltaWei");
|
|
1598
|
+
const nativeOutflow = nativeDeltaWei < 0n ? -nativeDeltaWei : 0n;
|
|
1599
|
+
const nativeInflow = nativeDeltaWei > 0n ? nativeDeltaWei : 0n;
|
|
1600
|
+
if (nativeOutflow > maxNativeOutflowWei) throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Simulated native outflow (${nativeOutflow}) exceeds maxNativeOutflowWei (${maxNativeOutflowWei})`);
|
|
1601
|
+
if (minNativeInflowWei !== void 0 && nativeInflow < minNativeInflowWei) throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Simulated native inflow (${nativeInflow}) below minNativeInflowWei (${minNativeInflowWei})`);
|
|
1602
|
+
const allowedTokenMax = /* @__PURE__ */ new Map();
|
|
1603
|
+
if (postConditions.maxTokenOutflows !== void 0) {
|
|
1604
|
+
const rawMaxMap = assertPlainSimulationRecord(postConditions.maxTokenOutflows, "postConditions.maxTokenOutflows");
|
|
1605
|
+
for (const tokenAddr of Object.keys(rawMaxMap)) {
|
|
1606
|
+
const cap = assertNonNegativeSimulationBigInt(rawMaxMap[tokenAddr], `maxTokenOutflows[${tokenAddr}]`);
|
|
1607
|
+
const tokenLower = normalizeSimulationTokenAddress(tokenAddr, "postConditions.maxTokenOutflows");
|
|
1608
|
+
const existingCap = allowedTokenMax.get(tokenLower);
|
|
1609
|
+
if (existingCap !== void 0 && existingCap !== cap) throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Conflicting duplicate token entry in maxTokenOutflows for ${tokenLower}`);
|
|
1610
|
+
allowedTokenMax.set(tokenLower, cap);
|
|
1611
|
+
}
|
|
1612
|
+
}
|
|
1613
|
+
const normalizedSimTokens = /* @__PURE__ */ new Map();
|
|
1614
|
+
if (simulatedDelta.tokenDeltas !== void 0) {
|
|
1615
|
+
const rawDeltaMap = assertPlainSimulationRecord(simulatedDelta.tokenDeltas, "simulatedDelta.tokenDeltas");
|
|
1616
|
+
for (const tokenAddr of Object.keys(rawDeltaMap)) {
|
|
1617
|
+
const delta = assertSignedSimulationBigInt(rawDeltaMap[tokenAddr], `tokenDeltas[${tokenAddr}]`);
|
|
1618
|
+
const key = normalizeSimulationTokenAddress(tokenAddr, "simulatedDelta.tokenDeltas");
|
|
1619
|
+
normalizedSimTokens.set(key, (normalizedSimTokens.get(key) ?? 0n) + delta);
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
for (const [tokenLower, delta] of normalizedSimTokens) if (delta < 0n) {
|
|
1623
|
+
const outflow = -delta;
|
|
1624
|
+
const cap = allowedTokenMax.get(tokenLower);
|
|
1625
|
+
if (cap === void 0) {
|
|
1626
|
+
if (postConditions.strictZeroUnlistedOutflow) throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Unlisted token outflow (${outflow}) detected on ${tokenLower}`);
|
|
1627
|
+
} else if (outflow > cap) throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Token ${tokenLower} outflow (${outflow}) exceeds maxTokenOutflows (${cap})`);
|
|
1628
|
+
}
|
|
1629
|
+
if (postConditions.minTokenInflows !== void 0) {
|
|
1630
|
+
const rawMinInMap = assertPlainSimulationRecord(postConditions.minTokenInflows, "postConditions.minTokenInflows");
|
|
1631
|
+
for (const tokenAddr of Object.keys(rawMinInMap)) {
|
|
1632
|
+
const minIn = assertNonNegativeSimulationBigInt(rawMinInMap[tokenAddr], `minTokenInflows[${tokenAddr}]`);
|
|
1633
|
+
const key = normalizeSimulationTokenAddress(tokenAddr, "postConditions.minTokenInflows");
|
|
1634
|
+
const actualDelta = normalizedSimTokens.get(key) ?? 0n;
|
|
1635
|
+
const actualInflow = actualDelta > 0n ? actualDelta : 0n;
|
|
1636
|
+
if (actualInflow < minIn) throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Token ${key} inflow (${actualInflow}) below minTokenInflows (${minIn})`);
|
|
1637
|
+
}
|
|
1638
|
+
}
|
|
1639
|
+
const allowedOutgoing = assertOptionalSimulationStringArray(postConditions.allowedOutgoingAssets, "postConditions.allowedOutgoingAssets");
|
|
1640
|
+
const outgoingIds = assertOptionalSimulationStringArray(simulatedDelta.outgoingAssetIds, "simulatedDelta.outgoingAssetIds");
|
|
1641
|
+
const normalizeAssetEntry = (rawAsset) => {
|
|
1642
|
+
if ((rawAsset.startsWith("0x") || rawAsset.startsWith("0X")) && rawAsset.includes(":")) return normalizeSimulationTokenAddress(rawAsset, "assetId");
|
|
1643
|
+
return rawAsset;
|
|
1644
|
+
};
|
|
1645
|
+
const allowedOutgoingSet = new Set((allowedOutgoing ?? []).map(normalizeAssetEntry));
|
|
1646
|
+
for (const rawAssetId of outgoingIds ?? []) {
|
|
1647
|
+
const assetId = normalizeAssetEntry(rawAssetId);
|
|
1648
|
+
const coveredByAllowedMax = allowedOutgoing === void 0 && (allowedTokenMax.get(assetId) ?? 0n) > 0n;
|
|
1649
|
+
if (!allowedOutgoingSet.has(assetId) && !coveredByAllowedMax) {
|
|
1650
|
+
if (postConditions.strictZeroUnlistedOutflow || allowedOutgoing !== void 0) throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Forbidden outgoing asset "${rawAssetId}" in simulation`);
|
|
1651
|
+
}
|
|
1652
|
+
}
|
|
1653
|
+
const mustOwnAfter = assertOptionalSimulationStringArray(postConditions.mustOwnAssetsAfter, "postConditions.mustOwnAssetsAfter");
|
|
1654
|
+
const ownedAfterList = assertOptionalSimulationStringArray(simulatedDelta.ownedAssetIdsAfter, "simulatedDelta.ownedAssetIdsAfter");
|
|
1655
|
+
if (mustOwnAfter && mustOwnAfter.length > 0) {
|
|
1656
|
+
const ownedAfter = new Set(ownedAfterList ?? []);
|
|
1657
|
+
for (const requiredAsset of mustOwnAfter) if (!ownedAfter.has(requiredAsset)) throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", `Required post-tx asset "${requiredAsset}" missing after simulation`);
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
function joinRequiredPolicyTiers(a, b) {
|
|
1661
|
+
if (a === b) return a;
|
|
1662
|
+
if (a === "L0") return b;
|
|
1663
|
+
if (b === "L0") return a;
|
|
1664
|
+
return "L3";
|
|
1665
|
+
}
|
|
1666
|
+
function evaluateSingleAssetTier(params) {
|
|
1667
|
+
const { canonical, chainStr, assetKey, txAmount, currentRolling, payeeAllowedInL0 } = params;
|
|
1668
|
+
if (txAmount > MAX_UINT128 || currentRolling > MAX_UINT128 || currentRolling + txAmount > MAX_UINT128) {
|
|
1669
|
+
if (!params.hasL2OrL3QuorumForOverflow) throw new MpcProtocolError("PERSONAL_AMOUNT_OVERFLOW", "Transaction amount or rolling 24h sum exceeds u128 velocity envelope without L2/L3 quorum proof");
|
|
1670
|
+
return {
|
|
1671
|
+
requiredTier: canonical.guardianRoster ? "L3" : "L2",
|
|
1672
|
+
projectedRolling: null
|
|
1673
|
+
};
|
|
1674
|
+
}
|
|
1675
|
+
const projectedRolling = currentRolling + txAmount;
|
|
1676
|
+
const assetRule = canonical.assetLimits.find((r) => r.chainId === chainStr && r.asset === assetKey);
|
|
1677
|
+
if (!assetRule) {
|
|
1678
|
+
if (Object.keys(canonical.roleRosters).length > 0 || canonical.guardianRoster) return {
|
|
1679
|
+
requiredTier: canonical.guardianRoster && Object.keys(canonical.roleRosters).length === 0 ? "L3" : "L2",
|
|
1680
|
+
projectedRolling
|
|
1681
|
+
};
|
|
1682
|
+
throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Asset ${assetKey} on chain ${chainStr} has no configured assetLimits`);
|
|
1683
|
+
}
|
|
1684
|
+
const l0PerTx = BigInt(assetRule.l0MaxPerTxAmount);
|
|
1685
|
+
const l0Roll = BigInt(assetRule.l0MaxRolling24hAmount);
|
|
1686
|
+
if (payeeAllowedInL0 && txAmount <= l0PerTx && projectedRolling <= l0Roll) return {
|
|
1687
|
+
requiredTier: "L0",
|
|
1688
|
+
projectedRolling
|
|
1689
|
+
};
|
|
1690
|
+
if (assetRule.l1MaxPerTxAmount !== void 0 && txAmount <= BigInt(assetRule.l1MaxPerTxAmount)) return {
|
|
1691
|
+
requiredTier: "L1",
|
|
1692
|
+
projectedRolling
|
|
1693
|
+
};
|
|
1694
|
+
if (assetRule.l2MaxPerTxAmount !== void 0 && txAmount <= BigInt(assetRule.l2MaxPerTxAmount)) return {
|
|
1695
|
+
requiredTier: "L2",
|
|
1696
|
+
projectedRolling
|
|
1697
|
+
};
|
|
1698
|
+
return {
|
|
1699
|
+
requiredTier: "L3",
|
|
1700
|
+
projectedRolling
|
|
1701
|
+
};
|
|
1702
|
+
}
|
|
1703
|
+
function resolveRequiredPolicyTier(params) {
|
|
1704
|
+
const canonical = "enforcePayeeAllowlistInL0" in params.policy && Array.isArray(params.policy.allowedChainIds) && params.policy.allowedChainIds.every((c) => typeof c === "string") ? params.policy : canonicalizePersonalVaultPolicy(params.policy).canonicalPolicy;
|
|
1705
|
+
const { verifiedTx } = params;
|
|
1706
|
+
const chainStr = verifiedTx.txFields.chainId.toString(10);
|
|
1707
|
+
if (!canonical.allowedChainIds.includes(chainStr)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Chain ${chainStr} is not allowlisted`);
|
|
1708
|
+
const currentRolling = params.currentRolling24hSpendAmount ?? 0n;
|
|
1709
|
+
if (currentRolling < 0n) throw new MpcProtocolError("INVALID_PARAMETER", "currentRolling24hSpendAmount cannot be negative");
|
|
1710
|
+
const currentNativeRolling = verifiedTx.velocityAssetKey === "native" ? params.currentNativeRolling24hSpendAmount ?? currentRolling : params.currentNativeRolling24hSpendAmount ?? 0n;
|
|
1711
|
+
if (currentNativeRolling < 0n) throw new MpcProtocolError("INVALID_PARAMETER", "currentNativeRolling24hSpendAmount cannot be negative");
|
|
1712
|
+
const maxGasFeeWei = verifiedTx.maxGasFeeWei ?? verifiedTx.txFields.gasLimit * verifiedTx.txFields.maxFeePerGasWei;
|
|
1713
|
+
if (maxGasFeeWei < 0n || maxGasFeeWei > MAX_UINT256) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Invalid maxGasFeeWei");
|
|
1714
|
+
const payeeAllowedInL0 = !canonical.enforcePayeeAllowlistInL0 || canonical.allowedPayees.includes(verifiedTx.payeeOrSpenderChecksumAddress);
|
|
1715
|
+
if (verifiedTx.velocityAssetKey === "native") {
|
|
1716
|
+
const evalNative = evaluateSingleAssetTier({
|
|
1717
|
+
canonical,
|
|
1718
|
+
chainStr,
|
|
1719
|
+
assetKey: "native",
|
|
1720
|
+
txAmount: verifiedTx.velocityAmount + maxGasFeeWei,
|
|
1721
|
+
currentRolling: currentNativeRolling,
|
|
1722
|
+
payeeAllowedInL0,
|
|
1723
|
+
hasL2OrL3QuorumForOverflow: params.hasL2OrL3QuorumForOverflow
|
|
1724
|
+
});
|
|
1725
|
+
return {
|
|
1726
|
+
requiredTier: evalNative.requiredTier,
|
|
1727
|
+
projectedRolling24hSpendAmount: evalNative.projectedRolling,
|
|
1728
|
+
projectedNativeRolling24hSpendAmount: evalNative.projectedRolling
|
|
1729
|
+
};
|
|
1730
|
+
}
|
|
1731
|
+
let tokenTier;
|
|
1732
|
+
let projectedTokenRolling;
|
|
1733
|
+
if (verifiedTx.isUnlimitedApprove) {
|
|
1734
|
+
if (!canonical.allowUnlimitedApproveByQuorum) throw new MpcProtocolError("PERSONAL_UNLIMITED_APPROVE_FORBIDDEN", "Unlimited ERC-20 approve is forbidden by policy");
|
|
1735
|
+
tokenTier = canonical.guardianRoster ? "L3" : "L2";
|
|
1736
|
+
projectedTokenRolling = null;
|
|
1737
|
+
} else {
|
|
1738
|
+
const evalToken = evaluateSingleAssetTier({
|
|
1739
|
+
canonical,
|
|
1740
|
+
chainStr,
|
|
1741
|
+
assetKey: verifiedTx.velocityAssetKey,
|
|
1742
|
+
txAmount: verifiedTx.velocityAmount,
|
|
1743
|
+
currentRolling,
|
|
1744
|
+
payeeAllowedInL0,
|
|
1745
|
+
hasL2OrL3QuorumForOverflow: params.hasL2OrL3QuorumForOverflow
|
|
1746
|
+
});
|
|
1747
|
+
tokenTier = evalToken.requiredTier;
|
|
1748
|
+
projectedTokenRolling = evalToken.projectedRolling;
|
|
1749
|
+
}
|
|
1750
|
+
if (maxGasFeeWei === 0n) return {
|
|
1751
|
+
requiredTier: tokenTier,
|
|
1752
|
+
projectedRolling24hSpendAmount: projectedTokenRolling,
|
|
1753
|
+
projectedNativeRolling24hSpendAmount: currentNativeRolling
|
|
1754
|
+
};
|
|
1755
|
+
const evalGas = evaluateSingleAssetTier({
|
|
1756
|
+
canonical,
|
|
1757
|
+
chainStr,
|
|
1758
|
+
assetKey: "native",
|
|
1759
|
+
txAmount: maxGasFeeWei,
|
|
1760
|
+
currentRolling: currentNativeRolling,
|
|
1761
|
+
payeeAllowedInL0: true,
|
|
1762
|
+
hasL2OrL3QuorumForOverflow: params.hasL2OrL3QuorumForOverflow
|
|
1763
|
+
});
|
|
1764
|
+
return {
|
|
1765
|
+
requiredTier: joinRequiredPolicyTiers(tokenTier, evalGas.requiredTier),
|
|
1766
|
+
projectedRolling24hSpendAmount: projectedTokenRolling,
|
|
1767
|
+
projectedNativeRolling24hSpendAmount: evalGas.projectedRolling
|
|
1768
|
+
};
|
|
1769
|
+
}
|
|
1770
|
+
function buildQuorumApprovalDigest32(params) {
|
|
1771
|
+
return hashTranscriptSha256(params.dst, utf8Bytes(params.vaultId), u64be(params.policyEpoch), params.policyHash32, utf8Bytes(params.roleOrGuardianTag), params.clearSigningPreviewHash32, params.signingDigest32, u64be(params.expiresAtSec));
|
|
1772
|
+
}
|
|
1773
|
+
function signQuorumDigestWithMemberKey(params) {
|
|
1774
|
+
if (params.secretKey32.length !== 32) throw new MpcProtocolError("INVALID_PARAMETER", "Approver secretKey32 must be 32 bytes");
|
|
1775
|
+
if (params.alg === "p256") {
|
|
1776
|
+
const pub65 = p256.getPublicKey(params.secretKey32, false);
|
|
1777
|
+
const sig = p256.sign(params.digest32, params.secretKey32, {
|
|
1778
|
+
prehash: true,
|
|
1779
|
+
lowS: true,
|
|
1780
|
+
format: "compact"
|
|
1781
|
+
});
|
|
1782
|
+
return {
|
|
1783
|
+
memberId: params.memberId,
|
|
1784
|
+
alg: "p256",
|
|
1785
|
+
publicKeyHex: `0x${bytesToHex(pub65)}`,
|
|
1786
|
+
signatureHex: `0x${bytesToHex(sig)}`
|
|
1787
|
+
};
|
|
1788
|
+
}
|
|
1789
|
+
if (params.alg === "ed25519") {
|
|
1790
|
+
const pub32 = ed25519.getPublicKey(params.secretKey32);
|
|
1791
|
+
const sig = ed25519.sign(params.digest32, params.secretKey32);
|
|
1792
|
+
return {
|
|
1793
|
+
memberId: params.memberId,
|
|
1794
|
+
alg: "ed25519",
|
|
1795
|
+
publicKeyHex: `0x${bytesToHex(pub32)}`,
|
|
1796
|
+
signatureHex: `0x${bytesToHex(sig)}`
|
|
1797
|
+
};
|
|
1798
|
+
}
|
|
1799
|
+
if (params.alg === "secp256k1") {
|
|
1800
|
+
const pub33 = secp256k1.getPublicKey(params.secretKey32, true);
|
|
1801
|
+
const sig = secp256k1.sign(params.digest32, params.secretKey32, {
|
|
1802
|
+
prehash: false,
|
|
1803
|
+
lowS: true,
|
|
1804
|
+
format: "compact"
|
|
1805
|
+
});
|
|
1806
|
+
return {
|
|
1807
|
+
memberId: params.memberId,
|
|
1808
|
+
alg: "secp256k1",
|
|
1809
|
+
publicKeyHex: `0x${bytesToHex(pub33)}`,
|
|
1810
|
+
signatureHex: `0x${bytesToHex(sig)}`
|
|
1811
|
+
};
|
|
1812
|
+
}
|
|
1813
|
+
throw new MpcProtocolError("INVALID_PARAMETER", `Unsupported quorum alg: ${String(params.alg)}`);
|
|
1814
|
+
}
|
|
1815
|
+
function verifySingleQuorumMemberApproval(entry, rosterMember, digest32) {
|
|
1816
|
+
if (entry.alg !== rosterMember.alg) return false;
|
|
1817
|
+
let normalizedEntryMember;
|
|
1818
|
+
let sigBytes;
|
|
1819
|
+
try {
|
|
1820
|
+
normalizedEntryMember = validateAndNormalizeQuorumMember({
|
|
1821
|
+
memberId: entry.memberId,
|
|
1822
|
+
alg: entry.alg,
|
|
1823
|
+
publicKeyHex: entry.publicKeyHex
|
|
1824
|
+
});
|
|
1825
|
+
sigBytes = normalizeHexBytes(entry.signatureHex);
|
|
1826
|
+
} catch {
|
|
1827
|
+
return false;
|
|
1828
|
+
}
|
|
1829
|
+
if (normalizedEntryMember.publicKeyHex !== rosterMember.publicKeyHex) return false;
|
|
1830
|
+
const pubBytes = normalizeHexBytes(rosterMember.publicKeyHex);
|
|
1831
|
+
if (entry.alg === "p256") return verifyP256Sha256SignatureFlexible(sigBytes, digest32, pubBytes);
|
|
1832
|
+
if (entry.alg === "ed25519") {
|
|
1833
|
+
if (sigBytes.length !== 64) return false;
|
|
1834
|
+
try {
|
|
1835
|
+
return ed25519.verify(sigBytes, digest32, pubBytes, { zip215: false });
|
|
1836
|
+
} catch {
|
|
1837
|
+
return false;
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1840
|
+
if (entry.alg === "secp256k1") {
|
|
1841
|
+
if (sigBytes.length !== 64) return false;
|
|
1842
|
+
try {
|
|
1843
|
+
return secp256k1.verify(sigBytes, digest32, pubBytes, {
|
|
1844
|
+
prehash: false,
|
|
1845
|
+
lowS: true,
|
|
1846
|
+
format: "compact"
|
|
1847
|
+
});
|
|
1848
|
+
} catch {
|
|
1849
|
+
return false;
|
|
1850
|
+
}
|
|
1851
|
+
}
|
|
1852
|
+
return false;
|
|
1853
|
+
}
|
|
1854
|
+
function signRoleQuorumApproval(params) {
|
|
1855
|
+
const digest32 = buildQuorumApprovalDigest32({
|
|
1856
|
+
dst: DST_PERSONAL_ROLE_QUORUM_V1,
|
|
1857
|
+
vaultId: params.vaultId,
|
|
1858
|
+
policyEpoch: params.policyEpoch,
|
|
1859
|
+
policyHash32: normalizeHexBytes(params.policyHash32, 32),
|
|
1860
|
+
roleOrGuardianTag: params.role,
|
|
1861
|
+
clearSigningPreviewHash32: normalizeHexBytes(params.clearSigningPreviewHash32, 32),
|
|
1862
|
+
signingDigest32: normalizeHexBytes(params.signingDigest32, 32),
|
|
1863
|
+
expiresAtSec: params.expiresAtSec
|
|
1864
|
+
});
|
|
1865
|
+
return signQuorumDigestWithMemberKey({
|
|
1866
|
+
memberId: params.memberId,
|
|
1867
|
+
alg: params.alg,
|
|
1868
|
+
secretKey32: params.secretKey32,
|
|
1869
|
+
digest32
|
|
1870
|
+
});
|
|
1871
|
+
}
|
|
1872
|
+
function verifyRoleQuorumProof(params) {
|
|
1873
|
+
const canonical = "enforcePayeeAllowlistInL0" in params.policy && Array.isArray(params.policy.allowedChainIds) && params.policy.allowedChainIds.every((c) => typeof c === "string") ? params.policy : canonicalizePersonalVaultPolicy(params.policy).canonicalPolicy;
|
|
1874
|
+
const { proof } = params;
|
|
1875
|
+
if (!proof || proof.kind !== "role-quorum" || proof.vaultId !== params.vaultId) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "RoleQuorumProof vaultId or kind mismatch");
|
|
1876
|
+
const expectedPolicyHash32 = normalizeHexBytes(params.policyHash32, 32);
|
|
1877
|
+
const expectedPreviewHash32 = normalizeHexBytes(params.clearSigningPreviewHash32, 32);
|
|
1878
|
+
const expectedSigningDigest32 = normalizeHexBytes(params.signingDigest32, 32);
|
|
1879
|
+
let proofEpoch;
|
|
1880
|
+
let expiresAtSec;
|
|
1881
|
+
let proofPolicyHash32;
|
|
1882
|
+
let proofPreviewHash32;
|
|
1883
|
+
let proofSigningDigest32;
|
|
1884
|
+
try {
|
|
1885
|
+
proofEpoch = parseStrictNonNegativeBigInt(proof.policyEpoch, MAX_UINT64, "policyEpoch", "PERSONAL_PROOF_INVALID");
|
|
1886
|
+
expiresAtSec = parseStrictNonNegativeBigInt(proof.expiresAtSec, MAX_UINT64, "expiresAtSec", "PERSONAL_PROOF_INVALID");
|
|
1887
|
+
proofPolicyHash32 = normalizeHexBytes(proof.policyHashHex, 32);
|
|
1888
|
+
proofPreviewHash32 = normalizeHexBytes(proof.clearSigningPreviewHashHex, 32);
|
|
1889
|
+
proofSigningDigest32 = normalizeHexBytes(proof.signingDigestHex, 32);
|
|
1890
|
+
} catch {
|
|
1891
|
+
throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "Malformed RoleQuorumProof header fields");
|
|
1892
|
+
}
|
|
1893
|
+
if (proofEpoch !== params.policyEpoch || !constantTimeEqual(proofPolicyHash32, expectedPolicyHash32) || !constantTimeEqual(proofPreviewHash32, expectedPreviewHash32) || !constantTimeEqual(proofSigningDigest32, expectedSigningDigest32)) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "RoleQuorumProof binding mismatch");
|
|
1894
|
+
if (params.nowSec > expiresAtSec) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "RoleQuorumProof has expired");
|
|
1895
|
+
const roster = canonical.roleRosters[proof.role];
|
|
1896
|
+
if (!roster) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", `Unknown role "${proof.role}" in RoleQuorumProof`);
|
|
1897
|
+
if (!Array.isArray(proof.approvals) || proof.approvals.length < roster.threshold) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", `Insufficient role quorum approvals (${proof.approvals?.length ?? 0} < ${roster.threshold})`);
|
|
1898
|
+
const digest32 = buildQuorumApprovalDigest32({
|
|
1899
|
+
dst: DST_PERSONAL_ROLE_QUORUM_V1,
|
|
1900
|
+
vaultId: params.vaultId,
|
|
1901
|
+
policyEpoch: params.policyEpoch,
|
|
1902
|
+
policyHash32: expectedPolicyHash32,
|
|
1903
|
+
roleOrGuardianTag: proof.role,
|
|
1904
|
+
clearSigningPreviewHash32: expectedPreviewHash32,
|
|
1905
|
+
signingDigest32: expectedSigningDigest32,
|
|
1906
|
+
expiresAtSec
|
|
1907
|
+
});
|
|
1908
|
+
const rosterById = new Map(roster.members.map((m) => [m.memberId, m]));
|
|
1909
|
+
const seenMemberIds = /* @__PURE__ */ new Set();
|
|
1910
|
+
const seenPubKeys = /* @__PURE__ */ new Set();
|
|
1911
|
+
let validCount = 0;
|
|
1912
|
+
for (const entry of proof.approvals) {
|
|
1913
|
+
if (!entry || seenMemberIds.has(entry.memberId)) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "Duplicate memberId in RoleQuorumProof");
|
|
1914
|
+
const rosterMember = rosterById.get(entry.memberId);
|
|
1915
|
+
if (!rosterMember) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", `Unknown roster member "${entry.memberId}"`);
|
|
1916
|
+
const pubKeyId = `${rosterMember.alg}:${rosterMember.publicKeyHex}`;
|
|
1917
|
+
if (seenPubKeys.has(pubKeyId)) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "Duplicate approver publicKey in RoleQuorumProof");
|
|
1918
|
+
if (!verifySingleQuorumMemberApproval(entry, rosterMember, digest32)) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", `Invalid quorum signature from "${entry.memberId}"`);
|
|
1919
|
+
seenMemberIds.add(entry.memberId);
|
|
1920
|
+
seenPubKeys.add(pubKeyId);
|
|
1921
|
+
validCount += 1;
|
|
1922
|
+
}
|
|
1923
|
+
if (validCount < roster.threshold) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "RoleQuorumProof threshold not met");
|
|
1924
|
+
}
|
|
1925
|
+
function signGuardianQuorumApproval(params) {
|
|
1926
|
+
const digest32 = buildQuorumApprovalDigest32({
|
|
1927
|
+
dst: DST_PERSONAL_GUARDIAN_QUORUM_V1,
|
|
1928
|
+
vaultId: params.vaultId,
|
|
1929
|
+
policyEpoch: params.policyEpoch,
|
|
1930
|
+
policyHash32: normalizeHexBytes(params.policyHash32, 32),
|
|
1931
|
+
roleOrGuardianTag: "guardian",
|
|
1932
|
+
clearSigningPreviewHash32: normalizeHexBytes(params.clearSigningPreviewHash32, 32),
|
|
1933
|
+
signingDigest32: normalizeHexBytes(params.signingDigest32, 32),
|
|
1934
|
+
expiresAtSec: params.expiresAtSec
|
|
1935
|
+
});
|
|
1936
|
+
return signQuorumDigestWithMemberKey({
|
|
1937
|
+
memberId: params.memberId,
|
|
1938
|
+
alg: params.alg,
|
|
1939
|
+
secretKey32: params.secretKey32,
|
|
1940
|
+
digest32
|
|
1941
|
+
});
|
|
1942
|
+
}
|
|
1943
|
+
function verifyGuardianQuorumProof(params) {
|
|
1944
|
+
const canonical = "enforcePayeeAllowlistInL0" in params.policy && Array.isArray(params.policy.allowedChainIds) && params.policy.allowedChainIds.every((c) => typeof c === "string") ? params.policy : canonicalizePersonalVaultPolicy(params.policy).canonicalPolicy;
|
|
1945
|
+
const { proof } = params;
|
|
1946
|
+
if (!proof || proof.kind !== "guardian-quorum" || proof.vaultId !== params.vaultId) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "GuardianQuorumProof vaultId or kind mismatch");
|
|
1947
|
+
if (!canonical.guardianRoster) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "Policy has no guardianRoster configured");
|
|
1948
|
+
const expectedPolicyHash32 = normalizeHexBytes(params.policyHash32, 32);
|
|
1949
|
+
const expectedPreviewHash32 = normalizeHexBytes(params.clearSigningPreviewHash32, 32);
|
|
1950
|
+
const expectedSigningDigest32 = normalizeHexBytes(params.signingDigest32, 32);
|
|
1951
|
+
let proofEpoch;
|
|
1952
|
+
let expiresAtSec;
|
|
1953
|
+
let proofPolicyHash32;
|
|
1954
|
+
let proofPreviewHash32;
|
|
1955
|
+
let proofSigningDigest32;
|
|
1956
|
+
try {
|
|
1957
|
+
proofEpoch = parseStrictNonNegativeBigInt(proof.policyEpoch, MAX_UINT64, "policyEpoch", "PERSONAL_PROOF_INVALID");
|
|
1958
|
+
expiresAtSec = parseStrictNonNegativeBigInt(proof.expiresAtSec, MAX_UINT64, "expiresAtSec", "PERSONAL_PROOF_INVALID");
|
|
1959
|
+
proofPolicyHash32 = normalizeHexBytes(proof.policyHashHex, 32);
|
|
1960
|
+
proofPreviewHash32 = normalizeHexBytes(proof.clearSigningPreviewHashHex, 32);
|
|
1961
|
+
proofSigningDigest32 = normalizeHexBytes(proof.signingDigestHex, 32);
|
|
1962
|
+
} catch {
|
|
1963
|
+
throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "Malformed GuardianQuorumProof header fields");
|
|
1964
|
+
}
|
|
1965
|
+
if (proofEpoch !== params.policyEpoch || !constantTimeEqual(proofPolicyHash32, expectedPolicyHash32) || !constantTimeEqual(proofPreviewHash32, expectedPreviewHash32) || !constantTimeEqual(proofSigningDigest32, expectedSigningDigest32)) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "GuardianQuorumProof binding mismatch");
|
|
1966
|
+
if (params.nowSec > expiresAtSec) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "GuardianQuorumProof has expired");
|
|
1967
|
+
const roster = canonical.guardianRoster;
|
|
1968
|
+
if (!Array.isArray(proof.approvals) || proof.approvals.length < roster.threshold) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "Insufficient guardian quorum approvals");
|
|
1969
|
+
const digest32 = buildQuorumApprovalDigest32({
|
|
1970
|
+
dst: DST_PERSONAL_GUARDIAN_QUORUM_V1,
|
|
1971
|
+
vaultId: params.vaultId,
|
|
1972
|
+
policyEpoch: params.policyEpoch,
|
|
1973
|
+
policyHash32: expectedPolicyHash32,
|
|
1974
|
+
roleOrGuardianTag: "guardian",
|
|
1975
|
+
clearSigningPreviewHash32: expectedPreviewHash32,
|
|
1976
|
+
signingDigest32: expectedSigningDigest32,
|
|
1977
|
+
expiresAtSec
|
|
1978
|
+
});
|
|
1979
|
+
const rosterById = new Map(roster.members.map((m) => [m.memberId, m]));
|
|
1980
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
1981
|
+
const seenKeys = /* @__PURE__ */ new Set();
|
|
1982
|
+
let validCount = 0;
|
|
1983
|
+
for (const entry of proof.approvals) {
|
|
1984
|
+
if (!entry || seenIds.has(entry.memberId)) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "Duplicate guardian memberId");
|
|
1985
|
+
const rosterMember = rosterById.get(entry.memberId);
|
|
1986
|
+
if (!rosterMember) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", `Unknown guardian member "${entry.memberId}"`);
|
|
1987
|
+
const pubKeyId = `${rosterMember.alg}:${rosterMember.publicKeyHex}`;
|
|
1988
|
+
if (seenKeys.has(pubKeyId)) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "Duplicate guardian publicKey");
|
|
1989
|
+
if (!verifySingleQuorumMemberApproval(entry, rosterMember, digest32)) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", `Invalid guardian signature from "${entry.memberId}"`);
|
|
1990
|
+
seenIds.add(entry.memberId);
|
|
1991
|
+
seenKeys.add(pubKeyId);
|
|
1992
|
+
validCount += 1;
|
|
1993
|
+
}
|
|
1994
|
+
if (validCount < roster.threshold) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "GuardianQuorumProof threshold not met");
|
|
1995
|
+
}
|
|
1996
|
+
function computeAnnounceTicketMac32(params) {
|
|
1997
|
+
return hmac(sha256, params.ticketMacKey32, lengthPrefixedEncode(DST_PERSONAL_ANNOUNCE_TICKET_V1, [
|
|
1998
|
+
utf8Bytes(params.ticketKid),
|
|
1999
|
+
utf8Bytes(params.vaultId),
|
|
2000
|
+
u64be(params.policyEpoch),
|
|
2001
|
+
u64be(params.vetoEpoch),
|
|
2002
|
+
params.clearSigningPreviewHash32,
|
|
2003
|
+
params.signingDigest32,
|
|
2004
|
+
u64be(params.announcedAtSec),
|
|
2005
|
+
u64be(params.executableAfterSec),
|
|
2006
|
+
u64be(params.expiresAtSec)
|
|
2007
|
+
]));
|
|
2008
|
+
}
|
|
2009
|
+
const MIN_ANNOUNCE_VALIDITY_WINDOW_SEC = 60;
|
|
2010
|
+
const MAX_ANNOUNCE_VALIDITY_WINDOW_SEC = 604800;
|
|
2011
|
+
function signAnnounceTicket(params) {
|
|
2012
|
+
if (params.ticketMacKey32.length !== 32) throw new MpcProtocolError("INVALID_PARAMETER", "ticketMacKey32 must be 32 bytes");
|
|
2013
|
+
assertPrintableIdentifierAscii(params.ticketKid, 32, "ticketKid", "INVALID_PARAMETER");
|
|
2014
|
+
if (!Number.isInteger(params.timelockDelaySec) || params.timelockDelaySec < 1) throw new MpcProtocolError("INVALID_PARAMETER", "timelockDelaySec must be >= 1");
|
|
2015
|
+
const windowSec = params.validityWindowSec ?? 3600;
|
|
2016
|
+
if (!Number.isInteger(windowSec) || windowSec < MIN_ANNOUNCE_VALIDITY_WINDOW_SEC || windowSec > MAX_ANNOUNCE_VALIDITY_WINDOW_SEC) throw new MpcProtocolError("INVALID_PARAMETER", `validityWindowSec must be an integer within ${MIN_ANNOUNCE_VALIDITY_WINDOW_SEC}..${MAX_ANNOUNCE_VALIDITY_WINDOW_SEC}`);
|
|
2017
|
+
const previewHash32 = normalizeHexBytes(params.clearSigningPreviewHash32, 32);
|
|
2018
|
+
const sigDigest32 = normalizeHexBytes(params.signingDigest32, 32);
|
|
2019
|
+
const executableAfterSec = params.announcedAtSec + BigInt(params.timelockDelaySec);
|
|
2020
|
+
const expiresAtSec = executableAfterSec + BigInt(windowSec);
|
|
2021
|
+
const mac32 = computeAnnounceTicketMac32({
|
|
2022
|
+
ticketMacKey32: params.ticketMacKey32,
|
|
2023
|
+
ticketKid: params.ticketKid,
|
|
2024
|
+
vaultId: params.vaultId,
|
|
2025
|
+
policyEpoch: params.policyEpoch,
|
|
2026
|
+
vetoEpoch: params.vetoEpoch,
|
|
2027
|
+
clearSigningPreviewHash32: previewHash32,
|
|
2028
|
+
signingDigest32: sigDigest32,
|
|
2029
|
+
announcedAtSec: params.announcedAtSec,
|
|
2030
|
+
executableAfterSec,
|
|
2031
|
+
expiresAtSec
|
|
2032
|
+
});
|
|
2033
|
+
return {
|
|
2034
|
+
kind: "announce-ticket",
|
|
2035
|
+
vaultId: params.vaultId,
|
|
2036
|
+
policyEpoch: params.policyEpoch.toString(10),
|
|
2037
|
+
vetoEpoch: params.vetoEpoch.toString(10),
|
|
2038
|
+
clearSigningPreviewHashHex: `0x${bytesToHex(previewHash32)}`,
|
|
2039
|
+
signingDigestHex: `0x${bytesToHex(sigDigest32)}`,
|
|
2040
|
+
announcedAtSec: params.announcedAtSec.toString(10),
|
|
2041
|
+
executableAfterSec: executableAfterSec.toString(10),
|
|
2042
|
+
expiresAtSec: expiresAtSec.toString(10),
|
|
2043
|
+
ticketKid: params.ticketKid,
|
|
2044
|
+
macHex: `0x${bytesToHex(mac32)}`
|
|
2045
|
+
};
|
|
2046
|
+
}
|
|
2047
|
+
function verifySignedAnnounceTicket(params) {
|
|
2048
|
+
const { ticket } = params;
|
|
2049
|
+
if (!ticket || ticket.kind !== "announce-ticket" || ticket.vaultId !== params.vaultId) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "Invalid SignedAnnounceTicket");
|
|
2050
|
+
const expectedPreview32 = normalizeHexBytes(params.clearSigningPreviewHash32, 32);
|
|
2051
|
+
const expectedDigest32 = normalizeHexBytes(params.signingDigest32, 32);
|
|
2052
|
+
let policyEpoch;
|
|
2053
|
+
let vetoEpoch;
|
|
2054
|
+
let announcedAtSec;
|
|
2055
|
+
let executableAfterSec;
|
|
2056
|
+
let expiresAtSec;
|
|
2057
|
+
let mac32;
|
|
2058
|
+
let ticketPreview32;
|
|
2059
|
+
let ticketDigest32;
|
|
2060
|
+
try {
|
|
2061
|
+
policyEpoch = parseStrictNonNegativeBigInt(ticket.policyEpoch, MAX_UINT64, "policyEpoch", "PERSONAL_PROOF_INVALID");
|
|
2062
|
+
vetoEpoch = parseStrictNonNegativeBigInt(ticket.vetoEpoch, MAX_UINT64, "vetoEpoch", "PERSONAL_PROOF_INVALID");
|
|
2063
|
+
announcedAtSec = parseStrictNonNegativeBigInt(ticket.announcedAtSec, MAX_UINT64, "announcedAtSec", "PERSONAL_PROOF_INVALID");
|
|
2064
|
+
executableAfterSec = parseStrictNonNegativeBigInt(ticket.executableAfterSec, MAX_UINT64, "executableAfterSec", "PERSONAL_PROOF_INVALID");
|
|
2065
|
+
expiresAtSec = parseStrictNonNegativeBigInt(ticket.expiresAtSec, MAX_UINT64, "expiresAtSec", "PERSONAL_PROOF_INVALID");
|
|
2066
|
+
mac32 = normalizeHexBytes(ticket.macHex, 32);
|
|
2067
|
+
ticketPreview32 = normalizeHexBytes(ticket.clearSigningPreviewHashHex, 32);
|
|
2068
|
+
ticketDigest32 = normalizeHexBytes(ticket.signingDigestHex, 32);
|
|
2069
|
+
} catch {
|
|
2070
|
+
throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "Malformed SignedAnnounceTicket fields");
|
|
2071
|
+
}
|
|
2072
|
+
const expectedMac32 = computeAnnounceTicketMac32({
|
|
2073
|
+
ticketMacKey32: params.ticketMacKey32,
|
|
2074
|
+
ticketKid: ticket.ticketKid,
|
|
2075
|
+
vaultId: ticket.vaultId,
|
|
2076
|
+
policyEpoch,
|
|
2077
|
+
vetoEpoch,
|
|
2078
|
+
clearSigningPreviewHash32: ticketPreview32,
|
|
2079
|
+
signingDigest32: ticketDigest32,
|
|
2080
|
+
announcedAtSec,
|
|
2081
|
+
executableAfterSec,
|
|
2082
|
+
expiresAtSec
|
|
2083
|
+
});
|
|
2084
|
+
if (!constantTimeEqual(mac32, expectedMac32)) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "SignedAnnounceTicket HMAC verification failed");
|
|
2085
|
+
if (policyEpoch !== params.policyEpoch || !constantTimeEqual(ticketPreview32, expectedPreview32) || !constantTimeEqual(ticketDigest32, expectedDigest32)) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "SignedAnnounceTicket transaction binding mismatch");
|
|
2086
|
+
if (vetoEpoch !== params.currentVetoEpoch) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "SignedAnnounceTicket invalidated by emergency vetoEpoch bump");
|
|
2087
|
+
if (executableAfterSec - announcedAtSec < BigInt(params.minTimelockDelaySec)) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "SignedAnnounceTicket delay shorter than policy timelockDelaySec");
|
|
2088
|
+
if (params.nowSec < executableAfterSec) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "SignedAnnounceTicket timelock has not matured yet");
|
|
2089
|
+
if (params.nowSec > expiresAtSec) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "SignedAnnounceTicket has expired");
|
|
2090
|
+
}
|
|
2091
|
+
const TIER_RANK = {
|
|
2092
|
+
L0: 0,
|
|
2093
|
+
L1: 1,
|
|
2094
|
+
L2: 2,
|
|
2095
|
+
L3: 3
|
|
2096
|
+
};
|
|
2097
|
+
function verifyPersonalPolicyProofBundle(params) {
|
|
2098
|
+
const canonical = "enforcePayeeAllowlistInL0" in params.policy && Array.isArray(params.policy.allowedChainIds) && params.policy.allowedChainIds.every((c) => typeof c === "string") ? params.policy : canonicalizePersonalVaultPolicy(params.policy).canonicalPolicy;
|
|
2099
|
+
const { requiredTier, proofBundle } = params;
|
|
2100
|
+
if (!proofBundle || TIER_RANK[proofBundle.tier] < TIER_RANK[requiredTier]) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Transaction requires policy tier ${requiredTier}, got ${proofBundle?.tier ?? "none"}`);
|
|
2101
|
+
if (requiredTier === "L1" && proofBundle.tier === "L2") throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "L1 timelock requirement can only be satisfied by L1 announceTicket or L3 quorum-and-timelock");
|
|
2102
|
+
if (proofBundle.tier === "L0") return;
|
|
2103
|
+
if (proofBundle.tier === "L1") {
|
|
2104
|
+
if (!params.ticketMacKey32) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "Missing ticketMacKey32 for L1 timelock verification");
|
|
2105
|
+
verifySignedAnnounceTicket({
|
|
2106
|
+
ticket: proofBundle.announceTicket,
|
|
2107
|
+
ticketMacKey32: params.ticketMacKey32,
|
|
2108
|
+
vaultId: params.vaultId,
|
|
2109
|
+
policyEpoch: params.policyEpoch,
|
|
2110
|
+
currentVetoEpoch: params.currentVetoEpoch,
|
|
2111
|
+
minTimelockDelaySec: canonical.timelockDelaySec,
|
|
2112
|
+
clearSigningPreviewHash32: params.clearSigningPreviewHash32,
|
|
2113
|
+
signingDigest32: params.signingDigest32,
|
|
2114
|
+
nowSec: params.nowSec
|
|
2115
|
+
});
|
|
2116
|
+
return;
|
|
2117
|
+
}
|
|
2118
|
+
if (proofBundle.tier === "L2") {
|
|
2119
|
+
if (!proofBundle.quorumProof || proofBundle.quorumProof.kind !== "role-quorum") throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "L2 requires a role-quorum proof");
|
|
2120
|
+
if (params.allowedL2Roles && params.allowedL2Roles.length > 0) {
|
|
2121
|
+
if (!params.allowedL2Roles.includes(proofBundle.quorumProof.role)) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", `RoleQuorumProof role "${proofBundle.quorumProof.role}" is not permitted for this L2 action`);
|
|
2122
|
+
} else {
|
|
2123
|
+
const requiredL2Role = canonical.defaultRoleForL2 ?? canonical.defaultRoleForL3;
|
|
2124
|
+
if (requiredL2Role !== void 0 && proofBundle.quorumProof.role !== requiredL2Role) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", `L2 RoleQuorumProof role "${proofBundle.quorumProof.role}" does not match required role "${requiredL2Role}"`);
|
|
2125
|
+
}
|
|
2126
|
+
verifyRoleQuorumProof({
|
|
2127
|
+
proof: proofBundle.quorumProof,
|
|
2128
|
+
policy: canonical,
|
|
2129
|
+
vaultId: params.vaultId,
|
|
2130
|
+
policyEpoch: params.policyEpoch,
|
|
2131
|
+
policyHash32: params.policyHash32,
|
|
2132
|
+
clearSigningPreviewHash32: params.clearSigningPreviewHash32,
|
|
2133
|
+
signingDigest32: params.signingDigest32,
|
|
2134
|
+
nowSec: params.nowSec
|
|
2135
|
+
});
|
|
2136
|
+
return;
|
|
2137
|
+
}
|
|
2138
|
+
if (proofBundle.tier === "L3") {
|
|
2139
|
+
if (!params.ticketMacKey32) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "Missing ticketMacKey32 for L3 timelock verification");
|
|
2140
|
+
verifySignedAnnounceTicket({
|
|
2141
|
+
ticket: proofBundle.announceTicket,
|
|
2142
|
+
ticketMacKey32: params.ticketMacKey32,
|
|
2143
|
+
vaultId: params.vaultId,
|
|
2144
|
+
policyEpoch: params.policyEpoch,
|
|
2145
|
+
currentVetoEpoch: params.currentVetoEpoch,
|
|
2146
|
+
minTimelockDelaySec: canonical.timelockDelaySec,
|
|
2147
|
+
clearSigningPreviewHash32: params.clearSigningPreviewHash32,
|
|
2148
|
+
signingDigest32: params.signingDigest32,
|
|
2149
|
+
nowSec: params.nowSec
|
|
2150
|
+
});
|
|
2151
|
+
if (canonical.guardianRoster !== void 0) {
|
|
2152
|
+
if (!proofBundle.quorumProof || proofBundle.quorumProof.kind !== "guardian-quorum") throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "L3 strictly requires guardian-quorum when guardianRoster is configured in policy");
|
|
2153
|
+
verifyGuardianQuorumProof({
|
|
2154
|
+
proof: proofBundle.quorumProof,
|
|
2155
|
+
policy: canonical,
|
|
2156
|
+
vaultId: params.vaultId,
|
|
2157
|
+
policyEpoch: params.policyEpoch,
|
|
2158
|
+
policyHash32: params.policyHash32,
|
|
2159
|
+
clearSigningPreviewHash32: params.clearSigningPreviewHash32,
|
|
2160
|
+
signingDigest32: params.signingDigest32,
|
|
2161
|
+
nowSec: params.nowSec
|
|
2162
|
+
});
|
|
2163
|
+
} else {
|
|
2164
|
+
if (!proofBundle.quorumProof || proofBundle.quorumProof.kind !== "role-quorum") throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "L3 requires role-quorum when policy has no guardianRoster");
|
|
2165
|
+
const requiredL3Role = canonical.defaultRoleForL3 ?? canonical.defaultRoleForL2;
|
|
2166
|
+
if (requiredL3Role !== void 0 && proofBundle.quorumProof.role !== requiredL3Role) throw new MpcProtocolError("PERSONAL_PROOF_INVALID", `L3 RoleQuorumProof role "${proofBundle.quorumProof.role}" does not match required role "${requiredL3Role}"`);
|
|
2167
|
+
verifyRoleQuorumProof({
|
|
2168
|
+
proof: proofBundle.quorumProof,
|
|
2169
|
+
policy: canonical,
|
|
2170
|
+
vaultId: params.vaultId,
|
|
2171
|
+
policyEpoch: params.policyEpoch,
|
|
2172
|
+
policyHash32: params.policyHash32,
|
|
2173
|
+
clearSigningPreviewHash32: params.clearSigningPreviewHash32,
|
|
2174
|
+
signingDigest32: params.signingDigest32,
|
|
2175
|
+
nowSec: params.nowSec
|
|
2176
|
+
});
|
|
2177
|
+
}
|
|
2178
|
+
return;
|
|
2179
|
+
}
|
|
2180
|
+
throw new MpcProtocolError("PERSONAL_PROOF_INVALID", "Unsupported PersonalPolicyProofBundle");
|
|
2181
|
+
}
|
|
2182
|
+
const ENTITLEMENT_TIER_CODE = {
|
|
2183
|
+
"free-trial": 0,
|
|
2184
|
+
"staked-quota": 1,
|
|
2185
|
+
"metered-credits": 2,
|
|
2186
|
+
"enterprise-sponsored": 3
|
|
2187
|
+
};
|
|
2188
|
+
function computeVaultEntitlementTicketDigest32(ticket) {
|
|
2189
|
+
const blindTag32 = normalizeHexBytes(ticket.blindVaultTagHex, 32);
|
|
2190
|
+
const tierCode = ENTITLEMENT_TIER_CODE[ticket.entitlementTier];
|
|
2191
|
+
if (tierCode === void 0) throw new MpcProtocolError("PERSONAL_ENTITLEMENT_REQUIRED", "Invalid VaultEntitlementTier");
|
|
2192
|
+
const epoch = parseStrictNonNegativeBigInt(ticket.entitlementEpoch, MAX_UINT64, "entitlementEpoch", "PERSONAL_ENTITLEMENT_REQUIRED");
|
|
2193
|
+
if (epoch < 1n) throw new MpcProtocolError("PERSONAL_ENTITLEMENT_REQUIRED", "entitlementEpoch must be >= 1n");
|
|
2194
|
+
const validUntilSec = parseStrictNonNegativeBigInt(ticket.validUntilSec, MAX_UINT64, "validUntilSec", "PERSONAL_ENTITLEMENT_REQUIRED");
|
|
2195
|
+
if (!Number.isInteger(ticket.grantedCredits) || ticket.grantedCredits < 0 || ticket.grantedCredits > 4294967295) throw new MpcProtocolError("PERSONAL_ENTITLEMENT_REQUIRED", "Invalid grantedCredits u32");
|
|
2196
|
+
if (!Number.isInteger(ticket.maxActorSlots) || ticket.maxActorSlots < 1 || ticket.maxActorSlots > 255) throw new MpcProtocolError("PERSONAL_ENTITLEMENT_REQUIRED", "Invalid maxActorSlots u8");
|
|
2197
|
+
const stakeRef32 = ticket.stakeRefHashHex ? normalizeHexBytes(ticket.stakeRefHashHex, 32) : new Uint8Array(0);
|
|
2198
|
+
const issuerPub32 = normalizeHexBytes(ticket.issuerPublicKeyHex, 32);
|
|
2199
|
+
validateEd25519PublicKeyNonTorsion32(issuerPub32, "PERSONAL_ENTITLEMENT_REQUIRED");
|
|
2200
|
+
return hashTranscriptSha256(DST_PERSONAL_ENTITLEMENT_TICKET_V1, blindTag32, u8(tierCode), u64be(epoch), u64be(validUntilSec), u32be(ticket.grantedCredits), u8(ticket.maxActorSlots), stakeRef32, issuerPub32);
|
|
2201
|
+
}
|
|
2202
|
+
function signVaultEntitlementTicket(params) {
|
|
2203
|
+
if (params.issuerEd25519SecretKey32.length !== 32) throw new MpcProtocolError("INVALID_PARAMETER", "issuerEd25519SecretKey32 must be 32 bytes");
|
|
2204
|
+
const issuerPub32 = ed25519.getPublicKey(params.issuerEd25519SecretKey32);
|
|
2205
|
+
const blindTag32 = normalizeHexBytes(params.blindVaultTag32, 32);
|
|
2206
|
+
const stakeRef32 = params.stakeRefHash32 !== void 0 ? normalizeHexBytes(params.stakeRefHash32, 32) : void 0;
|
|
2207
|
+
const unsigned = {
|
|
2208
|
+
version: 1,
|
|
2209
|
+
blindVaultTagHex: `0x${bytesToHex(blindTag32)}`,
|
|
2210
|
+
entitlementTier: params.entitlementTier,
|
|
2211
|
+
entitlementEpoch: params.entitlementEpoch.toString(10),
|
|
2212
|
+
validUntilSec: params.validUntilSec.toString(10),
|
|
2213
|
+
grantedCredits: params.grantedCredits,
|
|
2214
|
+
maxActorSlots: params.maxActorSlots,
|
|
2215
|
+
...stakeRef32 ? { stakeRefHashHex: `0x${bytesToHex(stakeRef32)}` } : {},
|
|
2216
|
+
issuerPublicKeyHex: `0x${bytesToHex(issuerPub32)}`
|
|
2217
|
+
};
|
|
2218
|
+
const digest32 = computeVaultEntitlementTicketDigest32(unsigned);
|
|
2219
|
+
const sig64 = ed25519.sign(digest32, params.issuerEd25519SecretKey32);
|
|
2220
|
+
return {
|
|
2221
|
+
...unsigned,
|
|
2222
|
+
signatureHex: `0x${bytesToHex(sig64)}`
|
|
2223
|
+
};
|
|
2224
|
+
}
|
|
2225
|
+
function verifyVaultEntitlementTicket(params) {
|
|
2226
|
+
const { ticket } = params;
|
|
2227
|
+
if (!ticket || ticket.version !== 1) throw new MpcProtocolError("PERSONAL_ENTITLEMENT_REQUIRED", "Missing or invalid VaultEntitlementTicket");
|
|
2228
|
+
const expectedTag32 = normalizeHexBytes(params.expectedBlindVaultTag32, 32);
|
|
2229
|
+
let ticketTag32;
|
|
2230
|
+
let issuerPub32;
|
|
2231
|
+
let sig64;
|
|
2232
|
+
try {
|
|
2233
|
+
ticketTag32 = normalizeHexBytes(ticket.blindVaultTagHex, 32);
|
|
2234
|
+
issuerPub32 = normalizeHexBytes(ticket.issuerPublicKeyHex, 32);
|
|
2235
|
+
sig64 = normalizeHexBytes(ticket.signatureHex, 64);
|
|
2236
|
+
validateEd25519PublicKeyNonTorsion32(issuerPub32, "PERSONAL_ENTITLEMENT_REQUIRED");
|
|
2237
|
+
} catch {
|
|
2238
|
+
throw new MpcProtocolError("PERSONAL_ENTITLEMENT_REQUIRED", "Malformed VaultEntitlementTicket binary fields");
|
|
2239
|
+
}
|
|
2240
|
+
if (!constantTimeEqual(ticketTag32, expectedTag32)) throw new MpcProtocolError("PERSONAL_ENTITLEMENT_REQUIRED", "VaultEntitlementTicket blindVaultTag32 mismatch");
|
|
2241
|
+
if (!params.trustedIssuerPublicKeys.some((k) => {
|
|
2242
|
+
try {
|
|
2243
|
+
return constantTimeEqual(normalizeHexBytes(k, 32), issuerPub32);
|
|
2244
|
+
} catch {
|
|
2245
|
+
return false;
|
|
2246
|
+
}
|
|
2247
|
+
})) throw new MpcProtocolError("PERSONAL_ENTITLEMENT_REQUIRED", "Untrusted VaultEntitlementTicket issuer");
|
|
2248
|
+
const digest32 = computeVaultEntitlementTicketDigest32(ticket);
|
|
2249
|
+
let sigOk = false;
|
|
2250
|
+
try {
|
|
2251
|
+
sigOk = ed25519.verify(sig64, digest32, issuerPub32, { zip215: false });
|
|
2252
|
+
} catch {
|
|
2253
|
+
sigOk = false;
|
|
2254
|
+
}
|
|
2255
|
+
if (!sigOk) throw new MpcProtocolError("PERSONAL_ENTITLEMENT_REQUIRED", "Invalid VaultEntitlementTicket Ed25519 signature");
|
|
2256
|
+
const epoch = BigInt(ticket.entitlementEpoch);
|
|
2257
|
+
const validUntilSec = BigInt(ticket.validUntilSec);
|
|
2258
|
+
if (params.minEntitlementEpochExclusive !== void 0 && epoch <= params.minEntitlementEpochExclusive) throw new MpcProtocolError("PERSONAL_ENTITLEMENT_REQUIRED", `Stale entitlementEpoch ${epoch} <= ${params.minEntitlementEpochExclusive}`);
|
|
2259
|
+
if (params.nowSec >= validUntilSec) throw new MpcProtocolError("PERSONAL_ENTITLEMENT_REQUIRED", "VaultEntitlementTicket has expired");
|
|
2260
|
+
if (ticket.entitlementTier === "metered-credits" && ticket.grantedCredits < 1) throw new MpcProtocolError("PERSONAL_ENTITLEMENT_REQUIRED", "metered-credits ticket requires grantedCredits >= 1");
|
|
2261
|
+
return {
|
|
2262
|
+
entitlementTier: ticket.entitlementTier,
|
|
2263
|
+
entitlementEpoch: epoch,
|
|
2264
|
+
validUntilSec,
|
|
2265
|
+
grantedCredits: ticket.grantedCredits,
|
|
2266
|
+
maxActorSlots: ticket.maxActorSlots,
|
|
2267
|
+
ticketHash32: digest32
|
|
2268
|
+
};
|
|
2269
|
+
}
|
|
2270
|
+
function computePairingPopDigest32(params) {
|
|
2271
|
+
return hashTranscriptSha256(DST_PERSONAL_PAIR_POP_V1, utf8Bytes(params.vaultId), utf8Bytes(params.targetSlotId), u8(actorKindAndAlgToByte(params.actorKindAndAlg)), params.actorPubKeyPadded65, params.ephemeralX25519PublicKey32, u64be(params.slotExpiresAtSec), params.pairNonce32);
|
|
2272
|
+
}
|
|
2273
|
+
async function createActorSlotPairingBootstrap(params) {
|
|
2274
|
+
const rng = params.rng ?? defaultRandomBytes;
|
|
2275
|
+
assertPrintableIdentifierAscii(params.vaultId, 64, "vaultId", "INVALID_PARAMETER");
|
|
2276
|
+
assertPrintableIdentifierAscii(params.targetSlotId, 64, "targetSlotId", "INVALID_PARAMETER");
|
|
2277
|
+
const slotExpiresAtSec = params.slotExpiresAtSec ?? 0n;
|
|
2278
|
+
if (isAgentActorKind(params.actorKindAndAlg) && slotExpiresAtSec <= 0n) throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", `Agent actor slot (${params.actorKindAndAlg}) requires slotExpiresAtSec > 0n`);
|
|
2279
|
+
const actorPubKeyPadded65 = normalizeActorPublicKeyToPadded65(params.actorKindAndAlg, params.actorPublicKey);
|
|
2280
|
+
const ephemeralX25519SecretKey32 = rng(32);
|
|
2281
|
+
const ephemeralX25519PublicKey32 = x25519.getPublicKey(ephemeralX25519SecretKey32);
|
|
2282
|
+
const pairNonce32 = rng(32);
|
|
2283
|
+
const popDigest32 = computePairingPopDigest32({
|
|
2284
|
+
vaultId: params.vaultId,
|
|
2285
|
+
targetSlotId: params.targetSlotId,
|
|
2286
|
+
actorKindAndAlg: params.actorKindAndAlg,
|
|
2287
|
+
actorPubKeyPadded65,
|
|
2288
|
+
ephemeralX25519PublicKey32,
|
|
2289
|
+
slotExpiresAtSec,
|
|
2290
|
+
pairNonce32
|
|
2291
|
+
});
|
|
2292
|
+
let popSignature;
|
|
2293
|
+
if (params.signPopDigest) popSignature = await params.signPopDigest(popDigest32);
|
|
2294
|
+
else if (params.actorSecretKey32) popSignature = signPersonalActorChallenge({
|
|
2295
|
+
mode: params.actorKindAndAlg === "agent-ed25519" ? "ed25519" : "raw-p256",
|
|
2296
|
+
actorSecretKey32: params.actorSecretKey32,
|
|
2297
|
+
challengeDigest32: popDigest32
|
|
2298
|
+
});
|
|
2299
|
+
else {
|
|
2300
|
+
zeroizeBytes(ephemeralX25519SecretKey32);
|
|
2301
|
+
throw new MpcProtocolError("INVALID_PARAMETER", "Provide actorSecretKey32 or signPopDigest");
|
|
2302
|
+
}
|
|
2303
|
+
return {
|
|
2304
|
+
bootstrapPackage: {
|
|
2305
|
+
version: 1,
|
|
2306
|
+
vaultId: params.vaultId,
|
|
2307
|
+
targetSlotId: params.targetSlotId,
|
|
2308
|
+
actorKindAndAlg: params.actorKindAndAlg,
|
|
2309
|
+
actorPubKeyPadded65Hex: `0x${bytesToHex(actorPubKeyPadded65)}`,
|
|
2310
|
+
slotExpiresAtSec: slotExpiresAtSec.toString(10),
|
|
2311
|
+
ephemeralX25519PublicKeyHex: `0x${bytesToHex(ephemeralX25519PublicKey32)}`,
|
|
2312
|
+
pairNonceHex: `0x${bytesToHex(pairNonce32)}`,
|
|
2313
|
+
popSignature
|
|
2314
|
+
},
|
|
2315
|
+
ephemeralX25519SecretKey32
|
|
2316
|
+
};
|
|
2317
|
+
}
|
|
2318
|
+
function verifyActorSlotPairingBootstrap(bootstrap, webauthnPolicy) {
|
|
2319
|
+
if (!bootstrap || bootstrap.version !== 1) throw new MpcProtocolError("PERSONAL_ACTOR_SIGNATURE_INVALID", "Invalid ActorSlotPairingBootstrapPackage");
|
|
2320
|
+
assertPrintableIdentifierAscii(bootstrap.vaultId, 64, "vaultId", "PERSONAL_BLOB_MALFORMED");
|
|
2321
|
+
assertPrintableIdentifierAscii(bootstrap.targetSlotId, 64, "targetSlotId", "PERSONAL_BLOB_MALFORMED");
|
|
2322
|
+
const actorPubKeyPadded65 = normalizeHexBytes(bootstrap.actorPubKeyPadded65Hex, 65);
|
|
2323
|
+
validateActorPublicKeyPadded65(bootstrap.actorKindAndAlg, actorPubKeyPadded65, "PERSONAL_BLOB_MALFORMED");
|
|
2324
|
+
const slotExpiresAtSec = parseStrictNonNegativeBigInt(bootstrap.slotExpiresAtSec, MAX_UINT64, "slotExpiresAtSec", "PERSONAL_BLOB_MALFORMED");
|
|
2325
|
+
if (isAgentActorKind(bootstrap.actorKindAndAlg) && slotExpiresAtSec <= 0n) throw new MpcProtocolError("PERSONAL_BLOB_MALFORMED", "Agent pairing bootstrap requires slotExpiresAtSec > 0n");
|
|
2326
|
+
const epk32 = normalizeHexBytes(bootstrap.ephemeralX25519PublicKeyHex, 32);
|
|
2327
|
+
assertValidX25519PublicKey(epk32, "PERSONAL_ACTOR_SIGNATURE_INVALID");
|
|
2328
|
+
const pairNonce32 = normalizeHexBytes(bootstrap.pairNonceHex, 32);
|
|
2329
|
+
const popDigest32 = computePairingPopDigest32({
|
|
2330
|
+
vaultId: bootstrap.vaultId,
|
|
2331
|
+
targetSlotId: bootstrap.targetSlotId,
|
|
2332
|
+
actorKindAndAlg: bootstrap.actorKindAndAlg,
|
|
2333
|
+
actorPubKeyPadded65,
|
|
2334
|
+
ephemeralX25519PublicKey32: epk32,
|
|
2335
|
+
slotExpiresAtSec,
|
|
2336
|
+
pairNonce32
|
|
2337
|
+
});
|
|
2338
|
+
verifyPersonalActorSignature({
|
|
2339
|
+
actorKindAndAlg: bootstrap.actorKindAndAlg,
|
|
2340
|
+
actorPublicKey: actorPubKeyPadded65,
|
|
2341
|
+
challengeDigest32: popDigest32,
|
|
2342
|
+
signature: bootstrap.popSignature,
|
|
2343
|
+
webauthnPolicy
|
|
2344
|
+
});
|
|
2345
|
+
return {
|
|
2346
|
+
actorPubKeyPadded65,
|
|
2347
|
+
ephemeralX25519PublicKey32: epk32,
|
|
2348
|
+
pairNonce32,
|
|
2349
|
+
slotExpiresAtSec
|
|
2350
|
+
};
|
|
2351
|
+
}
|
|
2352
|
+
/**
|
|
2353
|
+
* Validates and computes `s_actor_2 = (s_actor_1 - delta) mod n`, rejecting ALL degenerate cases:
|
|
2354
|
+
* `delta == 0`, `delta >= n`, `s_actor_2 == 0`, `X_actor_2 == O`, `X_actor_2 == P_root` (`s_hsm_2 == 0`),
|
|
2355
|
+
* and `X_actor_2 == X_actor_1`.
|
|
2356
|
+
*/
|
|
2357
|
+
function computeNonDegenerateActorResplitShare(params) {
|
|
2358
|
+
let sActor1;
|
|
2359
|
+
let delta;
|
|
2360
|
+
try {
|
|
2361
|
+
sActor1 = bytes32ToScalarNonZero(params.sActor1Bytes32);
|
|
2362
|
+
delta = bytes32ToScalarNonZero(params.deltaBytes32);
|
|
2363
|
+
} catch {
|
|
2364
|
+
throw new MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Resplit scalars must satisfy 1 <= scalar < n");
|
|
2365
|
+
}
|
|
2366
|
+
const pRoot = decodePointCompressed(normalizeHexBytes(params.rootPublicKeyComp33, 33), false);
|
|
2367
|
+
const xActor1 = mulBaseG(sActor1);
|
|
2368
|
+
if (xActor1.is0() || xActor1.equals(pRoot)) throw new MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Degenerate source X_actor_1");
|
|
2369
|
+
const sActor2 = subModN(sActor1, delta);
|
|
2370
|
+
if (sActor2 === 0n) throw new MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Degenerate resplit: s_actor_2 == 0");
|
|
2371
|
+
const xActor2 = mulBaseG(sActor2);
|
|
2372
|
+
if (xActor2.is0() || xActor2.equals(pRoot) || xActor2.equals(xActor1)) throw new MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Degenerate resplit: X_actor_2 hit O, P_root (s_hsm_2 == 0), or X_actor_1");
|
|
2373
|
+
return {
|
|
2374
|
+
sActor2Bytes32: scalarToBytes32(sActor2),
|
|
2375
|
+
xActor1Comp33: encodePointCompressed(xActor1),
|
|
2376
|
+
xActor2Comp33: encodePointCompressed(xActor2)
|
|
2377
|
+
};
|
|
2378
|
+
}
|
|
2379
|
+
/**
|
|
2380
|
+
* HSM-side zero-reconstruction re-split helper (`s_hsm_2 = (s_hsm_1 + delta) mod n`, `design.md` §4.2(2)).
|
|
2381
|
+
* Shared with Phase 2's `StatelessSealedHsmService.pairActorSlot`.
|
|
2382
|
+
*/
|
|
2383
|
+
function applyHsmSlotResplitDelta(params) {
|
|
2384
|
+
let sHsm1;
|
|
2385
|
+
let delta;
|
|
2386
|
+
try {
|
|
2387
|
+
sHsm1 = bytes32ToScalarNonZero(params.sHsm1Bytes32);
|
|
2388
|
+
delta = bytes32ToScalarNonZero(params.deltaBytes32);
|
|
2389
|
+
} catch {
|
|
2390
|
+
throw new MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "HSM resplit scalars must satisfy 1 <= scalar < n");
|
|
2391
|
+
}
|
|
2392
|
+
const pRoot = decodePointCompressed(normalizeHexBytes(params.rootPublicKeyComp33, 33), false);
|
|
2393
|
+
const xActor1 = decodePointCompressed(normalizeHexBytes(params.xActor1Comp33, 33), false);
|
|
2394
|
+
const xActor2 = decodePointCompressed(normalizeHexBytes(params.xActor2Comp33, 33), false);
|
|
2395
|
+
if (!xActor1.add(mulBaseG(sHsm1)).equals(pRoot)) throw new MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Source slot share does not match P_root");
|
|
2396
|
+
const sHsm2 = addModN(sHsm1, delta);
|
|
2397
|
+
if (sHsm2 === 0n) throw new MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Degenerate HSM resplit: s_hsm_2 == 0");
|
|
2398
|
+
if (xActor2.is0() || xActor2.equals(pRoot) || xActor2.equals(xActor1)) throw new MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Degenerate target X_actor_2");
|
|
2399
|
+
if (!xActor2.add(mulBaseG(sHsm2)).equals(pRoot)) throw new MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "X_actor_2 + s_hsm_2 * G != P_root");
|
|
2400
|
+
return scalarToBytes32(sHsm2);
|
|
2401
|
+
}
|
|
2402
|
+
function buildTargetShareBoxAad(vaultId, sourceSlotId, targetSlotId, xActor2Comp33, pairNonce32) {
|
|
2403
|
+
return lengthPrefixedEncode(DST_PERSONAL_PAIR_SHARE_AAD_V1, [
|
|
2404
|
+
utf8Bytes(vaultId),
|
|
2405
|
+
utf8Bytes(sourceSlotId),
|
|
2406
|
+
utf8Bytes(targetSlotId),
|
|
2407
|
+
xActor2Comp33,
|
|
2408
|
+
pairNonce32
|
|
2409
|
+
]);
|
|
2410
|
+
}
|
|
2411
|
+
async function initiateActorSlotResplit(params) {
|
|
2412
|
+
const rng = params.rng ?? defaultRandomBytes;
|
|
2413
|
+
if (params.targetBootstrap.vaultId !== params.vaultId) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Target pairing bootstrap vaultId mismatch");
|
|
2414
|
+
if (params.targetBootstrap.targetSlotId === params.sourceSlotId) throw new MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "targetSlotId must differ from sourceSlotId");
|
|
2415
|
+
if (params.kUnsealSecret1_32.length !== 32 || params.kUnsealSecret2_32.length !== 32) throw new MpcProtocolError("INVALID_PARAMETER", "kUnsealSecret1_32 and kUnsealSecret2_32 must be 32 bytes");
|
|
2416
|
+
const verifiedBoot = verifyActorSlotPairingBootstrap(params.targetBootstrap, params.webauthnPolicy);
|
|
2417
|
+
const pRootComp33 = encodePointCompressed(decodePointCompressed(normalizeHexBytes(params.rootPublicKeyComp33, 33), false));
|
|
2418
|
+
const { canonicalPolicyUtf8 } = canonicalizePersonalVaultPolicy(params.policy);
|
|
2419
|
+
let deltaBytes32 = null;
|
|
2420
|
+
let sActor2Bytes32 = null;
|
|
2421
|
+
let xActor2Comp33 = null;
|
|
2422
|
+
const senderEsk32 = rng(32);
|
|
2423
|
+
let sharedTarget32 = null;
|
|
2424
|
+
let targetBoxKey32 = null;
|
|
2425
|
+
let targetPlaintext = null;
|
|
2426
|
+
let hsmPlaintext96 = null;
|
|
2427
|
+
try {
|
|
2428
|
+
for (let attempt = 0; attempt < 64; attempt++) {
|
|
2429
|
+
const candidateDelta = scalarToBytes32(sampleScalarNonZero(rng));
|
|
2430
|
+
try {
|
|
2431
|
+
const res = computeNonDegenerateActorResplitShare({
|
|
2432
|
+
sActor1Bytes32: params.sActor1Bytes32,
|
|
2433
|
+
deltaBytes32: candidateDelta,
|
|
2434
|
+
rootPublicKeyComp33: pRootComp33
|
|
2435
|
+
});
|
|
2436
|
+
deltaBytes32 = candidateDelta;
|
|
2437
|
+
sActor2Bytes32 = res.sActor2Bytes32;
|
|
2438
|
+
xActor2Comp33 = res.xActor2Comp33;
|
|
2439
|
+
break;
|
|
2440
|
+
} catch {
|
|
2441
|
+
zeroizeBytes(candidateDelta);
|
|
2442
|
+
}
|
|
2443
|
+
}
|
|
2444
|
+
if (!deltaBytes32 || !sActor2Bytes32 || !xActor2Comp33) throw new MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Failed to sample non-degenerate resplit delta");
|
|
2445
|
+
const senderEpk32 = x25519.getPublicKey(senderEsk32);
|
|
2446
|
+
sharedTarget32 = computeX25519SharedSecret(senderEsk32, verifiedBoot.ephemeralX25519PublicKey32, "PERSONAL_ACTOR_SIGNATURE_INVALID");
|
|
2447
|
+
targetBoxKey32 = hkdf(sha256, sharedTarget32, concatBytes(senderEpk32, verifiedBoot.ephemeralX25519PublicKey32), utf8Bytes(DST_PERSONAL_PAIR_SHARE_BOX_V1), 32);
|
|
2448
|
+
targetPlaintext = concatBytes(sActor2Bytes32, pRootComp33, u64be(params.policyEpoch), canonicalPolicyUtf8);
|
|
2449
|
+
const targetIv12 = rng(12);
|
|
2450
|
+
const targetAad = buildTargetShareBoxAad(params.vaultId, params.sourceSlotId, params.targetBootstrap.targetSlotId, xActor2Comp33, verifiedBoot.pairNonce32);
|
|
2451
|
+
const { ciphertext: targetCt, tag16: targetTag16 } = await aes256GcmEncryptDetached({
|
|
2452
|
+
key32: targetBoxKey32,
|
|
2453
|
+
iv12: targetIv12,
|
|
2454
|
+
plaintext: targetPlaintext,
|
|
2455
|
+
aad: targetAad
|
|
2456
|
+
});
|
|
2457
|
+
hsmPlaintext96 = concatBytes(params.kUnsealSecret1_32, params.kUnsealSecret2_32, deltaBytes32);
|
|
2458
|
+
const hsmInboundTransportBox = await sealHsmInboundTransportBox({
|
|
2459
|
+
hsmTransportPub32: params.hsmTransportPub32,
|
|
2460
|
+
vaultId: params.vaultId,
|
|
2461
|
+
slotId: params.sourceSlotId,
|
|
2462
|
+
challengeNonce32: params.challengeNonce32,
|
|
2463
|
+
headerMac32: params.sourceHeaderMac32,
|
|
2464
|
+
plaintext: hsmPlaintext96,
|
|
2465
|
+
rng
|
|
2466
|
+
});
|
|
2467
|
+
const pairResplitChallengeDigest32 = buildPersonalPairResplitChallengeDigest32({
|
|
2468
|
+
vaultId: params.vaultId,
|
|
2469
|
+
sourceSlotId: params.sourceSlotId,
|
|
2470
|
+
challengeNonce32: params.challengeNonce32,
|
|
2471
|
+
sourceHeaderMac32: params.sourceHeaderMac32,
|
|
2472
|
+
targetSlotId: params.targetBootstrap.targetSlotId,
|
|
2473
|
+
targetActorKindAndAlg: params.targetBootstrap.actorKindAndAlg,
|
|
2474
|
+
targetActorPubKeyPadded65: verifiedBoot.actorPubKeyPadded65,
|
|
2475
|
+
xActor2Comp33,
|
|
2476
|
+
targetSlotExpiresAtSec: verifiedBoot.slotExpiresAtSec,
|
|
2477
|
+
targetPairNonce32: verifiedBoot.pairNonce32
|
|
2478
|
+
});
|
|
2479
|
+
return {
|
|
2480
|
+
xActor2Comp33,
|
|
2481
|
+
encryptedTargetShareBox: {
|
|
2482
|
+
epkX25519Hex: `0x${bytesToHex(senderEpk32)}`,
|
|
2483
|
+
ivHex: `0x${bytesToHex(targetIv12)}`,
|
|
2484
|
+
tagHex: `0x${bytesToHex(targetTag16)}`,
|
|
2485
|
+
ciphertextHex: `0x${bytesToHex(targetCt)}`,
|
|
2486
|
+
xActor2PublicKeyHex: `0x${bytesToHex(xActor2Comp33)}`
|
|
2487
|
+
},
|
|
2488
|
+
hsmInboundTransportBox,
|
|
2489
|
+
pairResplitChallengeDigest32
|
|
2490
|
+
};
|
|
2491
|
+
} finally {
|
|
2492
|
+
zeroizeBytes(deltaBytes32, sActor2Bytes32, senderEsk32, sharedTarget32, targetBoxKey32, targetPlaintext, hsmPlaintext96);
|
|
2493
|
+
}
|
|
2494
|
+
}
|
|
2495
|
+
async function completeActorSlotPairingOnTarget(params) {
|
|
2496
|
+
if (params.ephemeralX25519SecretKey32.length !== 32) throw new MpcProtocolError("INVALID_PARAMETER", "ephemeralX25519SecretKey32 must be 32 bytes");
|
|
2497
|
+
const parsedBlob2 = parseHsmSealedBlobHeader(params.hsmSealedBlob2);
|
|
2498
|
+
if (parsedBlob2.header.vaultId !== params.vaultId || parsedBlob2.header.slotId !== params.targetBootstrap.targetSlotId || parsedBlob2.header.actorKindAndAlg !== params.targetBootstrap.actorKindAndAlg) {
|
|
2499
|
+
zeroizeBytes(params.ephemeralX25519SecretKey32);
|
|
2500
|
+
throw new MpcProtocolError("PERSONAL_BLOB_TAMPERED", "HsmSealedBlob_2 header does not match target slot bootstrap");
|
|
2501
|
+
}
|
|
2502
|
+
const expectedPub65 = normalizeHexBytes(params.targetBootstrap.actorPubKeyPadded65Hex, 65);
|
|
2503
|
+
if (!constantTimeEqual(parsedBlob2.header.actorPubKeyPadded65, expectedPub65)) {
|
|
2504
|
+
zeroizeBytes(params.ephemeralX25519SecretKey32);
|
|
2505
|
+
throw new MpcProtocolError("PERSONAL_BLOB_TAMPERED", "HsmSealedBlob_2 actor public key mismatch");
|
|
2506
|
+
}
|
|
2507
|
+
let shared32 = null;
|
|
2508
|
+
let boxKey32 = null;
|
|
2509
|
+
let plaintext = null;
|
|
2510
|
+
let sActor2Bytes32 = null;
|
|
2511
|
+
try {
|
|
2512
|
+
const senderEpk32 = normalizeHexBytes(params.encryptedTargetShareBox.epkX25519Hex, 32);
|
|
2513
|
+
assertValidX25519PublicKey(senderEpk32, "PERSONAL_ENVELOPE_AUTH_FAILED");
|
|
2514
|
+
const targetEpk32 = x25519.getPublicKey(params.ephemeralX25519SecretKey32);
|
|
2515
|
+
const pairNonce32 = normalizeHexBytes(params.targetBootstrap.pairNonceHex, 32);
|
|
2516
|
+
const xActor2Comp33 = normalizeHexBytes(params.encryptedTargetShareBox.xActor2PublicKeyHex, 33);
|
|
2517
|
+
const iv12 = normalizeHexBytes(params.encryptedTargetShareBox.ivHex, 12);
|
|
2518
|
+
const tag16 = normalizeHexBytes(params.encryptedTargetShareBox.tagHex, 16);
|
|
2519
|
+
const ciphertext = normalizeHexBytes(params.encryptedTargetShareBox.ciphertextHex);
|
|
2520
|
+
shared32 = computeX25519SharedSecret(params.ephemeralX25519SecretKey32, senderEpk32, "PERSONAL_ENVELOPE_AUTH_FAILED");
|
|
2521
|
+
boxKey32 = hkdf(sha256, shared32, concatBytes(senderEpk32, targetEpk32), utf8Bytes(DST_PERSONAL_PAIR_SHARE_BOX_V1), 32);
|
|
2522
|
+
const aad = buildTargetShareBoxAad(params.vaultId, params.sourceSlotId, params.targetBootstrap.targetSlotId, xActor2Comp33, pairNonce32);
|
|
2523
|
+
plaintext = await aes256GcmDecryptDetached({
|
|
2524
|
+
key32: boxKey32,
|
|
2525
|
+
iv12,
|
|
2526
|
+
ciphertext,
|
|
2527
|
+
tag16,
|
|
2528
|
+
aad,
|
|
2529
|
+
authFailureCode: "PERSONAL_ENVELOPE_AUTH_FAILED"
|
|
2530
|
+
});
|
|
2531
|
+
if (plaintext.length < 75) throw new MpcProtocolError("PERSONAL_ENVELOPE_AUTH_FAILED", "Decrypted target share payload truncated");
|
|
2532
|
+
sActor2Bytes32 = plaintext.slice(0, 32);
|
|
2533
|
+
const pRootComp33 = plaintext.slice(32, 65);
|
|
2534
|
+
const policyEpoch = readU64BE(plaintext, 65);
|
|
2535
|
+
const policyJson = utf8DecodeStrict(plaintext.subarray(73), "PERSONAL_ENVELOPE_AUTH_FAILED");
|
|
2536
|
+
const sActor2 = bytes32ToScalarNonZero(sActor2Bytes32);
|
|
2537
|
+
const pRoot = decodePointCompressed(pRootComp33, false);
|
|
2538
|
+
const derivedXActor2 = mulBaseG(sActor2);
|
|
2539
|
+
if (derivedXActor2.is0() || derivedXActor2.equals(pRoot) || !constantTimeEqual(encodePointCompressed(derivedXActor2), xActor2Comp33)) throw new MpcProtocolError("PERSONAL_DEGENERATE_RESPLIT", "Target share X_actor_2 verification failed");
|
|
2540
|
+
const { canonicalPolicy, policyHash32 } = canonicalizePersonalVaultPolicy(JSON.parse(policyJson));
|
|
2541
|
+
if (!constantTimeEqual(parsedBlob2.header.rootPublicKeyComp33, pRootComp33) || parsedBlob2.header.policyEpoch !== policyEpoch || !constantTimeEqual(parsedBlob2.header.policyHash32, policyHash32)) throw new MpcProtocolError("PERSONAL_BLOB_TAMPERED", "HsmSealedBlob_2 policy/root mismatch against Slot 1 box");
|
|
2542
|
+
return {
|
|
2543
|
+
deviceEnvelope: await sealDeviceShareEnvelope({
|
|
2544
|
+
vaultId: params.vaultId,
|
|
2545
|
+
slotId: params.targetBootstrap.targetSlotId,
|
|
2546
|
+
rootPublicKeyComp33: pRootComp33,
|
|
2547
|
+
sActorBytes32: sActor2Bytes32,
|
|
2548
|
+
kHw32: params.kHw32,
|
|
2549
|
+
kPwdClient32: params.kPwdClient32,
|
|
2550
|
+
rng: params.rng
|
|
2551
|
+
}),
|
|
2552
|
+
rootPublicKeyComp33: pRootComp33,
|
|
2553
|
+
xActor2Comp33,
|
|
2554
|
+
policyEpoch,
|
|
2555
|
+
policy: canonicalPolicy
|
|
2556
|
+
};
|
|
2557
|
+
} finally {
|
|
2558
|
+
zeroizeBytes(params.ephemeralX25519SecretKey32, shared32, boxKey32, plaintext, sActor2Bytes32);
|
|
2559
|
+
}
|
|
2560
|
+
}
|
|
2561
|
+
function computeColdManifestHash32(manifest) {
|
|
2562
|
+
const parts = [
|
|
2563
|
+
utf8Bytes(manifest.vaultId),
|
|
2564
|
+
normalizeHexBytes(manifest.rootPublicKeyHex, 33),
|
|
2565
|
+
utf8Bytes(manifest.rootEthAddress),
|
|
2566
|
+
u8(manifest.tCold),
|
|
2567
|
+
u8(manifest.nCold),
|
|
2568
|
+
u8(manifest.coldFeldmanCommitmentsHex.length),
|
|
2569
|
+
...manifest.coldFeldmanCommitmentsHex.map((c) => normalizeHexBytes(c, 33)),
|
|
2570
|
+
u8(manifest.plates.length)
|
|
2571
|
+
];
|
|
2572
|
+
for (const plate of manifest.plates) parts.push(u8(plate.guardianIndex), utf8Bytes(plate.plateLabel), normalizeHexBytes(plate.coldPublicShareHex, 33), utf8Bytes(plate.decoyEthAddress));
|
|
2573
|
+
return hashTranscriptSha256(DST_PERSONAL_COLD_MANIFEST_V1, ...parts);
|
|
2574
|
+
}
|
|
2575
|
+
function verifyPersonalColdRecoveryKitManifest(manifest) {
|
|
2576
|
+
if (!manifest || manifest.version !== 1) throw new MpcProtocolError("SWEEP_INVALID_QUORUM", "Invalid PersonalColdRecoveryKitManifest version");
|
|
2577
|
+
if (manifest.tCold !== 2 || manifest.nCold !== 2 && manifest.nCold !== 3) throw new MpcProtocolError("SWEEP_INVALID_QUORUM", "Personal cold recovery kit requires 2-of-2 or 2-of-3");
|
|
2578
|
+
if (manifest.coldFeldmanCommitmentsHex.length !== manifest.tCold || manifest.plates.length !== manifest.nCold) throw new MpcProtocolError("SWEEP_INVALID_QUORUM", "Malformed Feldman commitments or plate count in manifest");
|
|
2579
|
+
const rootPubComp33 = encodePointCompressed(decodePointCompressed(normalizeHexBytes(manifest.rootPublicKeyHex, 33), false));
|
|
2580
|
+
if (!constantTimeEqual(rootPubComp33, normalizeHexBytes(manifest.coldFeldmanCommitmentsHex[0], 33))) throw new MpcProtocolError("SWEEP_INVALID_QUORUM", "Cold Feldman C_0 does not match rootPublicKeyHex");
|
|
2581
|
+
const derivedAddr = pointToEthAddress(rootPubComp33).checksumAddress;
|
|
2582
|
+
if (manifest.rootEthAddress !== derivedAddr) throw new MpcProtocolError("SWEEP_INVALID_QUORUM", "Manifest rootEthAddress mismatch against P_root");
|
|
2583
|
+
for (const cHex of manifest.coldFeldmanCommitmentsHex) decodePointCompressed(normalizeHexBytes(cHex, 33), false);
|
|
2584
|
+
for (let i = 0; i < manifest.plates.length; i++) {
|
|
2585
|
+
const p = manifest.plates[i];
|
|
2586
|
+
if (p.guardianIndex !== i + 1) throw new MpcProtocolError("SWEEP_INVALID_QUORUM", "Non-sequential plate guardianIndex in manifest");
|
|
2587
|
+
decodePointCompressed(normalizeHexBytes(p.coldPublicShareHex, 33), false);
|
|
2588
|
+
parseStrictEthAddress(p.decoyEthAddress);
|
|
2589
|
+
}
|
|
2590
|
+
if (!constantTimeEqual(computeColdManifestHash32(manifest), normalizeHexBytes(manifest.manifestHashHex, 32))) throw new MpcProtocolError("SWEEP_INVALID_QUORUM", "Cold recovery manifest integrity hash mismatch");
|
|
2591
|
+
return {
|
|
2592
|
+
rootPublicKeyComp33: rootPubComp33,
|
|
2593
|
+
rootEthAddress: derivedAddr
|
|
2594
|
+
};
|
|
2595
|
+
}
|
|
2596
|
+
async function bootstrapPersonalVaultClient(params) {
|
|
2597
|
+
const rng = params.rng ?? defaultRandomBytes;
|
|
2598
|
+
const tCold = params.tCold ?? 2;
|
|
2599
|
+
const nCold = params.nCold ?? 3;
|
|
2600
|
+
if (tCold !== 2 || nCold !== 2 && nCold !== 3) throw new MpcProtocolError("INVALID_PARAMETER", "Personal cold recovery supports 2-of-2 or 2-of-3");
|
|
2601
|
+
if (params.policy.vaultId !== params.vaultId) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "policy.vaultId must match vaultId");
|
|
2602
|
+
const policyEpoch = params.policyEpoch ?? 1n;
|
|
2603
|
+
const slotExpiresAtSec = params.slotExpiresAtSec ?? 0n;
|
|
2604
|
+
const { canonicalPolicyJson, policyHash32 } = canonicalizePersonalVaultPolicy(params.policy);
|
|
2605
|
+
let sk = 0n;
|
|
2606
|
+
let skBytes32 = null;
|
|
2607
|
+
let sActor1Bytes32 = null;
|
|
2608
|
+
let kPwdClient32 = null;
|
|
2609
|
+
const polyCoeffs = [];
|
|
2610
|
+
try {
|
|
2611
|
+
sk = sampleScalarNonZero(rng);
|
|
2612
|
+
skBytes32 = scalarToBytes32(sk);
|
|
2613
|
+
const pRoot = mulBaseG(sk);
|
|
2614
|
+
const rootPublicKeyComp33 = encodePointCompressed(pRoot);
|
|
2615
|
+
const rootEthAddress = pointToEthAddress(pRoot).checksumAddress;
|
|
2616
|
+
let sActor1 = 0n;
|
|
2617
|
+
let sHsm1 = 0n;
|
|
2618
|
+
for (;;) {
|
|
2619
|
+
const cand = sampleScalarNonZero(rng);
|
|
2620
|
+
const rem = subModN(sk, cand);
|
|
2621
|
+
if (rem >= 1n && rem < SECP256K1_N) {
|
|
2622
|
+
const xA = mulBaseG(cand);
|
|
2623
|
+
if (!xA.is0() && !xA.equals(pRoot)) {
|
|
2624
|
+
sActor1 = cand;
|
|
2625
|
+
sHsm1 = rem;
|
|
2626
|
+
break;
|
|
2627
|
+
}
|
|
2628
|
+
}
|
|
2629
|
+
}
|
|
2630
|
+
sActor1Bytes32 = scalarToBytes32(sActor1);
|
|
2631
|
+
const sHsm1Bytes32 = scalarToBytes32(sHsm1);
|
|
2632
|
+
const xActor1Comp33 = encodePointCompressed(mulBaseG(sActor1));
|
|
2633
|
+
const header319 = encodeHsmSealedBlobHeader319({
|
|
2634
|
+
kid: params.kid,
|
|
2635
|
+
vaultId: params.vaultId,
|
|
2636
|
+
slotId: params.initialSlotId,
|
|
2637
|
+
rootPublicKeyComp33,
|
|
2638
|
+
policyEpoch,
|
|
2639
|
+
actorKindAndAlg: params.actorKindAndAlg,
|
|
2640
|
+
actorPublicKey: params.actorPublicKey,
|
|
2641
|
+
slotExpiresAtSec,
|
|
2642
|
+
policyHash32
|
|
2643
|
+
});
|
|
2644
|
+
let coldSharesScalars = [];
|
|
2645
|
+
for (;;) {
|
|
2646
|
+
polyCoeffs.length = 0;
|
|
2647
|
+
polyCoeffs.push(sk);
|
|
2648
|
+
for (let l = 1; l < tCold; l++) polyCoeffs.push(sampleScalarNonZero(rng));
|
|
2649
|
+
let allNonZero = true;
|
|
2650
|
+
coldSharesScalars = [];
|
|
2651
|
+
for (let k = 1; k <= nCold; k++) {
|
|
2652
|
+
const yk = evaluatePolynomialModN(polyCoeffs, BigInt(k));
|
|
2653
|
+
if (yk === 0n) {
|
|
2654
|
+
allNonZero = false;
|
|
2655
|
+
break;
|
|
2656
|
+
}
|
|
2657
|
+
coldSharesScalars.push(yk);
|
|
2658
|
+
}
|
|
2659
|
+
if (allNonZero) break;
|
|
2660
|
+
}
|
|
2661
|
+
const coldFeldmanCommitmentsComp33 = polyCoeffs.map((c) => encodePointCompressed(mulBaseG(c)));
|
|
2662
|
+
const coldFeldmanCommitmentsHex = coldFeldmanCommitmentsComp33.map((c) => `0x${bytesToHex(c)}`);
|
|
2663
|
+
const platesPublic = [];
|
|
2664
|
+
const platesWords24 = [];
|
|
2665
|
+
for (let idx = 0; idx < nCold; idx++) {
|
|
2666
|
+
const guardianIndex = idx + 1;
|
|
2667
|
+
const shareBytes32 = scalarToBytes32(coldSharesScalars[idx]);
|
|
2668
|
+
coldSharesScalars[idx] = 0n;
|
|
2669
|
+
try {
|
|
2670
|
+
const words24 = encodeColdShareToBip39Words24(shareBytes32);
|
|
2671
|
+
const identified = identifyColdShareIndexViaFeldman(shareBytes32, coldFeldmanCommitmentsComp33, nCold);
|
|
2672
|
+
if (identified.guardianIndex !== guardianIndex) throw new MpcProtocolError("COLD_SHARE_UNKNOWN_INDEX", "Feldman self-check failed during bootstrap");
|
|
2673
|
+
const decoyEthAddress = deriveBip44EthAddressFromWords24(words24);
|
|
2674
|
+
const plateLabel = guardianIndexToPlateLabel(guardianIndex);
|
|
2675
|
+
platesPublic.push({
|
|
2676
|
+
guardianIndex,
|
|
2677
|
+
plateLabel,
|
|
2678
|
+
coldPublicShareHex: `0x${bytesToHex(identified.coldPublicShareComp33)}`,
|
|
2679
|
+
decoyEthAddress
|
|
2680
|
+
});
|
|
2681
|
+
platesWords24.push({
|
|
2682
|
+
guardianIndex,
|
|
2683
|
+
plateLabel,
|
|
2684
|
+
words24
|
|
2685
|
+
});
|
|
2686
|
+
} finally {
|
|
2687
|
+
zeroizeBytes(shareBytes32);
|
|
2688
|
+
}
|
|
2689
|
+
}
|
|
2690
|
+
const unsignedManifest = {
|
|
2691
|
+
version: 1,
|
|
2692
|
+
vaultId: params.vaultId,
|
|
2693
|
+
rootPublicKeyHex: `0x${bytesToHex(rootPublicKeyComp33)}`,
|
|
2694
|
+
rootEthAddress,
|
|
2695
|
+
tCold,
|
|
2696
|
+
nCold,
|
|
2697
|
+
coldFeldmanCommitmentsHex,
|
|
2698
|
+
plates: platesPublic
|
|
2699
|
+
};
|
|
2700
|
+
const manifest = {
|
|
2701
|
+
...unsignedManifest,
|
|
2702
|
+
manifestHashHex: `0x${bytesToHex(computeColdManifestHash32(unsignedManifest))}`
|
|
2703
|
+
};
|
|
2704
|
+
const vaultSalt32 = rng(32);
|
|
2705
|
+
const derivedPwd = derivePersonalWakePasswordKeys({
|
|
2706
|
+
password: params.wakePassword,
|
|
2707
|
+
vaultSalt32,
|
|
2708
|
+
kdf: params.kdf,
|
|
2709
|
+
pbkdf2Iterations: params.pbkdf2Iterations,
|
|
2710
|
+
scryptOpts: params.scryptOpts
|
|
2711
|
+
});
|
|
2712
|
+
kPwdClient32 = derivedPwd.kPwdClient32;
|
|
2713
|
+
const deviceEnvelope = await sealDeviceShareEnvelope({
|
|
2714
|
+
vaultId: params.vaultId,
|
|
2715
|
+
slotId: params.initialSlotId,
|
|
2716
|
+
rootPublicKeyComp33,
|
|
2717
|
+
sActorBytes32: sActor1Bytes32,
|
|
2718
|
+
kHw32: params.kHw32,
|
|
2719
|
+
kPwdClient32,
|
|
2720
|
+
rng
|
|
2721
|
+
});
|
|
2722
|
+
return {
|
|
2723
|
+
vaultId: params.vaultId,
|
|
2724
|
+
initialSlotId: params.initialSlotId,
|
|
2725
|
+
rootPublicKeyComp33,
|
|
2726
|
+
rootEthAddress,
|
|
2727
|
+
xActor1Comp33,
|
|
2728
|
+
header319,
|
|
2729
|
+
sHsm1Bytes32,
|
|
2730
|
+
kPwdHsm32: derivedPwd.kPwdHsm32,
|
|
2731
|
+
vaultSalt32,
|
|
2732
|
+
deviceEnvelope,
|
|
2733
|
+
policyEpoch,
|
|
2734
|
+
canonicalPolicyJson,
|
|
2735
|
+
policyHash32,
|
|
2736
|
+
coldRecoveryKit: {
|
|
2737
|
+
manifest,
|
|
2738
|
+
platesWords24
|
|
2739
|
+
}
|
|
2740
|
+
};
|
|
2741
|
+
} finally {
|
|
2742
|
+
sk = 0n;
|
|
2743
|
+
polyCoeffs.fill(0n);
|
|
2744
|
+
zeroizeBytes(skBytes32, sActor1Bytes32, kPwdClient32);
|
|
2745
|
+
}
|
|
2746
|
+
}
|
|
2747
|
+
function recoverPersonalVaultRootOffline(params) {
|
|
2748
|
+
const { rootPublicKeyComp33, rootEthAddress } = verifyPersonalColdRecoveryKitManifest(params.manifest);
|
|
2749
|
+
if (!Array.isArray(params.platesWords24) || params.platesWords24.length < params.manifest.tCold) throw new MpcProtocolError("SWEEP_INVALID_QUORUM", `Need at least ${params.manifest.tCold} 24-word plates, got ${params.platesWords24?.length ?? 0}`);
|
|
2750
|
+
const decodedShares = [];
|
|
2751
|
+
try {
|
|
2752
|
+
const seenIndices = /* @__PURE__ */ new Set();
|
|
2753
|
+
for (const mnemonic of params.platesWords24) {
|
|
2754
|
+
const shareBytes32 = decodeBip39Words24ToColdShare(mnemonic);
|
|
2755
|
+
let identified;
|
|
2756
|
+
try {
|
|
2757
|
+
identified = identifyColdShareIndexViaFeldman(shareBytes32, params.manifest.coldFeldmanCommitmentsHex, params.manifest.nCold);
|
|
2758
|
+
} catch (err) {
|
|
2759
|
+
zeroizeBytes(shareBytes32);
|
|
2760
|
+
throw err;
|
|
2761
|
+
}
|
|
2762
|
+
if (seenIndices.has(identified.guardianIndex)) {
|
|
2763
|
+
zeroizeBytes(shareBytes32);
|
|
2764
|
+
throw new MpcProtocolError("SWEEP_INVALID_QUORUM", `Duplicate cold recovery plate index ${identified.guardianIndex}`);
|
|
2765
|
+
}
|
|
2766
|
+
seenIndices.add(identified.guardianIndex);
|
|
2767
|
+
decodedShares.push({
|
|
2768
|
+
index: identified.guardianIndex,
|
|
2769
|
+
bytes32: shareBytes32
|
|
2770
|
+
});
|
|
2771
|
+
if (decodedShares.length === params.manifest.tCold) break;
|
|
2772
|
+
}
|
|
2773
|
+
const subset = decodedShares.map((s) => s.index);
|
|
2774
|
+
let sk = 0n;
|
|
2775
|
+
for (const item of decodedShares) {
|
|
2776
|
+
const yk = bytes32ToScalarNonZero(item.bytes32);
|
|
2777
|
+
const lambdaK = lagrangeCoefficientAtZero(item.index, subset);
|
|
2778
|
+
sk = addModN(sk, mulModN(lambdaK, yk));
|
|
2779
|
+
}
|
|
2780
|
+
assertScalarNonZero(sk, "recoveredRootScalar");
|
|
2781
|
+
if (!constantTimeEqual(encodePointCompressed(mulBaseG(sk)), rootPublicKeyComp33)) {
|
|
2782
|
+
sk = 0n;
|
|
2783
|
+
throw new MpcProtocolError("SWEEP_INVALID_QUORUM", "Interpolated cold shares do not match P_root");
|
|
2784
|
+
}
|
|
2785
|
+
const rootScalarBytes32 = scalarToBytes32(sk);
|
|
2786
|
+
sk = 0n;
|
|
2787
|
+
return {
|
|
2788
|
+
rootScalarBytes32,
|
|
2789
|
+
rootPublicKeyComp33,
|
|
2790
|
+
rootEthAddress,
|
|
2791
|
+
usedGuardianIndices: subset
|
|
2792
|
+
};
|
|
2793
|
+
} finally {
|
|
2794
|
+
for (const item of decodedShares) zeroizeBytes(item.bytes32);
|
|
2795
|
+
}
|
|
2796
|
+
}
|
|
2797
|
+
function derivePersonalVaultChildKey(params) {
|
|
2798
|
+
const pRootComp33 = normalizeHexBytes(params.rootPublicKeyComp33, 33);
|
|
2799
|
+
const spec = params.derivation ?? { tweakMode: "untweaked" };
|
|
2800
|
+
if (spec.tweakMode === "untweaked") return deriveUntweakedChild(pRootComp33);
|
|
2801
|
+
if (spec.tweakMode === "role-bound") return deriveRoleBoundChild({
|
|
2802
|
+
rootPublicKey: pRootComp33,
|
|
2803
|
+
rootId: params.vaultId,
|
|
2804
|
+
role: spec.role,
|
|
2805
|
+
ethChainId: spec.ethChainId,
|
|
2806
|
+
tweakLabel: spec.tweakLabel
|
|
2807
|
+
});
|
|
2808
|
+
if (spec.tweakMode === "rule-bound") return deriveRuleBoundChild({
|
|
2809
|
+
rootPublicKey: pRootComp33,
|
|
2810
|
+
rootId: params.vaultId,
|
|
2811
|
+
controllerDid: spec.controllerDid,
|
|
2812
|
+
ethChainId: spec.ethChainId,
|
|
2813
|
+
ruleHash: spec.ruleHash
|
|
2814
|
+
});
|
|
2815
|
+
throw new MpcProtocolError("INVALID_PARAMETER", "Unsupported PersonalChildDerivationInput");
|
|
2816
|
+
}
|
|
2817
|
+
function signPersonalVaultRecoverySweepOffline(params) {
|
|
2818
|
+
const parsedDest = parseStrictEthAddress(params.destinationAddress);
|
|
2819
|
+
if (!Array.isArray(params.sweeps) || params.sweeps.length === 0) throw new MpcProtocolError("INVALID_PARAMETER", "sweeps list must be non-empty");
|
|
2820
|
+
const recovered = recoverPersonalVaultRootOffline({
|
|
2821
|
+
manifest: params.manifest,
|
|
2822
|
+
platesWords24: params.platesWords24
|
|
2823
|
+
});
|
|
2824
|
+
let skRoot = 0n;
|
|
2825
|
+
let childSkBytes32 = null;
|
|
2826
|
+
try {
|
|
2827
|
+
skRoot = bytes32ToScalarNonZero(recovered.rootScalarBytes32);
|
|
2828
|
+
const results = [];
|
|
2829
|
+
for (const item of params.sweeps) {
|
|
2830
|
+
const derivedChild = derivePersonalVaultChildKey({
|
|
2831
|
+
vaultId: params.manifest.vaultId,
|
|
2832
|
+
rootPublicKeyComp33: recovered.rootPublicKeyComp33,
|
|
2833
|
+
derivation: item.derivation
|
|
2834
|
+
});
|
|
2835
|
+
const skChild = addModN(skRoot, derivedChild.tweakScalar);
|
|
2836
|
+
assertScalarNonZero(skChild, "skChild");
|
|
2837
|
+
childSkBytes32 = scalarToBytes32(skChild);
|
|
2838
|
+
try {
|
|
2839
|
+
let txFields;
|
|
2840
|
+
if (item.asset.kind === "native-eth") {
|
|
2841
|
+
if (item.asset.valueWei <= 0n) throw new MpcProtocolError("INVALID_PARAMETER", "Native ETH sweep valueWei must be > 0");
|
|
2842
|
+
txFields = {
|
|
2843
|
+
chainId: item.chainId,
|
|
2844
|
+
nonce: item.nonce,
|
|
2845
|
+
maxPriorityFeePerGasWei: item.maxPriorityFeePerGasWei,
|
|
2846
|
+
maxFeePerGasWei: item.maxFeePerGasWei,
|
|
2847
|
+
gasLimit: item.gasLimit ?? 21000n,
|
|
2848
|
+
to: parsedDest.checksumAddress,
|
|
2849
|
+
valueWei: item.asset.valueWei,
|
|
2850
|
+
data: "0x",
|
|
2851
|
+
accessList: item.accessList
|
|
2852
|
+
};
|
|
2853
|
+
} else {
|
|
2854
|
+
const tokenAddr = parseStrictEthAddress(item.asset.tokenContract).checksumAddress;
|
|
2855
|
+
const calldata = encodeErc20TransferCalldata(parsedDest.checksumAddress, item.asset.tokenAmount);
|
|
2856
|
+
txFields = {
|
|
2857
|
+
chainId: item.chainId,
|
|
2858
|
+
nonce: item.nonce,
|
|
2859
|
+
maxPriorityFeePerGasWei: item.maxPriorityFeePerGasWei,
|
|
2860
|
+
maxFeePerGasWei: item.maxFeePerGasWei,
|
|
2861
|
+
gasLimit: item.gasLimit ?? 65000n,
|
|
2862
|
+
to: tokenAddr,
|
|
2863
|
+
valueWei: 0n,
|
|
2864
|
+
data: calldata,
|
|
2865
|
+
accessList: item.accessList
|
|
2866
|
+
};
|
|
2867
|
+
}
|
|
2868
|
+
const unsigned = encodeUnsignedEip1559Tx(txFields);
|
|
2869
|
+
const sigRecovered65 = secp256k1.sign(unsigned.signingDigest32, childSkBytes32, {
|
|
2870
|
+
prehash: false,
|
|
2871
|
+
lowS: true,
|
|
2872
|
+
format: "recovered"
|
|
2873
|
+
});
|
|
2874
|
+
const yParity = sigRecovered65[0];
|
|
2875
|
+
const r = bytesToBigIntBE(sigRecovered65.subarray(1, 33));
|
|
2876
|
+
const s = bytesToBigIntBE(sigRecovered65.subarray(33, 65));
|
|
2877
|
+
if (s > SECP256K1_HALF_N) throw new MpcProtocolError("SIGN_AGGREGATION_FAILED", "Unexpected high-S offline sweep signature");
|
|
2878
|
+
const encodedSigned = encodeSignedEip1559Tx({
|
|
2879
|
+
tx: txFields,
|
|
2880
|
+
yParity,
|
|
2881
|
+
r,
|
|
2882
|
+
s
|
|
2883
|
+
});
|
|
2884
|
+
if (decodeAndRecoverSignedEip1559Tx(encodedSigned.rawSignedTxBytes).senderChecksumAddress !== derivedChild.ethAddress) throw new MpcProtocolError("SIGN_AGGREGATION_FAILED", "Offline sweep ecrecover sender mismatch");
|
|
2885
|
+
results.push({
|
|
2886
|
+
senderAddress: derivedChild.ethAddress,
|
|
2887
|
+
destinationAddress: parsedDest.checksumAddress,
|
|
2888
|
+
rawSignedTxBytes: encodedSigned.rawSignedTxBytes,
|
|
2889
|
+
rawSignedTxHex: encodedSigned.rawSignedTxHex,
|
|
2890
|
+
txHashHex: encodedSigned.txHashHex
|
|
2891
|
+
});
|
|
2892
|
+
} finally {
|
|
2893
|
+
zeroizeBytes(childSkBytes32);
|
|
2894
|
+
childSkBytes32 = null;
|
|
2895
|
+
}
|
|
2896
|
+
}
|
|
2897
|
+
return results;
|
|
2898
|
+
} finally {
|
|
2899
|
+
skRoot = 0n;
|
|
2900
|
+
zeroizeBytes(recovered.rootScalarBytes32, childSkBytes32);
|
|
2901
|
+
}
|
|
2902
|
+
}
|
|
2903
|
+
function derivePersonalBaseOtContext(cluster, sessionNonce32, senderSlotB, receiverSlotA) {
|
|
2904
|
+
return hashTranscriptSha256(DST_PERSONAL_BASEOT_CTX_V1, utf8Bytes(cluster.rootId), u64be(cluster.keyEpoch), cluster.hDkg32, sessionNonce32, u16be(senderSlotB), u16be(receiverSlotA));
|
|
2905
|
+
}
|
|
2906
|
+
/**
|
|
2907
|
+
* Stateful `Slot 2` (HSM Cosigner) 2-party presignature responder session.
|
|
2908
|
+
* Consumes `sHsmBytes32` once at construction (wiping it immediately after converting to Shamir Slot 2)
|
|
2909
|
+
* and stores the completed `PresignatureShareRecord` into the HSM's `VolatilePresignaturePool`.
|
|
2910
|
+
*/
|
|
2911
|
+
var PersonalCosignerResponderSession = class {
|
|
2912
|
+
constructor(params) {
|
|
2913
|
+
this.baseOtReceiverA2 = null;
|
|
2914
|
+
this.baseOtPendingB2 = null;
|
|
2915
|
+
this.baseOtSenderB2 = null;
|
|
2916
|
+
this.partySession = null;
|
|
2917
|
+
this.hsmR1Commitment = null;
|
|
2918
|
+
this.hsmR1Reveal = null;
|
|
2919
|
+
this.clientR3 = null;
|
|
2920
|
+
this.hsmR3 = null;
|
|
2921
|
+
this.hsmR4 = null;
|
|
2922
|
+
this.closed = false;
|
|
2923
|
+
this.presignSessionId = params.presignSessionId;
|
|
2924
|
+
this.rng = params.rng ?? defaultRandomBytes;
|
|
2925
|
+
this.sessionNonce32 = normalizeHexBytes(params.sessionNonce32, 32);
|
|
2926
|
+
try {
|
|
2927
|
+
this.cluster = buildPersonalVaultClusterInfo({
|
|
2928
|
+
vaultId: params.vaultId,
|
|
2929
|
+
slotId: params.slotId,
|
|
2930
|
+
policyEpoch: params.policyEpoch,
|
|
2931
|
+
rootPublicKeyComp33: params.rootPublicKeyComp33,
|
|
2932
|
+
xActorComp33: params.xActorComp33
|
|
2933
|
+
});
|
|
2934
|
+
this.shamirSlot2Share32 = additiveToShamirSlot2Share(params.sHsmBytes32);
|
|
2935
|
+
} finally {
|
|
2936
|
+
zeroizeBytes(params.sHsmBytes32);
|
|
2937
|
+
}
|
|
2938
|
+
}
|
|
2939
|
+
get isClosed() {
|
|
2940
|
+
return this.closed;
|
|
2941
|
+
}
|
|
2942
|
+
abort() {
|
|
2943
|
+
this.closed = true;
|
|
2944
|
+
zeroizeBytes(this.shamirSlot2Share32, this.baseOtPendingB2?.yScalarBytes32);
|
|
2945
|
+
this.shamirSlot2Share32 = null;
|
|
2946
|
+
if (this.baseOtReceiverA2) {
|
|
2947
|
+
wipeBaseOtReceiverState(this.baseOtReceiverA2);
|
|
2948
|
+
this.baseOtReceiverA2 = null;
|
|
2949
|
+
}
|
|
2950
|
+
if (this.baseOtSenderB2) {
|
|
2951
|
+
wipeBaseOtSenderState(this.baseOtSenderB2);
|
|
2952
|
+
this.baseOtSenderB2 = null;
|
|
2953
|
+
}
|
|
2954
|
+
if (this.partySession) {
|
|
2955
|
+
this.partySession.abort();
|
|
2956
|
+
this.partySession = null;
|
|
2957
|
+
}
|
|
2958
|
+
}
|
|
2959
|
+
handleInit(req) {
|
|
2960
|
+
if (this.closed || this.baseOtReceiverA2 !== null) {
|
|
2961
|
+
this.abort();
|
|
2962
|
+
throw new MpcProtocolError("PRESIG_STATE_VIOLATION", "Cosigner responder init already executed");
|
|
2963
|
+
}
|
|
2964
|
+
try {
|
|
2965
|
+
if (!constantTimeEqual(req.sessionNonce32, this.sessionNonce32)) throw new MpcProtocolError("INVALID_PARAMETER", "sessionNonce32 mismatch");
|
|
2966
|
+
const ctxB1A2 = derivePersonalBaseOtContext(this.cluster, this.sessionNonce32, 1, 2);
|
|
2967
|
+
const ctxB2A1 = derivePersonalBaseOtContext(this.cluster, this.sessionNonce32, 2, 1);
|
|
2968
|
+
const step2Res = baseOtReceiverStep2({
|
|
2969
|
+
ctxBaseOt: ctxB1A2,
|
|
2970
|
+
senderSlotB: 1,
|
|
2971
|
+
receiverSlotA: 2,
|
|
2972
|
+
step1Message: req.baseOtB1A2Step1,
|
|
2973
|
+
rng: this.rng
|
|
2974
|
+
});
|
|
2975
|
+
this.baseOtReceiverA2 = step2Res.receiverState;
|
|
2976
|
+
const step1Res = baseOtSenderStep1({
|
|
2977
|
+
ctxBaseOt: ctxB2A1,
|
|
2978
|
+
senderSlotB: 2,
|
|
2979
|
+
receiverSlotA: 1,
|
|
2980
|
+
rng: this.rng
|
|
2981
|
+
});
|
|
2982
|
+
this.baseOtPendingB2 = step1Res.pending;
|
|
2983
|
+
return {
|
|
2984
|
+
presignSessionId: this.presignSessionId,
|
|
2985
|
+
baseOtB1A2Step2: step2Res.message,
|
|
2986
|
+
baseOtB2A1Step1: step1Res.message
|
|
2987
|
+
};
|
|
2988
|
+
} catch (err) {
|
|
2989
|
+
this.abort();
|
|
2990
|
+
throw err;
|
|
2991
|
+
}
|
|
2992
|
+
}
|
|
2993
|
+
handleStep(req, targetPool) {
|
|
2994
|
+
if (this.closed || req.presignSessionId !== this.presignSessionId) {
|
|
2995
|
+
this.abort();
|
|
2996
|
+
throw new MpcProtocolError("PRESIG_STATE_VIOLATION", "Invalid or closed presignSessionId");
|
|
2997
|
+
}
|
|
2998
|
+
try {
|
|
2999
|
+
if (req.step === "r1-commit") {
|
|
3000
|
+
if (!this.baseOtPendingB2 || !this.baseOtReceiverA2 || !this.shamirSlot2Share32 || this.partySession) throw new MpcProtocolError("PRESIG_STATE_VIOLATION", "Unexpected r1-commit step");
|
|
3001
|
+
this.baseOtSenderB2 = baseOtSenderStep3({
|
|
3002
|
+
pending: this.baseOtPendingB2,
|
|
3003
|
+
step2Message: req.baseOtB2A1Step2
|
|
3004
|
+
});
|
|
3005
|
+
this.baseOtPendingB2 = null;
|
|
3006
|
+
const channels = {
|
|
3007
|
+
ownerSlot: 2,
|
|
3008
|
+
asExtendedSenderA: new Map([[1, this.baseOtReceiverA2]]),
|
|
3009
|
+
asExtendedReceiverB: new Map([[1, this.baseOtSenderB2]])
|
|
3010
|
+
};
|
|
3011
|
+
try {
|
|
3012
|
+
this.partySession = new PresignPartySession({
|
|
3013
|
+
slot: 2,
|
|
3014
|
+
nodeSecretShareBytes32: this.shamirSlot2Share32,
|
|
3015
|
+
cluster: this.cluster,
|
|
3016
|
+
subset: [1, 2],
|
|
3017
|
+
sessionNonce32: this.sessionNonce32,
|
|
3018
|
+
baseOtChannels: channels,
|
|
3019
|
+
rng: this.rng
|
|
3020
|
+
});
|
|
3021
|
+
} finally {
|
|
3022
|
+
zeroizeBytes(this.shamirSlot2Share32);
|
|
3023
|
+
this.shamirSlot2Share32 = null;
|
|
3024
|
+
}
|
|
3025
|
+
const c2 = this.partySession.round1CreateCommitment();
|
|
3026
|
+
const rev2 = this.partySession.round1ReceiveCommitmentsAndReveal([req.clientR1Commitment, c2]);
|
|
3027
|
+
this.hsmR1Commitment = c2;
|
|
3028
|
+
this.hsmR1Reveal = rev2.reveal;
|
|
3029
|
+
return {
|
|
3030
|
+
step: "r1-commit-ack",
|
|
3031
|
+
presigId32: rev2.presigId32,
|
|
3032
|
+
hsmR1Commitment: c2,
|
|
3033
|
+
hsmR1Reveal: rev2.reveal
|
|
3034
|
+
};
|
|
3035
|
+
}
|
|
3036
|
+
if (!this.partySession) throw new MpcProtocolError("PRESIG_STATE_VIOLATION", "PresignPartySession not initialized");
|
|
3037
|
+
if (req.step === "r1-reveal-and-ot1") {
|
|
3038
|
+
if (!this.hsmR1Commitment || !this.hsmR1Reveal) throw new MpcProtocolError("PRESIG_STATE_VIOLATION", "Missing Round-1 HSM state");
|
|
3039
|
+
this.partySession.round1VerifyAllReveals([req.clientR1Reveal, this.hsmR1Reveal]);
|
|
3040
|
+
return {
|
|
3041
|
+
step: "ot1-and-ot2",
|
|
3042
|
+
hsmOt1: this.partySession.round2CreateOtStep1Messages(),
|
|
3043
|
+
hsmOt2: this.partySession.round2ProcessOtStep1AndCreateStep2(req.clientOt1)
|
|
3044
|
+
};
|
|
3045
|
+
}
|
|
3046
|
+
if (req.step === "ot2-and-ot3") return {
|
|
3047
|
+
step: "ot3-and-mta",
|
|
3048
|
+
hsmOt3: this.partySession.round2ProcessOtStep2AndCreateStep3(req.clientOt2),
|
|
3049
|
+
hsmMta: this.partySession.round2VerifyKos15AndCreateMtaPayloads(req.clientOt3)
|
|
3050
|
+
};
|
|
3051
|
+
if (req.step === "mta-and-r3") {
|
|
3052
|
+
this.partySession.round2VerifyMtaPayloads(req.clientMta);
|
|
3053
|
+
const hsmR3 = this.partySession.round3CreateBroadcast();
|
|
3054
|
+
const hsmR4 = this.partySession.round3VerifyAndCreateRound4Broadcast([req.clientR3, hsmR3]);
|
|
3055
|
+
this.clientR3 = req.clientR3;
|
|
3056
|
+
this.hsmR3 = hsmR3;
|
|
3057
|
+
this.hsmR4 = hsmR4;
|
|
3058
|
+
return {
|
|
3059
|
+
step: "r3-and-r4",
|
|
3060
|
+
hsmR3,
|
|
3061
|
+
hsmR4
|
|
3062
|
+
};
|
|
3063
|
+
}
|
|
3064
|
+
if (req.step === "r4-finalize") {
|
|
3065
|
+
if (!this.clientR3 || !this.hsmR3 || !this.hsmR4) throw new MpcProtocolError("PRESIG_STATE_VIOLATION", "Missing Round-3/4 HSM state");
|
|
3066
|
+
const record = this.partySession.round4VerifyAndFinalize([req.clientR4, this.hsmR4]);
|
|
3067
|
+
targetPool.store(record);
|
|
3068
|
+
const presigIdHex = record.publicVerification.presigIdHex;
|
|
3069
|
+
this.abort();
|
|
3070
|
+
return {
|
|
3071
|
+
step: "finalized",
|
|
3072
|
+
presigIdHex
|
|
3073
|
+
};
|
|
3074
|
+
}
|
|
3075
|
+
throw new MpcProtocolError("PRESIG_STATE_VIOLATION", "Unknown presign step");
|
|
3076
|
+
} catch (err) {
|
|
3077
|
+
this.abort();
|
|
3078
|
+
throw err;
|
|
3079
|
+
}
|
|
3080
|
+
}
|
|
3081
|
+
};
|
|
3082
|
+
function computeSimulatedDeltaCommitment32(delta, extra) {
|
|
3083
|
+
assertPlainSimulationRecord(delta, "simulatedDelta");
|
|
3084
|
+
const nativeDeltaWei = assertSignedSimulationBigInt(delta.nativeDeltaWei, "simulatedDelta.nativeDeltaWei");
|
|
3085
|
+
const tokenMap = /* @__PURE__ */ new Map();
|
|
3086
|
+
if (delta.tokenDeltas !== void 0) {
|
|
3087
|
+
const rawDeltaMap = assertPlainSimulationRecord(delta.tokenDeltas, "simulatedDelta.tokenDeltas");
|
|
3088
|
+
for (const tokenAddr of Object.keys(rawDeltaMap)) {
|
|
3089
|
+
const val = assertSignedSimulationBigInt(rawDeltaMap[tokenAddr], `tokenDeltas[${tokenAddr}]`);
|
|
3090
|
+
const key = normalizeSimulationTokenAddress(tokenAddr, "simulatedDelta.tokenDeltas");
|
|
3091
|
+
tokenMap.set(key, (tokenMap.get(key) ?? 0n) + val);
|
|
3092
|
+
}
|
|
3093
|
+
}
|
|
3094
|
+
const sortedTokens = [...tokenMap.entries()].filter(([, v]) => v !== 0n).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${k}:${v.toString(10)}`);
|
|
3095
|
+
const outgoing = [...assertOptionalSimulationStringArray(delta.outgoingAssetIds, "outgoingAssetIds") ?? []].sort();
|
|
3096
|
+
const ownedAfter = [...assertOptionalSimulationStringArray(delta.ownedAssetIdsAfter, "ownedAssetIdsAfter") ?? []].sort();
|
|
3097
|
+
const proxyImplNorm = extra?.proxyImplementationAddress && extra.proxyImplementationAddress !== "0x" ? parseStrictEthAddress(extra.proxyImplementationAddress).lowercaseAddress : "";
|
|
3098
|
+
return sha256(lengthPrefixedEncode(DST_PERSONAL_SIMULATED_DELTA_V1, [utf8Bytes(deterministicJsonStringify({
|
|
3099
|
+
version: 1,
|
|
3100
|
+
simulationReverted: Boolean(delta.simulationReverted),
|
|
3101
|
+
nativeDeltaWei: nativeDeltaWei.toString(10),
|
|
3102
|
+
tokenDeltas: sortedTokens,
|
|
3103
|
+
outgoingAssetIds: outgoing,
|
|
3104
|
+
ownedAssetIdsAfter: ownedAfter,
|
|
3105
|
+
proxyImplementationAddress: proxyImplNorm
|
|
3106
|
+
}))]));
|
|
3107
|
+
}
|
|
3108
|
+
function buildFirewallAttestationSigningDigest32(params) {
|
|
3109
|
+
return sha256(lengthPrefixedEncode(DST_PERSONAL_FIREWALL_ATTESTATION_V1, [
|
|
3110
|
+
u8(1),
|
|
3111
|
+
utf8Bytes(params.attestationId),
|
|
3112
|
+
utf8Bytes(params.vaultId),
|
|
3113
|
+
u64be(params.policyEpoch),
|
|
3114
|
+
utf8Bytes(params.chainNamespace),
|
|
3115
|
+
utf8Bytes(params.chainId),
|
|
3116
|
+
utf8Bytes(params.fromAddress),
|
|
3117
|
+
utf8Bytes(params.toAddress),
|
|
3118
|
+
params.signingDigest32,
|
|
3119
|
+
params.clearSigningPreviewHash32,
|
|
3120
|
+
u64be(params.simulatedBlockNumber),
|
|
3121
|
+
params.simulatedDeltaHash32,
|
|
3122
|
+
utf8Bytes(params.tier),
|
|
3123
|
+
utf8Bytes(params.verdict),
|
|
3124
|
+
utf8Bytes(params.riskCodes.join(",")),
|
|
3125
|
+
u64be(params.issuedAtSec),
|
|
3126
|
+
u64be(params.expiresAtSec),
|
|
3127
|
+
params.verifierPublicKey32
|
|
3128
|
+
]));
|
|
3129
|
+
}
|
|
3130
|
+
function signPersonalFirewallAttestation(params) {
|
|
3131
|
+
const sk32 = normalizeHexBytes(params.verifierSecretKey32, 32);
|
|
3132
|
+
try {
|
|
3133
|
+
assertPrintableIdentifierAscii(params.attestationId, 64, "attestationId", "INVALID_PARAMETER");
|
|
3134
|
+
assertPrintableIdentifierAscii(params.vaultId, 64, "vaultId", "INVALID_PARAMETER");
|
|
3135
|
+
assertPrintableIdentifierAscii(params.chainId, 64, "chainId", "INVALID_PARAMETER");
|
|
3136
|
+
const normalizedFrom = normalizeOcapAddressOrEth(params.fromAddress, "fromAddress", "INVALID_PARAMETER");
|
|
3137
|
+
const normalizedTo = normalizeOcapAddressOrEth(params.toAddress, "toAddress", "INVALID_PARAMETER");
|
|
3138
|
+
const signingDigest32 = normalizeHexBytes(params.signingDigest32, 32);
|
|
3139
|
+
const previewHash32 = normalizeHexBytes(params.clearSigningPreviewHash32, 32);
|
|
3140
|
+
const simDeltaHash32 = normalizeHexBytes(params.simulatedDeltaHash32, 32);
|
|
3141
|
+
const ttl = params.ttlSeconds ?? 120;
|
|
3142
|
+
if (!Number.isInteger(ttl) || ttl < 1 || ttl > MAX_PERSONAL_FIREWALL_ATTESTATION_TTL_SECONDS) throw new MpcProtocolError("INVALID_PARAMETER", `Firewall attestation ttlSeconds must be 1..${MAX_PERSONAL_FIREWALL_ATTESTATION_TTL_SECONDS}`);
|
|
3143
|
+
const expiresAtSec = params.issuedAtSec + BigInt(ttl);
|
|
3144
|
+
const riskCodes = (params.riskCodes ?? []).map((code) => {
|
|
3145
|
+
assertPrintableIdentifierAscii(code, 64, "riskCode", "INVALID_PARAMETER");
|
|
3146
|
+
if (code.includes(",")) throw new MpcProtocolError("INVALID_PARAMETER", "riskCode must not contain commas");
|
|
3147
|
+
return code;
|
|
3148
|
+
});
|
|
3149
|
+
if (riskCodes.length > 32) throw new MpcProtocolError("INVALID_PARAMETER", "riskCodes exceeds maximum length 32");
|
|
3150
|
+
const verifierPub32 = ed25519.getPublicKey(sk32);
|
|
3151
|
+
validateEd25519PublicKeyNonTorsion32(verifierPub32, "INVALID_PARAMETER");
|
|
3152
|
+
const digest32 = buildFirewallAttestationSigningDigest32({
|
|
3153
|
+
attestationId: params.attestationId,
|
|
3154
|
+
vaultId: params.vaultId,
|
|
3155
|
+
policyEpoch: params.policyEpoch,
|
|
3156
|
+
chainNamespace: params.chainNamespace,
|
|
3157
|
+
chainId: params.chainId,
|
|
3158
|
+
fromAddress: normalizedFrom,
|
|
3159
|
+
toAddress: normalizedTo,
|
|
3160
|
+
signingDigest32,
|
|
3161
|
+
clearSigningPreviewHash32: previewHash32,
|
|
3162
|
+
simulatedBlockNumber: params.simulatedBlockNumber,
|
|
3163
|
+
simulatedDeltaHash32: simDeltaHash32,
|
|
3164
|
+
tier: params.tier,
|
|
3165
|
+
verdict: params.verdict,
|
|
3166
|
+
riskCodes,
|
|
3167
|
+
issuedAtSec: params.issuedAtSec,
|
|
3168
|
+
expiresAtSec,
|
|
3169
|
+
verifierPublicKey32: verifierPub32
|
|
3170
|
+
});
|
|
3171
|
+
const sig64 = ed25519.sign(digest32, sk32);
|
|
3172
|
+
return {
|
|
3173
|
+
version: 1,
|
|
3174
|
+
attestationId: params.attestationId,
|
|
3175
|
+
vaultId: params.vaultId,
|
|
3176
|
+
policyEpoch: params.policyEpoch.toString(10),
|
|
3177
|
+
chainNamespace: params.chainNamespace,
|
|
3178
|
+
chainId: params.chainId,
|
|
3179
|
+
fromAddress: normalizedFrom,
|
|
3180
|
+
toAddress: normalizedTo,
|
|
3181
|
+
signingDigestHex: `0x${bytesToHex(signingDigest32)}`,
|
|
3182
|
+
clearSigningPreviewHashHex: `0x${bytesToHex(previewHash32)}`,
|
|
3183
|
+
simulatedBlockNumber: params.simulatedBlockNumber.toString(10),
|
|
3184
|
+
simulatedDeltaHashHex: `0x${bytesToHex(simDeltaHash32)}`,
|
|
3185
|
+
tier: params.tier,
|
|
3186
|
+
verdict: params.verdict,
|
|
3187
|
+
riskCodes,
|
|
3188
|
+
issuedAtSec: params.issuedAtSec.toString(10),
|
|
3189
|
+
expiresAtSec: expiresAtSec.toString(10),
|
|
3190
|
+
verifierPublicKeyHex: `0x${bytesToHex(verifierPub32)}`,
|
|
3191
|
+
signatureHex: `0x${bytesToHex(sig64)}`
|
|
3192
|
+
};
|
|
3193
|
+
} finally {
|
|
3194
|
+
zeroizeBytes(sk32);
|
|
3195
|
+
}
|
|
3196
|
+
}
|
|
3197
|
+
function verifyPersonalFirewallAttestation(params) {
|
|
3198
|
+
const { attestation } = params;
|
|
3199
|
+
if (!attestation || typeof attestation !== "object" || attestation.version !== 1) throw new MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "Invalid SignedFirewallAttestation version");
|
|
3200
|
+
if (!Array.isArray(params.trustedVerifierPublicKeys) || params.trustedVerifierPublicKeys.length === 0) throw new MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_REQUIRED", "No trusted firewall verifier public keys available");
|
|
3201
|
+
let policyEpoch;
|
|
3202
|
+
let simulatedBlockNumber;
|
|
3203
|
+
let issuedAtSec;
|
|
3204
|
+
let expiresAtSec;
|
|
3205
|
+
let signingDigest32;
|
|
3206
|
+
let previewHash32;
|
|
3207
|
+
let simDeltaHash32;
|
|
3208
|
+
let verifierPub32;
|
|
3209
|
+
let sig64;
|
|
3210
|
+
let normalizedFrom;
|
|
3211
|
+
let normalizedTo;
|
|
3212
|
+
try {
|
|
3213
|
+
assertPrintableIdentifierAscii(attestation.attestationId, 64, "attestationId", "PERSONAL_FIREWALL_ATTESTATION_INVALID");
|
|
3214
|
+
assertPrintableIdentifierAscii(attestation.vaultId, 64, "vaultId", "PERSONAL_FIREWALL_ATTESTATION_INVALID");
|
|
3215
|
+
assertPrintableIdentifierAscii(attestation.chainId, 64, "chainId", "PERSONAL_FIREWALL_ATTESTATION_INVALID");
|
|
3216
|
+
if (attestation.chainNamespace !== "evm" && attestation.chainNamespace !== "ocap") throw new Error("bad namespace");
|
|
3217
|
+
if (attestation.tier !== "free-local" && attestation.tier !== "pro-shield" && attestation.tier !== "vault-enforced") throw new Error("bad tier");
|
|
3218
|
+
if (attestation.verdict !== "allow" && attestation.verdict !== "warn" && attestation.verdict !== "block") throw new Error("bad verdict");
|
|
3219
|
+
if (!Array.isArray(attestation.riskCodes) || attestation.riskCodes.length > 32) throw new Error("bad riskCodes");
|
|
3220
|
+
for (const rc of attestation.riskCodes) {
|
|
3221
|
+
assertPrintableIdentifierAscii(rc, 64, "riskCode", "PERSONAL_FIREWALL_ATTESTATION_INVALID");
|
|
3222
|
+
if (rc.includes(",")) throw new Error("comma in riskCode");
|
|
3223
|
+
}
|
|
3224
|
+
normalizedFrom = normalizeOcapAddressOrEth(attestation.fromAddress, "fromAddress", "PERSONAL_FIREWALL_ATTESTATION_INVALID");
|
|
3225
|
+
normalizedTo = normalizeOcapAddressOrEth(attestation.toAddress, "toAddress", "PERSONAL_FIREWALL_ATTESTATION_INVALID");
|
|
3226
|
+
policyEpoch = parseStrictNonNegativeBigInt(attestation.policyEpoch, MAX_UINT64, "policyEpoch", "PERSONAL_FIREWALL_ATTESTATION_INVALID");
|
|
3227
|
+
simulatedBlockNumber = parseStrictNonNegativeBigInt(attestation.simulatedBlockNumber, MAX_UINT64, "simulatedBlockNumber", "PERSONAL_FIREWALL_ATTESTATION_INVALID");
|
|
3228
|
+
issuedAtSec = parseStrictNonNegativeBigInt(attestation.issuedAtSec, MAX_UINT64, "issuedAtSec", "PERSONAL_FIREWALL_ATTESTATION_INVALID");
|
|
3229
|
+
expiresAtSec = parseStrictNonNegativeBigInt(attestation.expiresAtSec, MAX_UINT64, "expiresAtSec", "PERSONAL_FIREWALL_ATTESTATION_INVALID");
|
|
3230
|
+
signingDigest32 = normalizeHexBytes(attestation.signingDigestHex, 32);
|
|
3231
|
+
previewHash32 = normalizeHexBytes(attestation.clearSigningPreviewHashHex, 32);
|
|
3232
|
+
simDeltaHash32 = normalizeHexBytes(attestation.simulatedDeltaHashHex, 32);
|
|
3233
|
+
verifierPub32 = normalizeHexBytes(attestation.verifierPublicKeyHex, 32);
|
|
3234
|
+
validateEd25519PublicKeyNonTorsion32(verifierPub32, "PERSONAL_FIREWALL_ATTESTATION_INVALID");
|
|
3235
|
+
sig64 = normalizeHexBytes(attestation.signatureHex, 64);
|
|
3236
|
+
} catch (err) {
|
|
3237
|
+
if (err instanceof MpcProtocolError) throw err;
|
|
3238
|
+
throw new MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "Malformed SignedFirewallAttestation fields");
|
|
3239
|
+
}
|
|
3240
|
+
if (!params.trustedVerifierPublicKeys.some((rawKey) => {
|
|
3241
|
+
try {
|
|
3242
|
+
return constantTimeEqual(normalizeHexBytes(rawKey, 32), verifierPub32);
|
|
3243
|
+
} catch {
|
|
3244
|
+
return false;
|
|
3245
|
+
}
|
|
3246
|
+
})) throw new MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "SignedFirewallAttestation verifier key is not in trusted intersection");
|
|
3247
|
+
const digest32 = buildFirewallAttestationSigningDigest32({
|
|
3248
|
+
attestationId: attestation.attestationId,
|
|
3249
|
+
vaultId: attestation.vaultId,
|
|
3250
|
+
policyEpoch,
|
|
3251
|
+
chainNamespace: attestation.chainNamespace,
|
|
3252
|
+
chainId: attestation.chainId,
|
|
3253
|
+
fromAddress: normalizedFrom,
|
|
3254
|
+
toAddress: normalizedTo,
|
|
3255
|
+
signingDigest32,
|
|
3256
|
+
clearSigningPreviewHash32: previewHash32,
|
|
3257
|
+
simulatedBlockNumber,
|
|
3258
|
+
simulatedDeltaHash32: simDeltaHash32,
|
|
3259
|
+
tier: attestation.tier,
|
|
3260
|
+
verdict: attestation.verdict,
|
|
3261
|
+
riskCodes: attestation.riskCodes,
|
|
3262
|
+
issuedAtSec,
|
|
3263
|
+
expiresAtSec,
|
|
3264
|
+
verifierPublicKey32: verifierPub32
|
|
3265
|
+
});
|
|
3266
|
+
let sigOk = false;
|
|
3267
|
+
try {
|
|
3268
|
+
sigOk = ed25519.verify(sig64, digest32, verifierPub32, { zip215: false });
|
|
3269
|
+
} catch {
|
|
3270
|
+
sigOk = false;
|
|
3271
|
+
}
|
|
3272
|
+
if (!sigOk) throw new MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "Invalid Ed25519 signature on SignedFirewallAttestation");
|
|
3273
|
+
if (attestation.verdict !== "allow") throw new MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", `Firewall attestation verdict is "${attestation.verdict}", expected "allow"`);
|
|
3274
|
+
if (params.requirePaidTier && attestation.tier === "free-local") throw new MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "Paid pro-shield or vault-enforced firewall attestation is required");
|
|
3275
|
+
if (expiresAtSec <= issuedAtSec || expiresAtSec - issuedAtSec > BigInt(MAX_PERSONAL_FIREWALL_ATTESTATION_TTL_SECONDS)) throw new MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", `Firewall attestation TTL exceeds ${MAX_PERSONAL_FIREWALL_ATTESTATION_TTL_SECONDS}s maximum`);
|
|
3276
|
+
if (params.nowSec + 30n < issuedAtSec || params.nowSec >= expiresAtSec) throw new MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "SignedFirewallAttestation is expired or not yet valid");
|
|
3277
|
+
if (params.expectedVaultId !== void 0 && attestation.vaultId !== params.expectedVaultId) throw new MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "Firewall attestation vaultId mismatch");
|
|
3278
|
+
if (params.expectedPolicyEpoch !== void 0 && policyEpoch !== params.expectedPolicyEpoch) throw new MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "Firewall attestation policyEpoch mismatch");
|
|
3279
|
+
if (params.expectedChainNamespace !== void 0 && attestation.chainNamespace !== params.expectedChainNamespace) throw new MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "Firewall attestation chainNamespace mismatch");
|
|
3280
|
+
if (params.expectedChainId !== void 0 && attestation.chainId !== params.expectedChainId) throw new MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "Firewall attestation chainId mismatch");
|
|
3281
|
+
if (params.expectedFromAddress !== void 0) {
|
|
3282
|
+
const expFrom = normalizeOcapAddressOrEth(params.expectedFromAddress, "expectedFromAddress", "PERSONAL_FIREWALL_ATTESTATION_INVALID");
|
|
3283
|
+
if (normalizedFrom !== expFrom) throw new MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "Firewall attestation fromAddress mismatch");
|
|
3284
|
+
}
|
|
3285
|
+
if (params.expectedToAddress !== void 0) {
|
|
3286
|
+
const expTo = normalizeOcapAddressOrEth(params.expectedToAddress, "expectedToAddress", "PERSONAL_FIREWALL_ATTESTATION_INVALID");
|
|
3287
|
+
if (normalizedTo !== expTo) throw new MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "Firewall attestation toAddress mismatch");
|
|
3288
|
+
}
|
|
3289
|
+
if (params.expectedSigningDigest32 !== void 0) {
|
|
3290
|
+
const expDigest32 = normalizeHexBytes(params.expectedSigningDigest32, 32);
|
|
3291
|
+
if (!constantTimeEqual(signingDigest32, expDigest32)) throw new MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "Firewall attestation signingDigest32 mismatch");
|
|
3292
|
+
}
|
|
3293
|
+
if (params.expectedClearSigningPreviewHash32 !== void 0) {
|
|
3294
|
+
const expPreview32 = normalizeHexBytes(params.expectedClearSigningPreviewHash32, 32);
|
|
3295
|
+
if (!constantTimeEqual(previewHash32, expPreview32)) throw new MpcProtocolError("PERSONAL_FIREWALL_ATTESTATION_INVALID", "Firewall attestation clearSigningPreviewHash32 mismatch");
|
|
3296
|
+
}
|
|
3297
|
+
return {
|
|
3298
|
+
simulatedBlockNumber,
|
|
3299
|
+
simulatedDeltaHash32: simDeltaHash32,
|
|
3300
|
+
issuedAtSec,
|
|
3301
|
+
expiresAtSec,
|
|
3302
|
+
tier: attestation.tier
|
|
3303
|
+
};
|
|
3304
|
+
}
|
|
3305
|
+
async function runPersonalClientPresignWithTransport(params) {
|
|
3306
|
+
const rng = params.rng ?? defaultRandomBytes;
|
|
3307
|
+
const sessionNonce32 = rng(32);
|
|
3308
|
+
const shamirSlot1Share32 = additiveToShamirSlot1Share(params.sActorBytes32);
|
|
3309
|
+
let pendingB1 = null;
|
|
3310
|
+
let senderB1 = null;
|
|
3311
|
+
let receiverA1 = null;
|
|
3312
|
+
let clientSession = null;
|
|
3313
|
+
try {
|
|
3314
|
+
const ctxB1A2 = derivePersonalBaseOtContext(params.cluster, sessionNonce32, 1, 2);
|
|
3315
|
+
const ctxB2A1 = derivePersonalBaseOtContext(params.cluster, sessionNonce32, 2, 1);
|
|
3316
|
+
const b1Step1 = baseOtSenderStep1({
|
|
3317
|
+
ctxBaseOt: ctxB1A2,
|
|
3318
|
+
senderSlotB: 1,
|
|
3319
|
+
receiverSlotA: 2,
|
|
3320
|
+
rng
|
|
3321
|
+
});
|
|
3322
|
+
pendingB1 = b1Step1.pending;
|
|
3323
|
+
const initReply = await params.transport.initPresign({
|
|
3324
|
+
sessionNonce32,
|
|
3325
|
+
baseOtB1A2Step1: b1Step1.message
|
|
3326
|
+
});
|
|
3327
|
+
senderB1 = baseOtSenderStep3({
|
|
3328
|
+
pending: pendingB1,
|
|
3329
|
+
step2Message: initReply.baseOtB1A2Step2
|
|
3330
|
+
});
|
|
3331
|
+
pendingB1 = null;
|
|
3332
|
+
const a1Step2 = baseOtReceiverStep2({
|
|
3333
|
+
ctxBaseOt: ctxB2A1,
|
|
3334
|
+
senderSlotB: 2,
|
|
3335
|
+
receiverSlotA: 1,
|
|
3336
|
+
step1Message: initReply.baseOtB2A1Step1,
|
|
3337
|
+
rng
|
|
3338
|
+
});
|
|
3339
|
+
receiverA1 = a1Step2.receiverState;
|
|
3340
|
+
const channels = {
|
|
3341
|
+
ownerSlot: 1,
|
|
3342
|
+
asExtendedSenderA: new Map([[2, receiverA1]]),
|
|
3343
|
+
asExtendedReceiverB: new Map([[2, senderB1]])
|
|
3344
|
+
};
|
|
3345
|
+
clientSession = new PresignPartySession({
|
|
3346
|
+
slot: 1,
|
|
3347
|
+
nodeSecretShareBytes32: shamirSlot1Share32,
|
|
3348
|
+
cluster: params.cluster,
|
|
3349
|
+
subset: [1, 2],
|
|
3350
|
+
sessionNonce32,
|
|
3351
|
+
baseOtChannels: channels,
|
|
3352
|
+
rng
|
|
3353
|
+
});
|
|
3354
|
+
zeroizeBytes(shamirSlot1Share32);
|
|
3355
|
+
const c1 = clientSession.round1CreateCommitment();
|
|
3356
|
+
const ack1 = await params.transport.stepPresign({
|
|
3357
|
+
presignSessionId: initReply.presignSessionId,
|
|
3358
|
+
step: "r1-commit",
|
|
3359
|
+
baseOtB2A1Step2: a1Step2.message,
|
|
3360
|
+
clientR1Commitment: c1
|
|
3361
|
+
});
|
|
3362
|
+
if (ack1.step !== "r1-commit-ack") throw new MpcProtocolError("PRESIG_STATE_VIOLATION", "Unexpected step 1 response");
|
|
3363
|
+
const rev1 = clientSession.round1ReceiveCommitmentsAndReveal([c1, ack1.hsmR1Commitment]);
|
|
3364
|
+
clientSession.round1VerifyAllReveals([rev1.reveal, ack1.hsmR1Reveal]);
|
|
3365
|
+
const ot1Client = clientSession.round2CreateOtStep1Messages();
|
|
3366
|
+
const ack2 = await params.transport.stepPresign({
|
|
3367
|
+
presignSessionId: initReply.presignSessionId,
|
|
3368
|
+
step: "r1-reveal-and-ot1",
|
|
3369
|
+
clientR1Reveal: rev1.reveal,
|
|
3370
|
+
clientOt1: ot1Client
|
|
3371
|
+
});
|
|
3372
|
+
if (ack2.step !== "ot1-and-ot2") throw new MpcProtocolError("PRESIG_STATE_VIOLATION", "Unexpected step 2 response");
|
|
3373
|
+
const ot2Client = clientSession.round2ProcessOtStep1AndCreateStep2(ack2.hsmOt1);
|
|
3374
|
+
const ot3Client = clientSession.round2ProcessOtStep2AndCreateStep3(ack2.hsmOt2);
|
|
3375
|
+
const ack3 = await params.transport.stepPresign({
|
|
3376
|
+
presignSessionId: initReply.presignSessionId,
|
|
3377
|
+
step: "ot2-and-ot3",
|
|
3378
|
+
clientOt2: ot2Client,
|
|
3379
|
+
clientOt3: ot3Client
|
|
3380
|
+
});
|
|
3381
|
+
if (ack3.step !== "ot3-and-mta") throw new MpcProtocolError("PRESIG_STATE_VIOLATION", "Unexpected step 3 response");
|
|
3382
|
+
const mtaClient = clientSession.round2VerifyKos15AndCreateMtaPayloads(ack3.hsmOt3);
|
|
3383
|
+
clientSession.round2VerifyMtaPayloads(ack3.hsmMta);
|
|
3384
|
+
const r3Client = clientSession.round3CreateBroadcast();
|
|
3385
|
+
const ack4 = await params.transport.stepPresign({
|
|
3386
|
+
presignSessionId: initReply.presignSessionId,
|
|
3387
|
+
step: "mta-and-r3",
|
|
3388
|
+
clientMta: mtaClient,
|
|
3389
|
+
clientR3: r3Client
|
|
3390
|
+
});
|
|
3391
|
+
if (ack4.step !== "r3-and-r4") throw new MpcProtocolError("PRESIG_STATE_VIOLATION", "Unexpected step 4 response");
|
|
3392
|
+
const r4Client = clientSession.round3VerifyAndCreateRound4Broadcast([r3Client, ack4.hsmR3]);
|
|
3393
|
+
const record = clientSession.round4VerifyAndFinalize([r4Client, ack4.hsmR4]);
|
|
3394
|
+
const ack5 = await params.transport.stepPresign({
|
|
3395
|
+
presignSessionId: initReply.presignSessionId,
|
|
3396
|
+
step: "r4-finalize",
|
|
3397
|
+
clientR4: r4Client
|
|
3398
|
+
});
|
|
3399
|
+
if (ack5.step !== "finalized" || ack5.presigIdHex !== record.publicVerification.presigIdHex) {
|
|
3400
|
+
zeroizeBytes(record.kShareBytes32, record.chiShareBytes32);
|
|
3401
|
+
throw new MpcProtocolError("PRESIG_STATE_VIOLATION", "Cosigner finalize presigId mismatch");
|
|
3402
|
+
}
|
|
3403
|
+
return record;
|
|
3404
|
+
} catch (err) {
|
|
3405
|
+
clientSession?.abort();
|
|
3406
|
+
throw err;
|
|
3407
|
+
} finally {
|
|
3408
|
+
zeroizeBytes(shamirSlot1Share32, pendingB1?.yScalarBytes32);
|
|
3409
|
+
if (senderB1) wipeBaseOtSenderState(senderB1);
|
|
3410
|
+
if (receiverA1) wipeBaseOtReceiverState(receiverA1);
|
|
3411
|
+
}
|
|
3412
|
+
}
|
|
3413
|
+
function parseHexOrDecimalBigInt(raw, label) {
|
|
3414
|
+
if (typeof raw === "bigint") return raw;
|
|
3415
|
+
if (typeof raw === "number") {
|
|
3416
|
+
if (!Number.isSafeInteger(raw) || raw < 0) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `Invalid ${label}`);
|
|
3417
|
+
return BigInt(raw);
|
|
3418
|
+
}
|
|
3419
|
+
if (typeof raw === "string") {
|
|
3420
|
+
if (/^0x[0-9a-fA-F]+$/.test(raw)) return BigInt(raw);
|
|
3421
|
+
if (/^(?:0|[1-9][0-9]*)$/.test(raw)) return BigInt(raw);
|
|
3422
|
+
}
|
|
3423
|
+
throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `Invalid ${label}: ${String(raw)}`);
|
|
3424
|
+
}
|
|
3425
|
+
function parseEip1193TxObject(raw) {
|
|
3426
|
+
if (raw instanceof Uint8Array || typeof raw === "string") return decodeAndVerifyPersonalEip1559Tx({ txOrRawBytes: raw }).txFields;
|
|
3427
|
+
if (!raw || typeof raw !== "object") throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Expected EIP-1559 transaction object");
|
|
3428
|
+
const obj = raw;
|
|
3429
|
+
if (obj.type !== void 0 && obj.type !== "0x2" && obj.type !== "0x02" && obj.type !== 2 && obj.type !== "eip1559") {
|
|
3430
|
+
if (obj.type === "0x4" || obj.type === "0x04" || obj.type === 4 || obj.authorizationList !== void 0) throw new MpcProtocolError("PERSONAL_EIP7702_FORBIDDEN", "EIP-7702 transactions are forbidden");
|
|
3431
|
+
throw new MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "Only EIP-1559 Type-2 transactions are supported");
|
|
3432
|
+
}
|
|
3433
|
+
if (obj.authorizationList !== void 0) throw new MpcProtocolError("PERSONAL_EIP7702_FORBIDDEN", "EIP-7702 authorizationList is forbidden");
|
|
3434
|
+
if (typeof obj.to !== "string" || obj.to.trim() === "" || obj.to === "0x") throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Contract creation transactions are forbidden");
|
|
3435
|
+
return {
|
|
3436
|
+
chainId: parseHexOrDecimalBigInt(obj.chainId, "chainId"),
|
|
3437
|
+
nonce: parseHexOrDecimalBigInt(obj.nonce ?? 0, "nonce"),
|
|
3438
|
+
maxPriorityFeePerGasWei: parseHexOrDecimalBigInt(obj.maxPriorityFeePerGasWei ?? obj.maxPriorityFeePerGas, "maxPriorityFeePerGas"),
|
|
3439
|
+
maxFeePerGasWei: parseHexOrDecimalBigInt(obj.maxFeePerGasWei ?? obj.maxFeePerGas, "maxFeePerGas"),
|
|
3440
|
+
gasLimit: parseHexOrDecimalBigInt(obj.gasLimit ?? obj.gas, "gasLimit"),
|
|
3441
|
+
to: obj.to,
|
|
3442
|
+
valueWei: parseHexOrDecimalBigInt(obj.valueWei ?? obj.value ?? 0n, "value"),
|
|
3443
|
+
data: typeof obj.data === "string" || obj.data instanceof Uint8Array ? obj.data : "0x",
|
|
3444
|
+
accessList: Array.isArray(obj.accessList) ? obj.accessList : void 0
|
|
3445
|
+
};
|
|
3446
|
+
}
|
|
3447
|
+
/**
|
|
3448
|
+
* Creates an ergonomic `EIP-1193` & `viem`-compatible MPC EOA signer (`Slot 1` Client).
|
|
3449
|
+
* - Runs clear-signing & optional simulation post-condition verification locally BEFORE presign/sign.
|
|
3450
|
+
* - Executes 2-party `KOS15` + `GadgetMtA` presignature + Groth-Shoup online signing against `transport`.
|
|
3451
|
+
* - `s_1` (`MpcOnlineSignShare` for Slot 1) and `s_actor` NEVER leave the client!
|
|
3452
|
+
*/
|
|
3453
|
+
function createPersonalMpcEoaSigner(params) {
|
|
3454
|
+
const pRootComp33 = encodePointCompressed(decodePointCompressed(normalizeHexBytes(params.rootPublicKeyComp33, 33), false));
|
|
3455
|
+
const derivedChild = derivePersonalVaultChildKey({
|
|
3456
|
+
vaultId: params.vaultId,
|
|
3457
|
+
rootPublicKeyComp33: pRootComp33,
|
|
3458
|
+
derivation: params.childDerivation
|
|
3459
|
+
});
|
|
3460
|
+
let cachedCluster = params.xActorComp33 !== void 0 ? buildPersonalVaultClusterInfo({
|
|
3461
|
+
vaultId: params.vaultId,
|
|
3462
|
+
slotId: params.slotId,
|
|
3463
|
+
policyEpoch: params.policyEpoch,
|
|
3464
|
+
rootPublicKeyComp33: pRootComp33,
|
|
3465
|
+
xActorComp33: params.xActorComp33
|
|
3466
|
+
}) : null;
|
|
3467
|
+
const signTransaction = async (tx, options) => {
|
|
3468
|
+
const hasQuorum = options?.policyProof?.tier === "L2" || options?.policyProof?.tier === "L3";
|
|
3469
|
+
const verifiedTx = decodeAndVerifyPersonalEip1559Tx({
|
|
3470
|
+
txOrRawBytes: tx,
|
|
3471
|
+
policy: params.policy,
|
|
3472
|
+
hasL2OrL3QuorumProof: hasQuorum
|
|
3473
|
+
});
|
|
3474
|
+
if (options?.postConditions) {
|
|
3475
|
+
if (!options.simulatedDelta) throw new MpcProtocolError("PERSONAL_POST_CONDITION_VIOLATED", "simulatedDelta is required when postConditions are specified");
|
|
3476
|
+
verifyPersonalSimulationBalanceDelta({
|
|
3477
|
+
postConditions: options.postConditions,
|
|
3478
|
+
simulatedDelta: options.simulatedDelta
|
|
3479
|
+
});
|
|
3480
|
+
}
|
|
3481
|
+
const preview = buildPersonalClearSigningPreview({
|
|
3482
|
+
fromAddress: derivedChild.ethAddress,
|
|
3483
|
+
verifiedTx
|
|
3484
|
+
});
|
|
3485
|
+
const previewHash32 = computePersonalClearSigningPreviewHash32(preview);
|
|
3486
|
+
const callerSActor = await params.getActorShareBytes32();
|
|
3487
|
+
const sActorCopy32 = new Uint8Array(callerSActor);
|
|
3488
|
+
const localPool = new VolatilePresignaturePool();
|
|
3489
|
+
let presigPub = null;
|
|
3490
|
+
try {
|
|
3491
|
+
const xActorComp33 = encodePointCompressed(mulBaseG(bytes32ToScalarNonZero(sActorCopy32)));
|
|
3492
|
+
if (!cachedCluster) cachedCluster = buildPersonalVaultClusterInfo({
|
|
3493
|
+
vaultId: params.vaultId,
|
|
3494
|
+
slotId: params.slotId,
|
|
3495
|
+
policyEpoch: params.policyEpoch,
|
|
3496
|
+
rootPublicKeyComp33: pRootComp33,
|
|
3497
|
+
xActorComp33
|
|
3498
|
+
});
|
|
3499
|
+
const clientPresigRecord = await runPersonalClientPresignWithTransport({
|
|
3500
|
+
cluster: cachedCluster,
|
|
3501
|
+
sActorBytes32: sActorCopy32,
|
|
3502
|
+
transport: params.transport,
|
|
3503
|
+
rng: params.rng
|
|
3504
|
+
});
|
|
3505
|
+
presigPub = clientPresigRecord.publicVerification;
|
|
3506
|
+
localPool.store(clientPresigRecord);
|
|
3507
|
+
const onlineReq = {
|
|
3508
|
+
rootId: params.vaultId,
|
|
3509
|
+
presigId: presigPub.presigId32,
|
|
3510
|
+
subset: [1, 2],
|
|
3511
|
+
msgDigest32: verifiedTx.signingDigest32,
|
|
3512
|
+
childDerivation: derivedChild.derivationSpec
|
|
3513
|
+
};
|
|
3514
|
+
const localShareRes = createOnlineSignShare({
|
|
3515
|
+
pool: localPool,
|
|
3516
|
+
request: onlineReq
|
|
3517
|
+
});
|
|
3518
|
+
const cosignerRes = await params.transport.signOnline({
|
|
3519
|
+
vaultId: params.vaultId,
|
|
3520
|
+
slotId: params.slotId,
|
|
3521
|
+
presigIdHex: presigPub.presigIdHex,
|
|
3522
|
+
payloadKind: "eip1559",
|
|
3523
|
+
unsignedTx: verifiedTx.txFields,
|
|
3524
|
+
unsignedPayloadBytes: verifiedTx.unsignedPayloadBytes,
|
|
3525
|
+
signingDigest32: verifiedTx.signingDigest32,
|
|
3526
|
+
clearSigningPreview: preview,
|
|
3527
|
+
clearSigningPreviewHash32: previewHash32,
|
|
3528
|
+
childDerivation: derivedChild.derivationSpec,
|
|
3529
|
+
policyProof: options?.policyProof,
|
|
3530
|
+
entitlementTicket: options?.entitlementTicket,
|
|
3531
|
+
firewallAttestation: options?.firewallAttestation,
|
|
3532
|
+
attestedProxyImplementationAddress: options?.attestedProxyImplementationAddress,
|
|
3533
|
+
simulatedDelta: options?.simulatedDelta,
|
|
3534
|
+
postConditions: options?.postConditions
|
|
3535
|
+
});
|
|
3536
|
+
if (!cosignerRes?.share || cosignerRes.share.slot !== 2) throw new MpcProtocolError("SIGN_SHARE_VERIFICATION_FAILED", "Expected cosigner partial signature from slot 2", 2);
|
|
3537
|
+
const aggregated = aggregateOnlineSignature({
|
|
3538
|
+
shares: [localShareRes.share, cosignerRes.share],
|
|
3539
|
+
publicVerification: presigPub,
|
|
3540
|
+
request: onlineReq
|
|
3541
|
+
});
|
|
3542
|
+
const signedTx = encodeSignedEip1559Tx({
|
|
3543
|
+
tx: verifiedTx.txFields,
|
|
3544
|
+
yParity: aggregated.yParity,
|
|
3545
|
+
r: aggregated.r,
|
|
3546
|
+
s: aggregated.s
|
|
3547
|
+
});
|
|
3548
|
+
return {
|
|
3549
|
+
rawSignedTxBytes: signedTx.rawSignedTxBytes,
|
|
3550
|
+
rawSignedTxHex: signedTx.rawSignedTxHex,
|
|
3551
|
+
txHashHex: signedTx.txHashHex,
|
|
3552
|
+
signingDigest32: signedTx.signingDigest32,
|
|
3553
|
+
signerAddress: aggregated.signerAddress,
|
|
3554
|
+
signature: aggregated,
|
|
3555
|
+
clearSigningPreview: preview,
|
|
3556
|
+
clearSigningPreviewHash32: previewHash32
|
|
3557
|
+
};
|
|
3558
|
+
} finally {
|
|
3559
|
+
zeroizeBytes(sActorCopy32);
|
|
3560
|
+
localPool.wipeAll();
|
|
3561
|
+
}
|
|
3562
|
+
};
|
|
3563
|
+
const request = async (args) => {
|
|
3564
|
+
const method = args?.method;
|
|
3565
|
+
if (method === "eth_accounts" || method === "eth_requestAccounts") return [derivedChild.ethAddress];
|
|
3566
|
+
if (method === "eth_signTransaction") return (await signTransaction(parseEip1193TxObject(args.params?.[0]))).rawSignedTxHex;
|
|
3567
|
+
if (method === "eth_sendTransaction") {
|
|
3568
|
+
if (!params.transport.broadcastRawTransaction) throw new MpcProtocolError("INVALID_PARAMETER", "PersonalCosignerTransport.broadcastRawTransaction is not configured for eth_sendTransaction");
|
|
3569
|
+
const signed = await signTransaction(parseEip1193TxObject(args.params?.[0]));
|
|
3570
|
+
return params.transport.broadcastRawTransaction(signed.rawSignedTxHex);
|
|
3571
|
+
}
|
|
3572
|
+
if (method === "eth_sign" || method === "personal_sign" || method === "eth_signTypedData" || method === "eth_signTypedData_v3" || method === "eth_signTypedData_v4") throw new MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", `RPC method "${method}" is forbidden: MPC-secured EOA enforces EIP-1559 Clear-Signing`);
|
|
3573
|
+
throw new MpcProtocolError("INVALID_PARAMETER", `Unsupported EIP-1193 method: ${String(method)}`);
|
|
3574
|
+
};
|
|
3575
|
+
const placeholderCluster = cachedCluster ?? {
|
|
3576
|
+
rootId: params.vaultId,
|
|
3577
|
+
keyEpoch: params.policyEpoch,
|
|
3578
|
+
t: 2,
|
|
3579
|
+
nParties: 2,
|
|
3580
|
+
hDkg32: new Uint8Array(32),
|
|
3581
|
+
rootPublicKeyComp33: pRootComp33,
|
|
3582
|
+
publicSharesComp33BySlot: /* @__PURE__ */ new Map()
|
|
3583
|
+
};
|
|
3584
|
+
return {
|
|
3585
|
+
address: derivedChild.ethAddress,
|
|
3586
|
+
publicKeyComp33: derivedChild.childPublicKeyComp33,
|
|
3587
|
+
publicKeyHex: `0x${bytesToHex(derivedChild.childPublicKeyComp33)}`,
|
|
3588
|
+
childDerivation: derivedChild.derivationSpec,
|
|
3589
|
+
get cluster() {
|
|
3590
|
+
return cachedCluster ?? placeholderCluster;
|
|
3591
|
+
},
|
|
3592
|
+
signTransaction,
|
|
3593
|
+
request,
|
|
3594
|
+
toViemLocalAccount() {
|
|
3595
|
+
return {
|
|
3596
|
+
address: derivedChild.ethAddress,
|
|
3597
|
+
publicKey: `0x${bytesToHex(derivedChild.childPublicKeyComp33)}`,
|
|
3598
|
+
source: "mpc-personal-vault",
|
|
3599
|
+
type: "local",
|
|
3600
|
+
async signTransaction(tx, options) {
|
|
3601
|
+
return (await signTransaction(tx, options)).rawSignedTxHex;
|
|
3602
|
+
},
|
|
3603
|
+
async signMessage() {
|
|
3604
|
+
throw new MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "Blind personal_sign is forbidden");
|
|
3605
|
+
},
|
|
3606
|
+
async signTypedData() {
|
|
3607
|
+
throw new MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "Opaque signTypedData is forbidden");
|
|
3608
|
+
}
|
|
3609
|
+
};
|
|
3610
|
+
}
|
|
3611
|
+
};
|
|
3612
|
+
}
|
|
3613
|
+
|
|
3614
|
+
//#endregion
|
|
3615
|
+
export { ACTOR_KIND_AND_ALG_BYTE, ENTITLEMENT_TIER_CODE, ERC20_APPROVE_SELECTOR_HEX, HARD_BANNED_PERSONAL_EVM_SELECTORS, HSM_SEALED_BLOB_CIPHERTEXT_BYTES, HSM_SEALED_BLOB_CIPHERTEXT_OFFSET, HSM_SEALED_BLOB_HEADER_BYTES, HSM_SEALED_BLOB_HEADER_MAC_OFFSET, HSM_SEALED_BLOB_HEADER_WITH_MAC_BYTES, HSM_SEALED_BLOB_IV_OFFSET, HSM_SEALED_BLOB_MAX_POLICY_UTF8_BYTES, HSM_SEALED_BLOB_TAG_OFFSET, HSM_SEALED_BLOB_VERSION, MAX_ANNOUNCE_VALIDITY_WINDOW_SEC, MIN_ANNOUNCE_VALIDITY_WINDOW_SEC, PERSONAL_MAX_VELOCITY_UINT128, PersonalCosignerResponderSession, UNLIMITED_APPROVE_THRESHOLD, actorKindAndAlgToByte, additiveToShamirSlot1Share, additiveToShamirSlot2Share, aes256GcmDecryptDetached, aes256GcmEncryptDetached, applyHsmSlotResplitDelta, assertNoEip7702Bytes, assertPersonalSlotNotExpired, base64UrlDecodeBytes, base64UrlEncodeBytes, bootstrapPersonalVaultClient, buildPersonalAnnounceChallengeDigest32, buildPersonalClearSigningPreview, buildPersonalEntitlementApplyChallengeDigest32, buildPersonalPairResplitChallengeDigest32, buildPersonalPresignInitChallengeDigest32, buildPersonalResealKidChallengeDigest32, buildPersonalRevokeSlotChallengeDigest32, buildPersonalSealEnrollChallengeDigest32, buildPersonalSessionLockChallengeDigest32, buildPersonalSessionOpenChallengeDigest32, buildPersonalSignChallengeDigest32, buildPersonalVaultClusterInfo, buildPersonalVetoChallengeDigest32, byteToActorKindAndAlg, bytesToHex, canonicalizePersonalBlobAadBytes, canonicalizePersonalVaultPolicy, completeActorSlotPairingOnTarget, computeHsmSealedBlobHeaderMac32, computeNonDegenerateActorResplitShare, computePersonalActorChallengeDigest32, computePersonalClearSigningPreviewHash32, computePersonalPolicyHash32, computeSimulatedDeltaCommitment32, computeVaultEntitlementTicketDigest32, createActorSlotPairingBootstrap, createPersonalMpcEoaSigner, createPersonalSealEnrollActorPok, decodeAndVerifyPersonalEip1559Tx, decodeErc20ApproveCalldata, decodeHsmSealedBlobHeader319, decodeHsmSealedBlobInnerPlaintext3717, deriveBlindOcapVelocityTag32, deriveBlindSlotTag32, deriveBlindVaultTag32, deriveBlindVelocityTag32, deriveHsmPersonalSealKey32, derivePersonalVaultChildKey, derivePersonalWakePasswordKeys, encodeErc20ApproveCalldata, encodeHsmSealedBlobHeader319, encodeHsmSealedBlobInnerPlaintext3717, hexToBytes, initiateActorSlotResplit, isAgentActorKind, normalizeActorPublicKeyToPadded65, normalizeCanonicalOcapTokenKey, normalizeMaxTokenOutflowsCaps, normalizeOcapAddressOrEth, openHsmInboundTransportBox, parseHsmSealedBlobHeader, recoverPersonalVaultRootOffline, resolveRequiredPolicyTier, runPersonalClientPresignWithTransport, sealDeviceShareEnvelope, sealHsmInboundTransportBox, signAnnounceTicket, signGuardianQuorumApproval, signPersonalActorChallenge, signPersonalFirewallAttestation, signPersonalVaultRecoverySweepOffline, signRoleQuorumApproval, signVaultEntitlementTicket, unsealDeviceShareEnvelope, unwrapSealedBlobFromCloudSync, validateActorPublicKeyPadded65, verifyActorSlotPairingBootstrap, verifyGuardianQuorumProof, verifyPersonalActorSignature, verifyPersonalAdditiveSplitMatchesRoot, verifyPersonalColdRecoveryKitManifest, verifyPersonalFirewallAttestation, verifyPersonalPolicyProofBundle, verifyPersonalSealEnrollActorPok, verifyPersonalSimulationBalanceDelta, verifyRoleQuorumProof, verifySignedAnnounceTicket, verifyVaultEntitlementTicket, wrapSealedBlobForCloudSync, zeroizeBytes };
|