@ocap/mpc-hsm 1.33.6 → 1.33.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/esm/bip39-english-wordlist.d.mts +11 -0
  2. package/esm/bip39-english-wordlist.mjs +31 -0
  3. package/esm/constants.d.mts +66 -2
  4. package/esm/constants.mjs +65 -1
  5. package/esm/dkg.mjs +2 -2
  6. package/esm/index.d.mts +11 -3
  7. package/esm/index.mjs +11 -3
  8. package/esm/ocap-clear-signing.d.mts +125 -0
  9. package/esm/ocap-clear-signing.mjs +1170 -0
  10. package/esm/offline-ceremony.d.mts +127 -0
  11. package/esm/offline-ceremony.mjs +481 -0
  12. package/esm/ot.d.mts +7 -1
  13. package/esm/ot.mjs +149 -16
  14. package/esm/personal-vault.d.mts +1292 -0
  15. package/esm/personal-vault.mjs +3615 -0
  16. package/esm/personal.d.mts +10 -0
  17. package/esm/personal.mjs +11 -0
  18. package/esm/presign.mjs +1 -1
  19. package/esm/rlp-eip1559.d.mts +75 -0
  20. package/esm/rlp-eip1559.mjs +293 -0
  21. package/esm/secp256k1-scalar.d.mts +1 -1
  22. package/esm/secp256k1-scalar.mjs +14 -5
  23. package/esm/steel-mnemonic.d.mts +55 -0
  24. package/esm/steel-mnemonic.mjs +247 -0
  25. package/esm/ves-backup.d.mts +296 -0
  26. package/esm/ves-backup.mjs +1025 -0
  27. package/esm/x402-agent-guard.d.mts +111 -0
  28. package/esm/x402-agent-guard.mjs +780 -0
  29. package/lib/bip39-english-wordlist.cjs +33 -0
  30. package/lib/bip39-english-wordlist.d.cts +11 -0
  31. package/lib/constants.cjs +128 -0
  32. package/lib/constants.d.cts +66 -2
  33. package/lib/dkg.cjs +2 -2
  34. package/lib/index.cjs +249 -0
  35. package/lib/index.d.cts +11 -3
  36. package/lib/ocap-clear-signing.cjs +1176 -0
  37. package/lib/ocap-clear-signing.d.cts +125 -0
  38. package/lib/offline-ceremony.cjs +487 -0
  39. package/lib/offline-ceremony.d.cts +127 -0
  40. package/lib/ot.cjs +150 -15
  41. package/lib/ot.d.cts +7 -1
  42. package/lib/personal-vault.cjs +3725 -0
  43. package/lib/personal-vault.d.cts +1292 -0
  44. package/lib/personal.cjs +338 -0
  45. package/lib/personal.d.cts +10 -0
  46. package/lib/presign.cjs +1 -1
  47. package/lib/rlp-eip1559.cjs +303 -0
  48. package/lib/rlp-eip1559.d.cts +75 -0
  49. package/lib/secp256k1-scalar.cjs +14 -5
  50. package/lib/steel-mnemonic.cjs +253 -0
  51. package/lib/steel-mnemonic.d.cts +55 -0
  52. package/lib/ves-backup.cjs +1053 -0
  53. package/lib/ves-backup.d.cts +296 -0
  54. package/lib/x402-agent-guard.cjs +788 -0
  55. package/lib/x402-agent-guard.d.cts +111 -0
  56. package/package.json +6 -1
@@ -0,0 +1,1170 @@
1
+ import { MAX_PERSONAL_JWT_TTL_SECONDS, MAX_PERSONAL_JWT_UNSIGNED_BYTES, MAX_PERSONAL_OCAP_CBOR_DEPTH, MAX_PERSONAL_OCAP_DELEGATE_TTL_SECONDS, MAX_PERSONAL_OCAP_TX_BYTES, MpcProtocolError } from "./constants.mjs";
2
+ import { bytesToBigIntBE, bytesToHex, constantTimeEqual, decodePointCompressed, normalizeHexBytes } from "./secp256k1-scalar.mjs";
3
+ import { pointToEthAddress } from "./tweak.mjs";
4
+ import { base64UrlDecodeBytes, canonicalizePersonalVaultPolicy, computePersonalClearSigningPreviewHash32, normalizeActorPublicKeyToPadded65, normalizeCanonicalOcapTokenKey, normalizeOcapAddressOrEth } from "./personal-vault.mjs";
5
+ import { keccak_256, sha3_256 } from "@noble/hashes/sha3.js";
6
+
7
+ //#region src/ocap-clear-signing.ts
8
+ /**
9
+ * Pure Isomorphic Closed-Schema OCAP Canonical CBOR Transaction & ArcBlock JWT v1.1.0
10
+ * Clear-Signing Verifiers (`@ocap/mpc-hsm/personal`, #2333).
11
+ *
12
+ * Security invariants:
13
+ * 1. Pure WebCrypto + Uint8Array isomorphic runtime — 100% safe in Browser, Hermes/RN, and Node.
14
+ * 2. Strict RFC 8949 self-described canonical CBOR (`0xd9d9f7`) decoding with bounded depth (`<= 64`),
15
+ * bounded byte length (`<= 16_384B`), minimal integer/length encoding, sorted unique map keys,
16
+ * and zero trailing bytes.
17
+ * 3. Closed per-`typeUrl` OCAP `itx` schema dispatch (`fg:t:transfer`, `fg:t:transfer_v2`,
18
+ * `fg:t:exchange_v2`, `fg:t:declare`, `fg:t:revoke_delegate`, `fg:t:delegate`, `fg:t:account_migrate`):
19
+ * - `tx[17]` (`service_fee`) and `TokenInput[2]` (`value`) are parsed as canonical ASCII decimal strings.
20
+ * - `BigUint` fields (`TransferTx.value`, `TransferV2Tx.value`, `ExchangeInfoV2.value`) are parsed as CBOR Tag 2.
21
+ * - On-chain `fg:t:delegate` and off-chain `DelegationToken` JWTs are HARD-BANNED in `L0`/`L1` and require
22
+ * `allowDelegationTokenByQuorum === true` + `L2`/`L3` quorum + zero wildcards + `ops ⊆ allowedOcapTxTypes`.
23
+ * - `fg:t:account_migrate` requires `L3` guardian quorum.
24
+ * 4. Raw 32-byte blind digests are unconditionally rejected (`PERSONAL_BLIND_DIGEST_FORBIDDEN`).
25
+ */
26
+ const MAX_UINT64 = (1n << 64n) - 1n;
27
+ const MAX_UINT128 = (1n << 128n) - 1n;
28
+ const MAX_UINT256 = (1n << 256n) - 1n;
29
+ const SELF_DESCRIBE_CBOR_TAG = 55799;
30
+ const BIGINT_UNSIGNED_CBOR_TAG = 2;
31
+ const BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
32
+ const FORBIDDEN_JSON_KEYS = new Set([
33
+ "__proto__",
34
+ "constructor",
35
+ "prototype"
36
+ ]);
37
+ const STRICT_DECIMAL_UINT_RE = /^(?:0|[1-9][0-9]*)$/;
38
+ const OCAP_TX_TYPE_URL_RE = /^fg:t:[a-z0-9_]{1,64}$/;
39
+ const strictUtf8Decoder = new TextDecoder("utf-8", { fatal: true });
40
+ const utf8Encoder = new TextEncoder();
41
+ function base58EncodeBtc(bytes) {
42
+ if (bytes.length === 0) return "z";
43
+ let zeroes = 0;
44
+ while (zeroes < bytes.length && bytes[zeroes] === 0) zeroes++;
45
+ const num = bytesToBigIntBE(bytes);
46
+ let encoded = "";
47
+ let rem = num;
48
+ while (rem > 0n) {
49
+ const mod = Number(rem % 58n);
50
+ rem /= 58n;
51
+ encoded = BASE58_ALPHABET[mod] + encoded;
52
+ }
53
+ return `z${"1".repeat(zeroes)}${encoded}`;
54
+ }
55
+ /**
56
+ * Derives the canonical OCAP `SECP256K1` (`ROLE_ACCOUNT = 0`, `KeyType.SECP256K1 = 1`, `HashType.SHA3 = 1`, `BASE58`)
57
+ * bare address (`z...`) and uncompressed 65-byte (`0x04 || X || Y`) + Ethereum 64-byte (`X || Y`) public keys
58
+ * from a compressed 33-byte secp256k1 child public key.
59
+ */
60
+ function deriveOcapIdentitiesFromChildPoint(childPublicKeyComp33) {
61
+ const pt = decodePointCompressed(normalizeHexBytes(childPublicKeyComp33, 33), false);
62
+ const uncompressed65 = pt.toBytes(false);
63
+ const uncompressed64 = uncompressed65.subarray(1);
64
+ const { checksumAddress: ethChecksumAddress } = pointToEthAddress(pt);
65
+ const pkHash32 = sha3_256(uncompressed65);
66
+ const payload22 = new Uint8Array(22);
67
+ payload22[0] = 0;
68
+ payload22[1] = 33;
69
+ payload22.set(pkHash32.subarray(0, 20), 2);
70
+ const checksum32 = sha3_256(payload22);
71
+ const didBytes26 = new Uint8Array(26);
72
+ didBytes26.set(payload22, 0);
73
+ didBytes26.set(checksum32.subarray(0, 4), 22);
74
+ const ocapSecp256k1Address = base58EncodeBtc(didBytes26);
75
+ return {
76
+ ethChecksumAddress,
77
+ ethUncompressedPk64: new Uint8Array(uncompressed64),
78
+ ethUncompressedPkHex: `0x${bytesToHex(uncompressed64)}`,
79
+ ocapSecp256k1Address,
80
+ ocapSecp256k1Did: `did:abt:${ocapSecp256k1Address}`,
81
+ secp256k1UncompressedPk65: uncompressed65,
82
+ secp256k1UncompressedPkHex: `0x${bytesToHex(uncompressed65)}`
83
+ };
84
+ }
85
+ var CborTagValue = class {
86
+ constructor(tag, value) {
87
+ this.tag = tag;
88
+ this.value = value;
89
+ }
90
+ };
91
+ function readCanonicalCborUintArg(cursor, ai) {
92
+ if (ai < 24) return BigInt(ai);
93
+ if (ai === 24) {
94
+ if (cursor.offset + 1 > cursor.bytes.length) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Truncated 1-byte CBOR integer argument");
95
+ const v = cursor.bytes[cursor.offset++];
96
+ if (v < 24) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Non-canonical 1-byte CBOR integer encoding");
97
+ return BigInt(v);
98
+ }
99
+ if (ai === 25) {
100
+ if (cursor.offset + 2 > cursor.bytes.length) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Truncated 2-byte CBOR integer argument");
101
+ const v = (cursor.bytes[cursor.offset] << 8 | cursor.bytes[cursor.offset + 1]) >>> 0;
102
+ cursor.offset += 2;
103
+ if (v <= 255) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Non-canonical 2-byte CBOR integer encoding");
104
+ return BigInt(v);
105
+ }
106
+ if (ai === 26) {
107
+ if (cursor.offset + 4 > cursor.bytes.length) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Truncated 4-byte CBOR integer argument");
108
+ const v = (cursor.bytes[cursor.offset] << 24 | cursor.bytes[cursor.offset + 1] << 16 | cursor.bytes[cursor.offset + 2] << 8 | cursor.bytes[cursor.offset + 3]) >>> 0;
109
+ cursor.offset += 4;
110
+ if (v <= 65535) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Non-canonical 4-byte CBOR integer encoding");
111
+ return BigInt(v);
112
+ }
113
+ if (ai === 27) {
114
+ if (cursor.offset + 8 > cursor.bytes.length) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Truncated 8-byte CBOR integer argument");
115
+ let v = 0n;
116
+ for (let i = 0; i < 8; i++) v = v << 8n | BigInt(cursor.bytes[cursor.offset + i]);
117
+ cursor.offset += 8;
118
+ if (v <= 4294967295n) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Non-canonical 8-byte CBOR integer encoding");
119
+ return v;
120
+ }
121
+ throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Indefinite-length or reserved CBOR encoding is forbidden");
122
+ }
123
+ function compareEncodedKeyBytes(a, b) {
124
+ if (a.length !== b.length) return a.length - b.length;
125
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return a[i] - b[i];
126
+ return 0;
127
+ }
128
+ function decodeCanonicalCborItem(cursor, depth) {
129
+ if (depth > MAX_PERSONAL_OCAP_CBOR_DEPTH) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `CBOR nesting depth exceeds ${MAX_PERSONAL_OCAP_CBOR_DEPTH}`);
130
+ if (cursor.offset >= cursor.bytes.length) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Unexpected end of CBOR payload");
131
+ const initial = cursor.bytes[cursor.offset++];
132
+ const major = initial >>> 5;
133
+ const ai = initial & 31;
134
+ if (major === 0) {
135
+ const val = readCanonicalCborUintArg(cursor, ai);
136
+ return val <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(val) : val;
137
+ }
138
+ if (major === 1) {
139
+ const val = -1n - readCanonicalCborUintArg(cursor, ai);
140
+ return val >= BigInt(Number.MIN_SAFE_INTEGER) ? Number(val) : val;
141
+ }
142
+ if (major === 2) {
143
+ const lenBig = readCanonicalCborUintArg(cursor, ai);
144
+ if (lenBig > BigInt(MAX_PERSONAL_OCAP_TX_BYTES)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "CBOR byte string length exceeds limit");
145
+ const len = Number(lenBig);
146
+ if (cursor.offset + len > cursor.bytes.length) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Truncated CBOR byte string");
147
+ const slice = cursor.bytes.slice(cursor.offset, cursor.offset + len);
148
+ cursor.offset += len;
149
+ return slice;
150
+ }
151
+ if (major === 3) {
152
+ const lenBig = readCanonicalCborUintArg(cursor, ai);
153
+ if (lenBig > BigInt(MAX_PERSONAL_OCAP_TX_BYTES)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "CBOR text string length exceeds limit");
154
+ const len = Number(lenBig);
155
+ if (cursor.offset + len > cursor.bytes.length) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Truncated CBOR text string");
156
+ const slice = cursor.bytes.subarray(cursor.offset, cursor.offset + len);
157
+ cursor.offset += len;
158
+ try {
159
+ return strictUtf8Decoder.decode(slice);
160
+ } catch {
161
+ throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Invalid UTF-8 in CBOR text string");
162
+ }
163
+ }
164
+ if (major === 4) {
165
+ const lenBig = readCanonicalCborUintArg(cursor, ai);
166
+ if (lenBig > 256n) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "CBOR array length exceeds 256");
167
+ const len = Number(lenBig);
168
+ const arr = new Array(len);
169
+ for (let i = 0; i < len; i++) arr[i] = decodeCanonicalCborItem(cursor, depth + 1);
170
+ return arr;
171
+ }
172
+ if (major === 5) {
173
+ const lenBig = readCanonicalCborUintArg(cursor, ai);
174
+ if (lenBig > 256n) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "CBOR map length exceeds 256");
175
+ const len = Number(lenBig);
176
+ const map = /* @__PURE__ */ new Map();
177
+ let prevKeyBytes = null;
178
+ for (let i = 0; i < len; i++) {
179
+ const keyStart = cursor.offset;
180
+ const key = decodeCanonicalCborItem(cursor, depth + 1);
181
+ const keyBytes = cursor.bytes.subarray(keyStart, cursor.offset);
182
+ if (typeof key === "string" && FORBIDDEN_JSON_KEYS.has(key)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Forbidden prototype-polluting key in CBOR map");
183
+ if (prevKeyBytes !== null && compareEncodedKeyBytes(prevKeyBytes, keyBytes) >= 0) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Non-canonical or duplicate CBOR map key ordering");
184
+ prevKeyBytes = keyBytes;
185
+ const val = decodeCanonicalCborItem(cursor, depth + 1);
186
+ map.set(key, val);
187
+ }
188
+ return map;
189
+ }
190
+ if (major === 6) {
191
+ const tagNumBig = readCanonicalCborUintArg(cursor, ai);
192
+ if (tagNumBig > BigInt(Number.MAX_SAFE_INTEGER)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Unsupported CBOR tag number");
193
+ const inner = decodeCanonicalCborItem(cursor, depth + 1);
194
+ return new CborTagValue(Number(tagNumBig), inner);
195
+ }
196
+ if (major === 7) {
197
+ if (ai === 20) return false;
198
+ if (ai === 21) return true;
199
+ if (ai === 22) return null;
200
+ throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `Unsupported CBOR simple/float value (ai=${ai})`);
201
+ }
202
+ throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Malformed CBOR major type");
203
+ }
204
+ function parseCborBigUintField(raw, label) {
205
+ if (raw === void 0) return 0n;
206
+ if (!(raw instanceof CborTagValue) || raw.tag !== BIGINT_UNSIGNED_CBOR_TAG || !(raw.value instanceof Uint8Array)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `${label} must be a canonical CBOR Tag(2) BigUint`);
207
+ if (raw.value.length === 0 || raw.value.length > 32 || raw.value[0] === 0) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `Non-canonical CBOR Tag(2) BigUint bytes in ${label}`);
208
+ return bytesToBigIntBE(raw.value);
209
+ }
210
+ function parseCborDecimalStringUint(raw, label) {
211
+ if (raw === void 0) return 0n;
212
+ if (typeof raw !== "string" || raw.length === 0 || !STRICT_DECIMAL_UINT_RE.test(raw)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `${label} must be a non-empty canonical decimal uint string`);
213
+ const n = BigInt(raw);
214
+ if (n < 0n || n > MAX_UINT256) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `${label} exceeds uint256`);
215
+ return n;
216
+ }
217
+ function parseCborPositiveUintField(raw, maxVal, label) {
218
+ let n;
219
+ if (typeof raw === "number" && Number.isSafeInteger(raw) && raw > 0) n = BigInt(raw);
220
+ else if (typeof raw === "bigint" && raw > 0n) n = raw;
221
+ else throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `${label} must be a positive canonical integer (proto3 omits 0)`);
222
+ if (n > maxVal) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `${label} exceeds maximum integer bound`);
223
+ return n;
224
+ }
225
+ function assertClosedCborIntKeys(map, allowedKeys, label) {
226
+ for (const key of map.keys()) if (typeof key !== "number" || !allowedKeys.has(key)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `Unknown or forbidden CBOR field ${String(key)} in ${label}`);
227
+ }
228
+ function parseNonEmptyStringArray(raw, maxLen, label) {
229
+ if (raw === void 0) return [];
230
+ if (!Array.isArray(raw) || raw.length === 0 || raw.length > maxLen) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `${label} must be a non-empty array of 1..${maxLen} items (proto3 omits empty repeated fields)`);
231
+ const out = [];
232
+ for (let i = 0; i < raw.length; i++) {
233
+ const item = raw[i];
234
+ if (typeof item !== "string" || item.length === 0 || item.length > 256) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `${label}[${i}] must be a non-empty string (<= 256 chars)`);
235
+ out.push(item);
236
+ }
237
+ return out;
238
+ }
239
+ function summarizeOptionalItxData(rawData, label) {
240
+ if (rawData === void 0) return;
241
+ if (!(rawData instanceof Map)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `${label} must be a canonical CBOR Any map`);
242
+ assertClosedCborIntKeys(rawData, new Set([0, 1]), label);
243
+ const dataTypeUrl = rawData.get(0);
244
+ if (typeof dataTypeUrl !== "string" || dataTypeUrl.length === 0 || dataTypeUrl.length > 128) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `${label} missing valid Any.typeUrl (field 0)`);
245
+ for (let i = 0; i < dataTypeUrl.length; i++) {
246
+ const c = dataTypeUrl.charCodeAt(i);
247
+ if (c < 33 || c > 126) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `Non-printable character in ${label}.typeUrl`);
248
+ }
249
+ const innerVal = rawData.get(1);
250
+ let valueSummaryBytes;
251
+ if (innerVal === void 0) valueSummaryBytes = utf8Encoder.encode(dataTypeUrl);
252
+ else if (innerVal instanceof Uint8Array) {
253
+ if (innerVal.length === 0) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `${label}.value must not be empty bytes`);
254
+ valueSummaryBytes = innerVal;
255
+ } else {
256
+ const canonicalSummary = JSON.stringify(innerVal, (_k, v) => {
257
+ if (typeof v === "bigint") return v.toString(10);
258
+ if (v instanceof Uint8Array) return `0x${bytesToHex(v)}`;
259
+ if (v instanceof Map) return [...v.entries()];
260
+ return v;
261
+ });
262
+ valueSummaryBytes = utf8Encoder.encode(`${dataTypeUrl}:${canonicalSummary}`);
263
+ }
264
+ return `data=${dataTypeUrl}#${bytesToHex(sha3_256(valueSummaryBytes)).slice(0, 16)}`;
265
+ }
266
+ function parseTokenInputs(rawTokens, label) {
267
+ if (rawTokens === void 0) return [];
268
+ if (!Array.isArray(rawTokens) || rawTokens.length === 0 || rawTokens.length > 32) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `${label} must be a non-empty array of 1..32 TokenInput items`);
269
+ const aggregated = /* @__PURE__ */ new Map();
270
+ for (let i = 0; i < rawTokens.length; i++) {
271
+ const item = rawTokens[i];
272
+ if (!(item instanceof Map)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `${label}[${i}] must be a CBOR map`);
273
+ assertClosedCborIntKeys(item, new Set([1, 2]), `${label}[${i}]`);
274
+ const rawAddr = item.get(1);
275
+ if (typeof rawAddr !== "string" || rawAddr.length === 0) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `Missing TokenInput.address in ${label}[${i}]`);
276
+ const normAddr = normalizeCanonicalOcapTokenKey(rawAddr, `${label}[${i}].address`, "RLP_INVALID_TRANSACTION");
277
+ const val = parseCborDecimalStringUint(item.get(2), `${label}[${i}].value`);
278
+ if (val <= 0n) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `${label}[${i}].value must be > 0`);
279
+ if (val + (aggregated.get(normAddr) ?? 0n) > MAX_UINT256) throw new MpcProtocolError("PERSONAL_AMOUNT_OVERFLOW", `Token outflow overflow in ${label}`);
280
+ aggregated.set(normAddr, (aggregated.get(normAddr) ?? 0n) + val);
281
+ }
282
+ return [...aggregated.entries()].filter(([, amt]) => amt > 0n).sort(([a], [b]) => a.localeCompare(b)).map(([tokenAddress, amount]) => ({
283
+ tokenAddress,
284
+ amount
285
+ }));
286
+ }
287
+ function base58DecodeBtc(didOrAddress, label) {
288
+ const bare = didOrAddress.replace(/^did:[a-z0-9]+:/, "");
289
+ if (!bare.startsWith("z") || bare.length < 2) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `Invalid base58btc address in ${label}`);
290
+ const body = bare.slice(1);
291
+ let leadingZeroes = 0;
292
+ while (leadingZeroes < body.length && body[leadingZeroes] === "1") leadingZeroes++;
293
+ let acc = 0n;
294
+ for (let i = leadingZeroes; i < body.length; i++) {
295
+ const idx = BASE58_ALPHABET.indexOf(body[i]);
296
+ if (idx < 0) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `Invalid base58 character in ${label}`);
297
+ acc = acc * 58n + BigInt(idx);
298
+ }
299
+ const hex = acc === 0n ? "" : acc.toString(16);
300
+ const paddedHex = hex.length % 2 === 0 ? hex : `0${hex}`;
301
+ const tailLen = paddedHex.length / 2;
302
+ const out = new Uint8Array(leadingZeroes + tailLen);
303
+ for (let i = 0; i < tailLen; i++) out[leadingZeroes + i] = Number.parseInt(paddedHex.slice(i * 2, i * 2 + 2), 16);
304
+ return out;
305
+ }
306
+ function verifyMigratePkDerivesTargetAddress(migratePk, targetAddress) {
307
+ if (targetAddress.startsWith("0x") || targetAddress.startsWith("0X")) {
308
+ let uncompressed65;
309
+ if (migratePk.length === 64) {
310
+ uncompressed65 = new Uint8Array(65);
311
+ uncompressed65[0] = 4;
312
+ uncompressed65.set(migratePk, 1);
313
+ } else if (migratePk.length === 65 && migratePk[0] === 4) uncompressed65 = migratePk;
314
+ else if (migratePk.length === 33 && (migratePk[0] === 2 || migratePk[0] === 3)) uncompressed65 = decodePointCompressed(migratePk, false).toBytes(false);
315
+ else throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "AccountMigrateTx.pk length invalid for Ethereum target address");
316
+ const xy64 = uncompressed65.subarray(1);
317
+ const comp33 = new Uint8Array(33);
318
+ comp33[0] = (xy64[63] & 1) === 1 ? 3 : 2;
319
+ comp33.set(xy64.subarray(0, 32), 1);
320
+ const pt = decodePointCompressed(comp33, false);
321
+ if (!constantTimeEqual(pt.toBytes(false).subarray(1), xy64)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "AccountMigrateTx.pk is not a valid secp256k1 point");
322
+ const { checksumAddress } = pointToEthAddress(pt);
323
+ if (checksumAddress.toLowerCase() !== targetAddress.toLowerCase()) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "AccountMigrateTx.pk does not derive AccountMigrateTx.address");
324
+ return;
325
+ }
326
+ const didBytes = base58DecodeBtc(targetAddress, "AccountMigrateTx.address");
327
+ if (didBytes.length !== 26) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Invalid 26-byte ABT-DID payload in AccountMigrateTx.address");
328
+ const payload22 = didBytes.subarray(0, 22);
329
+ const checksum4 = didBytes.subarray(22, 26);
330
+ const typeWord = payload22[0] << 8 | payload22[1];
331
+ const pkAlg = typeWord >>> 5 & 31;
332
+ const hashAlg = typeWord & 31;
333
+ if (hashAlg !== 0 && hashAlg !== 1) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Unsupported hash algorithm (${hashAlg}) in AccountMigrateTx.address`);
334
+ if (!constantTimeEqual(checksum4, (hashAlg === 0 ? keccak_256(payload22) : sha3_256(payload22)).subarray(0, 4))) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "ABT-DID checksum mismatch in AccountMigrateTx.address");
335
+ let canonicalPkForHash;
336
+ if (pkAlg === 0) {
337
+ if (migratePk.length !== 32) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Ed25519 AccountMigrateTx.pk must be 32 bytes");
338
+ normalizeActorPublicKeyToPadded65("agent-ed25519", migratePk, "PERSONAL_POLICY_VIOLATION");
339
+ canonicalPkForHash = migratePk;
340
+ } else if (pkAlg === 1) {
341
+ if (migratePk.length === 33 && (migratePk[0] === 2 || migratePk[0] === 3)) try {
342
+ decodePointCompressed(migratePk, false);
343
+ } catch {
344
+ throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "AccountMigrateTx.pk is not a valid secp256k1 point");
345
+ }
346
+ else if (migratePk.length === 65 && migratePk[0] === 4) {
347
+ const xy64 = migratePk.subarray(1);
348
+ const comp33 = new Uint8Array(33);
349
+ comp33[0] = (xy64[63] & 1) === 1 ? 3 : 2;
350
+ comp33.set(xy64.subarray(0, 32), 1);
351
+ let pt;
352
+ try {
353
+ pt = decodePointCompressed(comp33, false);
354
+ } catch {
355
+ throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "AccountMigrateTx.pk is not a valid secp256k1 point");
356
+ }
357
+ if (!constantTimeEqual(pt.toBytes(false), migratePk)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "AccountMigrateTx.pk Y coordinate is off-curve");
358
+ } else throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Secp256k1 AccountMigrateTx.pk must be 33-byte compressed or 65-byte uncompressed secp256k1 point");
359
+ canonicalPkForHash = migratePk;
360
+ } else if (pkAlg === 2) {
361
+ let xy64;
362
+ if (migratePk.length === 64) xy64 = migratePk;
363
+ else if (migratePk.length === 65 && migratePk[0] === 4) xy64 = migratePk.subarray(1);
364
+ else throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Ethereum AccountMigrateTx.pk must be 64 bytes (x||y) or 65 bytes (0x04||x||y)");
365
+ const comp33 = new Uint8Array(33);
366
+ comp33[0] = (xy64[63] & 1) === 1 ? 3 : 2;
367
+ comp33.set(xy64.subarray(0, 32), 1);
368
+ let pt;
369
+ try {
370
+ pt = decodePointCompressed(comp33, false);
371
+ } catch {
372
+ throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "AccountMigrateTx.pk is not a valid secp256k1 point");
373
+ }
374
+ if (!constantTimeEqual(pt.toBytes(false).subarray(1), xy64)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "AccountMigrateTx.pk Y coordinate is off-curve");
375
+ canonicalPkForHash = xy64;
376
+ } else throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Unsupported key algorithm (${pkAlg}) in AccountMigrateTx.address`);
377
+ if (!constantTimeEqual((hashAlg === 0 ? keccak_256(canonicalPkForHash) : sha3_256(canonicalPkForHash)).subarray(0, 20), payload22.subarray(2, 22))) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "AccountMigrateTx.pk hash does not match AccountMigrateTx.address");
378
+ }
379
+ const ALLOWED_TOP_TX_KEYS = new Set([
380
+ 1,
381
+ 2,
382
+ 3,
383
+ 4,
384
+ 5,
385
+ 6,
386
+ 13,
387
+ 14,
388
+ 15,
389
+ 16,
390
+ 17
391
+ ]);
392
+ const MAX_UINT32 = 4294967295n;
393
+ function parseGasParamUint(raw, fallback, label) {
394
+ if (raw === void 0) return fallback;
395
+ if (typeof raw === "bigint") {
396
+ if (raw < 0n || raw > MAX_UINT128) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `${label} out of range`);
397
+ return raw;
398
+ }
399
+ if (typeof raw === "number") {
400
+ if (!Number.isSafeInteger(raw) || raw < 0) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `${label} must be a non-negative integer`);
401
+ return BigInt(raw);
402
+ }
403
+ const s = String(raw).trim();
404
+ if (!/^(0|[1-9][0-9]{0,39})$/.test(s)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `${label} must be a canonical non-negative integer`);
405
+ const v = BigInt(s);
406
+ if (v > MAX_UINT128) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `${label} exceeds uint128`);
407
+ return v;
408
+ }
409
+ /**
410
+ * Computes a deterministic, fail-closed upper bound on the OCAP execution gas + protocol `txFee`
411
+ * charged by `CreateGasEnsureFn` (`ensure-gas.ts`) and `EnsureTxCost` (`ensure-cost.ts`), even when
412
+ * `Transaction.gas` (field 5) is absent or `0` and the sender lacks a valid gas stake.
413
+ */
414
+ function estimateOcapExecutionCostUpperBound(params) {
415
+ const { gasConfig, itxTypeUrl } = params;
416
+ const price = parseGasParamUint(gasConfig.price, 0n, "ocapGasConfig.price");
417
+ const dataStorage = parseGasParamUint(gasConfig.dataStorage, price > 0n ? 0n : 1n, "ocapGasConfig.dataStorage");
418
+ const createState = parseGasParamUint(gasConfig.createState, price > 0n ? 0n : 1n, "ocapGasConfig.createState");
419
+ const updateState = parseGasParamUint(gasConfig.updateState, price > 0n ? 0n : 1n, "ocapGasConfig.updateState");
420
+ if (price > 0n && (dataStorage < 1n || createState < 1n || updateState < 1n)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "OCAP gasConfig with price > 0 requires positive dataStorage, createState, and updateState multipliers");
421
+ const defaultOverhead = itxTypeUrl === "fg:t:exchange_v2" || itxTypeUrl === "fg:t:account_migrate" ? 320 : 112;
422
+ const overheadBytes = gasConfig.signedEnvelopeOverheadBytes ?? defaultOverhead;
423
+ if (!Number.isSafeInteger(overheadBytes) || overheadBytes < 72 || overheadBytes > 4096) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Invalid signedEnvelopeOverheadBytes in OCAP gasConfig");
424
+ let estimatedExecutionGas = 0n;
425
+ if (price > 0n) {
426
+ const isMultisigV1 = itxTypeUrl === "fg:t:exchange_v2" || itxTypeUrl === "fg:t:account_migrate";
427
+ const baseSignedBytes = params.unsignedPayloadByteLength + overheadBytes;
428
+ const signedTxSize = BigInt(isMultisigV1 ? Math.max(baseSignedBytes, 1691) + 8192 : baseSignedBytes);
429
+ const maxStateWeight = createState >= updateState ? createState : updateState;
430
+ const outAssets = BigInt(Math.max(0, params.outgoingAssetCount));
431
+ const inAssets = BigInt(Math.max(0, params.incomingAssetCount));
432
+ let stateWeight;
433
+ switch (itxTypeUrl) {
434
+ case "fg:t:transfer":
435
+ case "fg:t:transfer_v2":
436
+ stateWeight = createState + updateState * (2n + outAssets) + maxStateWeight;
437
+ break;
438
+ case "fg:t:exchange_v2":
439
+ stateWeight = createState + updateState * (3n + outAssets + inAssets);
440
+ break;
441
+ case "fg:t:declare":
442
+ stateWeight = createState + maxStateWeight * 2n;
443
+ break;
444
+ case "fg:t:revoke_delegate":
445
+ stateWeight = createState + updateState * 2n;
446
+ break;
447
+ case "fg:t:delegate":
448
+ stateWeight = createState + updateState * 5n + maxStateWeight * 2n;
449
+ break;
450
+ case "fg:t:account_migrate":
451
+ stateWeight = createState * 3n + updateState * 4n;
452
+ break;
453
+ default: throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Cannot bound execution gas for unsupported OCAP tx type "${itxTypeUrl}"`);
454
+ }
455
+ estimatedExecutionGas = price * (dataStorage * signedTxSize + stateWeight);
456
+ }
457
+ let protocolTxFee = 0n;
458
+ if (gasConfig.txFeeBaseUnitsByType) {
459
+ const shortType = itxTypeUrl.startsWith("fg:t:") ? itxTypeUrl.slice(5) : itxTypeUrl;
460
+ const rawFee = gasConfig.txFeeBaseUnitsByType[itxTypeUrl] ?? gasConfig.txFeeBaseUnitsByType[shortType] ?? gasConfig.txFeeBaseUnitsByType.default;
461
+ if (rawFee !== void 0) protocolTxFee = parseGasParamUint(rawFee, 0n, `txFeeBaseUnitsByType[${itxTypeUrl}]`);
462
+ }
463
+ const totalExecutionCostUpperBound = estimatedExecutionGas + protocolTxFee;
464
+ if (totalExecutionCostUpperBound > MAX_UINT256) throw new MpcProtocolError("PERSONAL_AMOUNT_OVERFLOW", "OCAP bounded execution cost overflows uint256");
465
+ return {
466
+ estimatedExecutionGas,
467
+ protocolTxFee,
468
+ totalExecutionCostUpperBound
469
+ };
470
+ }
471
+ function resolveCanonicalPolicyHelper(policy) {
472
+ if (!policy) return void 0;
473
+ return "enforcePayeeAllowlistInL0" in policy && Array.isArray(policy.allowedChainIds) && policy.allowedChainIds.every((c) => typeof c === "string") ? policy : canonicalizePersonalVaultPolicy(policy).canonicalPolicy;
474
+ }
475
+ function decodeAndVerifyPersonalOcapTx(params) {
476
+ const bytes = normalizeHexBytes(params.rawTxBytes);
477
+ if (bytes.length === 32) throw new MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "Opaque 32-byte blind digest signing is strictly forbidden");
478
+ if (bytes.length < 4 || bytes.length > MAX_PERSONAL_OCAP_TX_BYTES) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `OCAP CBOR transaction length (${bytes.length}B) outside 4..${MAX_PERSONAL_OCAP_TX_BYTES}`);
479
+ if (bytes[0] !== 217 || bytes[1] !== 217 || bytes[2] !== 247) throw new MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "OCAP transaction must start with canonical self-describe CBOR tag 0xd9d9f7");
480
+ const cursor = {
481
+ bytes,
482
+ offset: 0
483
+ };
484
+ const root = decodeCanonicalCborItem(cursor, 0);
485
+ if (cursor.offset !== bytes.length) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Trailing bytes after canonical CBOR OCAP transaction");
486
+ if (!(root instanceof CborTagValue) || root.tag !== SELF_DESCRIBE_CBOR_TAG || !(root.value instanceof Map)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Expected Tag(55799, Map) OCAP Transaction");
487
+ const txMap = root.value;
488
+ for (const key of txMap.keys()) if (typeof key !== "number" || !ALLOWED_TOP_TX_KEYS.has(key)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `Unknown or non-integer Transaction proto key: ${String(key)}`);
489
+ if (txMap.has(13)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Unsigned OCAP transaction must not carry field 13 (signature)");
490
+ if (txMap.has(14)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Multisig OCAP wrapper (field 14) is not permitted");
491
+ if (txMap.has(16)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Unsigned OCAP transaction must not carry field 16 (receipts)");
492
+ if (txMap.has(6)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Delegated third-party sender (Transaction.delegator, field 6) is forbidden on Personal HSM vaults");
493
+ const rawFrom = txMap.get(1);
494
+ if (typeof rawFrom !== "string" || rawFrom.length === 0) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Missing Transaction.from (field 1)");
495
+ const fromAddress = normalizeOcapAddressOrEth(rawFrom, "Transaction.from", "RLP_INVALID_TRANSACTION");
496
+ const nonce = parseCborPositiveUintField(txMap.get(2), MAX_UINT64, "Transaction.nonce (field 2)");
497
+ const rawChainId = txMap.get(3);
498
+ if (typeof rawChainId !== "string" || rawChainId.length === 0 || rawChainId.length > 64) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Missing or invalid Transaction.chainId (field 3)");
499
+ for (let i = 0; i < rawChainId.length; i++) {
500
+ const c = rawChainId.charCodeAt(i);
501
+ if (c < 33 || c > 126) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Non-printable character in Transaction.chainId");
502
+ }
503
+ const rawPk = txMap.get(4);
504
+ if (!(rawPk instanceof Uint8Array) || rawPk.length === 0) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Missing Transaction.pk bytes (field 4)");
505
+ const identities = deriveOcapIdentitiesFromChildPoint(params.childPublicKeyComp33);
506
+ let signerScheme;
507
+ let derivedSignerAddress;
508
+ if (rawPk.length === 64 && constantTimeEqual(rawPk, identities.ethUncompressedPk64)) {
509
+ signerScheme = "ethereum";
510
+ derivedSignerAddress = identities.ethChecksumAddress;
511
+ } else if (rawPk.length === 65 && constantTimeEqual(rawPk, identities.secp256k1UncompressedPk65)) {
512
+ signerScheme = "secp256k1";
513
+ derivedSignerAddress = identities.ocapSecp256k1Address;
514
+ } else throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Transaction.pk does not match derived child public key (64B ETHEREUM or 65B SECP256K1)");
515
+ if (fromAddress !== derivedSignerAddress) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Transaction.from does not match derived child address");
516
+ const gasFee = txMap.has(5) ? parseCborPositiveUintField(txMap.get(5), MAX_UINT32, "Transaction.gas (field 5)") : 0n;
517
+ const serviceFee = txMap.has(17) ? parseCborDecimalStringUint(txMap.get(17), "Transaction.service_fee") : 0n;
518
+ const itxVal = txMap.get(15);
519
+ if (!(itxVal instanceof Map)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Missing Transaction.itx map (field 15)");
520
+ const itxTypeUrl = itxVal.get(0);
521
+ if (typeof itxTypeUrl !== "string" || !OCAP_TX_TYPE_URL_RE.test(itxTypeUrl)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `Invalid itx typeUrl: ${String(itxTypeUrl)}`);
522
+ const canonicalPolicy = resolveCanonicalPolicyHelper(params.policy);
523
+ if (canonicalPolicy) {
524
+ if (!(canonicalPolicy.allowedOcapChainIds ?? []).includes(rawChainId)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `OCAP chainId "${rawChainId}" is not allowlisted in allowedOcapChainIds`);
525
+ if (!(canonicalPolicy.allowedOcapTxTypes ?? []).includes(itxTypeUrl)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `OCAP transaction type "${itxTypeUrl}" is not allowlisted in allowedOcapTxTypes`);
526
+ }
527
+ let toAddress = fromAddress;
528
+ let nativeValueOutflow = 0n;
529
+ let tokenOutflows = [];
530
+ let outgoingAssetIds = [];
531
+ let nativeInflowExpected = 0n;
532
+ let tokenInflowsExpected = [];
533
+ let incomingAssetIds = [];
534
+ let expiredAtIso;
535
+ const delegatedOps = [];
536
+ const extraSummaryDetails = [];
537
+ let isTransferLike = false;
538
+ switch (itxTypeUrl) {
539
+ case "fg:t:transfer": {
540
+ assertClosedCborIntKeys(itxVal, new Set([
541
+ 0,
542
+ 1,
543
+ 2,
544
+ 3,
545
+ 15
546
+ ]), "TransferTx");
547
+ const rawTo = itxVal.get(1);
548
+ if (typeof rawTo !== "string" || rawTo.length === 0) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Missing TransferTx.to");
549
+ toAddress = normalizeOcapAddressOrEth(rawTo, "TransferTx.to", "RLP_INVALID_TRANSACTION");
550
+ nativeValueOutflow = parseCborBigUintField(itxVal.get(2), "TransferTx.value");
551
+ outgoingAssetIds = [...parseNonEmptyStringArray(itxVal.get(3), 64, "TransferTx.assets")];
552
+ const dataSummary = summarizeOptionalItxData(itxVal.get(15), "TransferTx.data");
553
+ if (dataSummary) extraSummaryDetails.push(dataSummary);
554
+ isTransferLike = true;
555
+ break;
556
+ }
557
+ case "fg:t:transfer_v2": {
558
+ assertClosedCborIntKeys(itxVal, new Set([
559
+ 0,
560
+ 1,
561
+ 2,
562
+ 3,
563
+ 4,
564
+ 15
565
+ ]), "TransferV2Tx");
566
+ const rawTo = itxVal.get(1);
567
+ if (typeof rawTo !== "string" || rawTo.length === 0) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Missing TransferV2Tx.to");
568
+ toAddress = normalizeOcapAddressOrEth(rawTo, "TransferV2Tx.to", "RLP_INVALID_TRANSACTION");
569
+ nativeValueOutflow = parseCborBigUintField(itxVal.get(2), "TransferV2Tx.value");
570
+ outgoingAssetIds = [...parseNonEmptyStringArray(itxVal.get(3), 64, "TransferV2Tx.assets")];
571
+ tokenOutflows = parseTokenInputs(itxVal.get(4), "TransferV2Tx.tokens");
572
+ const dataSummary = summarizeOptionalItxData(itxVal.get(15), "TransferV2Tx.data");
573
+ if (dataSummary) extraSummaryDetails.push(dataSummary);
574
+ isTransferLike = true;
575
+ break;
576
+ }
577
+ case "fg:t:exchange_v2": {
578
+ assertClosedCborIntKeys(itxVal, new Set([
579
+ 0,
580
+ 1,
581
+ 2,
582
+ 3,
583
+ 4,
584
+ 15
585
+ ]), "ExchangeV2Tx");
586
+ const rawTo = itxVal.get(1);
587
+ if (typeof rawTo !== "string" || rawTo.length === 0) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Missing explicit ExchangeV2Tx.to counterparty");
588
+ toAddress = normalizeOcapAddressOrEth(rawTo, "ExchangeV2Tx.to", "RLP_INVALID_TRANSACTION");
589
+ const senderMap = itxVal.get(2);
590
+ if (!(senderMap instanceof Map)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Missing ExchangeV2Tx.sender map (field 2)");
591
+ assertClosedCborIntKeys(senderMap, new Set([
592
+ 1,
593
+ 2,
594
+ 3
595
+ ]), "ExchangeV2Tx.sender");
596
+ nativeValueOutflow = parseCborBigUintField(senderMap.get(1), "ExchangeV2Tx.sender.value");
597
+ outgoingAssetIds = [...parseNonEmptyStringArray(senderMap.get(2), 64, "ExchangeV2Tx.sender.assets")];
598
+ tokenOutflows = parseTokenInputs(senderMap.get(3), "ExchangeV2Tx.sender.tokens");
599
+ const receiverMap = itxVal.get(3);
600
+ if (!(receiverMap instanceof Map)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Missing ExchangeV2Tx.receiver map (field 3)");
601
+ assertClosedCborIntKeys(receiverMap, new Set([
602
+ 1,
603
+ 2,
604
+ 3
605
+ ]), "ExchangeV2Tx.receiver");
606
+ const rawRecvNative = parseCborBigUintField(receiverMap.get(1), "ExchangeV2Tx.receiver.value");
607
+ incomingAssetIds = [...parseNonEmptyStringArray(receiverMap.get(2), 64, "ExchangeV2Tx.receiver.assets")];
608
+ const rawRecvTokens = parseTokenInputs(receiverMap.get(3), "ExchangeV2Tx.receiver.tokens");
609
+ nativeInflowExpected = rawRecvNative;
610
+ tokenInflowsExpected = rawRecvTokens;
611
+ const recvParts = [`native=${nativeInflowExpected.toString(10)}`];
612
+ if (tokenInflowsExpected.length > 0) recvParts.push(`tokens=[${tokenInflowsExpected.map((t) => `${t.amount.toString(10)} ${t.tokenAddress}`).join(", ")}]`);
613
+ if (incomingAssetIds.length > 0) recvParts.push(`assets=[${incomingAssetIds.join(", ")}]`);
614
+ extraSummaryDetails.push(`receive(${recvParts.join(", ")})`);
615
+ const rawExpiredAt = itxVal.get(4);
616
+ if (rawExpiredAt !== void 0) {
617
+ if (typeof rawExpiredAt !== "string" || rawExpiredAt.length === 0 || Number.isNaN(Date.parse(rawExpiredAt))) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Invalid ExchangeV2Tx.expired_at ISO-8601 timestamp");
618
+ const expEpochSec = BigInt(Math.floor(Date.parse(rawExpiredAt) / 1e3));
619
+ if (params.nowSec !== void 0 && expEpochSec <= params.nowSec) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "ExchangeV2Tx.expired_at has already expired");
620
+ expiredAtIso = rawExpiredAt;
621
+ extraSummaryDetails.push(`expiredAt=${rawExpiredAt}`);
622
+ }
623
+ const dataSummary = summarizeOptionalItxData(itxVal.get(15), "ExchangeV2Tx.data");
624
+ if (dataSummary) extraSummaryDetails.push(dataSummary);
625
+ break;
626
+ }
627
+ case "fg:t:declare": {
628
+ assertClosedCborIntKeys(itxVal, new Set([
629
+ 0,
630
+ 1,
631
+ 2,
632
+ 15
633
+ ]), "DeclareTx");
634
+ toAddress = fromAddress;
635
+ if (itxVal.has(1)) {
636
+ const moniker = itxVal.get(1);
637
+ if (typeof moniker !== "string" || moniker.length === 0 || moniker.length > 128) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Invalid DeclareTx.moniker");
638
+ extraSummaryDetails.push(`moniker=${moniker}`);
639
+ }
640
+ if (itxVal.has(2)) {
641
+ const issuer = itxVal.get(2);
642
+ if (typeof issuer !== "string" || issuer.length === 0) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Invalid DeclareTx.issuer");
643
+ const normIssuer = normalizeOcapAddressOrEth(issuer, "DeclareTx.issuer", "RLP_INVALID_TRANSACTION");
644
+ extraSummaryDetails.push(`issuer=${normIssuer}`);
645
+ }
646
+ const dataSummary = summarizeOptionalItxData(itxVal.get(15), "DeclareTx.data");
647
+ if (dataSummary) extraSummaryDetails.push(dataSummary);
648
+ break;
649
+ }
650
+ case "fg:t:revoke_delegate": {
651
+ assertClosedCborIntKeys(itxVal, new Set([
652
+ 0,
653
+ 1,
654
+ 2,
655
+ 3,
656
+ 15
657
+ ]), "RevokeDelegateTx");
658
+ if (itxVal.has(1)) {
659
+ const delAddr = itxVal.get(1);
660
+ if (typeof delAddr !== "string" || delAddr.length === 0) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Invalid RevokeDelegateTx.address");
661
+ normalizeOcapAddressOrEth(delAddr, "RevokeDelegateTx.address", "RLP_INVALID_TRANSACTION");
662
+ }
663
+ const rawTo = itxVal.get(2);
664
+ if (typeof rawTo !== "string" || rawTo.length === 0) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Missing RevokeDelegateTx.to");
665
+ toAddress = normalizeOcapAddressOrEth(rawTo, "RevokeDelegateTx.to", "RLP_INVALID_TRANSACTION");
666
+ const revokedUrls = parseNonEmptyStringArray(itxVal.get(3), 32, "RevokeDelegateTx.type_urls");
667
+ if (revokedUrls.length > 0) extraSummaryDetails.push(`revokeOps=[${revokedUrls.join(", ")}]`);
668
+ const dataSummary = summarizeOptionalItxData(itxVal.get(15), "RevokeDelegateTx.data");
669
+ if (dataSummary) extraSummaryDetails.push(dataSummary);
670
+ break;
671
+ }
672
+ case "fg:t:delegate": {
673
+ assertClosedCborIntKeys(itxVal, new Set([
674
+ 0,
675
+ 1,
676
+ 2,
677
+ 3,
678
+ 4,
679
+ 5,
680
+ 15
681
+ ]), "DelegateTx");
682
+ if (!canonicalPolicy?.allowDelegationTokenByQuorum || !params.hasL2OrL3QuorumProof) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "On-chain fg:t:delegate requires allowDelegationTokenByQuorum=true and an L2/L3 quorum proof");
683
+ if (itxVal.has(1)) {
684
+ const delAddr = itxVal.get(1);
685
+ if (typeof delAddr !== "string" || delAddr.length === 0) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Invalid DelegateTx.address");
686
+ normalizeOcapAddressOrEth(delAddr, "DelegateTx.address", "RLP_INVALID_TRANSACTION");
687
+ }
688
+ const rawTo = itxVal.get(2);
689
+ if (typeof rawTo !== "string" || rawTo.length === 0) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Missing DelegateTx.to");
690
+ toAddress = normalizeOcapAddressOrEth(rawTo, "DelegateTx.to", "RLP_INVALID_TRANSACTION");
691
+ const validUntil = parseCborPositiveUintField(itxVal.get(5), MAX_UINT64, "DelegateTx.valid_until (explicit positive expiry required)");
692
+ if (params.nowSec !== void 0) {
693
+ if (validUntil <= params.nowSec || validUntil - params.nowSec > BigInt(MAX_PERSONAL_OCAP_DELEGATE_TTL_SECONDS)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `DelegateTx.valid_until must satisfy nowSec < valid_until <= nowSec + ${MAX_PERSONAL_OCAP_DELEGATE_TTL_SECONDS}s`);
694
+ } else if (validUntil > 281474976710655n) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "DelegateTx.valid_until exceeds realistic epoch range");
695
+ const denyPatterns = parseNonEmptyStringArray(itxVal.get(4), 32, "DelegateTx.deny");
696
+ for (const pat of denyPatterns) if (!/^fg:[a-z0-9_:*]{1,64}$/.test(pat)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Invalid DelegateTx.deny pattern: "${pat}"`);
697
+ const rawOps = itxVal.get(3);
698
+ if (!Array.isArray(rawOps) || rawOps.length === 0 || rawOps.length > 32) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "DelegateTx.ops must contain 1..32 operations");
699
+ const allowedSet = new Set(canonicalPolicy.allowedOcapTxTypes ?? []);
700
+ const opLimitSummaries = [];
701
+ for (let i = 0; i < rawOps.length; i++) {
702
+ const opEntry = rawOps[i];
703
+ if (!(opEntry instanceof Map)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `DelegateTx.ops[${i}] must be a CBOR map`);
704
+ assertClosedCborIntKeys(opEntry, new Set([
705
+ 1,
706
+ 2,
707
+ 3
708
+ ]), `DelegateTx.ops[${i}]`);
709
+ const opUrl = opEntry.get(1);
710
+ if (typeof opUrl !== "string" || opUrl.includes("*") || !OCAP_TX_TYPE_URL_RE.test(opUrl)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Forbidden or wildcard DelegateOp.type_url: ${String(opUrl)}`);
711
+ if (!allowedSet.has(opUrl) || opUrl === "fg:t:delegate" || opUrl === "fg:t:account_migrate") throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `DelegateOp "${opUrl}" is not permitted by allowedOcapTxTypes`);
712
+ if (opEntry.has(2)) parseNonEmptyStringArray(opEntry.get(2), 32, `DelegateTx.ops[${i}].rules`);
713
+ const limitMap = opEntry.get(3);
714
+ if (!(limitMap instanceof Map)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `DelegateTx.ops[${i}] must specify an explicit bounded DelegateLimit (field 3)`);
715
+ assertClosedCborIntKeys(limitMap, new Set([1, 2]), `DelegateTx.ops[${i}].limit`);
716
+ const rawTokLimits = limitMap.get(1);
717
+ const rawAssetLimits = limitMap.get(2);
718
+ const hasTokLimits = Array.isArray(rawTokLimits) && rawTokLimits.length > 0;
719
+ const hasAssetLimits = Array.isArray(rawAssetLimits) && rawAssetLimits.length > 0;
720
+ if (!hasTokLimits && !hasAssetLimits) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `DelegateTx.ops[${i}].limit must define at least one bounded TokenLimit or AssetLimit`);
721
+ const singleOpSummaryParts = [];
722
+ if (rawTokLimits !== void 0) {
723
+ if (!Array.isArray(rawTokLimits) || rawTokLimits.length === 0 || rawTokLimits.length > 16) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `DelegateTx.ops[${i}].limit.tokens must be 1..16 items`);
724
+ for (let j = 0; j < rawTokLimits.length; j++) {
725
+ const tl = rawTokLimits[j];
726
+ if (!(tl instanceof Map)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `TokenLimit[${j}] must be a CBOR map`);
727
+ assertClosedCborIntKeys(tl, new Set([
728
+ 1,
729
+ 2,
730
+ 3,
731
+ 4,
732
+ 5,
733
+ 6
734
+ ]), `DelegateTx.ops[${i}].limit.tokens[${j}]`);
735
+ const rawTokAddr = tl.get(1);
736
+ if (typeof rawTokAddr !== "string" || rawTokAddr.length === 0) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `TokenLimit[${j}] missing token address`);
737
+ const normTokAddr = normalizeOcapAddressOrEth(rawTokAddr, `TokenLimit[${j}].address`, "RLP_INVALID_TRANSACTION");
738
+ const txAllow = parseCborDecimalStringUint(tl.get(4), `TokenLimit[${j}].txAllowance`);
739
+ const totalAllow = parseCborDecimalStringUint(tl.get(5), `TokenLimit[${j}].totalAllowance`);
740
+ if (txAllow <= 0n || totalAllow <= 0n || totalAllow < txAllow) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `TokenLimit[${j}] requires positive txAllowance and totalAllowance >= txAllowance (0 = unlimited is forbidden)`);
741
+ if (tl.has(2)) {
742
+ const toArr = parseNonEmptyStringArray(tl.get(2), 16, `TokenLimit[${j}].to`);
743
+ for (const tAddr of toArr) normalizeOcapAddressOrEth(tAddr, `TokenLimit[${j}].to`, "RLP_INVALID_TRANSACTION");
744
+ }
745
+ if (tl.has(3)) parseCborPositiveUintField(tl.get(3), MAX_UINT32, `TokenLimit[${j}].txCount`);
746
+ if (tl.has(6)) parseCborPositiveUintField(tl.get(6), MAX_UINT64, `TokenLimit[${j}].validUntil`);
747
+ singleOpSummaryParts.push(`${normTokAddr}:tx<=${txAllow.toString(10)}/tot<=${totalAllow.toString(10)}`);
748
+ }
749
+ }
750
+ if (rawAssetLimits !== void 0) {
751
+ if (!Array.isArray(rawAssetLimits) || rawAssetLimits.length === 0 || rawAssetLimits.length > 16) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `DelegateTx.ops[${i}].limit.assets must be 1..16 items`);
752
+ for (let j = 0; j < rawAssetLimits.length; j++) {
753
+ const al = rawAssetLimits[j];
754
+ if (!(al instanceof Map)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", `AssetLimit[${j}] must be a CBOR map`);
755
+ assertClosedCborIntKeys(al, new Set([
756
+ 1,
757
+ 2,
758
+ 3,
759
+ 4
760
+ ]), `DelegateTx.ops[${i}].limit.assets[${j}]`);
761
+ const assetAddrs = parseNonEmptyStringArray(al.get(1), 16, `AssetLimit[${j}].address`).map((aAddr) => normalizeOcapAddressOrEth(aAddr, `AssetLimit[${j}].address`, "RLP_INVALID_TRANSACTION"));
762
+ const txCount = parseCborPositiveUintField(al.get(3), MAX_UINT32, `AssetLimit[${j}].txCount`);
763
+ if (al.has(2)) {
764
+ const toArr = parseNonEmptyStringArray(al.get(2), 16, `AssetLimit[${j}].to`);
765
+ for (const tAddr of toArr) normalizeOcapAddressOrEth(tAddr, `AssetLimit[${j}].to`, "RLP_INVALID_TRANSACTION");
766
+ }
767
+ if (al.has(4)) parseCborPositiveUintField(al.get(4), MAX_UINT64, `AssetLimit[${j}].validUntil`);
768
+ singleOpSummaryParts.push(`assets[${assetAddrs.join(",")}]:cnt<=${txCount.toString(10)}`);
769
+ }
770
+ }
771
+ delegatedOps.push(opUrl);
772
+ opLimitSummaries.push(`${opUrl}(${singleOpSummaryParts.join(";")})`);
773
+ }
774
+ extraSummaryDetails.push(`ops=[${opLimitSummaries.join(", ")}]`);
775
+ extraSummaryDetails.push(`validUntil=${validUntil.toString(10)}`);
776
+ if (denyPatterns.length > 0) extraSummaryDetails.push(`deny=[${denyPatterns.join(", ")}]`);
777
+ const dataSummary = summarizeOptionalItxData(itxVal.get(15), "DelegateTx.data");
778
+ if (dataSummary) extraSummaryDetails.push(dataSummary);
779
+ break;
780
+ }
781
+ case "fg:t:account_migrate": {
782
+ assertClosedCborIntKeys(itxVal, new Set([
783
+ 0,
784
+ 1,
785
+ 2,
786
+ 3,
787
+ 15
788
+ ]), "AccountMigrateTx");
789
+ if (!params.hasL3GuardianQuorumProof) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "fg:t:account_migrate requires an L3 guardian-quorum proof");
790
+ const migratePk = itxVal.get(1);
791
+ if (!(migratePk instanceof Uint8Array) || migratePk.length < 32 || migratePk.length > 65) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Missing or invalid AccountMigrateTx.pk (32..65B)");
792
+ if (itxVal.has(2)) {
793
+ const wtMap = itxVal.get(2);
794
+ if (!(wtMap instanceof Map)) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "AccountMigrateTx.type must be a WalletType CBOR map");
795
+ assertClosedCborIntKeys(wtMap, new Set([
796
+ 1,
797
+ 2,
798
+ 3,
799
+ 4
800
+ ]), "AccountMigrateTx.type");
801
+ }
802
+ const rawTarget = itxVal.get(3);
803
+ if (typeof rawTarget !== "string" || rawTarget.length === 0) throw new MpcProtocolError("RLP_INVALID_TRANSACTION", "Missing AccountMigrateTx.address");
804
+ toAddress = normalizeOcapAddressOrEth(rawTarget, "AccountMigrateTx.address", "RLP_INVALID_TRANSACTION");
805
+ if (toAddress.startsWith("0x") || fromAddress.startsWith("0x") ? toAddress.toLowerCase() === fromAddress.toLowerCase() : toAddress === fromAddress) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Self-migration (AccountMigrateTx.address === Transaction.from) is forbidden");
806
+ verifyMigratePkDerivesTargetAddress(migratePk, toAddress);
807
+ extraSummaryDetails.push(`newPk=0x${bytesToHex(migratePk)}`);
808
+ const dataSummary = summarizeOptionalItxData(itxVal.get(15), "AccountMigrateTx.data");
809
+ if (dataSummary) extraSummaryDetails.push(dataSummary);
810
+ break;
811
+ }
812
+ default: throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Unsupported OCAP clear-signing transaction type: "${itxTypeUrl}"`);
813
+ }
814
+ if (outgoingAssetIds.length > 0 && !params.hasL2OrL3QuorumProof) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "OCAP NFT asset transfers (assets[]) require an L2/L3 quorum proof");
815
+ const resolvedGasConfig = params.ocapGasConfig ?? canonicalPolicy?.ocapGasConfigByChainId?.[rawChainId];
816
+ if ((canonicalPolicy !== void 0 || params.requireExecutionGasBound) && !resolvedGasConfig) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Missing trusted ocapGasConfigByChainId["${rawChainId}"] to bound OCAP execution gas`);
817
+ const declaredGasField = gasFee;
818
+ let effectiveGasFee = declaredGasField;
819
+ if (resolvedGasConfig) {
820
+ const est = estimateOcapExecutionCostUpperBound({
821
+ unsignedPayloadByteLength: bytes.length,
822
+ itxTypeUrl,
823
+ outgoingAssetCount: outgoingAssetIds.length,
824
+ incomingAssetCount: incomingAssetIds.length,
825
+ gasConfig: resolvedGasConfig
826
+ });
827
+ if (est.totalExecutionCostUpperBound > effectiveGasFee) effectiveGasFee = est.totalExecutionCostUpperBound;
828
+ }
829
+ const totalFees = serviceFee + effectiveGasFee;
830
+ const totalNativeOutflow = nativeValueOutflow + totalFees;
831
+ if (totalFees > MAX_UINT256 || totalNativeOutflow > MAX_UINT256) throw new MpcProtocolError("PERSONAL_AMOUNT_OVERFLOW", "OCAP value + serviceFee + gas overflows uint256");
832
+ const signingDigest32 = signerScheme === "ethereum" ? keccak_256(bytes) : sha3_256(bytes);
833
+ const signingDigestHex = `0x${bytesToHex(signingDigest32)}`;
834
+ const previewTokens = tokenOutflows.length > 0 ? tokenOutflows.map((t) => ({
835
+ tokenAddress: t.tokenAddress,
836
+ amount: t.amount.toString(10)
837
+ })) : void 0;
838
+ const buildOcapPreviewForFees = (outflowAmt, feesAmt) => {
839
+ const sParts = [`OCAP ${itxTypeUrl} on ${rawChainId} from ${fromAddress} to ${toAddress} (native ${outflowAmt.toString(10)})`];
840
+ if (previewTokens) sParts.push(`tokens [${previewTokens.map((t) => `${t.amount} ${t.tokenAddress}`).join(", ")}]`);
841
+ if (outgoingAssetIds.length > 0) sParts.push(`assets [${outgoingAssetIds.join(", ")}]`);
842
+ if (extraSummaryDetails.length > 0) sParts.push(extraSummaryDetails.join(" "));
843
+ return {
844
+ version: 1,
845
+ chainId: rawChainId,
846
+ fromAddress,
847
+ toAddress,
848
+ callKind: "ocap-tx",
849
+ selector: itxTypeUrl,
850
+ payeeOrSpenderAddress: toAddress,
851
+ assetIdentifier: "native",
852
+ outflowAmount: outflowAmt.toString(10),
853
+ maxGasFeeWei: feesAmt.toString(10),
854
+ nonce: nonce.toString(10),
855
+ signingDigestHex,
856
+ summaryText: sParts.join(" "),
857
+ itxTypeUrl,
858
+ ...previewTokens ? { tokenOutflows: previewTokens } : {}
859
+ };
860
+ };
861
+ const clearSigningPreview = buildOcapPreviewForFees(totalNativeOutflow, totalFees);
862
+ const clearSigningPreviewHash32 = computePersonalClearSigningPreviewHash32(clearSigningPreview);
863
+ const intrinsicFees = serviceFee + declaredGasField;
864
+ const intrinsicOutflow = nativeValueOutflow + intrinsicFees;
865
+ const intrinsicClearSigningPreviewHash32 = intrinsicOutflow === totalNativeOutflow && intrinsicFees === totalFees ? clearSigningPreviewHash32 : computePersonalClearSigningPreviewHash32(buildOcapPreviewForFees(intrinsicOutflow, intrinsicFees));
866
+ return {
867
+ verifiedOcapTx: {
868
+ unsignedPayloadBytes: bytes,
869
+ signingDigest32,
870
+ signingDigestHex,
871
+ signerAddress: derivedSignerAddress,
872
+ signerScheme,
873
+ fromAddress,
874
+ toAddress,
875
+ chainId: rawChainId,
876
+ nonce,
877
+ itxTypeUrl,
878
+ gasFee: effectiveGasFee,
879
+ declaredGasField,
880
+ serviceFee,
881
+ nativeValueOutflow,
882
+ totalNativeOutflow,
883
+ tokenOutflows,
884
+ outgoingAssetIds,
885
+ nativeInflowExpected,
886
+ tokenInflowsExpected,
887
+ incomingAssetIds,
888
+ ...expiredAtIso ? { expiredAtIso } : {},
889
+ delegatedOps,
890
+ isTransferLike
891
+ },
892
+ clearSigningPreview,
893
+ clearSigningPreviewHash32,
894
+ intrinsicClearSigningPreviewHash32
895
+ };
896
+ }
897
+ function joinTiers(a, b) {
898
+ if (a === b) return a;
899
+ if (a === "L0") return b;
900
+ if (b === "L0") return a;
901
+ return "L3";
902
+ }
903
+ function resolveRequiredOcapPolicyTier(params) {
904
+ const canonical = resolveCanonicalPolicyHelper(params.policy);
905
+ if (!canonical) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Missing policy for OCAP tier evaluation");
906
+ const { verifiedOcapTx } = params;
907
+ if (!(canonical.allowedOcapChainIds ?? []).includes(verifiedOcapTx.chainId)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `OCAP chainId "${verifiedOcapTx.chainId}" is not allowlisted`);
908
+ if (!(canonical.allowedOcapTxTypes ?? []).includes(verifiedOcapTx.itxTypeUrl)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `OCAP tx type "${verifiedOcapTx.itxTypeUrl}" is not allowlisted`);
909
+ const chainGasConfig = canonical.ocapGasConfigByChainId?.[verifiedOcapTx.chainId];
910
+ if (!chainGasConfig) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Missing trusted ocapGasConfigByChainId["${verifiedOcapTx.chainId}"] to bound OCAP execution gas`);
911
+ const gasEst = estimateOcapExecutionCostUpperBound({
912
+ unsignedPayloadByteLength: verifiedOcapTx.unsignedPayloadBytes.length,
913
+ itxTypeUrl: verifiedOcapTx.itxTypeUrl,
914
+ outgoingAssetCount: verifiedOcapTx.outgoingAssetIds.length,
915
+ incomingAssetCount: verifiedOcapTx.incomingAssetIds.length,
916
+ gasConfig: chainGasConfig
917
+ });
918
+ const minBoundedNativeOutflow = verifiedOcapTx.nativeValueOutflow + verifiedOcapTx.serviceFee + gasEst.totalExecutionCostUpperBound;
919
+ const baseNativeOutflow = verifiedOcapTx.totalNativeOutflow >= minBoundedNativeOutflow ? verifiedOcapTx.totalNativeOutflow : minBoundedNativeOutflow;
920
+ if (verifiedOcapTx.itxTypeUrl === "fg:t:account_migrate") return {
921
+ requiredTier: "L3",
922
+ projectedRollingByAsset: /* @__PURE__ */ new Map()
923
+ };
924
+ if (verifiedOcapTx.itxTypeUrl === "fg:t:delegate") return {
925
+ requiredTier: canonical.guardianRoster ? "L3" : "L2",
926
+ projectedRollingByAsset: /* @__PURE__ */ new Map()
927
+ };
928
+ const payeeAllowedInL0 = !canonical.enforcePayeeAllowlistInL0 || verifiedOcapTx.toAddress === verifiedOcapTx.fromAddress || (canonical.allowedOcapPayees ?? []).includes(verifiedOcapTx.toAddress) || canonical.allowedPayees.includes(verifiedOcapTx.toAddress);
929
+ const primaryTokenNorm = canonical.ocapPrimaryTokenByChainId?.[verifiedOcapTx.chainId];
930
+ const assetAmounts = /* @__PURE__ */ new Map();
931
+ assetAmounts.set("native", baseNativeOutflow);
932
+ for (const tok of verifiedOcapTx.tokenOutflows) {
933
+ const targetKey = primaryTokenNorm && tok.tokenAddress === primaryTokenNorm ? "native" : tok.tokenAddress;
934
+ const nextVal = (assetAmounts.get(targetKey) ?? 0n) + tok.amount;
935
+ if (nextVal > MAX_UINT256) throw new MpcProtocolError("PERSONAL_AMOUNT_OVERFLOW", `OCAP outflow for ${targetKey} overflows uint256`);
936
+ assetAmounts.set(targetKey, nextVal);
937
+ }
938
+ if (params.attestedSimulatedNativeDeltaWei !== void 0) {
939
+ let foldedPrimaryInflow = verifiedOcapTx.nativeInflowExpected;
940
+ if (primaryTokenNorm) {
941
+ for (const tokIn of verifiedOcapTx.tokenInflowsExpected) if (tokIn.tokenAddress === primaryTokenNorm) foldedPrimaryInflow += tokIn.amount;
942
+ }
943
+ const impliedAttestedOutflow = foldedPrimaryInflow - params.attestedSimulatedNativeDeltaWei;
944
+ if (impliedAttestedOutflow > (assetAmounts.get("native") ?? 0n)) assetAmounts.set("native", impliedAttestedOutflow);
945
+ }
946
+ let requiredTier = verifiedOcapTx.outgoingAssetIds.length > 0 ? "L2" : "L0";
947
+ const projectedRollingByAsset = /* @__PURE__ */ new Map();
948
+ const limits = canonical.ocapAssetLimits ?? [];
949
+ for (const [assetKey, txAmount] of assetAmounts.entries()) {
950
+ const currentRolling = params.currentRollingByAsset?.get(assetKey) ?? 0n;
951
+ if (txAmount === 0n && payeeAllowedInL0) {
952
+ projectedRollingByAsset.set(assetKey, currentRolling);
953
+ continue;
954
+ }
955
+ if (txAmount > MAX_UINT128 || currentRolling > MAX_UINT128 || currentRolling + txAmount > MAX_UINT128) {
956
+ if (!params.hasL2OrL3QuorumForOverflow) throw new MpcProtocolError("PERSONAL_AMOUNT_OVERFLOW", `OCAP outflow for ${assetKey} exceeds u128 velocity bound`);
957
+ projectedRollingByAsset.set(assetKey, MAX_UINT128);
958
+ requiredTier = joinTiers(requiredTier, canonical.guardianRoster ? "L3" : "L2");
959
+ continue;
960
+ }
961
+ const rule = limits.find((r) => r.chainId === verifiedOcapTx.chainId && r.asset === assetKey);
962
+ if (!rule) {
963
+ if (txAmount > 0n) projectedRollingByAsset.set(assetKey, currentRolling + txAmount > MAX_UINT128 ? MAX_UINT128 : currentRolling + txAmount);
964
+ requiredTier = joinTiers(requiredTier, canonical.guardianRoster ? "L3" : "L2");
965
+ continue;
966
+ }
967
+ const projected = currentRolling + txAmount;
968
+ const l0MaxPerTx = BigInt(rule.l0MaxPerTxAmount);
969
+ const l0MaxRolling = BigInt(rule.l0MaxRolling24hAmount);
970
+ let singleTier;
971
+ if (payeeAllowedInL0 && txAmount <= l0MaxPerTx && projected <= l0MaxRolling) {
972
+ singleTier = "L0";
973
+ projectedRollingByAsset.set(assetKey, projected);
974
+ } else if (rule.l1MaxPerTxAmount !== void 0 && txAmount <= BigInt(rule.l1MaxPerTxAmount)) {
975
+ singleTier = "L1";
976
+ projectedRollingByAsset.set(assetKey, projected);
977
+ } else if (rule.l2MaxPerTxAmount !== void 0 && txAmount <= BigInt(rule.l2MaxPerTxAmount)) {
978
+ singleTier = "L2";
979
+ projectedRollingByAsset.set(assetKey, projected);
980
+ } else {
981
+ singleTier = "L3";
982
+ projectedRollingByAsset.set(assetKey, projected);
983
+ }
984
+ requiredTier = joinTiers(requiredTier, singleTier);
985
+ }
986
+ return {
987
+ requiredTier,
988
+ projectedRollingByAsset
989
+ };
990
+ }
991
+ const ALLOWED_JWT_HEADER_KEYS = new Set([
992
+ "alg",
993
+ "type",
994
+ "typ",
995
+ "kid"
996
+ ]);
997
+ const ALLOWED_STANDARD_JWT_BODY_KEYS = new Set([
998
+ "iss",
999
+ "sub",
1000
+ "aud",
1001
+ "iat",
1002
+ "nbf",
1003
+ "exp",
1004
+ "jti",
1005
+ "nonce",
1006
+ "version"
1007
+ ]);
1008
+ const ALLOWED_DELEGATION_JWT_BODY_KEYS = new Set([
1009
+ "iss",
1010
+ "sub",
1011
+ "aud",
1012
+ "pk",
1013
+ "ops",
1014
+ "deny",
1015
+ "iat",
1016
+ "nbf",
1017
+ "exp",
1018
+ "jti",
1019
+ "version"
1020
+ ]);
1021
+ function assertPrintableJwtClaimString(val, maxLen, label) {
1022
+ if (typeof val !== "string" || val.length === 0 || val.length > maxLen) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Invalid JWT ${label} string`);
1023
+ for (let i = 0; i < val.length; i++) {
1024
+ const c = val.charCodeAt(i);
1025
+ if (c < 32 || c > 126) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Non-printable ASCII character in JWT ${label}`);
1026
+ }
1027
+ return val;
1028
+ }
1029
+ function parseOptionalJwtAudience(rawAud) {
1030
+ if (rawAud === void 0) return void 0;
1031
+ if (typeof rawAud === "string") return assertPrintableJwtClaimString(rawAud, 256, "aud");
1032
+ if (Array.isArray(rawAud) && rawAud.length >= 1 && rawAud.length <= 8) return rawAud.map((item, idx) => assertPrintableJwtClaimString(item, 256, `aud[${idx}]`)).join(",");
1033
+ throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Invalid JWT aud claim");
1034
+ }
1035
+ function assertJsonPlainNoProto(val) {
1036
+ if (!val || typeof val !== "object" || Array.isArray(val)) throw new MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "JWT segment must decode to a JSON object");
1037
+ for (const k of Object.getOwnPropertyNames(val)) if (FORBIDDEN_JSON_KEYS.has(k)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "Forbidden prototype key in JWT JSON");
1038
+ return val;
1039
+ }
1040
+ function decodeJwtSegmentJson(b64u) {
1041
+ const bytes = base64UrlDecodeBytes(b64u, "PERSONAL_BLIND_DIGEST_FORBIDDEN");
1042
+ let text;
1043
+ try {
1044
+ text = strictUtf8Decoder.decode(bytes);
1045
+ } catch {
1046
+ throw new MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "Invalid UTF-8 in JWT segment");
1047
+ }
1048
+ let parsed;
1049
+ try {
1050
+ parsed = JSON.parse(text);
1051
+ } catch {
1052
+ throw new MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "Invalid JSON in JWT segment");
1053
+ }
1054
+ return assertJsonPlainNoProto(parsed);
1055
+ }
1056
+ function decodeAndVerifyPersonalArcblockJwt(params) {
1057
+ const rawBytes = typeof params.unsignedTokenOrBytes === "string" ? utf8Encoder.encode(params.unsignedTokenOrBytes) : params.unsignedTokenOrBytes;
1058
+ if (rawBytes.length === 32) throw new MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "Opaque 32-byte blind digest is forbidden");
1059
+ if (rawBytes.length < 16 || rawBytes.length > MAX_PERSONAL_JWT_UNSIGNED_BYTES) throw new MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", `Unsigned JWT length (${rawBytes.length}B) outside 16..${MAX_PERSONAL_JWT_UNSIGNED_BYTES}`);
1060
+ let unsignedToken;
1061
+ try {
1062
+ unsignedToken = strictUtf8Decoder.decode(rawBytes);
1063
+ } catch {
1064
+ throw new MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "Invalid ASCII/UTF-8 in unsigned JWT");
1065
+ }
1066
+ const parts = unsignedToken.split(".");
1067
+ if (parts.length !== 2 || !parts[0] || !parts[1]) throw new MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "ArcBlock JWT clear-signing requires a 2-part headerB64.bodyB64 token");
1068
+ const canonical = resolveCanonicalPolicyHelper(params.policy);
1069
+ if (canonical && !canonical.allowArcblockJwt) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "ArcBlock JWT signing is disabled by policy (allowArcblockJwt !== true)");
1070
+ const header = decodeJwtSegmentJson(parts[0]);
1071
+ const body = decodeJwtSegmentJson(parts[1]);
1072
+ for (const hk of Object.keys(header)) if (!ALLOWED_JWT_HEADER_KEYS.has(hk)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Forbidden or unknown JWT header key: "${hk}"`);
1073
+ if (header.kid !== void 0) assertPrintableJwtClaimString(header.kid, 128, "header.kid");
1074
+ const alg = header.alg;
1075
+ const isDelegationToken = header.typ === "DelegationToken" && header.type === void 0;
1076
+ const isStandardJwt = header.type === "JWT" && header.typ === void 0;
1077
+ if (!isDelegationToken && !isStandardJwt) throw new MpcProtocolError("PERSONAL_BLIND_DIGEST_FORBIDDEN", "Unsupported JWT header type/typ");
1078
+ if (alg !== "Ethereum" && alg !== "ES256K") throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Unsupported MPC JWT alg: ${String(alg)}`);
1079
+ if (body.version !== "1.1.0") throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "ArcBlock JWT clear-signing requires version \"1.1.0\"");
1080
+ const allowedBodyKeys = isDelegationToken ? ALLOWED_DELEGATION_JWT_BODY_KEYS : ALLOWED_STANDARD_JWT_BODY_KEYS;
1081
+ for (const bk of Object.keys(body)) if (!allowedBodyKeys.has(bk)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Forbidden JWT claim "${bk}" in ${isDelegationToken ? "DelegationToken" : "L0 authentication JWT"}`);
1082
+ const identities = deriveOcapIdentitiesFromChildPoint(params.childPublicKeyComp33);
1083
+ const expectedAddress = alg === "Ethereum" ? identities.ethChecksumAddress : identities.ocapSecp256k1Address;
1084
+ const rawIss = typeof body.iss === "string" ? body.iss : "";
1085
+ if (rawIss.replace(/^did:[a-z0-9]+:/, "") !== expectedAddress) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "JWT iss does not match derived child DID/address");
1086
+ const parseClaimUint = (val, name) => {
1087
+ const s = typeof val === "number" && Number.isSafeInteger(val) ? String(val) : val;
1088
+ if (typeof s !== "string" || !STRICT_DECIMAL_UINT_RE.test(s)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Invalid JWT ${name} timestamp`);
1089
+ const n = BigInt(s);
1090
+ if (n <= 0n || n > MAX_UINT64) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Out-of-range JWT ${name} timestamp`);
1091
+ return n;
1092
+ };
1093
+ const iatSec = parseClaimUint(body.iat, "iat");
1094
+ const expSec = parseClaimUint(body.exp, "exp");
1095
+ const nbfSec = body.nbf !== void 0 ? parseClaimUint(body.nbf, "nbf") : iatSec;
1096
+ if (iatSec + 120n < params.nowSec || iatSec > params.nowSec + 60n) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "JWT iat timestamp outside allowed HSM wall-clock skew [-120s, +60s]");
1097
+ if (nbfSec + 120n < iatSec || nbfSec > expSec || expSec <= iatSec || expSec - iatSec > BigInt(MAX_PERSONAL_JWT_TTL_SECONDS)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `JWT lifetime must satisfy 0 < exp - iat <= ${MAX_PERSONAL_JWT_TTL_SECONDS}s and iat - 120 <= nbf <= exp`);
1098
+ const audSummary = parseOptionalJwtAudience(body.aud);
1099
+ if (body.jti !== void 0) assertPrintableJwtClaimString(body.jti, 128, "jti");
1100
+ if (body.nonce !== void 0) assertPrintableJwtClaimString(body.nonce, 128, "nonce");
1101
+ let requiredTier = "L0";
1102
+ let denyList = [];
1103
+ if (isDelegationToken) {
1104
+ if (!canonical?.allowDelegationTokenByQuorum || !params.hasL2OrL3QuorumProof) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "DelegationToken signing is hard-banned in L0/L1; requires allowDelegationTokenByQuorum=true and L2/L3 quorum");
1105
+ requiredTier = canonical.guardianRoster ? "L3" : "L2";
1106
+ if (typeof body.pk !== "string") throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "DelegationToken missing body.pk");
1107
+ const expectedPkBytes = alg === "Ethereum" ? identities.ethUncompressedPk64 : identities.secp256k1UncompressedPk65;
1108
+ const bodyPkBytes = normalizeHexBytes(body.pk);
1109
+ if (bodyPkBytes.length !== expectedPkBytes.length || !constantTimeEqual(bodyPkBytes, expectedPkBytes)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "DelegationToken body.pk mismatch against child key");
1110
+ if (!Array.isArray(body.ops) || body.ops.length === 0 || body.ops.length > 32) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "DelegationToken body.ops must contain 1..32 scopes");
1111
+ const allowedSet = new Set(canonical.allowedOcapTxTypes ?? []);
1112
+ for (const op of body.ops) {
1113
+ if (typeof op !== "string" || op.includes("*") || !OCAP_TX_TYPE_URL_RE.test(op)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Wildcard or invalid DelegationToken op: ${String(op)}`);
1114
+ if (!allowedSet.has(op) || op === "fg:t:delegate" || op === "fg:t:account_migrate") throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `DelegationToken op "${op}" is not allowlisted`);
1115
+ }
1116
+ if (body.deny !== void 0) {
1117
+ if (!Array.isArray(body.deny) || body.deny.length === 0 || body.deny.length > 32) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "DelegationToken body.deny must contain 1..32 scopes");
1118
+ denyList = body.deny.map((d) => {
1119
+ if (typeof d !== "string" || !/^fg:[a-z0-9_:*]{1,64}$/.test(d)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", `Invalid DelegationToken deny pattern: ${String(d)}`);
1120
+ return d;
1121
+ });
1122
+ }
1123
+ }
1124
+ if (isDelegationToken) {
1125
+ if (typeof body.sub !== "string" || body.sub.length === 0) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "DelegationToken requires a non-empty string body.sub");
1126
+ } else if (body.sub !== void 0 && (typeof body.sub !== "string" || body.sub.length === 0)) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "JWT body.sub must be a non-empty DID/address string");
1127
+ const signingDigest32 = sha3_256(rawBytes);
1128
+ const signingDigestHex = `0x${bytesToHex(signingDigest32)}`;
1129
+ const toTarget = normalizeOcapAddressOrEth(body.sub !== void 0 ? body.sub : rawIss, "JWT.sub", "PERSONAL_POLICY_VIOLATION");
1130
+ if (isDelegationToken && toTarget === expectedAddress) throw new MpcProtocolError("PERSONAL_POLICY_VIOLATION", "DelegationToken self-delegation (sub === iss) is forbidden");
1131
+ const summaryExtras = [];
1132
+ if (!isDelegationToken && body.sub !== void 0) summaryExtras.push(`sub ${toTarget}`);
1133
+ if (audSummary) summaryExtras.push(`aud ${audSummary}`);
1134
+ if (denyList.length > 0) summaryExtras.push(`deny [${denyList.join(", ")}]`);
1135
+ summaryExtras.push(`exp ${expSec.toString(10)}`);
1136
+ const clearSigningPreview = {
1137
+ version: 1,
1138
+ chainId: "arcblock-jwt",
1139
+ fromAddress: expectedAddress,
1140
+ toAddress: toTarget,
1141
+ callKind: "arcblock-jwt",
1142
+ selector: isDelegationToken ? "DelegationToken" : "JWT",
1143
+ payeeOrSpenderAddress: toTarget,
1144
+ assetIdentifier: "none",
1145
+ outflowAmount: "0",
1146
+ maxGasFeeWei: "0",
1147
+ nonce: iatSec.toString(10),
1148
+ signingDigestHex,
1149
+ summaryText: isDelegationToken ? `Delegate [${body.ops.join(", ")}] from ${expectedAddress} to ${toTarget} (${summaryExtras.join(", ")})` : `Authenticate ${expectedAddress} via ArcBlock JWT v1.1.0 (${summaryExtras.join(", ")})`
1150
+ };
1151
+ return {
1152
+ verifiedJwt: {
1153
+ unsignedToken,
1154
+ unsignedPayloadBytes: rawBytes,
1155
+ signingDigest32,
1156
+ signingDigestHex,
1157
+ isDelegationToken,
1158
+ requiredTier,
1159
+ issuerDid: rawIss,
1160
+ subject: toTarget,
1161
+ iatSec,
1162
+ expSec
1163
+ },
1164
+ clearSigningPreview,
1165
+ clearSigningPreviewHash32: computePersonalClearSigningPreviewHash32(clearSigningPreview)
1166
+ };
1167
+ }
1168
+
1169
+ //#endregion
1170
+ export { CborTagValue, decodeAndVerifyPersonalArcblockJwt, decodeAndVerifyPersonalOcapTx, deriveOcapIdentitiesFromChildPoint, estimateOcapExecutionCostUpperBound, resolveRequiredOcapPolicyTier };