@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.
@@ -0,0 +1,399 @@
1
+ /**
2
+ * Portable JSON WalletStorage serializer and persistent adapter (`@outpost-protocol/core`).
3
+ *
4
+ * Designed for mobile WebViews (Capacitor Preferences, Expo SecureStore, MMKV, SQLite),
5
+ * browser extensions (`chrome.storage.local` / IndexedDB), Electron, and Node.js.
6
+ *
7
+ * SECURITY NOTE: Serialized snapshots include each pocket's 32-byte `deviceSecretKey`.
8
+ * Always store the serialized JSON string in encrypted platform storage (iOS Keychain,
9
+ * Android Keystore, Expo SecureStore, or encrypted SQLite).
10
+ */
11
+ import { assertBytesLength, assertSortedUniqueWitnesses, assertU16, assertU32, ed25519PublicKeyFromSecret, MAX_U64, } from "./digest.js";
12
+ import { DEFAULT_MAX_SIGNED_ORDERS_LRU, InMemoryWalletStorage, MAX_EXIT_DELAY_SECS, MIN_EXIT_DELAY_SECS, } from "./wallet.js";
13
+ import { bytesToHex, hexToBytes } from "./witnessClient.js";
14
+ import { assertNetworkHint, bytesEqual, normalizeContractHash, } from "./xdr.js";
15
+ export const WALLET_STATE_SCHEMA_VERSION = 1;
16
+ export const MAX_SERIALIZED_POCKETS = 1_024;
17
+ export const MAX_SERIALIZED_SIGNED_ORDERS = 2_048;
18
+ const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
19
+ function parseUnsignedBigIntString(raw, label, maxVal = MAX_U64) {
20
+ if (typeof raw !== "string" || !/^\d+$/.test(raw)) {
21
+ throw new Error(`${label} must be an unsigned decimal integer string`);
22
+ }
23
+ const value = BigInt(raw);
24
+ if (value < 0n || value > maxVal) {
25
+ throw new RangeError(`${label} out of range: ${raw}`);
26
+ }
27
+ return value;
28
+ }
29
+ function parseHexFixed(raw, expectedLen, label) {
30
+ if (typeof raw !== "string") {
31
+ throw new Error(`${label} must be a hex string`);
32
+ }
33
+ const bytes = hexToBytes(raw);
34
+ assertBytesLength(bytes, expectedLen, label);
35
+ return bytes;
36
+ }
37
+ /**
38
+ * Serialize a `WalletStateSnapshot` (`pockets` + `signedOrders`) to canonical versioned JSON.
39
+ */
40
+ export function serializeWalletState(snapshot) {
41
+ const pocketEntries = Object.entries(snapshot.pockets);
42
+ if (pocketEntries.length > MAX_SERIALIZED_POCKETS) {
43
+ throw new Error(`Cannot serialize ${pocketEntries.length} pockets (max ${MAX_SERIALIZED_POCKETS})`);
44
+ }
45
+ if (snapshot.signedOrders.length > MAX_SERIALIZED_SIGNED_ORDERS) {
46
+ throw new Error(`Cannot serialize ${snapshot.signedOrders.length} signed orders (max ${MAX_SERIALIZED_SIGNED_ORDERS})`);
47
+ }
48
+ const serializedPockets = {};
49
+ for (const [key, rec] of pocketEntries) {
50
+ if (FORBIDDEN_KEYS.has(key)) {
51
+ throw new Error(`Invalid pocketKey "${key}"`);
52
+ }
53
+ const token = rec.token.kind === "custom"
54
+ ? { kind: "custom", contractIdHex: bytesToHex(rec.token.contractId) }
55
+ : { kind: rec.token.kind };
56
+ serializedPockets[key] = {
57
+ networkHint: rec.networkHint,
58
+ ...(rec.networkPassphrase !== undefined ? { networkPassphrase: rec.networkPassphrase } : {}),
59
+ factoryVer: rec.factoryVer,
60
+ factoryId: rec.factoryId,
61
+ owner: {
62
+ type: rec.owner.type,
63
+ rawHex: bytesToHex(rec.owner.raw),
64
+ },
65
+ vaultId: rec.vaultId,
66
+ pocketId: rec.pocketId,
67
+ epoch: rec.epoch,
68
+ token,
69
+ tokenContractId: rec.tokenContractId,
70
+ deviceSecretKeyHex: bytesToHex(rec.deviceSecretKey),
71
+ devicePubkeyHex: bytesToHex(rec.devicePubkey),
72
+ witnessesHex: rec.witnesses.map((w) => bytesToHex(w)),
73
+ witnessThreshold: rec.witnessThreshold,
74
+ epochTotalDeposited: rec.epochTotalDeposited.toString(10),
75
+ exitDelaySecs: rec.exitDelaySecs.toString(10),
76
+ anchor: {
77
+ ledgerSeq: rec.anchor.ledgerSeq,
78
+ timestamp: rec.anchor.timestamp,
79
+ },
80
+ localSeq: rec.localSeq,
81
+ estimatedSpent: (rec.estimatedSpent ?? 0n).toString(10),
82
+ };
83
+ }
84
+ const serializedOrders = snapshot.signedOrders.map((ord) => ({
85
+ pocketKey: ord.pocketKey,
86
+ recipientStrKey: ord.recipientStrKey,
87
+ orderId: ord.orderId.toString(10),
88
+ seq: ord.seq,
89
+ tokenContractId: ord.tokenContractId,
90
+ amount: ord.amount.toString(10),
91
+ maxTip: ord.maxTip.toString(10),
92
+ effectiveNowTs: ord.effectiveNowTs,
93
+ intentDigestHex: bytesToHex(ord.intentDigest),
94
+ encoded: ord.encoded,
95
+ }));
96
+ const payload = {
97
+ version: WALLET_STATE_SCHEMA_VERSION,
98
+ pockets: serializedPockets,
99
+ signedOrders: serializedOrders,
100
+ };
101
+ return JSON.stringify(payload);
102
+ }
103
+ /**
104
+ * Deserialize and strictly validate a versioned JSON wallet snapshot produced by
105
+ * `serializeWalletState`. Fails closed on unknown schema versions, invalid key lengths,
106
+ * corrupted keypairs, prototype-pollution keys, or cap violations.
107
+ */
108
+ export function deserializeWalletState(json) {
109
+ if (typeof json !== "string" || json.trim().length === 0) {
110
+ throw new Error("Serialized wallet state must be a non-empty JSON string");
111
+ }
112
+ let parsed;
113
+ try {
114
+ parsed = JSON.parse(json);
115
+ }
116
+ catch (err) {
117
+ throw new Error(`Invalid wallet state JSON: ${err instanceof Error ? err.message : String(err)}`);
118
+ }
119
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
120
+ throw new Error("Wallet state JSON root must be an object");
121
+ }
122
+ const obj = parsed;
123
+ if (obj.version !== WALLET_STATE_SCHEMA_VERSION) {
124
+ throw new Error(`Unsupported wallet state schema version: ${String(obj.version)} (expected ${WALLET_STATE_SCHEMA_VERSION})`);
125
+ }
126
+ if (typeof obj.pockets !== "object" || obj.pockets === null || Array.isArray(obj.pockets)) {
127
+ throw new Error("Wallet state JSON missing pockets object");
128
+ }
129
+ const rawPocketEntries = Object.entries(obj.pockets);
130
+ if (rawPocketEntries.length > MAX_SERIALIZED_POCKETS) {
131
+ throw new Error(`Wallet state JSON exceeds max pockets (${rawPocketEntries.length} > ${MAX_SERIALIZED_POCKETS})`);
132
+ }
133
+ const pockets = Object.create(null);
134
+ for (const [key, rawRec] of rawPocketEntries) {
135
+ if (FORBIDDEN_KEYS.has(key) || key.length === 0 || key.length > 256) {
136
+ throw new Error(`Invalid pocketKey in wallet state JSON: "${key}"`);
137
+ }
138
+ if (typeof rawRec !== "object" || rawRec === null || Array.isArray(rawRec)) {
139
+ throw new Error(`Invalid pocket record for "${key}"`);
140
+ }
141
+ const r = rawRec;
142
+ const networkHint = assertNetworkHint(Number(r.networkHint));
143
+ const networkPassphrase = r.networkPassphrase !== undefined ? String(r.networkPassphrase) : undefined;
144
+ const factoryVer = Number(r.factoryVer);
145
+ if (!Number.isInteger(factoryVer) || factoryVer < 1 || factoryVer > 15) {
146
+ throw new Error(`Invalid factoryVer for "${key}": ${String(r.factoryVer)}`);
147
+ }
148
+ if (typeof r.factoryId !== "string")
149
+ throw new Error(`Invalid factoryId for "${key}"`);
150
+ normalizeContractHash(r.factoryId);
151
+ if (typeof r.vaultId !== "string")
152
+ throw new Error(`Invalid vaultId for "${key}"`);
153
+ normalizeContractHash(r.vaultId);
154
+ if (typeof r.tokenContractId !== "string") {
155
+ throw new Error(`Invalid tokenContractId for "${key}"`);
156
+ }
157
+ normalizeContractHash(r.tokenContractId);
158
+ const ownerObj = r.owner;
159
+ if (!ownerObj || typeof ownerObj !== "object") {
160
+ throw new Error(`Invalid owner for "${key}"`);
161
+ }
162
+ if (ownerObj.type !== "account" && ownerObj.type !== "contract") {
163
+ throw new Error(`Invalid owner.type for "${key}": ${String(ownerObj.type)}`);
164
+ }
165
+ const owner = {
166
+ type: ownerObj.type,
167
+ raw: parseHexFixed(ownerObj.rawHex, 32, `${key}.owner.rawHex`),
168
+ };
169
+ const pocketId = assertU16(Number(r.pocketId), `${key}.pocketId`);
170
+ const epoch = assertU32(Number(r.epoch), `${key}.epoch`);
171
+ if (epoch === 0)
172
+ throw new Error(`${key}.epoch must be >= 1`);
173
+ const tokObj = r.token;
174
+ if (!tokObj || typeof tokObj !== "object") {
175
+ throw new Error(`Invalid token for "${key}"`);
176
+ }
177
+ let token;
178
+ if (tokObj.kind === "native_xlm" ||
179
+ tokObj.kind === "canonical_usdc" ||
180
+ tokObj.kind === "canonical_eurc") {
181
+ token = { kind: tokObj.kind };
182
+ }
183
+ else if (tokObj.kind === "custom") {
184
+ token = {
185
+ kind: "custom",
186
+ contractId: parseHexFixed(tokObj.contractIdHex, 32, `${key}.token.contractIdHex`),
187
+ };
188
+ }
189
+ else {
190
+ throw new Error(`Invalid token.kind for "${key}": ${String(tokObj.kind)}`);
191
+ }
192
+ const deviceSecretKey = parseHexFixed(r.deviceSecretKeyHex, 32, `${key}.deviceSecretKeyHex`);
193
+ const devicePubkey = parseHexFixed(r.devicePubkeyHex, 32, `${key}.devicePubkeyHex`);
194
+ const derivedPubkey = ed25519PublicKeyFromSecret(deviceSecretKey);
195
+ if (!bytesEqual(derivedPubkey, devicePubkey)) {
196
+ throw new Error(`Corrupted device keypair for "${key}": pubkey does not match secret key`);
197
+ }
198
+ if (!Array.isArray(r.witnessesHex)) {
199
+ throw new Error(`Invalid witnessesHex for "${key}"`);
200
+ }
201
+ const witnesses = r.witnessesHex.map((w, idx) => parseHexFixed(w, 32, `${key}.witnessesHex[${idx}]`));
202
+ assertSortedUniqueWitnesses(witnesses);
203
+ const witnessThreshold = Number(r.witnessThreshold);
204
+ if (!Number.isInteger(witnessThreshold) ||
205
+ witnessThreshold < 1 ||
206
+ witnessThreshold > witnesses.length ||
207
+ witnessThreshold * 2 <= witnesses.length) {
208
+ throw new Error(`Invalid witnessThreshold for "${key}": ${String(r.witnessThreshold)}`);
209
+ }
210
+ const epochTotalDeposited = parseUnsignedBigIntString(r.epochTotalDeposited, `${key}.epochTotalDeposited`);
211
+ if (epochTotalDeposited <= 0n) {
212
+ throw new Error(`${key}.epochTotalDeposited must be > 0`);
213
+ }
214
+ const exitDelaySecs = parseUnsignedBigIntString(r.exitDelaySecs, `${key}.exitDelaySecs`);
215
+ if (exitDelaySecs < MIN_EXIT_DELAY_SECS || exitDelaySecs > MAX_EXIT_DELAY_SECS) {
216
+ throw new Error(`${key}.exitDelaySecs out of allowed range`);
217
+ }
218
+ const anchorObj = r.anchor;
219
+ if (!anchorObj || typeof anchorObj !== "object") {
220
+ throw new Error(`Invalid anchor for "${key}"`);
221
+ }
222
+ const anchor = {
223
+ ledgerSeq: assertU32(Number(anchorObj.ledgerSeq), `${key}.anchor.ledgerSeq`),
224
+ timestamp: assertU32(Number(anchorObj.timestamp), `${key}.anchor.timestamp`),
225
+ };
226
+ const localSeq = assertU32(Number(r.localSeq), `${key}.localSeq`);
227
+ const estimatedSpent = r.estimatedSpent !== undefined
228
+ ? parseUnsignedBigIntString(r.estimatedSpent, `${key}.estimatedSpent`)
229
+ : 0n;
230
+ pockets[key] = {
231
+ networkHint,
232
+ ...(networkPassphrase !== undefined ? { networkPassphrase } : {}),
233
+ factoryVer,
234
+ factoryId: r.factoryId,
235
+ owner,
236
+ vaultId: r.vaultId,
237
+ pocketId,
238
+ epoch,
239
+ token,
240
+ tokenContractId: r.tokenContractId,
241
+ deviceSecretKey,
242
+ devicePubkey,
243
+ witnesses,
244
+ witnessThreshold,
245
+ epochTotalDeposited,
246
+ exitDelaySecs,
247
+ anchor,
248
+ localSeq,
249
+ estimatedSpent,
250
+ };
251
+ }
252
+ const rawOrders = obj.signedOrders ?? [];
253
+ if (!Array.isArray(rawOrders)) {
254
+ throw new Error("Wallet state JSON signedOrders must be an array");
255
+ }
256
+ if (rawOrders.length > MAX_SERIALIZED_SIGNED_ORDERS) {
257
+ throw new Error(`Wallet state JSON exceeds max signedOrders (${rawOrders.length} > ${MAX_SERIALIZED_SIGNED_ORDERS})`);
258
+ }
259
+ const signedOrders = rawOrders.map((rawOrd, idx) => {
260
+ if (typeof rawOrd !== "object" || rawOrd === null || Array.isArray(rawOrd)) {
261
+ throw new Error(`Invalid signedOrders[${idx}]`);
262
+ }
263
+ const o = rawOrd;
264
+ if (typeof o.pocketKey !== "string" || o.pocketKey.length === 0) {
265
+ throw new Error(`Invalid signedOrders[${idx}].pocketKey`);
266
+ }
267
+ if (typeof o.recipientStrKey !== "string" || o.recipientStrKey.length === 0) {
268
+ throw new Error(`Invalid signedOrders[${idx}].recipientStrKey`);
269
+ }
270
+ if (typeof o.tokenContractId !== "string" || o.tokenContractId.length === 0) {
271
+ throw new Error(`Invalid signedOrders[${idx}].tokenContractId`);
272
+ }
273
+ if (typeof o.encoded !== "string" || o.encoded.length === 0) {
274
+ throw new Error(`Invalid signedOrders[${idx}].encoded`);
275
+ }
276
+ return {
277
+ pocketKey: o.pocketKey,
278
+ recipientStrKey: o.recipientStrKey,
279
+ orderId: parseUnsignedBigIntString(o.orderId, `signedOrders[${idx}].orderId`),
280
+ seq: assertU32(Number(o.seq), `signedOrders[${idx}].seq`),
281
+ tokenContractId: o.tokenContractId,
282
+ amount: parseUnsignedBigIntString(o.amount, `signedOrders[${idx}].amount`),
283
+ maxTip: parseUnsignedBigIntString(o.maxTip, `signedOrders[${idx}].maxTip`),
284
+ effectiveNowTs: assertU32(Number(o.effectiveNowTs), `signedOrders[${idx}].effectiveNowTs`),
285
+ intentDigest: parseHexFixed(o.intentDigestHex, 32, `signedOrders[${idx}].intentDigestHex`),
286
+ encoded: o.encoded,
287
+ };
288
+ });
289
+ return { pockets, signedOrders };
290
+ }
291
+ /**
292
+ * Durable `WalletStorage` backed by any string key-value persistence adapter (`JsonWalletStorageAdapter`).
293
+ *
294
+ * Guarantees:
295
+ * - Hydrates lazily on first read/write (or explicitly via `await storage.hydrate()`).
296
+ * - Serializes all mutations through a strict FIFO async mutex so concurrent writes never race.
297
+ * - Durably invokes `adapter.save(serialized)` BEFORE resolving `burnNextSeq` (preserving the
298
+ * burn-before-display invariant across crashes).
299
+ * - Rolls back in-memory state if `adapter.save(...)` throws (`AGENTS.md` §1.1).
300
+ */
301
+ export class JsonWalletStorage {
302
+ adapter;
303
+ maxSignedOrders;
304
+ inner;
305
+ hydrated = false;
306
+ hydratePromise;
307
+ writeChain = Promise.resolve();
308
+ constructor(options) {
309
+ this.adapter = options.adapter;
310
+ this.maxSignedOrders = options.maxSignedOrders ?? DEFAULT_MAX_SIGNED_ORDERS_LRU;
311
+ this.inner = new InMemoryWalletStorage({ maxSignedOrders: this.maxSignedOrders });
312
+ }
313
+ /**
314
+ * Explicitly hydrate from the underlying adapter (idempotent; also called automatically on first access).
315
+ */
316
+ async hydrate() {
317
+ if (this.hydrated)
318
+ return;
319
+ if (!this.hydratePromise) {
320
+ this.hydratePromise = (async () => {
321
+ const raw = await this.adapter.load();
322
+ if (typeof raw === "string" && raw.trim().length > 0) {
323
+ const snapshot = deserializeWalletState(raw);
324
+ const loaded = new InMemoryWalletStorage({ maxSignedOrders: this.maxSignedOrders });
325
+ loaded.importSnapshot(snapshot);
326
+ this.inner = loaded;
327
+ }
328
+ this.hydrated = true;
329
+ })().finally(() => {
330
+ if (!this.hydrated) {
331
+ this.hydratePromise = undefined;
332
+ }
333
+ });
334
+ }
335
+ return this.hydratePromise;
336
+ }
337
+ async runSerializedMutation(mutate) {
338
+ const prev = this.writeChain;
339
+ let release;
340
+ this.writeChain = new Promise((resolve) => {
341
+ release = resolve;
342
+ });
343
+ await prev;
344
+ try {
345
+ await this.hydrate();
346
+ const backupJson = serializeWalletState(this.inner.exportSnapshot());
347
+ const result = await mutate(this.inner);
348
+ const nextJson = serializeWalletState(this.inner.exportSnapshot());
349
+ try {
350
+ await this.adapter.save(nextJson);
351
+ }
352
+ catch (saveErr) {
353
+ // Roll back in-memory state if durable persistence failed (AGENTS.md §1.1)
354
+ const restored = new InMemoryWalletStorage({ maxSignedOrders: this.maxSignedOrders });
355
+ restored.importSnapshot(deserializeWalletState(backupJson));
356
+ this.inner = restored;
357
+ throw saveErr;
358
+ }
359
+ return result;
360
+ }
361
+ finally {
362
+ release();
363
+ }
364
+ }
365
+ async exportJson() {
366
+ await this.hydrate();
367
+ return serializeWalletState(this.inner.exportSnapshot());
368
+ }
369
+ async getPocket(pocketKey) {
370
+ await this.hydrate();
371
+ return this.inner.getPocket(pocketKey);
372
+ }
373
+ async savePocket(pocketKey, record) {
374
+ return this.runSerializedMutation((s) => s.savePocket(pocketKey, record));
375
+ }
376
+ async burnNextSeq(pocketKey, costDelta) {
377
+ return this.runSerializedMutation((s) => s.burnNextSeq(pocketKey, costDelta));
378
+ }
379
+ async advanceSeq(pocketKey, newSeq) {
380
+ return this.runSerializedMutation((s) => s.advanceSeq(pocketKey, newSeq));
381
+ }
382
+ async syncEstimatedSpent(pocketKey, cumulativeSpent) {
383
+ return this.runSerializedMutation((s) => s.syncEstimatedSpent(pocketKey, cumulativeSpent));
384
+ }
385
+ async updateAnchor(pocketKey, anchor) {
386
+ return this.runSerializedMutation((s) => s.updateAnchor(pocketKey, anchor));
387
+ }
388
+ async listPocketKeys() {
389
+ await this.hydrate();
390
+ return this.inner.listPocketKeys();
391
+ }
392
+ async getSignedOrder(pocketKey, recipientStrKey, orderId) {
393
+ await this.hydrate();
394
+ return this.inner.getSignedOrder(pocketKey, recipientStrKey, orderId);
395
+ }
396
+ async saveSignedOrder(record) {
397
+ return this.runSerializedMutation((s) => s.saveSignedOrder(record));
398
+ }
399
+ }
package/dist/wire.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type UrSmeshFrame } from "./bcur.js";
2
+ import { type Smeshh1Packet } from "./hw.js";
2
3
  import { NetworkHint, type WireAddress, type WireToken } from "./xdr.js";
3
4
  export declare const HRP_SREQ = "SREQ";
4
5
  export declare const HRP_SMESHD = "SMESHD";
@@ -22,6 +23,9 @@ export declare const SREQ1_TLV_GATEWAY = 3;
22
23
  export declare const SREQ1_TLV_CLASSIC_ASSET = 4;
23
24
  export declare const SREQ1_TLV_ACCEPTED_FACTORY_VERS = 5;
24
25
  export declare const SREQ1_TLV_MEMO = 6;
26
+ /** Optional odd TLV (`0xF1`, safely ignored by v1.2 wallets): `1..=4` concatenated 32B Ed25519 pubkeys of trusted v2 Hardware Attestation Verifiers. */
27
+ export declare const SREQ1_TLV_HW_VERIFIER_PUBKEYS = 241;
28
+ export declare const MAX_SREQ1_HW_VERIFIER_PUBKEYS = 4;
25
29
  export type ClassicAssetWire = {
26
30
  readonly kind: "native";
27
31
  } | {
@@ -64,6 +68,8 @@ export interface Sreq1Packet {
64
68
  readonly classicAsset?: ClassicAssetWire;
65
69
  readonly acceptedFactoryVers?: readonly number[];
66
70
  readonly memo?: string;
71
+ /** Optional odd TLV `0xF1`: `1..=4` trusted 32B Ed25519 hardware attestation verifier pubkeys (advertises v2 `SMESHH1` acceptance). */
72
+ readonly hwVerifierPubkeys?: readonly Uint8Array[];
67
73
  }
68
74
  export declare function encodeSreq1Bytes(packet: Sreq1Packet): Uint8Array;
69
75
  export declare function decodeSreq1Bytes(raw: Uint8Array): Sreq1Packet;
@@ -163,6 +169,10 @@ export type ClassifiedPayload = {
163
169
  readonly mode: "witnessed_vault_cert";
164
170
  readonly prefix: "SMESHC1";
165
171
  readonly decoded: Smeshc1Packet;
172
+ } | {
173
+ readonly mode: "hw_roaming_payment";
174
+ readonly prefix: "SMESHH1";
175
+ readonly decoded: Smeshh1Packet;
166
176
  } | {
167
177
  readonly mode: "ur_smesh_frame";
168
178
  readonly prefix: "UR:SMESH";
package/dist/wire.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { decodeFramed, encodeFramed, MAX_FRAMED_BASE32_LEN, splitFramed } from "./base32.js";
2
2
  import { parseUrSmeshFrame, UR_SMESH_PREFIX } from "./bcur.js";
3
+ import { decodeSmeshh1Bytes, HRP_SMESHH } from "./hw.js";
3
4
  import { assertBigInt, assertBytesLength, assertSortedUniqueWitnesses, assertU16, assertU32, assertU8, concatBytes, decodeI64Be, decodeU128Be, decodeU16Be, decodeU32Be, decodeU64Be, encodeI64Be, encodeU128Be, encodeU16Be, encodeU32Be, encodeU64Be, encodeU8, MAX_I128, MAX_I64, MAX_U128, MAX_U64, MAX_WITNESSES, } from "./digest.js";
4
5
  import { assertNetworkHint, assertValidWireAddress, decodeWireAddress, decodeWireToken, encodeWireAddress, encodeWireToken, WIRE_ADDRESS_BYTE_LENGTH, } from "./xdr.js";
5
6
  // ---------------------------------------------------------------------------
@@ -28,6 +29,9 @@ export const SREQ1_TLV_GATEWAY = 0x03;
28
29
  export const SREQ1_TLV_CLASSIC_ASSET = 0x04;
29
30
  export const SREQ1_TLV_ACCEPTED_FACTORY_VERS = 0x05;
30
31
  export const SREQ1_TLV_MEMO = 0x06;
32
+ /** Optional odd TLV (`0xF1`, safely ignored by v1.2 wallets): `1..=4` concatenated 32B Ed25519 pubkeys of trusted v2 Hardware Attestation Verifiers. */
33
+ export const SREQ1_TLV_HW_VERIFIER_PUBKEYS = 0xf1;
34
+ export const MAX_SREQ1_HW_VERIFIER_PUBKEYS = 4;
31
35
  const utf8Encoder = new TextEncoder();
32
36
  const utf8Decoder = new TextDecoder("utf-8", { fatal: true });
33
37
  const ASSET_CODE_REGEX = /^[A-Za-z0-9]{1,12}$/;
@@ -182,6 +186,16 @@ export function encodeSreq1Bytes(packet) {
182
186
  }
183
187
  parts.push(encodeTlv(SREQ1_TLV_MEMO, memoBytes));
184
188
  }
189
+ if (packet.hwVerifierPubkeys !== undefined) {
190
+ if (packet.hwVerifierPubkeys.length < 1 ||
191
+ packet.hwVerifierPubkeys.length > MAX_SREQ1_HW_VERIFIER_PUBKEYS) {
192
+ throw new Error(`SREQ1 hwVerifierPubkeys count must be in 1..=${MAX_SREQ1_HW_VERIFIER_PUBKEYS}, got ${packet.hwVerifierPubkeys.length}`);
193
+ }
194
+ for (let i = 0; i < packet.hwVerifierPubkeys.length; i++) {
195
+ assertBytesLength(packet.hwVerifierPubkeys[i], 32, `hwVerifierPubkeys[${i}]`);
196
+ }
197
+ parts.push(encodeTlv(SREQ1_TLV_HW_VERIFIER_PUBKEYS, concatBytes(...packet.hwVerifierPubkeys)));
198
+ }
185
199
  return concatBytes(...parts);
186
200
  }
187
201
  export function decodeSreq1Bytes(raw) {
@@ -227,6 +241,7 @@ export function decodeSreq1Bytes(raw) {
227
241
  let classicAsset;
228
242
  let acceptedFactoryVers;
229
243
  let memo;
244
+ let hwVerifierPubkeys;
230
245
  const seenKnownTlvs = new Set();
231
246
  let unknownOddTlvCount = 0;
232
247
  while (offset < raw.length) {
@@ -313,6 +328,19 @@ export function decodeSreq1Bytes(raw) {
313
328
  memo = utf8Decoder.decode(val);
314
329
  break;
315
330
  }
331
+ case SREQ1_TLV_HW_VERIFIER_PUBKEYS: {
332
+ if (seenKnownTlvs.has(tlvType))
333
+ throw new Error("Duplicate SREQ1 hw_verifier_pubkeys TLV");
334
+ seenKnownTlvs.add(tlvType);
335
+ if (tlvLen === 0 || tlvLen % 32 !== 0 || tlvLen / 32 > MAX_SREQ1_HW_VERIFIER_PUBKEYS) {
336
+ throw new Error(`Invalid SREQ1 hw_verifier_pubkeys TLV length: ${tlvLen} (must be 32..=${MAX_SREQ1_HW_VERIFIER_PUBKEYS * 32}, multiple of 32)`);
337
+ }
338
+ hwVerifierPubkeys = [];
339
+ for (let i = 0; i < tlvLen; i += 32) {
340
+ hwVerifierPubkeys.push(val.slice(i, i + 32));
341
+ }
342
+ break;
343
+ }
316
344
  default: {
317
345
  // WIRE-FORMAT-v1.2.md §4.1: Even unknown types MUST fail; odd unknown types skip.
318
346
  if ((tlvType & 1) === 0) {
@@ -350,6 +378,7 @@ export function decodeSreq1Bytes(raw) {
350
378
  ...(classicAsset !== undefined ? { classicAsset } : {}),
351
379
  ...(acceptedFactoryVers !== undefined ? { acceptedFactoryVers } : {}),
352
380
  ...(memo !== undefined ? { memo } : {}),
381
+ ...(hwVerifierPubkeys !== undefined ? { hwVerifierPubkeys } : {}),
353
382
  };
354
383
  }
355
384
  export function encodeSreq1(packet) {
@@ -991,6 +1020,8 @@ export function classifyPayload(encoded) {
991
1020
  };
992
1021
  case HRP_SMESHC:
993
1022
  return { mode: "witnessed_vault_cert", prefix: "SMESHC1", decoded: decodeSmeshc1Bytes(payload) };
1023
+ case HRP_SMESHH:
1024
+ return { mode: "hw_roaming_payment", prefix: "SMESHH1", decoded: decodeSmeshh1Bytes(payload) };
994
1025
  default:
995
1026
  throw new Error(`Unknown Outpost wire prefix "${hrp}1"`);
996
1027
  }
@@ -36,9 +36,12 @@ export interface WitnessChallengeResponseDto {
36
36
  readonly instance_uuid: string;
37
37
  readonly latest_known_ledger: number;
38
38
  readonly signature: string;
39
+ readonly signature_v2?: string;
40
+ readonly signature_v3?: string;
39
41
  }
40
42
  export interface WitnessInfoResponse {
41
43
  readonly station_id?: string;
44
+ readonly moniker?: string;
42
45
  readonly version: string;
43
46
  readonly protocol_version?: string;
44
47
  readonly network_hint?: number;
@@ -74,6 +77,10 @@ export interface StoredGenesisCertMeta {
74
77
  readonly witness_threshold: number;
75
78
  readonly witnesses: readonly string[];
76
79
  readonly genesis_sigs: readonly WitnessSigEntryDto[];
80
+ /** Optional token symbol (e.g. `"XLM"`, `"USDC"`, or on-chain SEP-41 symbol) learned at L1 genesis or canonical wire token. */
81
+ readonly token_symbol?: string;
82
+ /** Optional token decimals (`0..=18`) learned at L1 genesis or canonical wire token (omitted if unknown). */
83
+ readonly token_decimals?: number;
77
84
  }
78
85
  /**
79
86
  * Canonical `"SMW1_FRESH"` checkpoint DTO exchanged with Rust `witness-node` (`DS-05`).
@@ -147,6 +154,18 @@ export interface WitnessPendingLock {
147
154
  /** Optional `SMESHC1` quorum cert (`seq < first_link.seq`) proving pre-chain base for out-of-order locks (`V1-NEW-1` / `R5-H8`). */
148
155
  readonly base_cert?: string;
149
156
  }
157
+ /**
158
+ * Non-authoritative per-`seq` settlement relay hint returned by a Station on `GET /state`.
159
+ *
160
+ * Security invariant (`AGENTS.md` §1.6): wallets/receivers may show this as an informational
161
+ * UX hint while still offline, but MUST NEVER treat a single Station's claim as terminal
162
+ * `L1_FINAL` finality or delete `SMESHC1` without direct Stellar L1 confirmation.
163
+ */
164
+ export interface RelayedReceiptHintDto {
165
+ readonly seq: number;
166
+ readonly relayed_at: number;
167
+ readonly tx_hash?: string;
168
+ }
150
169
  export interface GetStateResponse {
151
170
  readonly cert_0?: string | null;
152
171
  readonly cert_0_meta?: StoredGenesisCertMeta;
@@ -160,6 +179,7 @@ export interface GetStateResponse {
160
179
  readonly closed?: boolean;
161
180
  readonly frozen?: boolean;
162
181
  readonly equivocation_proof?: Record<string, unknown> | null;
182
+ readonly relayed_receipts?: readonly RelayedReceiptHintDto[];
163
183
  }
164
184
  export interface WitnessSignRequest {
165
185
  /** Framed `SMESHI1...` unwitnessed intent string. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@outpost-protocol/core",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "description": "Outpost v1.2 offline Stellar payment wire codec, cryptographic digests, BLE transport, and wallet SDK",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://outpost.cash",