@outpost-protocol/core 0.3.0 → 0.3.1
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 +6 -5
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/mesh.d.ts +165 -0
- package/dist/mesh.js +528 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# `@outpost-protocol/core`
|
|
2
2
|
|
|
3
|
-
Outpost v1.2 offline-resilient Stellar payment wire codec, cryptographic digests, BLE
|
|
3
|
+
Outpost v2 (Hardware Roaming) & v1.2 (Witness Pockets) offline-resilient Stellar payment wire codec, cryptographic digests, QR / `UR:SMESH` & BLE GATT transports, Soroban builders, and non-custodial sender wallet SDK.
|
|
4
4
|
|
|
5
5
|
## Install
|
|
6
6
|
|
|
@@ -12,11 +12,12 @@ npm install @outpost-protocol/core
|
|
|
12
12
|
|
|
13
13
|
## What's Included
|
|
14
14
|
|
|
15
|
-
- **
|
|
15
|
+
- **Outpost v2 Hardware Roaming (`0.3.0+`)** — `SMESHH1` canonical binary & Base32 CRC-32C codec (`encodeSmeshh1` / `decodeSmeshh1` / `MAX_SMESHH1_BYTES = 28_000`), `SMW2_HW*` SHA-256 digests (`computeHwAttestationChallenge`, `computeHwIntentDigest`, `computeHwVoidDigest`, `computeHwGenesisDigest`), Android KeyMint Merkle tree (`hwMerkleBuildTree` / `hwMerkleVerifyProof`), ASN.1 DER to canonical low-S P-256 normalization (`normalizeP256DerToLowS64`), `HwGatewayClient`, JSON-serializable `HwPocketSession`, Static QR / Animated `UR:SMESH` handover (`encodeSmeshh1ForQr` / `Smeshh1QrCollector`), and BLE GATT P2P (`OUTPOST_BLE_P2P_SERVICE_UUID`, `BleHwPaymentSender`, `BleHwPaymentReceiver`, `BleRequestReassembler`).
|
|
16
|
+
- **v2 Soroban Hardware Contract Builders (`0.3.0+`)** — browser/WebView-safe `buildDepositHwOp`, `buildSettleHwOp`, `buildVoidHwSeqsOp`, `buildCloseHwInstantOp`, `buildRequestHwExitOp`, `buildFinalizeHwExitOp`, `encodeHwProofScVal`, and `decodeHwPocketStateScVal`.
|
|
17
|
+
- **v1.2 Wire Codecs (`SREQ1` + odd TLV `0xF1`, `SMESHI1`, `SMESHC1`, `SMESHD1`, `SMESHF1`, `UR:SMESH`)** — strict `BigInt` asset-agnostic encoding/decoding with CRC-32C framing, canonical Base32, `classifyPayload`, and cross-language golden-vector parity with Soroban & Rust (`outpost-wire`).
|
|
16
18
|
- **Cryptographic Digests & Vault Derivation** — cofactorless RFC 8032 Ed25519 helpers, canonical `UserVault` deterministic ID derivation, and domain-separated `GENESIS` / `INTENT` / `WITNESS_LOCK` / `WITNESS_CERT` preimages.
|
|
17
|
-
- **Soroban Contract
|
|
18
|
-
- **
|
|
19
|
-
- **Non-Custodial `OfflineWallet` & `JsonWalletStorage`** — per-pocket async mutex, burn-before-display monotonic `localSeq`, running pocket budget enforcement (`getPocketBudget`), portable JSON state persistence (`JsonWalletStorage` / `serializeWalletState`), asset-agnostic untrusted `SREQ1.tip` caps, duplicate `(recipient, orderId)` retry protection, and authenticated `SEQ_TOO_LOW` resync.
|
|
19
|
+
- **v1.2 Soroban Contract Builders & Coordinators (`0.2.0+`)** — `buildCreateVaultOp`, `buildDepositOp`, `buildSettleDelegatedOp`, `buildClosePocketCooperativeOp`, `buildRequestExitOp`, `buildFinalizeExitOp`, `buildClaimCreditOp`, `coordinateInitGenesis`, `coordinateRefreshFreshness`, and `coordinateCloseCooperative`.
|
|
20
|
+
- **Non-Custodial `OfflineWallet` & `JsonWalletStorage`** — per-pocket async mutex, burn-before-display monotonic `localSeq`, running pocket budget enforcement (`getPocketBudget`), portable JSON state persistence, asset-agnostic untrusted `SREQ1.tip` caps, duplicate `(recipient, orderId)` retry protection, and authenticated `SEQ_TOO_LOW` resync.
|
|
20
21
|
- **Direct & Classic Settlement Builders** — `order_id`-bound CAP-0046-11 `relay_direct` (`SMESHD1`) and hardened CAP-0015 `FeeBumpTransaction` (`SMESHF1`).
|
|
21
22
|
- **Station Transports** — `WitnessClient` (LAN/WAN HTTP) and `BleWitnessClient` (`OUTPOST_BLE_V1` GATT framing for internet-free mobile/POS witnessing).
|
|
22
23
|
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
package/dist/mesh.d.ts
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonical Transport-Agnostic Station Mesh Gossip & v2 Settlement Mule Wire Codec + Client
|
|
3
|
+
* (`@outpost-protocol/core`).
|
|
4
|
+
*
|
|
5
|
+
* Byte-for-byte parity with `crates/outpost-wire/src/mesh.rs` (`OUTPOST_GOSSIP_V1`, magic `0xA1`).
|
|
6
|
+
*
|
|
7
|
+
* Enables wallets, merchant POS apps, and passing Stations to:
|
|
8
|
+
* 1. Hand v1.2 `SMESHI1` intents + `cert_0` to ANY random nearby Station (`POST /mesh/gossip` over
|
|
9
|
+
* BLE GATT, LAN HTTP, Wi-Fi Direct, or LoRa), even if that Station is not in the pocket's pinned
|
|
10
|
+
* `[W0, W1, W2]` set.
|
|
11
|
+
* 2. Route reverse-path `V12_WITNESS_LOCK_RESP` confirmations back across the mesh to the POS.
|
|
12
|
+
* 3. Hand verified v1.2 (`SMESHC1`) and v2 (`SMESHH1`) settlement packets to ANY nearby Station
|
|
13
|
+
* (`POST /v2/relay` or `OutpostGossipFrame`) for permissionless store-and-forward L1 settlement.
|
|
14
|
+
*/
|
|
15
|
+
import { type Smeshh1Packet } from "./hw.js";
|
|
16
|
+
import { type EpochGenesisCert, type IndexedWitnessSignature, type Smeshc1Packet, type Smeshi1Packet } from "./wire.js";
|
|
17
|
+
import { type FetchLike, type WitnessSigEntryDto } from "./witnessClient.js";
|
|
18
|
+
export declare const OUTPOST_GOSSIP_MAGIC_V1 = 161;
|
|
19
|
+
export declare const TAG_GOSSIP_ID_V1: Uint8Array<ArrayBuffer>;
|
|
20
|
+
export declare const GOSSIP_HEADER_LEN = 46;
|
|
21
|
+
export declare const GOSSIP_TRAILER_LEN = 4;
|
|
22
|
+
export declare const MAX_GOSSIP_HOP_TTL = 8;
|
|
23
|
+
export declare const DEFAULT_GOSSIP_HOP_TTL = 5;
|
|
24
|
+
export declare const MAX_GOSSIP_PAYLOAD_BYTES = 28672;
|
|
25
|
+
export declare const MAX_GOSSIP_FRAME_BYTES: number;
|
|
26
|
+
export declare const MAX_MESH_CERT0_BYTES = 4096;
|
|
27
|
+
export declare const MAX_MESH_LATEST_CERT_BYTES = 4096;
|
|
28
|
+
export declare const GossipFrameKind: {
|
|
29
|
+
readonly V12_INTENT_REQ: 1;
|
|
30
|
+
readonly V12_WITNESS_LOCK_RESP: 2;
|
|
31
|
+
readonly V12_LOCKED_SETTLE: 3;
|
|
32
|
+
readonly V2_HW_SETTLE: 4;
|
|
33
|
+
};
|
|
34
|
+
export type GossipFrameKind = (typeof GossipFrameKind)[keyof typeof GossipFrameKind];
|
|
35
|
+
export declare function gossipFrameKindToString(kind: GossipFrameKind): string;
|
|
36
|
+
export interface OutpostGossipFrame {
|
|
37
|
+
readonly kind: GossipFrameKind;
|
|
38
|
+
readonly hopTtl: number;
|
|
39
|
+
readonly msgId: Uint8Array;
|
|
40
|
+
readonly createdTs: bigint;
|
|
41
|
+
readonly payload: Uint8Array;
|
|
42
|
+
}
|
|
43
|
+
export interface V12IntentReqPayload {
|
|
44
|
+
readonly intent: Smeshi1Packet;
|
|
45
|
+
readonly cert0: EpochGenesisCert;
|
|
46
|
+
readonly cumulativeSpent: bigint;
|
|
47
|
+
readonly latestCert?: Smeshc1Packet;
|
|
48
|
+
}
|
|
49
|
+
export interface V12WitnessLockRespPayload {
|
|
50
|
+
readonly vaultId: Uint8Array;
|
|
51
|
+
readonly pocketId: number;
|
|
52
|
+
readonly epoch: number;
|
|
53
|
+
readonly seq: number;
|
|
54
|
+
readonly intentDigest: Uint8Array;
|
|
55
|
+
readonly cumulativeSpent: bigint;
|
|
56
|
+
readonly witnessSigs: readonly IndexedWitnessSignature[];
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Computes canonical hop-invariant `msg_id`:
|
|
60
|
+
* `SHA-256("OUTPOST_GOSSIP_ID_V1" || kind(u8) || payload)`.
|
|
61
|
+
*/
|
|
62
|
+
export declare function computeGossipMsgId(kind: GossipFrameKind, payload: Uint8Array): Uint8Array;
|
|
63
|
+
export declare function createGossipFrame(params: {
|
|
64
|
+
readonly kind: GossipFrameKind;
|
|
65
|
+
readonly hopTtl?: number;
|
|
66
|
+
readonly createdTs?: bigint | number;
|
|
67
|
+
readonly payload: Uint8Array;
|
|
68
|
+
}): OutpostGossipFrame;
|
|
69
|
+
export declare function decrementGossipFrameHop(frame: OutpostGossipFrame): OutpostGossipFrame | undefined;
|
|
70
|
+
export declare function encodeGossipFrame(frame: OutpostGossipFrame): Uint8Array;
|
|
71
|
+
export declare function decodeGossipFrame(raw: Uint8Array): OutpostGossipFrame;
|
|
72
|
+
export declare function encodeV12IntentReqPayload(req: V12IntentReqPayload): Uint8Array;
|
|
73
|
+
export declare function decodeV12IntentReqPayload(raw: Uint8Array): V12IntentReqPayload;
|
|
74
|
+
export declare function encodeV12WitnessLockRespPayload(resp: V12WitnessLockRespPayload): Uint8Array;
|
|
75
|
+
export declare function decodeV12WitnessLockRespPayload(raw: Uint8Array): V12WitnessLockRespPayload;
|
|
76
|
+
/**
|
|
77
|
+
* Cryptographically verifies EVERY Ed25519 `"SMW1_WITNESS"` signature inside a
|
|
78
|
+
* `V12WitnessLockRespPayload` against `sortedWitnesses`. Throws on any invalid signature.
|
|
79
|
+
*/
|
|
80
|
+
export declare function verifyV12WitnessLockResp(resp: V12WitnessLockRespPayload, networkId: Uint8Array, sortedWitnesses: readonly Uint8Array[]): Uint8Array;
|
|
81
|
+
export declare function buildV12IntentReqGossipFrame(req: V12IntentReqPayload, options?: {
|
|
82
|
+
readonly hopTtl?: number;
|
|
83
|
+
readonly createdTs?: bigint | number;
|
|
84
|
+
}): OutpostGossipFrame;
|
|
85
|
+
export declare function buildV12WitnessLockRespGossipFrame(resp: V12WitnessLockRespPayload, options?: {
|
|
86
|
+
readonly hopTtl?: number;
|
|
87
|
+
readonly createdTs?: bigint | number;
|
|
88
|
+
}): OutpostGossipFrame;
|
|
89
|
+
export declare function buildV12LockedSettleGossipFrame(cert: Smeshc1Packet, options?: {
|
|
90
|
+
readonly hopTtl?: number;
|
|
91
|
+
readonly createdTs?: bigint | number;
|
|
92
|
+
}): OutpostGossipFrame;
|
|
93
|
+
export declare function buildV2HwSettleGossipFrame(packet: Smeshh1Packet, options?: {
|
|
94
|
+
readonly hopTtl?: number;
|
|
95
|
+
readonly createdTs?: bigint | number;
|
|
96
|
+
}): OutpostGossipFrame;
|
|
97
|
+
export interface MeshGossipResponseDto {
|
|
98
|
+
readonly accepted: boolean;
|
|
99
|
+
readonly duplicate: boolean;
|
|
100
|
+
readonly kind: string;
|
|
101
|
+
readonly msg_id: string;
|
|
102
|
+
readonly status: "PENDING_WITNESS_LOCK" | "WITNESS_LOCKED" | "QUEUED_FOR_SETTLEMENT" | "ALREADY_SETTLED" | string;
|
|
103
|
+
readonly intent_digest?: string;
|
|
104
|
+
readonly collected_sigs?: readonly WitnessSigEntryDto[];
|
|
105
|
+
readonly witness_threshold?: number;
|
|
106
|
+
readonly lock_frame_hex?: string;
|
|
107
|
+
readonly smeshc1?: string;
|
|
108
|
+
readonly forward_frame_hex?: string;
|
|
109
|
+
readonly mule_queue_id?: number;
|
|
110
|
+
}
|
|
111
|
+
export interface MeshPollIntentResponseDto {
|
|
112
|
+
readonly found: boolean;
|
|
113
|
+
readonly status?: "PENDING_WITNESS_LOCK" | "WITNESS_LOCKED" | string;
|
|
114
|
+
readonly intent_digest?: string;
|
|
115
|
+
readonly witness_threshold?: number;
|
|
116
|
+
readonly collected_sigs?: readonly WitnessSigEntryDto[];
|
|
117
|
+
readonly lock_frame_hex?: string;
|
|
118
|
+
readonly smeshc1?: string;
|
|
119
|
+
}
|
|
120
|
+
export interface MeshPollFramesResponseDto {
|
|
121
|
+
readonly frames_hex: readonly string[];
|
|
122
|
+
readonly next_since_ts: number;
|
|
123
|
+
}
|
|
124
|
+
export interface MeshStatusResponseDto {
|
|
125
|
+
readonly mesh_enabled: boolean;
|
|
126
|
+
readonly blackout_mode: boolean;
|
|
127
|
+
readonly gateway_url_configured: boolean;
|
|
128
|
+
readonly payout_address_configured: boolean;
|
|
129
|
+
readonly hw_verifier_count: number;
|
|
130
|
+
readonly witness_directory_count: number;
|
|
131
|
+
readonly counts: {
|
|
132
|
+
readonly pending_intents: number;
|
|
133
|
+
readonly locked_intents: number;
|
|
134
|
+
readonly mule_pending_v12: number;
|
|
135
|
+
readonly mule_pending_v2: number;
|
|
136
|
+
readonly mule_settled_total: number;
|
|
137
|
+
readonly mule_failed_total: number;
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
export interface StationMeshClientOptions {
|
|
141
|
+
readonly fetch?: FetchLike;
|
|
142
|
+
readonly timeoutMs?: number;
|
|
143
|
+
readonly maxResponseBytes?: number;
|
|
144
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* HTTP / BLE-backed client for any Outpost Station's unpinned Mesh Gossip (`/mesh/gossip`,
|
|
148
|
+
* `/mesh/poll`, `/mesh/status`) and v2 Settlement Mule (`/v2/relay`) endpoints.
|
|
149
|
+
*/
|
|
150
|
+
export declare class StationMeshClient {
|
|
151
|
+
readonly baseUrl: string;
|
|
152
|
+
private readonly fetchImpl;
|
|
153
|
+
private readonly timeoutMs;
|
|
154
|
+
private readonly maxResponseBytes;
|
|
155
|
+
private readonly headers;
|
|
156
|
+
constructor(baseUrl: string, options?: StationMeshClientOptions);
|
|
157
|
+
private requestJson;
|
|
158
|
+
submitGossipFrame(frame: OutpostGossipFrame | Uint8Array, options?: {
|
|
159
|
+
readonly peerWitnessUrls?: Readonly<Record<string, string>>;
|
|
160
|
+
}): Promise<MeshGossipResponseDto>;
|
|
161
|
+
relayV2Smeshh1(smeshh1: string, hopTtl?: number): Promise<MeshGossipResponseDto>;
|
|
162
|
+
pollIntentLock(intentDigestHex: string): Promise<MeshPollIntentResponseDto>;
|
|
163
|
+
pollPendingGossipFrames(sinceTs?: number, limit?: number): Promise<MeshPollFramesResponseDto>;
|
|
164
|
+
getMeshStatus(): Promise<MeshStatusResponseDto>;
|
|
165
|
+
}
|
package/dist/mesh.js
ADDED
|
@@ -0,0 +1,528 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonical Transport-Agnostic Station Mesh Gossip & v2 Settlement Mule Wire Codec + Client
|
|
3
|
+
* (`@outpost-protocol/core`).
|
|
4
|
+
*
|
|
5
|
+
* Byte-for-byte parity with `crates/outpost-wire/src/mesh.rs` (`OUTPOST_GOSSIP_V1`, magic `0xA1`).
|
|
6
|
+
*
|
|
7
|
+
* Enables wallets, merchant POS apps, and passing Stations to:
|
|
8
|
+
* 1. Hand v1.2 `SMESHI1` intents + `cert_0` to ANY random nearby Station (`POST /mesh/gossip` over
|
|
9
|
+
* BLE GATT, LAN HTTP, Wi-Fi Direct, or LoRa), even if that Station is not in the pocket's pinned
|
|
10
|
+
* `[W0, W1, W2]` set.
|
|
11
|
+
* 2. Route reverse-path `V12_WITNESS_LOCK_RESP` confirmations back across the mesh to the POS.
|
|
12
|
+
* 3. Hand verified v1.2 (`SMESHC1`) and v2 (`SMESHH1`) settlement packets to ANY nearby Station
|
|
13
|
+
* (`POST /v2/relay` or `OutpostGossipFrame`) for permissionless store-and-forward L1 settlement.
|
|
14
|
+
*/
|
|
15
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
16
|
+
import { decodeCert0Bytes, encodeCert0Bytes } from "./cert0.js";
|
|
17
|
+
import { crc32c } from "./crc32c.js";
|
|
18
|
+
import { assertBigInt, assertBytesLength, assertU16, assertU32, assertU8, computeWitnessDigest, concatBytes, MAX_U64, MAX_WITNESSES, verifyEd25519, } from "./digest.js";
|
|
19
|
+
import { encodeSmeshh1Bytes } from "./hw.js";
|
|
20
|
+
import { decodeSmeshc1Bytes, decodeSmeshi1Bytes, encodeSmeshc1Bytes, encodeSmeshi1Bytes, SMESHI1_BYTE_LENGTH, } from "./wire.js";
|
|
21
|
+
import { bytesToHex, hexToBytes, MAX_RESPONSE_BYTES, WitnessApiError, } from "./witnessClient.js";
|
|
22
|
+
import { bytesEqual } from "./xdr.js";
|
|
23
|
+
function u16be(n) {
|
|
24
|
+
return new Uint8Array([(n >>> 8) & 0xff, n & 0xff]);
|
|
25
|
+
}
|
|
26
|
+
function u32be(n) {
|
|
27
|
+
return new Uint8Array([(n >>> 24) & 0xff, (n >>> 16) & 0xff, (n >>> 8) & 0xff, n & 0xff]);
|
|
28
|
+
}
|
|
29
|
+
function u64be(n) {
|
|
30
|
+
const out = new Uint8Array(8);
|
|
31
|
+
const hi = Number((n >> 32n) & 0xffffffffn);
|
|
32
|
+
const lo = Number(n & 0xffffffffn);
|
|
33
|
+
out[0] = (hi >>> 24) & 0xff;
|
|
34
|
+
out[1] = (hi >>> 16) & 0xff;
|
|
35
|
+
out[2] = (hi >>> 8) & 0xff;
|
|
36
|
+
out[3] = hi & 0xff;
|
|
37
|
+
out[4] = (lo >>> 24) & 0xff;
|
|
38
|
+
out[5] = (lo >>> 16) & 0xff;
|
|
39
|
+
out[6] = (lo >>> 8) & 0xff;
|
|
40
|
+
out[7] = lo & 0xff;
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
43
|
+
function assertBigIntRange(v, min, max, label) {
|
|
44
|
+
assertBigInt(v, label);
|
|
45
|
+
if (v < min || v > max) {
|
|
46
|
+
throw new Error(`${label} (${v}) out of range [${min}, ${max}]`);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
const utf8Encoder = new TextEncoder();
|
|
50
|
+
const utf8Decoder = new TextDecoder("utf-8", { fatal: false });
|
|
51
|
+
export const OUTPOST_GOSSIP_MAGIC_V1 = 0xa1;
|
|
52
|
+
export const TAG_GOSSIP_ID_V1 = utf8Encoder.encode("OUTPOST_GOSSIP_ID_V1");
|
|
53
|
+
export const GOSSIP_HEADER_LEN = 46;
|
|
54
|
+
export const GOSSIP_TRAILER_LEN = 4;
|
|
55
|
+
export const MAX_GOSSIP_HOP_TTL = 8;
|
|
56
|
+
export const DEFAULT_GOSSIP_HOP_TTL = 5;
|
|
57
|
+
export const MAX_GOSSIP_PAYLOAD_BYTES = 28_672;
|
|
58
|
+
export const MAX_GOSSIP_FRAME_BYTES = GOSSIP_HEADER_LEN + MAX_GOSSIP_PAYLOAD_BYTES + GOSSIP_TRAILER_LEN;
|
|
59
|
+
export const MAX_MESH_CERT0_BYTES = 4_096;
|
|
60
|
+
export const MAX_MESH_LATEST_CERT_BYTES = 4_096;
|
|
61
|
+
export const GossipFrameKind = {
|
|
62
|
+
V12_INTENT_REQ: 1,
|
|
63
|
+
V12_WITNESS_LOCK_RESP: 2,
|
|
64
|
+
V12_LOCKED_SETTLE: 3,
|
|
65
|
+
V2_HW_SETTLE: 4,
|
|
66
|
+
};
|
|
67
|
+
export function gossipFrameKindToString(kind) {
|
|
68
|
+
switch (kind) {
|
|
69
|
+
case GossipFrameKind.V12_INTENT_REQ:
|
|
70
|
+
return "V12_INTENT_REQ";
|
|
71
|
+
case GossipFrameKind.V12_WITNESS_LOCK_RESP:
|
|
72
|
+
return "V12_WITNESS_LOCK_RESP";
|
|
73
|
+
case GossipFrameKind.V12_LOCKED_SETTLE:
|
|
74
|
+
return "V12_LOCKED_SETTLE";
|
|
75
|
+
case GossipFrameKind.V2_HW_SETTLE:
|
|
76
|
+
return "V2_HW_SETTLE";
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function readU16BE(buf, offset) {
|
|
80
|
+
return (buf[offset] << 8) | buf[offset + 1];
|
|
81
|
+
}
|
|
82
|
+
function readU32BE(buf, offset) {
|
|
83
|
+
return (((buf[offset] << 24) |
|
|
84
|
+
(buf[offset + 1] << 16) |
|
|
85
|
+
(buf[offset + 2] << 8) |
|
|
86
|
+
buf[offset + 3]) >>>
|
|
87
|
+
0);
|
|
88
|
+
}
|
|
89
|
+
function readU64BE(buf, offset) {
|
|
90
|
+
const hi = BigInt(readU32BE(buf, offset));
|
|
91
|
+
const lo = BigInt(readU32BE(buf, offset + 4));
|
|
92
|
+
return (hi << 32n) | lo;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Computes canonical hop-invariant `msg_id`:
|
|
96
|
+
* `SHA-256("OUTPOST_GOSSIP_ID_V1" || kind(u8) || payload)`.
|
|
97
|
+
*/
|
|
98
|
+
export function computeGossipMsgId(kind, payload) {
|
|
99
|
+
return sha256(concatBytes(TAG_GOSSIP_ID_V1, new Uint8Array([kind]), payload));
|
|
100
|
+
}
|
|
101
|
+
export function createGossipFrame(params) {
|
|
102
|
+
const hopTtl = params.hopTtl ?? DEFAULT_GOSSIP_HOP_TTL;
|
|
103
|
+
assertU8(hopTtl, "hopTtl");
|
|
104
|
+
if (hopTtl > MAX_GOSSIP_HOP_TTL) {
|
|
105
|
+
throw new Error(`hopTtl (${hopTtl}) exceeds MAX_GOSSIP_HOP_TTL (${MAX_GOSSIP_HOP_TTL})`);
|
|
106
|
+
}
|
|
107
|
+
if (params.payload.length === 0 || params.payload.length > MAX_GOSSIP_PAYLOAD_BYTES) {
|
|
108
|
+
throw new Error(`gossip payload length (${params.payload.length}) must be in 1..=${MAX_GOSSIP_PAYLOAD_BYTES}`);
|
|
109
|
+
}
|
|
110
|
+
const createdTs = params.createdTs !== undefined
|
|
111
|
+
? typeof params.createdTs === "bigint"
|
|
112
|
+
? params.createdTs
|
|
113
|
+
: BigInt(Math.trunc(params.createdTs))
|
|
114
|
+
: BigInt(Math.floor(Date.now() / 1000));
|
|
115
|
+
assertBigIntRange(createdTs, 0n, MAX_U64, "createdTs");
|
|
116
|
+
const payloadCopy = new Uint8Array(params.payload);
|
|
117
|
+
return {
|
|
118
|
+
kind: params.kind,
|
|
119
|
+
hopTtl,
|
|
120
|
+
msgId: computeGossipMsgId(params.kind, payloadCopy),
|
|
121
|
+
createdTs,
|
|
122
|
+
payload: payloadCopy,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
export function decrementGossipFrameHop(frame) {
|
|
126
|
+
if (frame.hopTtl <= 0)
|
|
127
|
+
return undefined;
|
|
128
|
+
return {
|
|
129
|
+
kind: frame.kind,
|
|
130
|
+
hopTtl: frame.hopTtl - 1,
|
|
131
|
+
msgId: new Uint8Array(frame.msgId),
|
|
132
|
+
createdTs: frame.createdTs,
|
|
133
|
+
payload: new Uint8Array(frame.payload),
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
export function encodeGossipFrame(frame) {
|
|
137
|
+
assertU8(frame.hopTtl, "hopTtl");
|
|
138
|
+
if (frame.hopTtl > MAX_GOSSIP_HOP_TTL) {
|
|
139
|
+
throw new Error(`hopTtl (${frame.hopTtl}) exceeds MAX_GOSSIP_HOP_TTL (${MAX_GOSSIP_HOP_TTL})`);
|
|
140
|
+
}
|
|
141
|
+
if (frame.payload.length === 0 || frame.payload.length > MAX_GOSSIP_PAYLOAD_BYTES) {
|
|
142
|
+
throw new Error(`gossip payload length (${frame.payload.length}) must be in 1..=${MAX_GOSSIP_PAYLOAD_BYTES}`);
|
|
143
|
+
}
|
|
144
|
+
assertBytesLength(frame.msgId, 32, "msgId");
|
|
145
|
+
const expectedId = computeGossipMsgId(frame.kind, frame.payload);
|
|
146
|
+
if (!bytesEqual(frame.msgId, expectedId)) {
|
|
147
|
+
throw new Error("gossip frame msgId does not match payload digest");
|
|
148
|
+
}
|
|
149
|
+
assertBigIntRange(frame.createdTs, 0n, MAX_U64, "createdTs");
|
|
150
|
+
const body = concatBytes(new Uint8Array([OUTPOST_GOSSIP_MAGIC_V1, frame.kind, frame.hopTtl, 0x00]), frame.msgId, u64be(frame.createdTs), u16be(frame.payload.length), frame.payload);
|
|
151
|
+
const checksum = crc32c(body);
|
|
152
|
+
return concatBytes(body, u32be(checksum));
|
|
153
|
+
}
|
|
154
|
+
export function decodeGossipFrame(raw) {
|
|
155
|
+
if (raw.length < GOSSIP_HEADER_LEN + 1 + GOSSIP_TRAILER_LEN) {
|
|
156
|
+
throw new Error("OutpostGossipFrame truncated");
|
|
157
|
+
}
|
|
158
|
+
if (raw.length > MAX_GOSSIP_FRAME_BYTES) {
|
|
159
|
+
throw new Error(`OutpostGossipFrame exceeds MAX_GOSSIP_FRAME_BYTES (${MAX_GOSSIP_FRAME_BYTES})`);
|
|
160
|
+
}
|
|
161
|
+
const bodyEnd = raw.length - GOSSIP_TRAILER_LEN;
|
|
162
|
+
const expectedCrc = readU32BE(raw, bodyEnd);
|
|
163
|
+
const actualCrc = crc32c(raw.subarray(0, bodyEnd));
|
|
164
|
+
if (actualCrc !== expectedCrc) {
|
|
165
|
+
throw new Error("OutpostGossipFrame CRC32C mismatch");
|
|
166
|
+
}
|
|
167
|
+
if (raw[0] !== OUTPOST_GOSSIP_MAGIC_V1) {
|
|
168
|
+
throw new Error(`Unexpected OutpostGossipFrame magic 0x${raw[0].toString(16)}`);
|
|
169
|
+
}
|
|
170
|
+
const kindVal = raw[1];
|
|
171
|
+
if (kindVal !== GossipFrameKind.V12_INTENT_REQ &&
|
|
172
|
+
kindVal !== GossipFrameKind.V12_WITNESS_LOCK_RESP &&
|
|
173
|
+
kindVal !== GossipFrameKind.V12_LOCKED_SETTLE &&
|
|
174
|
+
kindVal !== GossipFrameKind.V2_HW_SETTLE) {
|
|
175
|
+
throw new Error(`Unknown OutpostGossipFrame kind ${kindVal}`);
|
|
176
|
+
}
|
|
177
|
+
const hopTtl = raw[2];
|
|
178
|
+
if (hopTtl > MAX_GOSSIP_HOP_TTL) {
|
|
179
|
+
throw new Error(`OutpostGossipFrame hopTtl (${hopTtl}) exceeds ${MAX_GOSSIP_HOP_TTL}`);
|
|
180
|
+
}
|
|
181
|
+
if (raw[3] !== 0x00) {
|
|
182
|
+
throw new Error(`Non-zero reserved OutpostGossipFrame flags 0x${raw[3].toString(16)}`);
|
|
183
|
+
}
|
|
184
|
+
const msgId = new Uint8Array(raw.subarray(4, 36));
|
|
185
|
+
const createdTs = readU64BE(raw, 36);
|
|
186
|
+
const payloadLen = readU16BE(raw, 44);
|
|
187
|
+
if (payloadLen === 0 || payloadLen > MAX_GOSSIP_PAYLOAD_BYTES) {
|
|
188
|
+
throw new Error(`Invalid OutpostGossipFrame payloadLen ${payloadLen}`);
|
|
189
|
+
}
|
|
190
|
+
if (GOSSIP_HEADER_LEN + payloadLen !== bodyEnd) {
|
|
191
|
+
throw new Error("OutpostGossipFrame payload length does not match frame size");
|
|
192
|
+
}
|
|
193
|
+
const payload = new Uint8Array(raw.subarray(GOSSIP_HEADER_LEN, bodyEnd));
|
|
194
|
+
const expectedId = computeGossipMsgId(kindVal, payload);
|
|
195
|
+
if (!bytesEqual(msgId, expectedId)) {
|
|
196
|
+
throw new Error("OutpostGossipFrame msgId mismatch");
|
|
197
|
+
}
|
|
198
|
+
return {
|
|
199
|
+
kind: kindVal,
|
|
200
|
+
hopTtl,
|
|
201
|
+
msgId,
|
|
202
|
+
createdTs,
|
|
203
|
+
payload,
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
// ---------------------------------------------------------------------------
|
|
207
|
+
// Inner Binary Payload Codecs (Exact Parity with crates/outpost-wire/src/mesh.rs)
|
|
208
|
+
// ---------------------------------------------------------------------------
|
|
209
|
+
export function encodeV12IntentReqPayload(req) {
|
|
210
|
+
const intentBytes = encodeSmeshi1Bytes(req.intent);
|
|
211
|
+
if (intentBytes.length !== SMESHI1_BYTE_LENGTH) {
|
|
212
|
+
throw new Error(`Expected SMESHI1 binary length ${SMESHI1_BYTE_LENGTH}, got ${intentBytes.length}`);
|
|
213
|
+
}
|
|
214
|
+
const cert0Bytes = encodeCert0Bytes(req.cert0);
|
|
215
|
+
if (cert0Bytes.length === 0 || cert0Bytes.length > MAX_MESH_CERT0_BYTES) {
|
|
216
|
+
throw new Error(`cert0 length (${cert0Bytes.length}) exceeds ${MAX_MESH_CERT0_BYTES}`);
|
|
217
|
+
}
|
|
218
|
+
const cost = req.intent.amount + req.intent.maxTip;
|
|
219
|
+
assertBigIntRange(req.cumulativeSpent, cost, req.cert0.epochTotalDeposited, "cumulativeSpent");
|
|
220
|
+
const latestBytes = req.latestCert ? encodeSmeshc1Bytes(req.latestCert) : new Uint8Array(0);
|
|
221
|
+
if (latestBytes.length > MAX_MESH_LATEST_CERT_BYTES) {
|
|
222
|
+
throw new Error(`latestCert length (${latestBytes.length}) exceeds ${MAX_MESH_LATEST_CERT_BYTES}`);
|
|
223
|
+
}
|
|
224
|
+
return concatBytes(u16be(intentBytes.length), intentBytes, u16be(cert0Bytes.length), cert0Bytes, u64be(req.cumulativeSpent), u16be(latestBytes.length), latestBytes);
|
|
225
|
+
}
|
|
226
|
+
export function decodeV12IntentReqPayload(raw) {
|
|
227
|
+
if (raw.length > MAX_GOSSIP_PAYLOAD_BYTES) {
|
|
228
|
+
throw new Error("V12IntentReq payload exceeds MAX_GOSSIP_PAYLOAD_BYTES");
|
|
229
|
+
}
|
|
230
|
+
let pos = 0;
|
|
231
|
+
const take = (n) => {
|
|
232
|
+
if (pos + n > raw.length)
|
|
233
|
+
throw new Error("V12IntentReq truncated");
|
|
234
|
+
const slice = raw.subarray(pos, pos + n);
|
|
235
|
+
pos += n;
|
|
236
|
+
return slice;
|
|
237
|
+
};
|
|
238
|
+
const intentLen = readU16BE(take(2), 0);
|
|
239
|
+
if (intentLen !== SMESHI1_BYTE_LENGTH) {
|
|
240
|
+
throw new Error(`Invalid intentLen ${intentLen} (expected ${SMESHI1_BYTE_LENGTH})`);
|
|
241
|
+
}
|
|
242
|
+
const intent = decodeSmeshi1Bytes(take(intentLen));
|
|
243
|
+
const cert0Len = readU16BE(take(2), 0);
|
|
244
|
+
if (cert0Len === 0 || cert0Len > MAX_MESH_CERT0_BYTES) {
|
|
245
|
+
throw new Error(`Invalid cert0Len ${cert0Len}`);
|
|
246
|
+
}
|
|
247
|
+
const cert0 = decodeCert0Bytes(take(cert0Len));
|
|
248
|
+
const cumulativeSpent = readU64BE(take(8), 0);
|
|
249
|
+
const latestLen = readU16BE(take(2), 0);
|
|
250
|
+
if (latestLen > MAX_MESH_LATEST_CERT_BYTES) {
|
|
251
|
+
throw new Error(`Invalid latestLen ${latestLen}`);
|
|
252
|
+
}
|
|
253
|
+
const latestCert = latestLen > 0 ? decodeSmeshc1Bytes(take(latestLen)) : undefined;
|
|
254
|
+
if (pos !== raw.length) {
|
|
255
|
+
throw new Error("V12IntentReq has trailing bytes");
|
|
256
|
+
}
|
|
257
|
+
const cost = intent.amount + intent.maxTip;
|
|
258
|
+
if (cumulativeSpent < cost || cumulativeSpent > cert0.epochTotalDeposited) {
|
|
259
|
+
throw new Error("V12IntentReq cumulativeSpent out of pocket bounds");
|
|
260
|
+
}
|
|
261
|
+
return { intent, cert0, cumulativeSpent, latestCert };
|
|
262
|
+
}
|
|
263
|
+
const V12_LOCK_RESP_FIXED_LEN = 32 + 2 + 4 + 4 + 32 + 8 + 1;
|
|
264
|
+
export function encodeV12WitnessLockRespPayload(resp) {
|
|
265
|
+
assertBytesLength(resp.vaultId, 32, "vaultId");
|
|
266
|
+
assertU16(resp.pocketId, "pocketId");
|
|
267
|
+
assertU32(resp.epoch, "epoch");
|
|
268
|
+
assertU32(resp.seq, "seq");
|
|
269
|
+
if (resp.epoch === 0 || resp.seq === 0) {
|
|
270
|
+
throw new Error("epoch and seq must be >= 1");
|
|
271
|
+
}
|
|
272
|
+
assertBytesLength(resp.intentDigest, 32, "intentDigest");
|
|
273
|
+
assertBigIntRange(resp.cumulativeSpent, 1n, MAX_U64, "cumulativeSpent");
|
|
274
|
+
if (resp.witnessSigs.length === 0 || resp.witnessSigs.length > MAX_WITNESSES) {
|
|
275
|
+
throw new Error(`witnessSigs count must be in 1..=${MAX_WITNESSES}`);
|
|
276
|
+
}
|
|
277
|
+
const parts = [
|
|
278
|
+
resp.vaultId,
|
|
279
|
+
u16be(resp.pocketId),
|
|
280
|
+
u32be(resp.epoch),
|
|
281
|
+
u32be(resp.seq),
|
|
282
|
+
resp.intentDigest,
|
|
283
|
+
u64be(resp.cumulativeSpent),
|
|
284
|
+
new Uint8Array([resp.witnessSigs.length]),
|
|
285
|
+
];
|
|
286
|
+
let prev = -1;
|
|
287
|
+
for (const ws of resp.witnessSigs) {
|
|
288
|
+
assertU8(ws.index, "index");
|
|
289
|
+
if (ws.index >= MAX_WITNESSES || ws.index <= prev) {
|
|
290
|
+
throw new Error("witnessSigs must be strictly ascending and unique (< MAX_WITNESSES)");
|
|
291
|
+
}
|
|
292
|
+
prev = ws.index;
|
|
293
|
+
assertBytesLength(ws.signature, 64, "witness signature");
|
|
294
|
+
parts.push(new Uint8Array([ws.index]), ws.signature);
|
|
295
|
+
}
|
|
296
|
+
return concatBytes(...parts);
|
|
297
|
+
}
|
|
298
|
+
export function decodeV12WitnessLockRespPayload(raw) {
|
|
299
|
+
if (raw.length < V12_LOCK_RESP_FIXED_LEN + 65) {
|
|
300
|
+
throw new Error("V12WitnessLockResp truncated");
|
|
301
|
+
}
|
|
302
|
+
const vaultId = new Uint8Array(raw.subarray(0, 32));
|
|
303
|
+
const pocketId = readU16BE(raw, 32);
|
|
304
|
+
const epoch = readU32BE(raw, 34);
|
|
305
|
+
const seq = readU32BE(raw, 38);
|
|
306
|
+
const intentDigest = new Uint8Array(raw.subarray(42, 74));
|
|
307
|
+
const cumulativeSpent = readU64BE(raw, 74);
|
|
308
|
+
const sigCount = raw[82];
|
|
309
|
+
if (sigCount === 0 || sigCount > MAX_WITNESSES) {
|
|
310
|
+
throw new Error(`Invalid V12WitnessLockResp sigCount ${sigCount}`);
|
|
311
|
+
}
|
|
312
|
+
const expectedLen = V12_LOCK_RESP_FIXED_LEN + sigCount * 65;
|
|
313
|
+
if (raw.length !== expectedLen) {
|
|
314
|
+
throw new Error("V12WitnessLockResp length mismatch");
|
|
315
|
+
}
|
|
316
|
+
const witnessSigs = [];
|
|
317
|
+
let pos = V12_LOCK_RESP_FIXED_LEN;
|
|
318
|
+
let prev = -1;
|
|
319
|
+
for (let i = 0; i < sigCount; i++) {
|
|
320
|
+
const index = raw[pos];
|
|
321
|
+
if (index >= MAX_WITNESSES || index <= prev) {
|
|
322
|
+
throw new Error("V12WitnessLockResp witness indices must be strictly ascending");
|
|
323
|
+
}
|
|
324
|
+
prev = index;
|
|
325
|
+
const signature = new Uint8Array(raw.subarray(pos + 1, pos + 65));
|
|
326
|
+
witnessSigs.push({ index, signature });
|
|
327
|
+
pos += 65;
|
|
328
|
+
}
|
|
329
|
+
if (epoch === 0 || seq === 0 || cumulativeSpent === 0n) {
|
|
330
|
+
throw new Error("V12WitnessLockResp epoch/seq/cumulativeSpent must be > 0");
|
|
331
|
+
}
|
|
332
|
+
return {
|
|
333
|
+
vaultId,
|
|
334
|
+
pocketId,
|
|
335
|
+
epoch,
|
|
336
|
+
seq,
|
|
337
|
+
intentDigest,
|
|
338
|
+
cumulativeSpent,
|
|
339
|
+
witnessSigs,
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Cryptographically verifies EVERY Ed25519 `"SMW1_WITNESS"` signature inside a
|
|
344
|
+
* `V12WitnessLockRespPayload` against `sortedWitnesses`. Throws on any invalid signature.
|
|
345
|
+
*/
|
|
346
|
+
export function verifyV12WitnessLockResp(resp, networkId, sortedWitnesses) {
|
|
347
|
+
const wDigest = computeWitnessDigest({
|
|
348
|
+
networkId,
|
|
349
|
+
vaultId: resp.vaultId,
|
|
350
|
+
pocketId: resp.pocketId,
|
|
351
|
+
epoch: resp.epoch,
|
|
352
|
+
seq: resp.seq,
|
|
353
|
+
cumulativeSpent: resp.cumulativeSpent,
|
|
354
|
+
intentDigest: resp.intentDigest,
|
|
355
|
+
});
|
|
356
|
+
for (const ws of resp.witnessSigs) {
|
|
357
|
+
if (ws.index < 0 || ws.index >= sortedWitnesses.length) {
|
|
358
|
+
throw new Error(`witness index ${ws.index} out of range`);
|
|
359
|
+
}
|
|
360
|
+
if (!verifyEd25519(ws.signature, wDigest, sortedWitnesses[ws.index])) {
|
|
361
|
+
throw new Error(`invalid Ed25519 SMW1_WITNESS signature for witness index ${ws.index}`);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
return wDigest;
|
|
365
|
+
}
|
|
366
|
+
export function buildV12IntentReqGossipFrame(req, options) {
|
|
367
|
+
return createGossipFrame({
|
|
368
|
+
kind: GossipFrameKind.V12_INTENT_REQ,
|
|
369
|
+
hopTtl: options?.hopTtl,
|
|
370
|
+
createdTs: options?.createdTs,
|
|
371
|
+
payload: encodeV12IntentReqPayload(req),
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
export function buildV12WitnessLockRespGossipFrame(resp, options) {
|
|
375
|
+
return createGossipFrame({
|
|
376
|
+
kind: GossipFrameKind.V12_WITNESS_LOCK_RESP,
|
|
377
|
+
hopTtl: options?.hopTtl,
|
|
378
|
+
createdTs: options?.createdTs,
|
|
379
|
+
payload: encodeV12WitnessLockRespPayload(resp),
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
export function buildV12LockedSettleGossipFrame(cert, options) {
|
|
383
|
+
return createGossipFrame({
|
|
384
|
+
kind: GossipFrameKind.V12_LOCKED_SETTLE,
|
|
385
|
+
hopTtl: options?.hopTtl,
|
|
386
|
+
createdTs: options?.createdTs,
|
|
387
|
+
payload: encodeSmeshc1Bytes(cert),
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
export function buildV2HwSettleGossipFrame(packet, options) {
|
|
391
|
+
return createGossipFrame({
|
|
392
|
+
kind: GossipFrameKind.V2_HW_SETTLE,
|
|
393
|
+
hopTtl: options?.hopTtl,
|
|
394
|
+
createdTs: options?.createdTs,
|
|
395
|
+
payload: encodeSmeshh1Bytes(packet),
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
async function readBoundedMeshResponse(res, maxBytes) {
|
|
399
|
+
const cl = res.headers?.get?.("content-length");
|
|
400
|
+
if (cl !== null && cl !== undefined) {
|
|
401
|
+
const n = Number(cl.trim());
|
|
402
|
+
if (Number.isFinite(n) && n > maxBytes) {
|
|
403
|
+
try {
|
|
404
|
+
await res.body?.cancel();
|
|
405
|
+
}
|
|
406
|
+
catch {
|
|
407
|
+
// ignore cancel errors
|
|
408
|
+
}
|
|
409
|
+
throw new WitnessApiError(502, "RESPONSE_TOO_LARGE", `Mesh response exceeded ${maxBytes}B`);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
if (res.body && typeof res.body.getReader === "function") {
|
|
413
|
+
const reader = res.body.getReader();
|
|
414
|
+
const chunks = [];
|
|
415
|
+
let total = 0;
|
|
416
|
+
try {
|
|
417
|
+
for (;;) {
|
|
418
|
+
const { done, value } = await reader.read();
|
|
419
|
+
if (done)
|
|
420
|
+
break;
|
|
421
|
+
if (value) {
|
|
422
|
+
total += value.byteLength;
|
|
423
|
+
if (total > maxBytes) {
|
|
424
|
+
await reader.cancel();
|
|
425
|
+
throw new WitnessApiError(502, "RESPONSE_TOO_LARGE", `Mesh response exceeded ${maxBytes}B`);
|
|
426
|
+
}
|
|
427
|
+
chunks.push(value);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
finally {
|
|
432
|
+
reader.releaseLock();
|
|
433
|
+
}
|
|
434
|
+
const merged = new Uint8Array(total);
|
|
435
|
+
let off = 0;
|
|
436
|
+
for (const c of chunks) {
|
|
437
|
+
merged.set(c, off);
|
|
438
|
+
off += c.byteLength;
|
|
439
|
+
}
|
|
440
|
+
return utf8Decoder.decode(merged);
|
|
441
|
+
}
|
|
442
|
+
const text = await res.text();
|
|
443
|
+
if (utf8Encoder.encode(text).byteLength > maxBytes) {
|
|
444
|
+
throw new WitnessApiError(502, "RESPONSE_TOO_LARGE", `Mesh response exceeded ${maxBytes}B`);
|
|
445
|
+
}
|
|
446
|
+
return text;
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* HTTP / BLE-backed client for any Outpost Station's unpinned Mesh Gossip (`/mesh/gossip`,
|
|
450
|
+
* `/mesh/poll`, `/mesh/status`) and v2 Settlement Mule (`/v2/relay`) endpoints.
|
|
451
|
+
*/
|
|
452
|
+
export class StationMeshClient {
|
|
453
|
+
baseUrl;
|
|
454
|
+
fetchImpl;
|
|
455
|
+
timeoutMs;
|
|
456
|
+
maxResponseBytes;
|
|
457
|
+
headers;
|
|
458
|
+
constructor(baseUrl, options = {}) {
|
|
459
|
+
this.baseUrl = baseUrl.replace(/\/+$/, "");
|
|
460
|
+
this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
461
|
+
this.timeoutMs = options.timeoutMs ?? 10_000;
|
|
462
|
+
this.maxResponseBytes = options.maxResponseBytes ?? MAX_RESPONSE_BYTES;
|
|
463
|
+
this.headers = options.headers ?? {};
|
|
464
|
+
}
|
|
465
|
+
async requestJson(method, path, body) {
|
|
466
|
+
const controller = new AbortController();
|
|
467
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
468
|
+
try {
|
|
469
|
+
const headers = {
|
|
470
|
+
accept: "application/json",
|
|
471
|
+
...this.headers,
|
|
472
|
+
};
|
|
473
|
+
const init = {
|
|
474
|
+
method,
|
|
475
|
+
headers,
|
|
476
|
+
signal: controller.signal,
|
|
477
|
+
};
|
|
478
|
+
if (body !== undefined) {
|
|
479
|
+
headers["content-type"] = "application/json";
|
|
480
|
+
init.body = JSON.stringify(body);
|
|
481
|
+
}
|
|
482
|
+
const res = await this.fetchImpl(`${this.baseUrl}${path}`, init);
|
|
483
|
+
const text = await readBoundedMeshResponse(res, this.maxResponseBytes);
|
|
484
|
+
let parsed;
|
|
485
|
+
try {
|
|
486
|
+
parsed = text.length > 0 ? JSON.parse(text) : {};
|
|
487
|
+
}
|
|
488
|
+
catch {
|
|
489
|
+
throw new WitnessApiError(res.status, "INVALID_JSON", `Malformed JSON from ${path}`);
|
|
490
|
+
}
|
|
491
|
+
if (!res.ok) {
|
|
492
|
+
const obj = (parsed && typeof parsed === "object" ? parsed : {});
|
|
493
|
+
const code = typeof obj.code === "string" ? obj.code : `HTTP_${res.status}`;
|
|
494
|
+
const msg = typeof obj.message === "string" ? obj.message : `Mesh HTTP ${res.status}`;
|
|
495
|
+
throw new WitnessApiError(res.status, code, msg, parsed);
|
|
496
|
+
}
|
|
497
|
+
return parsed;
|
|
498
|
+
}
|
|
499
|
+
finally {
|
|
500
|
+
clearTimeout(timer);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
async submitGossipFrame(frame, options) {
|
|
504
|
+
const raw = frame instanceof Uint8Array ? frame : encodeGossipFrame(frame);
|
|
505
|
+
const body = { frame_hex: bytesToHex(raw) };
|
|
506
|
+
if (options?.peerWitnessUrls) {
|
|
507
|
+
body.peer_witness_urls = options.peerWitnessUrls;
|
|
508
|
+
}
|
|
509
|
+
return this.requestJson("POST", "/mesh/gossip", body);
|
|
510
|
+
}
|
|
511
|
+
async relayV2Smeshh1(smeshh1, hopTtl) {
|
|
512
|
+
const body = { smeshh1 };
|
|
513
|
+
if (hopTtl !== undefined)
|
|
514
|
+
body.hop_ttl = hopTtl;
|
|
515
|
+
return this.requestJson("POST", "/v2/relay", body);
|
|
516
|
+
}
|
|
517
|
+
async pollIntentLock(intentDigestHex) {
|
|
518
|
+
const clean = bytesToHex(hexToBytes(intentDigestHex));
|
|
519
|
+
return this.requestJson("GET", `/mesh/poll?intent_digest=${encodeURIComponent(clean)}`);
|
|
520
|
+
}
|
|
521
|
+
async pollPendingGossipFrames(sinceTs = 0, limit = 16) {
|
|
522
|
+
const cap = Math.max(1, Math.min(32, Math.trunc(limit)));
|
|
523
|
+
return this.requestJson("GET", `/mesh/poll?since_ts=${Math.max(0, Math.trunc(sinceTs))}&limit=${cap}`);
|
|
524
|
+
}
|
|
525
|
+
async getMeshStatus() {
|
|
526
|
+
return this.requestJson("GET", "/mesh/status");
|
|
527
|
+
}
|
|
528
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@outpost-protocol/core",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.1",
|
|
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",
|