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