@outpost-protocol/core 0.1.1 → 0.3.0
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/README.md +3 -1
- package/dist/cert0.d.ts +12 -0
- package/dist/cert0.js +125 -0
- package/dist/contracts.d.ts +256 -0
- package/dist/contracts.js +665 -0
- package/dist/coordinators.d.ts +131 -0
- package/dist/coordinators.js +457 -0
- package/dist/hw.d.ts +243 -0
- package/dist/hw.js +858 -0
- package/dist/hwClient.d.ts +270 -0
- package/dist/hwClient.js +794 -0
- package/dist/hwTransport.d.ts +173 -0
- package/dist/hwTransport.js +431 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +7 -0
- package/dist/wallet.d.ts +43 -4
- package/dist/wallet.js +136 -5
- package/dist/walletStorage.d.ts +128 -0
- package/dist/walletStorage.js +399 -0
- package/dist/wire.d.ts +10 -0
- package/dist/wire.js +31 -0
- package/dist/witnessClient.d.ts +20 -0
- package/package.json +1 -1
package/dist/hw.js
ADDED
|
@@ -0,0 +1,858 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Outpost v2 Hardware-Backed Roaming Pockets (`iOS AppAttest` + `Android KeyMint/StrongBox`).
|
|
3
|
+
*
|
|
4
|
+
* Pure browser / React Native / Cloudflare Worker / Node compatible (`Uint8Array`, zero Node
|
|
5
|
+
* `Buffer` dependencies), byte-for-byte identical to `contracts/user-vault/src/lib.rs` and
|
|
6
|
+
* `crates/outpost-wire/src/hw.rs`.
|
|
7
|
+
*/
|
|
8
|
+
import { p256 } from "@noble/curves/nist.js";
|
|
9
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
10
|
+
import { decodeFramed, encodeFramed } from "./base32.js";
|
|
11
|
+
import { assertBigInt, assertBytesLength, assertU16, assertU32, concatBytes, decodeU16Be, decodeU32Be, decodeU64Be, MAX_U64, verifyEd25519, } from "./digest.js";
|
|
12
|
+
import { bytesToHex, hexToBytes } from "./witnessClient.js";
|
|
13
|
+
import { addressToScValXdr, assertNetworkHint, assertValidWireAddress, decodeWireAddress, encodeWireAddress, normalizeContractHash, strKeyToWireAddress, WIRE_ADDRESS_BYTE_LENGTH, wireAddressToStrKey, } from "./xdr.js";
|
|
14
|
+
const ascii = new TextEncoder();
|
|
15
|
+
export const HRP_SMESHH = "SMESHH";
|
|
16
|
+
export const SMESHH1_WIRE_VERSION = 2;
|
|
17
|
+
export const MAX_SMESHH1_BYTES = 28_000;
|
|
18
|
+
export const HW_KIND_IOS_APP_ATTEST = 1;
|
|
19
|
+
export const HW_KIND_ANDROID_KEYMINT_MERKLE = 2;
|
|
20
|
+
export const MAX_HW_SEQ = 64;
|
|
21
|
+
export const MAX_HW_MERKLE_DEPTH = 6;
|
|
22
|
+
export const MIN_IOS_AUTH_DATA_LEN = 37;
|
|
23
|
+
export const MAX_IOS_AUTH_DATA_LEN = 256;
|
|
24
|
+
export const HW_MIN_EXIT_DELAY_SECS = 259200n; // 72h
|
|
25
|
+
export const HW_MAX_EXIT_DELAY_SECS = 2592000n; // 30d
|
|
26
|
+
export const DOMAIN_TAG_HW_INTENT = ascii.encode("SMW2_HWINTENT");
|
|
27
|
+
export const DOMAIN_TAG_HW_VOID = ascii.encode("SMW2_HWVOID");
|
|
28
|
+
export const DOMAIN_TAG_HW_LEAF = ascii.encode("SMW2_HWLEAF");
|
|
29
|
+
export const DOMAIN_TAG_HW_NODE = ascii.encode("SMW2_HWNODE");
|
|
30
|
+
export const DOMAIN_TAG_HW_EMPTY = ascii.encode("SMW2_HWEMPTY");
|
|
31
|
+
export const DOMAIN_TAG_HW_GENESIS = ascii.encode("SMW2_HWGENESIS");
|
|
32
|
+
export const DOMAIN_TAG_HW_CHAL = ascii.encode("SMW2_HWCHAL");
|
|
33
|
+
function u16be(n) {
|
|
34
|
+
assertU16(n, "u16");
|
|
35
|
+
const out = new Uint8Array(2);
|
|
36
|
+
out[0] = (n >>> 8) & 0xff;
|
|
37
|
+
out[1] = n & 0xff;
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
function u32be(n) {
|
|
41
|
+
assertU32(n, "u32");
|
|
42
|
+
const out = new Uint8Array(4);
|
|
43
|
+
out[0] = (n >>> 24) & 0xff;
|
|
44
|
+
out[1] = (n >>> 16) & 0xff;
|
|
45
|
+
out[2] = (n >>> 8) & 0xff;
|
|
46
|
+
out[3] = n & 0xff;
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
function assertBigIntRange(v, min, max, label) {
|
|
50
|
+
assertBigInt(v, label);
|
|
51
|
+
if (v < min || v > max) {
|
|
52
|
+
throw new RangeError(`${label} out of range [${min}, ${max}]: ${v}`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function u64be(v) {
|
|
56
|
+
assertBigIntRange(v, 0n, MAX_U64, "u64");
|
|
57
|
+
const out = new Uint8Array(8);
|
|
58
|
+
let x = v;
|
|
59
|
+
for (let i = 7; i >= 0; i--) {
|
|
60
|
+
out[i] = Number(x & 0xffn);
|
|
61
|
+
x >>= 8n;
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
function i128be(v) {
|
|
66
|
+
const min = -(1n << 127n);
|
|
67
|
+
const max = (1n << 127n) - 1n;
|
|
68
|
+
assertBigIntRange(v, min, max, "i128");
|
|
69
|
+
let x = v < 0n ? (1n << 128n) + v : v;
|
|
70
|
+
const out = new Uint8Array(16);
|
|
71
|
+
for (let i = 15; i >= 0; i--) {
|
|
72
|
+
out[i] = Number(x & 0xffn);
|
|
73
|
+
x >>= 8n;
|
|
74
|
+
}
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
function bytesEqual(a, b) {
|
|
78
|
+
if (a.length !== b.length)
|
|
79
|
+
return false;
|
|
80
|
+
let diff = 0;
|
|
81
|
+
for (let i = 0; i < a.length; i++)
|
|
82
|
+
diff |= a[i] ^ b[i];
|
|
83
|
+
return diff === 0;
|
|
84
|
+
}
|
|
85
|
+
function isAllZero(bytes) {
|
|
86
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
87
|
+
if (bytes[i] !== 0)
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
return true;
|
|
91
|
+
}
|
|
92
|
+
// ---------------------------------------------------------------------------
|
|
93
|
+
// Merkle Tree Helpers (Android KeyMint / StrongBox Single-Use Key Batches)
|
|
94
|
+
// ---------------------------------------------------------------------------
|
|
95
|
+
/** Exact binary tree depth for `maxSeq` (`1..=64`), matching `UserVault::merkle_depth_for`. */
|
|
96
|
+
export function hwMerkleDepthFor(maxSeq) {
|
|
97
|
+
if (!Number.isInteger(maxSeq) || maxSeq < 1 || maxSeq > MAX_HW_SEQ) {
|
|
98
|
+
throw new RangeError(`maxSeq must be in 1..=${MAX_HW_SEQ}, got ${maxSeq}`);
|
|
99
|
+
}
|
|
100
|
+
if (maxSeq === 1)
|
|
101
|
+
return 0;
|
|
102
|
+
return 32 - Math.clz32(maxSeq - 1);
|
|
103
|
+
}
|
|
104
|
+
/** Canonical Android KeyMint single-use key leaf digest for `seq` (`1..=maxSeq`). */
|
|
105
|
+
export function hwMerkleLeaf(seq, pubkey65) {
|
|
106
|
+
assertU32(seq, "seq");
|
|
107
|
+
assertBytesLength(pubkey65, 65, "pubkey65");
|
|
108
|
+
return sha256(concatBytes(DOMAIN_TAG_HW_LEAF, u32be(seq), pubkey65));
|
|
109
|
+
}
|
|
110
|
+
/** Domain-separated internal Merkle node digest. */
|
|
111
|
+
export function hwMerkleNode(left, right) {
|
|
112
|
+
assertBytesLength(left, 32, "left");
|
|
113
|
+
assertBytesLength(right, 32, "right");
|
|
114
|
+
return sha256(concatBytes(DOMAIN_TAG_HW_NODE, left, right));
|
|
115
|
+
}
|
|
116
|
+
/** Canonical padding leaf for non-power-of-two Android KeyMint key batches. */
|
|
117
|
+
export function hwMerkleEmptyLeaf() {
|
|
118
|
+
return sha256(DOMAIN_TAG_HW_EMPTY);
|
|
119
|
+
}
|
|
120
|
+
/** Builds the canonical Android KeyMint Merkle root and per-leaf inclusion proofs. */
|
|
121
|
+
export function hwMerkleBuildTree(pubkeys65) {
|
|
122
|
+
const n = pubkeys65.length;
|
|
123
|
+
if (n < 1 || n > MAX_HW_SEQ) {
|
|
124
|
+
throw new RangeError(`hw pubkey count must be in 1..=${MAX_HW_SEQ}, got ${n}`);
|
|
125
|
+
}
|
|
126
|
+
for (let i = 0; i < n; i++) {
|
|
127
|
+
const pk = pubkeys65[i];
|
|
128
|
+
assertBytesLength(pk, 65, `pubkeys65[${i}]`);
|
|
129
|
+
if (pk[0] !== 0x04) {
|
|
130
|
+
throw new Error(`pubkeys65[${i}] must be uncompressed SEC1 (0x04 prefix)`);
|
|
131
|
+
}
|
|
132
|
+
// Validate point is actually on secp256r1 curve.
|
|
133
|
+
p256.Point.fromBytes(pk);
|
|
134
|
+
}
|
|
135
|
+
const depth = hwMerkleDepthFor(n);
|
|
136
|
+
const width = 1 << depth;
|
|
137
|
+
const emptyLeaf = hwMerkleEmptyLeaf();
|
|
138
|
+
let level = [];
|
|
139
|
+
for (let i = 0; i < width; i++) {
|
|
140
|
+
level.push(i < n ? hwMerkleLeaf(i + 1, pubkeys65[i]) : emptyLeaf);
|
|
141
|
+
}
|
|
142
|
+
const levels = [level];
|
|
143
|
+
for (let lv = 0; lv < depth; lv++) {
|
|
144
|
+
const next = [];
|
|
145
|
+
for (let i = 0; i < level.length; i += 2) {
|
|
146
|
+
next.push(hwMerkleNode(level[i], level[i + 1]));
|
|
147
|
+
}
|
|
148
|
+
level = next;
|
|
149
|
+
levels.push(level);
|
|
150
|
+
}
|
|
151
|
+
const root = levels[depth][0];
|
|
152
|
+
const proofs = [];
|
|
153
|
+
for (let idx = 0; idx < n; idx++) {
|
|
154
|
+
const proof = [];
|
|
155
|
+
let cur = idx;
|
|
156
|
+
for (let lv = 0; lv < depth; lv++) {
|
|
157
|
+
proof.push(levels[lv][cur ^ 1]);
|
|
158
|
+
cur >>>= 1;
|
|
159
|
+
}
|
|
160
|
+
proofs.push(proof);
|
|
161
|
+
}
|
|
162
|
+
return { root, depth, proofs };
|
|
163
|
+
}
|
|
164
|
+
/** Verifies an Android KeyMint Merkle inclusion proof for `(seq, leafPubkey65)` against `expectedRoot`. */
|
|
165
|
+
export function hwMerkleVerifyProof(expectedRoot, maxSeq, seq, leafPubkey65, merkleProof) {
|
|
166
|
+
try {
|
|
167
|
+
assertBytesLength(expectedRoot, 32, "expectedRoot");
|
|
168
|
+
if (!Number.isInteger(maxSeq) || maxSeq < 1 || maxSeq > MAX_HW_SEQ)
|
|
169
|
+
return false;
|
|
170
|
+
if (!Number.isInteger(seq) || seq < 1 || seq > maxSeq)
|
|
171
|
+
return false;
|
|
172
|
+
if (leafPubkey65.length !== 65 || leafPubkey65[0] !== 0x04)
|
|
173
|
+
return false;
|
|
174
|
+
const depth = hwMerkleDepthFor(maxSeq);
|
|
175
|
+
if (depth > MAX_HW_MERKLE_DEPTH || merkleProof.length !== depth)
|
|
176
|
+
return false;
|
|
177
|
+
let cur = hwMerkleLeaf(seq, leafPubkey65);
|
|
178
|
+
const leafIndex = seq - 1;
|
|
179
|
+
for (let lv = 0; lv < depth; lv++) {
|
|
180
|
+
const sibling = merkleProof[lv];
|
|
181
|
+
if (sibling.length !== 32)
|
|
182
|
+
return false;
|
|
183
|
+
cur = ((leafIndex >>> lv) & 1) === 1 ? hwMerkleNode(sibling, cur) : hwMerkleNode(cur, sibling);
|
|
184
|
+
}
|
|
185
|
+
return bytesEqual(cur, expectedRoot);
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
return false;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
// ---------------------------------------------------------------------------
|
|
192
|
+
// ECDSA secp256r1 (P-256) Low-S Normalization & Strict Verification
|
|
193
|
+
// ---------------------------------------------------------------------------
|
|
194
|
+
/**
|
|
195
|
+
* Converts an ASN.1 DER ECDSA P-256 signature (as emitted by Apple `DCAppAttestService` and
|
|
196
|
+
* Android `Signature("SHA256withECDSA")`) into canonical 64-byte low-S `(r || s)` required by
|
|
197
|
+
* Stellar Soroban `CAP-0051` (`secp256r1_verify`).
|
|
198
|
+
*/
|
|
199
|
+
export function normalizeP256DerToLowS64(der) {
|
|
200
|
+
const parsed = p256.Signature.fromBytes(der, "der");
|
|
201
|
+
const normalized = parsed.hasHighS()
|
|
202
|
+
? new p256.Signature(parsed.r, p256.Point.Fn.ORDER - parsed.s)
|
|
203
|
+
: parsed;
|
|
204
|
+
return normalized.toBytes("compact");
|
|
205
|
+
}
|
|
206
|
+
/** Checks that `pubkey65` is a valid 65-byte uncompressed SEC1 point on `secp256r1` (`0x04 || x || y`). */
|
|
207
|
+
export function isValidP256UncompressedPubkey(pubkey65) {
|
|
208
|
+
if (!(pubkey65 instanceof Uint8Array) || pubkey65.length !== 65 || pubkey65[0] !== 0x04) {
|
|
209
|
+
return false;
|
|
210
|
+
}
|
|
211
|
+
try {
|
|
212
|
+
p256.Point.fromBytes(pubkey65);
|
|
213
|
+
return true;
|
|
214
|
+
}
|
|
215
|
+
catch {
|
|
216
|
+
return false;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Strictly verifies a 64-byte **low-S** ECDSA P-256 signature over a 32-byte prehashed digest,
|
|
221
|
+
* mirroring Stellar Soroban `CAP-0051` (`secp256r1_verify`, rejecting high-S malleability).
|
|
222
|
+
*/
|
|
223
|
+
export function verifyP256PrehashLowS(pubkey65, digest32, sig64) {
|
|
224
|
+
if (pubkey65.length !== 65 || pubkey65[0] !== 0x04)
|
|
225
|
+
return false;
|
|
226
|
+
if (digest32.length !== 32 || sig64.length !== 64)
|
|
227
|
+
return false;
|
|
228
|
+
try {
|
|
229
|
+
return p256.verify(sig64, digest32, pubkey65, { prehash: false, lowS: true });
|
|
230
|
+
}
|
|
231
|
+
catch {
|
|
232
|
+
return false;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
function parseContractOrHex32(val, label) {
|
|
236
|
+
if (val instanceof Uint8Array) {
|
|
237
|
+
assertBytesLength(val, 32, label);
|
|
238
|
+
return new Uint8Array(val);
|
|
239
|
+
}
|
|
240
|
+
const clean = val.trim();
|
|
241
|
+
if (/^(0x)?[0-9a-fA-F]{64}$/.test(clean)) {
|
|
242
|
+
return hexToBytes(clean);
|
|
243
|
+
}
|
|
244
|
+
return normalizeContractHash(clean);
|
|
245
|
+
}
|
|
246
|
+
/** Computes `"SMW2_HWINTENT"` 32-byte digest matching `UserVault::compute_hw_intent_digest`. */
|
|
247
|
+
export function computeHwIntentDigest(params) {
|
|
248
|
+
assertBytesLength(params.networkId, 32, "networkId");
|
|
249
|
+
const vaultBytes = parseContractOrHex32(params.vaultId, "vaultId");
|
|
250
|
+
const tokenBytes = parseContractOrHex32(params.tokenId, "tokenId");
|
|
251
|
+
const tokenXdr = addressToScValXdr({ type: "contract", raw: tokenBytes });
|
|
252
|
+
const toAddr = typeof params.to === "string" ? strKeyToWireAddress(params.to) : params.to;
|
|
253
|
+
const toXdr = addressToScValXdr(toAddr);
|
|
254
|
+
return sha256(concatBytes(DOMAIN_TAG_HW_INTENT, params.networkId, vaultBytes, u16be(params.pocketId), u32be(params.epoch), u32be(params.seq), tokenXdr, toXdr, i128be(params.amount), i128be(params.maxTip), i128be(params.cumulativeSpent), u64be(params.expiryTs), u32be(params.expiryLedger), u64be(params.orderId)));
|
|
255
|
+
}
|
|
256
|
+
/** Computes `"SMW2_HWVOID"` 32-byte digest matching `UserVault::compute_hw_void_digest`. */
|
|
257
|
+
export function computeHwVoidDigest(params) {
|
|
258
|
+
assertBytesLength(params.networkId, 32, "networkId");
|
|
259
|
+
const vaultBytes = parseContractOrHex32(params.vaultId, "vaultId");
|
|
260
|
+
return sha256(concatBytes(DOMAIN_TAG_HW_VOID, params.networkId, vaultBytes, u16be(params.pocketId), u32be(params.epoch), u32be(params.seq)));
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Computes canonical `"SMW2_HWCHAL"` 32-byte attestation challenge bound to
|
|
264
|
+
* `(networkId, vaultId, pocketId, epoch, seq)`.
|
|
265
|
+
* - iOS `DCAppAttestService.attestKey(keyId, clientDataHash)`: pass `seq = 0`.
|
|
266
|
+
* - Android `KeyGenParameterSpec.setAttestationChallenge(challenge)`: pass `seq = 1..=maxSeq`.
|
|
267
|
+
*/
|
|
268
|
+
export function computeHwAttestationChallenge(params) {
|
|
269
|
+
assertBytesLength(params.networkId, 32, "networkId");
|
|
270
|
+
const vaultBytes = parseContractOrHex32(params.vaultId, "vaultId");
|
|
271
|
+
return sha256(concatBytes(DOMAIN_TAG_HW_CHAL, params.networkId, vaultBytes, u16be(params.pocketId), u32be(params.epoch), u32be(params.seq)));
|
|
272
|
+
}
|
|
273
|
+
export function hwProofToDto(proof) {
|
|
274
|
+
if (proof.kind === "ios_app_attest") {
|
|
275
|
+
return {
|
|
276
|
+
kind: "ios_app_attest",
|
|
277
|
+
auth_data: bytesToHex(proof.authData),
|
|
278
|
+
sig_64: bytesToHex(proof.sig64),
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
return {
|
|
282
|
+
kind: "android_keymint_merkle",
|
|
283
|
+
leaf_pubkey_65: bytesToHex(proof.leafPubkey65),
|
|
284
|
+
merkle_proof: proof.merkleProof.map(bytesToHex),
|
|
285
|
+
sig_64: bytesToHex(proof.sig64),
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
export function hwProofFromDto(dto) {
|
|
289
|
+
if (dto.kind === "ios_app_attest") {
|
|
290
|
+
const authData = hexToBytes(dto.auth_data);
|
|
291
|
+
if (authData.length < MIN_IOS_AUTH_DATA_LEN || authData.length > MAX_IOS_AUTH_DATA_LEN) {
|
|
292
|
+
throw new Error(`Invalid iOS auth_data length: ${authData.length}`);
|
|
293
|
+
}
|
|
294
|
+
const sig64 = hexToBytes(dto.sig_64);
|
|
295
|
+
assertBytesLength(sig64, 64, "sig_64");
|
|
296
|
+
return { kind: "ios_app_attest", authData, sig64 };
|
|
297
|
+
}
|
|
298
|
+
if (dto.kind === "android_keymint_merkle") {
|
|
299
|
+
const leafPubkey65 = hexToBytes(dto.leaf_pubkey_65);
|
|
300
|
+
assertBytesLength(leafPubkey65, 65, "leaf_pubkey_65");
|
|
301
|
+
if (leafPubkey65[0] !== 0x04) {
|
|
302
|
+
throw new Error("leaf_pubkey_65 must start with 0x04");
|
|
303
|
+
}
|
|
304
|
+
if (!Array.isArray(dto.merkle_proof) || dto.merkle_proof.length > MAX_HW_MERKLE_DEPTH) {
|
|
305
|
+
throw new Error("Invalid merkle_proof array");
|
|
306
|
+
}
|
|
307
|
+
const merkleProof = dto.merkle_proof.map((h, i) => {
|
|
308
|
+
const b = hexToBytes(h);
|
|
309
|
+
assertBytesLength(b, 32, `merkle_proof[${i}]`);
|
|
310
|
+
return b;
|
|
311
|
+
});
|
|
312
|
+
const sig64 = hexToBytes(dto.sig_64);
|
|
313
|
+
assertBytesLength(sig64, 64, "sig_64");
|
|
314
|
+
return { kind: "android_keymint_merkle", leafPubkey65, merkleProof, sig64 };
|
|
315
|
+
}
|
|
316
|
+
throw new Error(`Unknown hw_proof kind`);
|
|
317
|
+
}
|
|
318
|
+
/** Verifies an Apple Secure Enclave `DCAppAttestService` assertion proof. */
|
|
319
|
+
export function verifyIosAppAttestProof(params) {
|
|
320
|
+
if (params.authData.length < MIN_IOS_AUTH_DATA_LEN ||
|
|
321
|
+
params.authData.length > MAX_IOS_AUTH_DATA_LEN) {
|
|
322
|
+
return false;
|
|
323
|
+
}
|
|
324
|
+
if (params.expectedAppIdHash.length !== 32 || params.clientDataHash.length !== 32) {
|
|
325
|
+
return false;
|
|
326
|
+
}
|
|
327
|
+
if (!bytesEqual(params.authData.subarray(0, 32), params.expectedAppIdHash)) {
|
|
328
|
+
return false;
|
|
329
|
+
}
|
|
330
|
+
const signCount = ((params.authData[33] << 24) |
|
|
331
|
+
(params.authData[34] << 16) |
|
|
332
|
+
(params.authData[35] << 8) |
|
|
333
|
+
params.authData[36]) >>>
|
|
334
|
+
0;
|
|
335
|
+
if (signCount !== params.expectedSeq) {
|
|
336
|
+
return false;
|
|
337
|
+
}
|
|
338
|
+
const nonce = sha256(concatBytes(params.authData, params.clientDataHash));
|
|
339
|
+
const ecdsaDigest = sha256(nonce);
|
|
340
|
+
return verifyP256PrehashLowS(params.pubkey65, ecdsaDigest, params.sig64);
|
|
341
|
+
}
|
|
342
|
+
/** Verifies an Android KeyMint / StrongBox single-use key proof against `expectedMerkleRoot`. */
|
|
343
|
+
export function verifyAndroidKeyMintProof(params) {
|
|
344
|
+
if (params.clientDataHash.length !== 32)
|
|
345
|
+
return false;
|
|
346
|
+
if (!hwMerkleVerifyProof(params.expectedMerkleRoot, params.maxSeq, params.expectedSeq, params.leafPubkey65, params.merkleProof)) {
|
|
347
|
+
return false;
|
|
348
|
+
}
|
|
349
|
+
const ecdsaDigest = sha256(params.clientDataHash);
|
|
350
|
+
return verifyP256PrehashLowS(params.leafPubkey65, ecdsaDigest, params.sig64);
|
|
351
|
+
}
|
|
352
|
+
export function hwGenesisCertToDto(cert) {
|
|
353
|
+
return {
|
|
354
|
+
factory_ver: cert.factoryVer,
|
|
355
|
+
owner: wireAddressToStrKey(cert.owner),
|
|
356
|
+
vault_id: bytesToHex(cert.vaultId),
|
|
357
|
+
pocket_id: cert.pocketId,
|
|
358
|
+
epoch: cert.epoch,
|
|
359
|
+
token_id: bytesToHex(cert.tokenId),
|
|
360
|
+
epoch_total_deposited: cert.epochTotalDeposited.toString(),
|
|
361
|
+
hw_kind: cert.hwKind,
|
|
362
|
+
max_seq: cert.maxSeq,
|
|
363
|
+
hw_anchor: bytesToHex(cert.hwAnchor),
|
|
364
|
+
app_id_hash: bytesToHex(cert.appIdHash),
|
|
365
|
+
attestation_digest: bytesToHex(cert.attestationDigest),
|
|
366
|
+
exit_delay_secs: cert.exitDelaySecs.toString(),
|
|
367
|
+
synced_at_ts: cert.syncedAtTs.toString(),
|
|
368
|
+
synced_ledger_seq: cert.syncedLedgerSeq,
|
|
369
|
+
verifier_sig: bytesToHex(cert.verifierSig),
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
export function hwGenesisCertFromDto(dto) {
|
|
373
|
+
if (!Number.isInteger(dto.factory_ver) || dto.factory_ver < 1 || dto.factory_ver > 15) {
|
|
374
|
+
throw new Error(`Invalid factory_ver: ${dto.factory_ver}`);
|
|
375
|
+
}
|
|
376
|
+
if (dto.hw_kind !== HW_KIND_IOS_APP_ATTEST && dto.hw_kind !== HW_KIND_ANDROID_KEYMINT_MERKLE) {
|
|
377
|
+
throw new Error(`Invalid hw_kind: ${dto.hw_kind}`);
|
|
378
|
+
}
|
|
379
|
+
return {
|
|
380
|
+
factoryVer: dto.factory_ver,
|
|
381
|
+
owner: strKeyToWireAddress(dto.owner),
|
|
382
|
+
vaultId: parseContractOrHex32(dto.vault_id, "vault_id"),
|
|
383
|
+
pocketId: dto.pocket_id,
|
|
384
|
+
epoch: dto.epoch,
|
|
385
|
+
tokenId: parseContractOrHex32(dto.token_id, "token_id"),
|
|
386
|
+
epochTotalDeposited: BigInt(dto.epoch_total_deposited),
|
|
387
|
+
hwKind: dto.hw_kind,
|
|
388
|
+
maxSeq: dto.max_seq,
|
|
389
|
+
hwAnchor: hexToBytes(dto.hw_anchor),
|
|
390
|
+
appIdHash: (() => {
|
|
391
|
+
const b = hexToBytes(dto.app_id_hash);
|
|
392
|
+
assertBytesLength(b, 32, "app_id_hash");
|
|
393
|
+
return b;
|
|
394
|
+
})(),
|
|
395
|
+
attestationDigest: (() => {
|
|
396
|
+
const b = hexToBytes(dto.attestation_digest);
|
|
397
|
+
assertBytesLength(b, 32, "attestation_digest");
|
|
398
|
+
return b;
|
|
399
|
+
})(),
|
|
400
|
+
exitDelaySecs: BigInt(dto.exit_delay_secs),
|
|
401
|
+
syncedAtTs: BigInt(dto.synced_at_ts),
|
|
402
|
+
syncedLedgerSeq: dto.synced_ledger_seq,
|
|
403
|
+
verifierSig: (() => {
|
|
404
|
+
const b = hexToBytes(dto.verifier_sig);
|
|
405
|
+
assertBytesLength(b, 64, "verifier_sig");
|
|
406
|
+
return b;
|
|
407
|
+
})(),
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
/** Computes canonical `"SMW2_HWGENESIS"` 32-byte digest matching `crates/outpost-wire/src/hw.rs`. */
|
|
411
|
+
export function computeHwGenesisDigest(networkId, cert) {
|
|
412
|
+
assertBytesLength(networkId, 32, "networkId");
|
|
413
|
+
const ownerXdr = addressToScValXdr(cert.owner);
|
|
414
|
+
const tokenXdr = addressToScValXdr({ type: "contract", raw: cert.tokenId });
|
|
415
|
+
return sha256(concatBytes(DOMAIN_TAG_HW_GENESIS, networkId, new Uint8Array([cert.factoryVer]), ownerXdr, cert.vaultId, u16be(cert.pocketId), u32be(cert.epoch), tokenXdr, i128be(cert.epochTotalDeposited), u32be(cert.hwKind), u32be(cert.maxSeq), u32be(cert.hwAnchor.length), cert.hwAnchor, cert.appIdHash, cert.attestationDigest, u64be(cert.exitDelaySecs), u64be(cert.syncedAtTs), u32be(cert.syncedLedgerSeq)));
|
|
416
|
+
}
|
|
417
|
+
export function hwPaymentEntryToDto(entry) {
|
|
418
|
+
return {
|
|
419
|
+
seq: entry.seq,
|
|
420
|
+
to: wireAddressToStrKey(entry.to),
|
|
421
|
+
amount: entry.amount.toString(),
|
|
422
|
+
max_tip: entry.maxTip.toString(),
|
|
423
|
+
cumulative_spent: entry.cumulativeSpent.toString(),
|
|
424
|
+
expiry_ts: entry.expiryTs.toString(),
|
|
425
|
+
expiry_ledger: entry.expiryLedger,
|
|
426
|
+
order_id: entry.orderId.toString(),
|
|
427
|
+
hw_proof: hwProofToDto(entry.hwProof),
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
export function hwPaymentEntryFromDto(dto) {
|
|
431
|
+
return {
|
|
432
|
+
seq: dto.seq,
|
|
433
|
+
to: strKeyToWireAddress(dto.to),
|
|
434
|
+
amount: BigInt(dto.amount),
|
|
435
|
+
maxTip: BigInt(dto.max_tip),
|
|
436
|
+
cumulativeSpent: BigInt(dto.cumulative_spent),
|
|
437
|
+
expiryTs: BigInt(dto.expiry_ts),
|
|
438
|
+
expiryLedger: dto.expiry_ledger,
|
|
439
|
+
orderId: BigInt(dto.order_id),
|
|
440
|
+
hwProof: hwProofFromDto(dto.hw_proof),
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
/**
|
|
444
|
+
* Verifies an unbroken contiguous offline Hardware Roaming Pocket spend chain `[1..=k]` with
|
|
445
|
+
* **zero internet** and **zero fixed nearby Stations**. Mirrors `crates/outpost-wire::verify_hw_spend_chain`.
|
|
446
|
+
*
|
|
447
|
+
* Returns the verified `cumulativeSpent` (`bigint`) on success, or throws on any violation.
|
|
448
|
+
*/
|
|
449
|
+
export function verifyHwSpendChain(params) {
|
|
450
|
+
const { networkId, trustedVerifierPubkey, cert, entries, localNowTs, exitMarginSecs } = params;
|
|
451
|
+
assertBytesLength(networkId, 32, "networkId");
|
|
452
|
+
assertBytesLength(trustedVerifierPubkey, 32, "trustedVerifierPubkey");
|
|
453
|
+
if (cert.epochTotalDeposited <= 0n || cert.epochTotalDeposited > MAX_U64) {
|
|
454
|
+
throw new Error("epochTotalDeposited out of range");
|
|
455
|
+
}
|
|
456
|
+
if (!Number.isInteger(cert.maxSeq) || cert.maxSeq < 1 || cert.maxSeq > MAX_HW_SEQ) {
|
|
457
|
+
throw new Error("maxSeq out of range");
|
|
458
|
+
}
|
|
459
|
+
if (cert.exitDelaySecs < HW_MIN_EXIT_DELAY_SECS || cert.exitDelaySecs > HW_MAX_EXIT_DELAY_SECS) {
|
|
460
|
+
throw new Error("exitDelaySecs out of range");
|
|
461
|
+
}
|
|
462
|
+
if (entries.length < 1 || entries.length > cert.maxSeq) {
|
|
463
|
+
throw new Error("hw spend chain length must be in 1..=maxSeq");
|
|
464
|
+
}
|
|
465
|
+
// 1. Verify Outpost Attestation Verifier Ed25519 signature over HwGenesisCert (strict RFC 8032).
|
|
466
|
+
const gDigest = computeHwGenesisDigest(networkId, cert);
|
|
467
|
+
if (!verifyEd25519(cert.verifierSig, gDigest, trustedVerifierPubkey)) {
|
|
468
|
+
throw new Error("Invalid HwGenesisCert verifier signature");
|
|
469
|
+
}
|
|
470
|
+
const safeExitHorizon = cert.syncedAtTs + cert.exitDelaySecs - exitMarginSecs;
|
|
471
|
+
if (safeExitHorizon <= 0n) {
|
|
472
|
+
throw new Error("Invalid exit horizon");
|
|
473
|
+
}
|
|
474
|
+
// 2. Validate hw_anchor format.
|
|
475
|
+
if (cert.hwKind === HW_KIND_IOS_APP_ATTEST) {
|
|
476
|
+
if (cert.hwAnchor.length !== 65 || cert.hwAnchor[0] !== 0x04 || isAllZero(cert.appIdHash)) {
|
|
477
|
+
throw new Error("Invalid iOS hwAnchor or appIdHash");
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
else if (cert.hwKind === HW_KIND_ANDROID_KEYMINT_MERKLE) {
|
|
481
|
+
if (cert.hwAnchor.length !== 32 || isAllZero(cert.hwAnchor)) {
|
|
482
|
+
throw new Error("Invalid Android hwAnchor Merkle root");
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
else {
|
|
486
|
+
throw new Error(`Unknown hwKind: ${String(cert.hwKind)}`);
|
|
487
|
+
}
|
|
488
|
+
// 3. Walk unbroken contiguous sequence 1..=k and verify every hardware signature & balance delta.
|
|
489
|
+
let runningCum = 0n;
|
|
490
|
+
for (let idx = 0; idx < entries.length; idx++) {
|
|
491
|
+
const entry = entries[idx];
|
|
492
|
+
const expectedSeq = idx + 1;
|
|
493
|
+
if (entry.seq !== expectedSeq) {
|
|
494
|
+
throw new Error(`hw spend chain gap: expected seq ${expectedSeq}, got ${entry.seq}`);
|
|
495
|
+
}
|
|
496
|
+
if (entry.amount <= 0n || entry.maxTip < 0n) {
|
|
497
|
+
throw new Error("Invalid payment amount or maxTip");
|
|
498
|
+
}
|
|
499
|
+
const worstCase = entry.amount + entry.maxTip;
|
|
500
|
+
runningCum += worstCase;
|
|
501
|
+
if (entry.cumulativeSpent !== runningCum || runningCum > cert.epochTotalDeposited) {
|
|
502
|
+
throw new Error("cumulativeSpent mismatch or exceeds pocket deposit");
|
|
503
|
+
}
|
|
504
|
+
if (entry.expiryTs > safeExitHorizon) {
|
|
505
|
+
throw new Error("Intent expiry exceeds safe exit delay horizon");
|
|
506
|
+
}
|
|
507
|
+
if (idx + 1 === entries.length && entry.expiryTs <= localNowTs) {
|
|
508
|
+
throw new Error("Active payment intent is expired");
|
|
509
|
+
}
|
|
510
|
+
const digest = computeHwIntentDigest({
|
|
511
|
+
networkId,
|
|
512
|
+
vaultId: cert.vaultId,
|
|
513
|
+
pocketId: cert.pocketId,
|
|
514
|
+
epoch: cert.epoch,
|
|
515
|
+
seq: entry.seq,
|
|
516
|
+
tokenId: cert.tokenId,
|
|
517
|
+
to: entry.to,
|
|
518
|
+
amount: entry.amount,
|
|
519
|
+
maxTip: entry.maxTip,
|
|
520
|
+
cumulativeSpent: entry.cumulativeSpent,
|
|
521
|
+
expiryTs: entry.expiryTs,
|
|
522
|
+
expiryLedger: entry.expiryLedger,
|
|
523
|
+
orderId: entry.orderId,
|
|
524
|
+
});
|
|
525
|
+
if (cert.hwKind === HW_KIND_IOS_APP_ATTEST && entry.hwProof.kind === "ios_app_attest") {
|
|
526
|
+
if (!verifyIosAppAttestProof({
|
|
527
|
+
pubkey65: cert.hwAnchor,
|
|
528
|
+
expectedAppIdHash: cert.appIdHash,
|
|
529
|
+
expectedSeq,
|
|
530
|
+
clientDataHash: digest,
|
|
531
|
+
authData: entry.hwProof.authData,
|
|
532
|
+
sig64: entry.hwProof.sig64,
|
|
533
|
+
})) {
|
|
534
|
+
throw new Error(`Invalid iOS AppAttest proof at seq ${expectedSeq}`);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
else if (cert.hwKind === HW_KIND_ANDROID_KEYMINT_MERKLE &&
|
|
538
|
+
entry.hwProof.kind === "android_keymint_merkle") {
|
|
539
|
+
if (!verifyAndroidKeyMintProof({
|
|
540
|
+
expectedMerkleRoot: cert.hwAnchor,
|
|
541
|
+
maxSeq: cert.maxSeq,
|
|
542
|
+
expectedSeq,
|
|
543
|
+
clientDataHash: digest,
|
|
544
|
+
leafPubkey65: entry.hwProof.leafPubkey65,
|
|
545
|
+
merkleProof: entry.hwProof.merkleProof,
|
|
546
|
+
sig64: entry.hwProof.sig64,
|
|
547
|
+
})) {
|
|
548
|
+
throw new Error(`Invalid Android KeyMint Merkle proof at seq ${expectedSeq}`);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
else {
|
|
552
|
+
throw new Error(`Hardware proof kind mismatch at seq ${expectedSeq}`);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
return runningCum;
|
|
556
|
+
}
|
|
557
|
+
/** Encodes a `Smeshh1Packet` into canonical raw binary bytes (<= `MAX_SMESHH1_BYTES`). */
|
|
558
|
+
export function encodeSmeshh1Bytes(packet) {
|
|
559
|
+
assertNetworkHint(packet.networkHint);
|
|
560
|
+
const { cert, entries } = packet;
|
|
561
|
+
if (!Number.isInteger(cert.factoryVer) || cert.factoryVer < 1 || cert.factoryVer > 15) {
|
|
562
|
+
throw new Error(`Invalid SMESHH1 factoryVer: ${cert.factoryVer}`);
|
|
563
|
+
}
|
|
564
|
+
assertValidWireAddress(cert.owner);
|
|
565
|
+
assertBytesLength(cert.vaultId, 32, "cert.vaultId");
|
|
566
|
+
assertU16(cert.pocketId, "cert.pocketId");
|
|
567
|
+
assertU32(cert.epoch, "cert.epoch");
|
|
568
|
+
if (cert.epoch < 1) {
|
|
569
|
+
throw new Error(`SMESHH1 epoch must be >= 1, got ${cert.epoch}`);
|
|
570
|
+
}
|
|
571
|
+
assertBytesLength(cert.tokenId, 32, "cert.tokenId");
|
|
572
|
+
assertBigIntRange(cert.epochTotalDeposited, 1n, MAX_U64, "cert.epochTotalDeposited");
|
|
573
|
+
if (!Number.isInteger(cert.maxSeq) || cert.maxSeq < 1 || cert.maxSeq > MAX_HW_SEQ) {
|
|
574
|
+
throw new Error(`SMESHH1 maxSeq out of range: ${cert.maxSeq}`);
|
|
575
|
+
}
|
|
576
|
+
const expectedAnchorLen = cert.hwKind === HW_KIND_IOS_APP_ATTEST
|
|
577
|
+
? 65
|
|
578
|
+
: cert.hwKind === HW_KIND_ANDROID_KEYMINT_MERKLE
|
|
579
|
+
? 32
|
|
580
|
+
: -1;
|
|
581
|
+
if (expectedAnchorLen < 0) {
|
|
582
|
+
throw new Error(`Unknown SMESHH1 hwKind: ${String(cert.hwKind)}`);
|
|
583
|
+
}
|
|
584
|
+
if (cert.hwAnchor.length !== expectedAnchorLen) {
|
|
585
|
+
throw new Error(`SMESHH1 hwAnchor length mismatch: expected ${expectedAnchorLen}, got ${cert.hwAnchor.length}`);
|
|
586
|
+
}
|
|
587
|
+
if (cert.hwKind === HW_KIND_IOS_APP_ATTEST && cert.hwAnchor[0] !== 0x04) {
|
|
588
|
+
throw new Error("SMESHH1 iOS hwAnchor must start with 0x04");
|
|
589
|
+
}
|
|
590
|
+
assertBytesLength(cert.appIdHash, 32, "cert.appIdHash");
|
|
591
|
+
assertBytesLength(cert.attestationDigest, 32, "cert.attestationDigest");
|
|
592
|
+
assertBigIntRange(cert.exitDelaySecs, HW_MIN_EXIT_DELAY_SECS, HW_MAX_EXIT_DELAY_SECS, "cert.exitDelaySecs");
|
|
593
|
+
assertBigIntRange(cert.syncedAtTs, 0n, MAX_U64, "cert.syncedAtTs");
|
|
594
|
+
assertU32(cert.syncedLedgerSeq, "cert.syncedLedgerSeq");
|
|
595
|
+
assertBytesLength(cert.verifierSig, 64, "cert.verifierSig");
|
|
596
|
+
if (entries.length < 1 || entries.length > cert.maxSeq) {
|
|
597
|
+
throw new Error(`SMESHH1 entries length (${entries.length}) must be in 1..=${cert.maxSeq}`);
|
|
598
|
+
}
|
|
599
|
+
const expectedDepth = cert.hwKind === HW_KIND_ANDROID_KEYMINT_MERKLE ? hwMerkleDepthFor(cert.maxSeq) : 0;
|
|
600
|
+
const flags = (SMESHH1_WIRE_VERSION << 4) | (packet.networkHint & 0x03);
|
|
601
|
+
const parts = [
|
|
602
|
+
new Uint8Array([flags, cert.factoryVer]),
|
|
603
|
+
encodeWireAddress(cert.owner),
|
|
604
|
+
cert.vaultId,
|
|
605
|
+
u16be(cert.pocketId),
|
|
606
|
+
u32be(cert.epoch),
|
|
607
|
+
cert.tokenId,
|
|
608
|
+
u64be(cert.epochTotalDeposited),
|
|
609
|
+
new Uint8Array([cert.hwKind, cert.maxSeq, cert.hwAnchor.length]),
|
|
610
|
+
cert.hwAnchor,
|
|
611
|
+
cert.appIdHash,
|
|
612
|
+
cert.attestationDigest,
|
|
613
|
+
u64be(cert.exitDelaySecs),
|
|
614
|
+
u64be(cert.syncedAtTs),
|
|
615
|
+
u32be(cert.syncedLedgerSeq),
|
|
616
|
+
cert.verifierSig,
|
|
617
|
+
new Uint8Array([entries.length]),
|
|
618
|
+
];
|
|
619
|
+
for (let idx = 0; idx < entries.length; idx++) {
|
|
620
|
+
const entry = entries[idx];
|
|
621
|
+
const expectedSeq = idx + 1;
|
|
622
|
+
if (entry.seq !== expectedSeq) {
|
|
623
|
+
throw new Error(`SMESHH1 entries must be contiguous 1..=k (expected ${expectedSeq}, got ${entry.seq})`);
|
|
624
|
+
}
|
|
625
|
+
assertValidWireAddress(entry.to);
|
|
626
|
+
assertBigIntRange(entry.amount, 1n, MAX_U64, `entries[${idx}].amount`);
|
|
627
|
+
assertBigIntRange(entry.maxTip, 0n, MAX_U64, `entries[${idx}].maxTip`);
|
|
628
|
+
assertBigIntRange(entry.cumulativeSpent, 0n, MAX_U64, `entries[${idx}].cumulativeSpent`);
|
|
629
|
+
assertBigIntRange(entry.expiryTs, 0n, MAX_U64, `entries[${idx}].expiryTs`);
|
|
630
|
+
assertU32(entry.expiryLedger, `entries[${idx}].expiryLedger`);
|
|
631
|
+
assertBigIntRange(entry.orderId, 0n, MAX_U64, `entries[${idx}].orderId`);
|
|
632
|
+
parts.push(new Uint8Array([entry.seq]), encodeWireAddress(entry.to), u64be(entry.amount), u64be(entry.maxTip), u64be(entry.cumulativeSpent), u64be(entry.expiryTs), u32be(entry.expiryLedger), u64be(entry.orderId));
|
|
633
|
+
if (cert.hwKind === HW_KIND_IOS_APP_ATTEST && entry.hwProof.kind === "ios_app_attest") {
|
|
634
|
+
if (entry.hwProof.authData.length < MIN_IOS_AUTH_DATA_LEN ||
|
|
635
|
+
entry.hwProof.authData.length > MAX_IOS_AUTH_DATA_LEN) {
|
|
636
|
+
throw new Error(`SMESHH1 iOS authData length out of range: ${entry.hwProof.authData.length}`);
|
|
637
|
+
}
|
|
638
|
+
assertBytesLength(entry.hwProof.sig64, 64, `entries[${idx}].hwProof.sig64`);
|
|
639
|
+
parts.push(u16be(entry.hwProof.authData.length), entry.hwProof.authData, entry.hwProof.sig64);
|
|
640
|
+
}
|
|
641
|
+
else if (cert.hwKind === HW_KIND_ANDROID_KEYMINT_MERKLE &&
|
|
642
|
+
entry.hwProof.kind === "android_keymint_merkle") {
|
|
643
|
+
assertBytesLength(entry.hwProof.leafPubkey65, 65, `entries[${idx}].hwProof.leafPubkey65`);
|
|
644
|
+
if (entry.hwProof.leafPubkey65[0] !== 0x04) {
|
|
645
|
+
throw new Error(`SMESHH1 leafPubkey65[${idx}] must start with 0x04`);
|
|
646
|
+
}
|
|
647
|
+
if (entry.hwProof.merkleProof.length !== expectedDepth) {
|
|
648
|
+
throw new Error(`SMESHH1 merkleProof depth mismatch at seq ${expectedSeq}: expected ${expectedDepth}, got ${entry.hwProof.merkleProof.length}`);
|
|
649
|
+
}
|
|
650
|
+
parts.push(entry.hwProof.leafPubkey65, new Uint8Array([entry.hwProof.merkleProof.length]));
|
|
651
|
+
for (let m = 0; m < entry.hwProof.merkleProof.length; m++) {
|
|
652
|
+
assertBytesLength(entry.hwProof.merkleProof[m], 32, `merkleProof[${m}]`);
|
|
653
|
+
parts.push(entry.hwProof.merkleProof[m]);
|
|
654
|
+
}
|
|
655
|
+
assertBytesLength(entry.hwProof.sig64, 64, `entries[${idx}].hwProof.sig64`);
|
|
656
|
+
parts.push(entry.hwProof.sig64);
|
|
657
|
+
}
|
|
658
|
+
else {
|
|
659
|
+
throw new Error(`SMESHH1 hwProof kind mismatch at seq ${expectedSeq}`);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
const out = concatBytes(...parts);
|
|
663
|
+
if (out.length > MAX_SMESHH1_BYTES) {
|
|
664
|
+
throw new Error(`SMESHH1 payload (${out.length}B) exceeds MAX_SMESHH1_BYTES (${MAX_SMESHH1_BYTES}B)`);
|
|
665
|
+
}
|
|
666
|
+
return out;
|
|
667
|
+
}
|
|
668
|
+
/** Decodes and structurally validates a `Smeshh1Packet` from canonical raw binary bytes. */
|
|
669
|
+
export function decodeSmeshh1Bytes(raw) {
|
|
670
|
+
if (!(raw instanceof Uint8Array) || raw.length === 0 || raw.length > MAX_SMESHH1_BYTES) {
|
|
671
|
+
throw new Error(`SMESHH1 byte length (${raw?.length ?? 0}) out of bounds [1, ${MAX_SMESHH1_BYTES}]`);
|
|
672
|
+
}
|
|
673
|
+
let pos = 0;
|
|
674
|
+
const need = (n) => {
|
|
675
|
+
if (pos + n > raw.length) {
|
|
676
|
+
throw new Error(`Truncated SMESHH1 payload at offset ${pos} (need ${n}B)`);
|
|
677
|
+
}
|
|
678
|
+
};
|
|
679
|
+
const readU8 = () => {
|
|
680
|
+
need(1);
|
|
681
|
+
return raw[pos++];
|
|
682
|
+
};
|
|
683
|
+
const readSlice = (n) => {
|
|
684
|
+
need(n);
|
|
685
|
+
const out = raw.slice(pos, pos + n);
|
|
686
|
+
pos += n;
|
|
687
|
+
return out;
|
|
688
|
+
};
|
|
689
|
+
const flags = readU8();
|
|
690
|
+
const ver = (flags >>> 4) & 0x0f;
|
|
691
|
+
if (ver !== SMESHH1_WIRE_VERSION) {
|
|
692
|
+
throw new Error(`Unsupported SMESHH1 version nibble: 0x${ver.toString(16)}`);
|
|
693
|
+
}
|
|
694
|
+
if ((flags & 0x0c) !== 0) {
|
|
695
|
+
throw new Error(`Non-zero reserved bits in SMESHH1 flags: 0x${flags.toString(16)}`);
|
|
696
|
+
}
|
|
697
|
+
const networkHint = assertNetworkHint(flags & 0x03);
|
|
698
|
+
const factoryVer = readU8();
|
|
699
|
+
if (factoryVer < 1 || factoryVer > 15) {
|
|
700
|
+
throw new Error(`Invalid SMESHH1 factoryVer: ${factoryVer}`);
|
|
701
|
+
}
|
|
702
|
+
need(WIRE_ADDRESS_BYTE_LENGTH);
|
|
703
|
+
const owner = decodeWireAddress(raw, pos);
|
|
704
|
+
pos += WIRE_ADDRESS_BYTE_LENGTH;
|
|
705
|
+
const vaultId = readSlice(32);
|
|
706
|
+
need(2);
|
|
707
|
+
const pocketId = decodeU16Be(raw, pos);
|
|
708
|
+
pos += 2;
|
|
709
|
+
need(4);
|
|
710
|
+
const epoch = decodeU32Be(raw, pos);
|
|
711
|
+
pos += 4;
|
|
712
|
+
if (epoch < 1) {
|
|
713
|
+
throw new Error(`SMESHH1 epoch must be >= 1, got ${epoch}`);
|
|
714
|
+
}
|
|
715
|
+
const tokenId = readSlice(32);
|
|
716
|
+
need(8);
|
|
717
|
+
const epochTotalDeposited = decodeU64Be(raw, pos);
|
|
718
|
+
pos += 8;
|
|
719
|
+
if (epochTotalDeposited <= 0n) {
|
|
720
|
+
throw new Error("SMESHH1 epochTotalDeposited must be > 0");
|
|
721
|
+
}
|
|
722
|
+
const hwKindRaw = readU8();
|
|
723
|
+
if (hwKindRaw !== HW_KIND_IOS_APP_ATTEST && hwKindRaw !== HW_KIND_ANDROID_KEYMINT_MERKLE) {
|
|
724
|
+
throw new Error(`Unknown SMESHH1 hwKind: ${hwKindRaw}`);
|
|
725
|
+
}
|
|
726
|
+
const hwKind = hwKindRaw;
|
|
727
|
+
const maxSeq = readU8();
|
|
728
|
+
if (maxSeq < 1 || maxSeq > MAX_HW_SEQ) {
|
|
729
|
+
throw new Error(`SMESHH1 maxSeq out of range: ${maxSeq}`);
|
|
730
|
+
}
|
|
731
|
+
const expectedAnchorLen = hwKind === HW_KIND_IOS_APP_ATTEST ? 65 : 32;
|
|
732
|
+
const anchorLen = readU8();
|
|
733
|
+
if (anchorLen !== expectedAnchorLen) {
|
|
734
|
+
throw new Error(`SMESHH1 hwAnchor length mismatch: expected ${expectedAnchorLen}, got ${anchorLen}`);
|
|
735
|
+
}
|
|
736
|
+
const hwAnchor = readSlice(anchorLen);
|
|
737
|
+
if (hwKind === HW_KIND_IOS_APP_ATTEST && hwAnchor[0] !== 0x04) {
|
|
738
|
+
throw new Error("SMESHH1 iOS hwAnchor must start with 0x04");
|
|
739
|
+
}
|
|
740
|
+
const appIdHash = readSlice(32);
|
|
741
|
+
const attestationDigest = readSlice(32);
|
|
742
|
+
need(8);
|
|
743
|
+
const exitDelaySecs = decodeU64Be(raw, pos);
|
|
744
|
+
pos += 8;
|
|
745
|
+
if (exitDelaySecs < HW_MIN_EXIT_DELAY_SECS || exitDelaySecs > HW_MAX_EXIT_DELAY_SECS) {
|
|
746
|
+
throw new Error(`SMESHH1 exitDelaySecs out of range: ${exitDelaySecs}`);
|
|
747
|
+
}
|
|
748
|
+
need(8);
|
|
749
|
+
const syncedAtTs = decodeU64Be(raw, pos);
|
|
750
|
+
pos += 8;
|
|
751
|
+
need(4);
|
|
752
|
+
const syncedLedgerSeq = decodeU32Be(raw, pos);
|
|
753
|
+
pos += 4;
|
|
754
|
+
const verifierSig = readSlice(64);
|
|
755
|
+
const entryCount = readU8();
|
|
756
|
+
if (entryCount < 1 || entryCount > maxSeq) {
|
|
757
|
+
throw new Error(`SMESHH1 entryCount (${entryCount}) must be in 1..=${maxSeq}`);
|
|
758
|
+
}
|
|
759
|
+
const expectedDepth = hwKind === HW_KIND_ANDROID_KEYMINT_MERKLE ? hwMerkleDepthFor(maxSeq) : 0;
|
|
760
|
+
const entries = [];
|
|
761
|
+
for (let idx = 0; idx < entryCount; idx++) {
|
|
762
|
+
const seq = readU8();
|
|
763
|
+
if (seq !== idx + 1) {
|
|
764
|
+
throw new Error(`SMESHH1 entries must be contiguous 1..=k (expected ${idx + 1}, got ${seq})`);
|
|
765
|
+
}
|
|
766
|
+
need(WIRE_ADDRESS_BYTE_LENGTH);
|
|
767
|
+
const to = decodeWireAddress(raw, pos);
|
|
768
|
+
pos += WIRE_ADDRESS_BYTE_LENGTH;
|
|
769
|
+
need(44);
|
|
770
|
+
const amount = decodeU64Be(raw, pos);
|
|
771
|
+
pos += 8;
|
|
772
|
+
if (amount <= 0n) {
|
|
773
|
+
throw new Error(`SMESHH1 amount must be > 0 at seq ${seq}`);
|
|
774
|
+
}
|
|
775
|
+
const maxTip = decodeU64Be(raw, pos);
|
|
776
|
+
pos += 8;
|
|
777
|
+
const cumulativeSpent = decodeU64Be(raw, pos);
|
|
778
|
+
pos += 8;
|
|
779
|
+
const expiryTs = decodeU64Be(raw, pos);
|
|
780
|
+
pos += 8;
|
|
781
|
+
const expiryLedger = decodeU32Be(raw, pos);
|
|
782
|
+
pos += 4;
|
|
783
|
+
const orderId = decodeU64Be(raw, pos);
|
|
784
|
+
pos += 8;
|
|
785
|
+
let hwProof;
|
|
786
|
+
if (hwKind === HW_KIND_IOS_APP_ATTEST) {
|
|
787
|
+
need(2);
|
|
788
|
+
const authLen = decodeU16Be(raw, pos);
|
|
789
|
+
pos += 2;
|
|
790
|
+
if (authLen < MIN_IOS_AUTH_DATA_LEN || authLen > MAX_IOS_AUTH_DATA_LEN) {
|
|
791
|
+
throw new Error(`SMESHH1 iOS authData length out of range: ${authLen}`);
|
|
792
|
+
}
|
|
793
|
+
const authData = readSlice(authLen);
|
|
794
|
+
const sig64 = readSlice(64);
|
|
795
|
+
hwProof = { kind: "ios_app_attest", authData, sig64 };
|
|
796
|
+
}
|
|
797
|
+
else {
|
|
798
|
+
const leafPubkey65 = readSlice(65);
|
|
799
|
+
if (leafPubkey65[0] !== 0x04) {
|
|
800
|
+
throw new Error(`SMESHH1 Android leafPubkey65 must start with 0x04 at seq ${seq}`);
|
|
801
|
+
}
|
|
802
|
+
const proofLen = readU8();
|
|
803
|
+
if (proofLen !== expectedDepth || proofLen > MAX_HW_MERKLE_DEPTH) {
|
|
804
|
+
throw new Error(`SMESHH1 Android merkleProof length mismatch at seq ${seq}`);
|
|
805
|
+
}
|
|
806
|
+
const merkleProof = [];
|
|
807
|
+
for (let m = 0; m < proofLen; m++) {
|
|
808
|
+
merkleProof.push(readSlice(32));
|
|
809
|
+
}
|
|
810
|
+
const sig64 = readSlice(64);
|
|
811
|
+
hwProof = { kind: "android_keymint_merkle", leafPubkey65, merkleProof, sig64 };
|
|
812
|
+
}
|
|
813
|
+
entries.push({
|
|
814
|
+
seq,
|
|
815
|
+
to,
|
|
816
|
+
amount,
|
|
817
|
+
maxTip,
|
|
818
|
+
cumulativeSpent,
|
|
819
|
+
expiryTs,
|
|
820
|
+
expiryLedger,
|
|
821
|
+
orderId,
|
|
822
|
+
hwProof,
|
|
823
|
+
});
|
|
824
|
+
}
|
|
825
|
+
if (pos !== raw.length) {
|
|
826
|
+
throw new Error(`Unexpected trailing bytes in SMESHH1: ${raw.length - pos} extra bytes`);
|
|
827
|
+
}
|
|
828
|
+
return {
|
|
829
|
+
networkHint,
|
|
830
|
+
cert: {
|
|
831
|
+
factoryVer,
|
|
832
|
+
owner,
|
|
833
|
+
vaultId,
|
|
834
|
+
pocketId,
|
|
835
|
+
epoch,
|
|
836
|
+
tokenId,
|
|
837
|
+
epochTotalDeposited,
|
|
838
|
+
hwKind,
|
|
839
|
+
maxSeq,
|
|
840
|
+
hwAnchor,
|
|
841
|
+
appIdHash,
|
|
842
|
+
attestationDigest,
|
|
843
|
+
exitDelaySecs,
|
|
844
|
+
syncedAtTs,
|
|
845
|
+
syncedLedgerSeq,
|
|
846
|
+
verifierSig,
|
|
847
|
+
},
|
|
848
|
+
entries,
|
|
849
|
+
};
|
|
850
|
+
}
|
|
851
|
+
/** Encodes `SMESHH1<UPPERCASE_UNPADDED_RFC4648_BASE32(raw_bytes || crc32c_be_4B)>`. */
|
|
852
|
+
export function encodeSmeshh1(packet) {
|
|
853
|
+
return encodeFramed(HRP_SMESHH, encodeSmeshh1Bytes(packet));
|
|
854
|
+
}
|
|
855
|
+
/** Decodes `SMESHH1<BASE32(raw_bytes || crc32c_be_4B)>` (case-insensitive). */
|
|
856
|
+
export function decodeSmeshh1(encoded) {
|
|
857
|
+
return decodeSmeshh1Bytes(decodeFramed(HRP_SMESHH, encoded));
|
|
858
|
+
}
|