@inversealtruism/csd-client 0.1.3 → 0.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +153 -20
- package/dist/index.d.cts +100 -16
- package/dist/index.d.ts +100 -16
- package/dist/index.js +151 -19
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -22,33 +22,101 @@ var index_exports = {};
|
|
|
22
22
|
__export(index_exports, {
|
|
23
23
|
CsdClient: () => CsdClient,
|
|
24
24
|
rpcHeaderToHeader: () => rpcHeaderToHeader,
|
|
25
|
-
rpcTxToTx: () => rpcTxToTx
|
|
25
|
+
rpcTxToTx: () => rpcTxToTx,
|
|
26
|
+
verifyInputValues: () => verifyInputValues
|
|
26
27
|
});
|
|
27
28
|
module.exports = __toCommonJS(index_exports);
|
|
29
|
+
var import_csd_codec = require("@inversealtruism/csd-codec");
|
|
28
30
|
var CsdClient = class {
|
|
29
31
|
base;
|
|
30
32
|
f;
|
|
31
33
|
timeoutMs;
|
|
34
|
+
retries;
|
|
35
|
+
maxBytes;
|
|
32
36
|
constructor(opts) {
|
|
33
37
|
this.base = opts.baseUrl.replace(/\/+$/, "");
|
|
34
|
-
this.
|
|
38
|
+
this.maxBytes = Math.max(1, opts.maxResponseBytes ?? 16 * 1024 * 1024);
|
|
39
|
+
const gf = globalThis.fetch;
|
|
40
|
+
this.f = opts.fetch ?? (gf ? gf.bind(globalThis) : gf);
|
|
35
41
|
this.timeoutMs = opts.timeoutMs ?? 1e4;
|
|
42
|
+
this.retries = Math.max(0, opts.retries ?? 0);
|
|
36
43
|
if (!this.f) throw new Error("no fetch available \u2014 pass opts.fetch");
|
|
37
44
|
}
|
|
38
|
-
async
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
45
|
+
async req(path, init) {
|
|
46
|
+
let lastErr;
|
|
47
|
+
for (let attempt = 0; ; attempt++) {
|
|
48
|
+
try {
|
|
49
|
+
const r = await this.f(`${this.base}${path}`, { ...init, signal: AbortSignal.timeout(this.timeoutMs) });
|
|
50
|
+
if (r.status >= 500 && attempt < this.retries) {
|
|
51
|
+
lastErr = new Error(`HTTP ${r.status}`);
|
|
52
|
+
} else if (!r.ok) throw new Error(`${init?.method ?? "GET"} ${path} \u2192 HTTP ${r.status}`);
|
|
53
|
+
else return await this.readCapped(r, path);
|
|
54
|
+
} catch (e) {
|
|
55
|
+
if (attempt >= this.retries) throw e;
|
|
56
|
+
lastErr = e;
|
|
57
|
+
}
|
|
58
|
+
const cap = Math.min(5e3, 250 * 2 ** attempt);
|
|
59
|
+
await new Promise((res) => setTimeout(res, Math.floor(Math.random() * cap)));
|
|
60
|
+
void lastErr;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Read a response body as JSON with a hard byte ceiling (`maxResponseBytes`). Rejects an
|
|
65
|
+
* oversized `Content-Length` up front, and otherwise streams the body and aborts the moment
|
|
66
|
+
* it exceeds the cap — so a malicious node cannot make us buffer a giant body and OOM before
|
|
67
|
+
* we ever validate it (audit M2). Falls back to a size-checked `text()` on runtimes without a
|
|
68
|
+
* streaming body (older MV3/Node), preserving the cap as a best effort.
|
|
69
|
+
*/
|
|
70
|
+
async readCapped(r, path) {
|
|
71
|
+
const max = this.maxBytes;
|
|
72
|
+
const cl = r.headers.get("content-length");
|
|
73
|
+
if (cl && Number(cl) > max) throw new Error(`GET ${path} \u2192 response too large (${cl} > ${max} bytes)`);
|
|
74
|
+
const body = r.body;
|
|
75
|
+
if (!body || typeof body.getReader !== "function") {
|
|
76
|
+
const t = await r.text();
|
|
77
|
+
if (t.length > max) throw new Error(`GET ${path} \u2192 response too large (${t.length} > ${max} bytes)`);
|
|
78
|
+
return JSON.parse(t);
|
|
79
|
+
}
|
|
80
|
+
const reader = body.getReader();
|
|
81
|
+
const chunks = [];
|
|
82
|
+
let total = 0;
|
|
83
|
+
for (; ; ) {
|
|
84
|
+
const { value, done } = await reader.read();
|
|
85
|
+
if (done) break;
|
|
86
|
+
if (value) {
|
|
87
|
+
total += value.length;
|
|
88
|
+
if (total > max) {
|
|
89
|
+
try {
|
|
90
|
+
await reader.cancel();
|
|
91
|
+
} catch {
|
|
92
|
+
}
|
|
93
|
+
throw new Error(`GET ${path} \u2192 response exceeded ${max} bytes`);
|
|
94
|
+
}
|
|
95
|
+
chunks.push(value);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const buf = new Uint8Array(total);
|
|
99
|
+
let off = 0;
|
|
100
|
+
for (const c of chunks) {
|
|
101
|
+
buf.set(c, off);
|
|
102
|
+
off += c.length;
|
|
103
|
+
}
|
|
104
|
+
return JSON.parse(new TextDecoder().decode(buf));
|
|
105
|
+
}
|
|
106
|
+
get(path) {
|
|
107
|
+
return this.req(path);
|
|
108
|
+
}
|
|
109
|
+
post(path, body) {
|
|
110
|
+
return this.req(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
|
111
|
+
}
|
|
112
|
+
// The node returns application errors as `{ok:false, err}` with HTTP **200**, so a bare `get()`
|
|
113
|
+
// can't see them. For endpoints whose `{ok:false}` result is useless to the caller (a missing
|
|
114
|
+
// block), surface it as a thrown error — otherwise a beyond-tip/not-found block flows downstream
|
|
115
|
+
// as a malformed object and crashes opaquely (e.g. the light client reading `header.prev`).
|
|
116
|
+
async getOk(path) {
|
|
117
|
+
const j = await this.get(path);
|
|
118
|
+
if (j && j.ok === false) throw new Error(`GET ${path} \u2192 node error: ${j.err ?? "ok:false"}`);
|
|
119
|
+
return j;
|
|
52
120
|
}
|
|
53
121
|
tip() {
|
|
54
122
|
return this.get("/tip");
|
|
@@ -57,10 +125,10 @@ var CsdClient = class {
|
|
|
57
125
|
return this.get("/health");
|
|
58
126
|
}
|
|
59
127
|
blockByHeight(h) {
|
|
60
|
-
return this.
|
|
128
|
+
return this.getOk(`/block/height/${h}`);
|
|
61
129
|
}
|
|
62
130
|
blockByHash(hash) {
|
|
63
|
-
return this.
|
|
131
|
+
return this.getOk(`/block/${hash}`);
|
|
64
132
|
}
|
|
65
133
|
tx(id) {
|
|
66
134
|
return this.get(`/tx/${id}`);
|
|
@@ -83,10 +151,46 @@ var CsdClient = class {
|
|
|
83
151
|
mempool() {
|
|
84
152
|
return this.get("/mempool");
|
|
85
153
|
}
|
|
86
|
-
/**
|
|
154
|
+
/**
|
|
155
|
+
* Await a txid reaching `confirmations` (default 1) — the submit-then-confirm flow every
|
|
156
|
+
* consumer was hand-rolling. Polls /tx + /tip; resolves {txid, height, confirmations};
|
|
157
|
+
* rejects on timeout (default 10 min — CSD blocks are ~2 min but the live miner is lumpy).
|
|
158
|
+
* A tx that drops OUT of the chain mid-wait (reorg) keeps polling until it re-confirms or
|
|
159
|
+
* times out — never resolves on a stale sighting.
|
|
160
|
+
*/
|
|
161
|
+
async waitForTx(txid, opts = {}) {
|
|
162
|
+
const want = Math.max(1, opts.confirmations ?? 1);
|
|
163
|
+
const deadline = Date.now() + (opts.timeoutMs ?? 6e5);
|
|
164
|
+
const poll = Math.max(500, opts.pollMs ?? 5e3);
|
|
165
|
+
for (; ; ) {
|
|
166
|
+
try {
|
|
167
|
+
const t = await this.tx(txid);
|
|
168
|
+
if (t.ok && t.height != null) {
|
|
169
|
+
const tip = await this.tip();
|
|
170
|
+
const conf = tip.height - t.height + 1;
|
|
171
|
+
if (conf >= want) return { txid, height: t.height, confirmations: conf };
|
|
172
|
+
}
|
|
173
|
+
} catch {
|
|
174
|
+
}
|
|
175
|
+
if (Date.now() > deadline) throw new Error(`waitForTx ${txid}: not at ${want} confirmation(s) within ${opts.timeoutMs ?? 6e5}ms`);
|
|
176
|
+
await new Promise((res) => setTimeout(res, poll));
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Broadcast a node-JSON tx (from @inversealtruism/csd-tx `txToNodeJson`).
|
|
181
|
+
* ⚠ The node returns `{ok:false, err}` with HTTP 200 on REJECTION — and **`txid` is populated even
|
|
182
|
+
* then** (it's the computed id of the rejected tx). Callers MUST check `.ok`; reading `.txid`
|
|
183
|
+
* alone mistakes a rejected tx for a broadcast one. Use `submitOrThrow` if you want a hard failure.
|
|
184
|
+
*/
|
|
87
185
|
submit(nodeJsonTx) {
|
|
88
186
|
return this.post("/tx/submit", { tx: nodeJsonTx });
|
|
89
187
|
}
|
|
188
|
+
/** As `submit`, but throws on node rejection (`ok:false`) instead of returning a misleading txid. */
|
|
189
|
+
async submitOrThrow(nodeJsonTx) {
|
|
190
|
+
const r = await this.submit(nodeJsonTx);
|
|
191
|
+
if (!r.ok) throw new Error(`tx rejected by node: ${r.err ?? "unknown error"}`);
|
|
192
|
+
return r;
|
|
193
|
+
}
|
|
90
194
|
templatePropose(body) {
|
|
91
195
|
return this.post("/tx/template/propose", body);
|
|
92
196
|
}
|
|
@@ -104,6 +208,34 @@ function rpcTxToTx(j) {
|
|
|
104
208
|
outputs: j.outputs.map((o) => ({ value: o.value, scriptPubkey: o.script_pubkey }))
|
|
105
209
|
};
|
|
106
210
|
}
|
|
211
|
+
async function verifyInputValues(client, inputs) {
|
|
212
|
+
const norm = (s) => String(s).toLowerCase().replace(/^0x/, "");
|
|
213
|
+
let total = 0;
|
|
214
|
+
for (const i of inputs) {
|
|
215
|
+
let info;
|
|
216
|
+
try {
|
|
217
|
+
info = await client.tx(i.txid);
|
|
218
|
+
} catch {
|
|
219
|
+
return { ok: false, total: 0 };
|
|
220
|
+
}
|
|
221
|
+
const body = info?.tx ?? info;
|
|
222
|
+
if (!body || !Array.isArray(body.outputs) || !Array.isArray(body.inputs)) return { ok: false, total: 0 };
|
|
223
|
+
let tx;
|
|
224
|
+
try {
|
|
225
|
+
tx = rpcTxToTx(body);
|
|
226
|
+
} catch {
|
|
227
|
+
return { ok: false, total: 0 };
|
|
228
|
+
}
|
|
229
|
+
if (norm((0, import_csd_codec.txid)(tx)) !== norm(i.txid)) return { ok: false, total: 0 };
|
|
230
|
+
const out = tx.outputs[i.vout];
|
|
231
|
+
if (!out) return { ok: false, total: 0 };
|
|
232
|
+
const v = Number(out.value);
|
|
233
|
+
if (!Number.isSafeInteger(v) || v <= 0) return { ok: false, total: 0 };
|
|
234
|
+
total += v;
|
|
235
|
+
if (!Number.isSafeInteger(total)) return { ok: false, total: 0 };
|
|
236
|
+
}
|
|
237
|
+
return { ok: true, total };
|
|
238
|
+
}
|
|
107
239
|
function rpcHeaderToHeader(h) {
|
|
108
240
|
return { version: h.version, prev: h.prev, merkle: h.merkle, time: h.time, bits: h.bits, nonce: h.nonce };
|
|
109
241
|
}
|
|
@@ -111,5 +243,6 @@ function rpcHeaderToHeader(h) {
|
|
|
111
243
|
0 && (module.exports = {
|
|
112
244
|
CsdClient,
|
|
113
245
|
rpcHeaderToHeader,
|
|
114
|
-
rpcTxToTx
|
|
246
|
+
rpcTxToTx,
|
|
247
|
+
verifyInputValues
|
|
115
248
|
});
|
package/dist/index.d.cts
CHANGED
|
@@ -71,45 +71,129 @@ interface RpcSubmit {
|
|
|
71
71
|
mempool_len?: number;
|
|
72
72
|
err?: string | null;
|
|
73
73
|
}
|
|
74
|
+
interface RpcProposal {
|
|
75
|
+
ok?: boolean;
|
|
76
|
+
txid: string;
|
|
77
|
+
domain: string;
|
|
78
|
+
payload_hash: string;
|
|
79
|
+
uri: string;
|
|
80
|
+
expires_epoch: number;
|
|
81
|
+
proposer: string;
|
|
82
|
+
height: number;
|
|
83
|
+
attestations?: unknown[];
|
|
84
|
+
[k: string]: unknown;
|
|
85
|
+
}
|
|
86
|
+
interface RpcTxInfo {
|
|
87
|
+
ok: boolean;
|
|
88
|
+
txid: string;
|
|
89
|
+
block_hash?: string;
|
|
90
|
+
height?: number;
|
|
91
|
+
time?: number;
|
|
92
|
+
tx?: RpcTxJson;
|
|
93
|
+
err?: string;
|
|
94
|
+
}
|
|
95
|
+
interface RpcHealth {
|
|
96
|
+
ok: boolean;
|
|
97
|
+
height?: number;
|
|
98
|
+
peers?: number;
|
|
99
|
+
mempool_len?: number;
|
|
100
|
+
[k: string]: unknown;
|
|
101
|
+
}
|
|
102
|
+
interface WaitForTxResult {
|
|
103
|
+
txid: string;
|
|
104
|
+
height: number;
|
|
105
|
+
confirmations: number;
|
|
106
|
+
}
|
|
74
107
|
interface ClientOptions {
|
|
75
108
|
baseUrl: string;
|
|
76
109
|
fetch?: typeof fetch;
|
|
77
110
|
timeoutMs?: number;
|
|
111
|
+
/** retry NETWORK failures (timeouts, refused, 5xx) this many times with jittered backoff.
|
|
112
|
+
* NEVER retries an application result (`ok:false`) or 4xx — those are answers, not outages. */
|
|
113
|
+
retries?: number;
|
|
114
|
+
/**
|
|
115
|
+
* Hard ceiling (bytes) on a response body before it is parsed. A lying/malicious node can
|
|
116
|
+
* otherwise stream a multi-hundred-MB body that the verifier buffers (`await r.json()`) and
|
|
117
|
+
* OOM-crashes BEFORE any PoW/merkle/LWMA check runs — a remote DoS of the trusted light-client
|
|
118
|
+
* path (audit M2). Default 16 MiB ≫ any real block; raise it for an unusually large block source.
|
|
119
|
+
*/
|
|
120
|
+
maxResponseBytes?: number;
|
|
78
121
|
}
|
|
79
122
|
declare class CsdClient {
|
|
80
123
|
private readonly base;
|
|
81
124
|
private readonly f;
|
|
82
125
|
private readonly timeoutMs;
|
|
126
|
+
private readonly retries;
|
|
127
|
+
private readonly maxBytes;
|
|
83
128
|
constructor(opts: ClientOptions);
|
|
129
|
+
private req;
|
|
130
|
+
/**
|
|
131
|
+
* Read a response body as JSON with a hard byte ceiling (`maxResponseBytes`). Rejects an
|
|
132
|
+
* oversized `Content-Length` up front, and otherwise streams the body and aborts the moment
|
|
133
|
+
* it exceeds the cap — so a malicious node cannot make us buffer a giant body and OOM before
|
|
134
|
+
* we ever validate it (audit M2). Falls back to a size-checked `text()` on runtimes without a
|
|
135
|
+
* streaming body (older MV3/Node), preserving the cap as a best effort.
|
|
136
|
+
*/
|
|
137
|
+
private readCapped;
|
|
84
138
|
private get;
|
|
85
139
|
private post;
|
|
140
|
+
private getOk;
|
|
86
141
|
tip(): Promise<RpcTip>;
|
|
87
142
|
health(): Promise<any>;
|
|
88
143
|
blockByHeight(h: number): Promise<RpcBlock>;
|
|
89
144
|
blockByHash(hash: string): Promise<RpcBlock>;
|
|
90
|
-
tx(id: string): Promise<
|
|
91
|
-
ok: boolean;
|
|
92
|
-
txid: string;
|
|
93
|
-
block_hash?: string;
|
|
94
|
-
height?: number;
|
|
95
|
-
time?: number;
|
|
96
|
-
tx?: RpcTxJson;
|
|
97
|
-
err?: string;
|
|
98
|
-
}>;
|
|
145
|
+
tx(id: string): Promise<RpcTxInfo>;
|
|
99
146
|
utxos(addr: string): Promise<RpcUtxos>;
|
|
100
|
-
proposal(id: string): Promise<
|
|
101
|
-
proposals(domain: string, limit?: number): Promise<
|
|
102
|
-
topDomain(domain: string, epoch?: number): Promise<
|
|
103
|
-
domains(): Promise<
|
|
104
|
-
mempool(): Promise<
|
|
105
|
-
/**
|
|
147
|
+
proposal(id: string): Promise<RpcProposal>;
|
|
148
|
+
proposals(domain: string, limit?: number): Promise<RpcProposal[]>;
|
|
149
|
+
topDomain(domain: string, epoch?: number): Promise<unknown>;
|
|
150
|
+
domains(): Promise<string[]>;
|
|
151
|
+
mempool(): Promise<unknown>;
|
|
152
|
+
/**
|
|
153
|
+
* Await a txid reaching `confirmations` (default 1) — the submit-then-confirm flow every
|
|
154
|
+
* consumer was hand-rolling. Polls /tx + /tip; resolves {txid, height, confirmations};
|
|
155
|
+
* rejects on timeout (default 10 min — CSD blocks are ~2 min but the live miner is lumpy).
|
|
156
|
+
* A tx that drops OUT of the chain mid-wait (reorg) keeps polling until it re-confirms or
|
|
157
|
+
* times out — never resolves on a stale sighting.
|
|
158
|
+
*/
|
|
159
|
+
waitForTx(txid: string, opts?: {
|
|
160
|
+
confirmations?: number;
|
|
161
|
+
timeoutMs?: number;
|
|
162
|
+
pollMs?: number;
|
|
163
|
+
}): Promise<WaitForTxResult>;
|
|
164
|
+
/**
|
|
165
|
+
* Broadcast a node-JSON tx (from @inversealtruism/csd-tx `txToNodeJson`).
|
|
166
|
+
* ⚠ The node returns `{ok:false, err}` with HTTP 200 on REJECTION — and **`txid` is populated even
|
|
167
|
+
* then** (it's the computed id of the rejected tx). Callers MUST check `.ok`; reading `.txid`
|
|
168
|
+
* alone mistakes a rejected tx for a broadcast one. Use `submitOrThrow` if you want a hard failure.
|
|
169
|
+
*/
|
|
106
170
|
submit(nodeJsonTx: unknown): Promise<RpcSubmit>;
|
|
171
|
+
/** As `submit`, but throws on node rejection (`ok:false`) instead of returning a misleading txid. */
|
|
172
|
+
submitOrThrow(nodeJsonTx: unknown): Promise<RpcSubmit>;
|
|
107
173
|
templatePropose(body: unknown): Promise<any>;
|
|
108
174
|
templateAttest(body: unknown): Promise<any>;
|
|
109
175
|
}
|
|
110
176
|
/** Convert a node /tx or /block tx JSON back into the codec's Tx struct (for re-verification). */
|
|
111
177
|
declare function rpcTxToTx(j: RpcTxJson): Tx;
|
|
178
|
+
/** UTXO-VALUE-1 cure (audit). A CSD fee is implicit (Σin − Σout) and uncapped by consensus, so a
|
|
179
|
+
* builder that trusts a hostile RPC's /utxos `value` can compute too-small a change and silently
|
|
180
|
+
* BURN the difference as fee. This confirms each selected input's REAL value by fetching its source
|
|
181
|
+
* tx and RECOMPUTING its txid with the consensus codec — the txid commits to the output values, so
|
|
182
|
+
* a forged body whose recomputed txid still matches the prevout is impossible. Fail-CLOSED: any
|
|
183
|
+
* unreachable/forged/missing source aborts. Returns the verified input total (use it to compute
|
|
184
|
+
* change from REAL values, not the reported ones). RPC-facing builders (wallet, cairn-sdk) should
|
|
185
|
+
* call this before assembling a spend; csd-tx itself is pure and cannot fetch.
|
|
186
|
+
* (Mirrors the proven cairn-wallet `node.ts` implementation; the wallet's TXB-1 cure made canonical.) */
|
|
187
|
+
declare function verifyInputValues(client: {
|
|
188
|
+
tx(id: string): Promise<any>;
|
|
189
|
+
}, inputs: {
|
|
190
|
+
txid: string;
|
|
191
|
+
vout: number;
|
|
192
|
+
}[]): Promise<{
|
|
193
|
+
ok: boolean;
|
|
194
|
+
total: number;
|
|
195
|
+
}>;
|
|
112
196
|
/** Convert a node /block header JSON into the codec's BlockHeader. */
|
|
113
197
|
declare function rpcHeaderToHeader(h: RpcHeaderJson): BlockHeader;
|
|
114
198
|
|
|
115
|
-
export { type ClientOptions, CsdClient, type RpcBlock, type RpcHeaderJson, type RpcSubmit, type RpcTip, type RpcTxJson, type RpcUtxo, type RpcUtxos, rpcHeaderToHeader, rpcTxToTx };
|
|
199
|
+
export { type ClientOptions, CsdClient, type RpcBlock, type RpcHeaderJson, type RpcHealth, type RpcProposal, type RpcSubmit, type RpcTip, type RpcTxInfo, type RpcTxJson, type RpcUtxo, type RpcUtxos, type WaitForTxResult, rpcHeaderToHeader, rpcTxToTx, verifyInputValues };
|
package/dist/index.d.ts
CHANGED
|
@@ -71,45 +71,129 @@ interface RpcSubmit {
|
|
|
71
71
|
mempool_len?: number;
|
|
72
72
|
err?: string | null;
|
|
73
73
|
}
|
|
74
|
+
interface RpcProposal {
|
|
75
|
+
ok?: boolean;
|
|
76
|
+
txid: string;
|
|
77
|
+
domain: string;
|
|
78
|
+
payload_hash: string;
|
|
79
|
+
uri: string;
|
|
80
|
+
expires_epoch: number;
|
|
81
|
+
proposer: string;
|
|
82
|
+
height: number;
|
|
83
|
+
attestations?: unknown[];
|
|
84
|
+
[k: string]: unknown;
|
|
85
|
+
}
|
|
86
|
+
interface RpcTxInfo {
|
|
87
|
+
ok: boolean;
|
|
88
|
+
txid: string;
|
|
89
|
+
block_hash?: string;
|
|
90
|
+
height?: number;
|
|
91
|
+
time?: number;
|
|
92
|
+
tx?: RpcTxJson;
|
|
93
|
+
err?: string;
|
|
94
|
+
}
|
|
95
|
+
interface RpcHealth {
|
|
96
|
+
ok: boolean;
|
|
97
|
+
height?: number;
|
|
98
|
+
peers?: number;
|
|
99
|
+
mempool_len?: number;
|
|
100
|
+
[k: string]: unknown;
|
|
101
|
+
}
|
|
102
|
+
interface WaitForTxResult {
|
|
103
|
+
txid: string;
|
|
104
|
+
height: number;
|
|
105
|
+
confirmations: number;
|
|
106
|
+
}
|
|
74
107
|
interface ClientOptions {
|
|
75
108
|
baseUrl: string;
|
|
76
109
|
fetch?: typeof fetch;
|
|
77
110
|
timeoutMs?: number;
|
|
111
|
+
/** retry NETWORK failures (timeouts, refused, 5xx) this many times with jittered backoff.
|
|
112
|
+
* NEVER retries an application result (`ok:false`) or 4xx — those are answers, not outages. */
|
|
113
|
+
retries?: number;
|
|
114
|
+
/**
|
|
115
|
+
* Hard ceiling (bytes) on a response body before it is parsed. A lying/malicious node can
|
|
116
|
+
* otherwise stream a multi-hundred-MB body that the verifier buffers (`await r.json()`) and
|
|
117
|
+
* OOM-crashes BEFORE any PoW/merkle/LWMA check runs — a remote DoS of the trusted light-client
|
|
118
|
+
* path (audit M2). Default 16 MiB ≫ any real block; raise it for an unusually large block source.
|
|
119
|
+
*/
|
|
120
|
+
maxResponseBytes?: number;
|
|
78
121
|
}
|
|
79
122
|
declare class CsdClient {
|
|
80
123
|
private readonly base;
|
|
81
124
|
private readonly f;
|
|
82
125
|
private readonly timeoutMs;
|
|
126
|
+
private readonly retries;
|
|
127
|
+
private readonly maxBytes;
|
|
83
128
|
constructor(opts: ClientOptions);
|
|
129
|
+
private req;
|
|
130
|
+
/**
|
|
131
|
+
* Read a response body as JSON with a hard byte ceiling (`maxResponseBytes`). Rejects an
|
|
132
|
+
* oversized `Content-Length` up front, and otherwise streams the body and aborts the moment
|
|
133
|
+
* it exceeds the cap — so a malicious node cannot make us buffer a giant body and OOM before
|
|
134
|
+
* we ever validate it (audit M2). Falls back to a size-checked `text()` on runtimes without a
|
|
135
|
+
* streaming body (older MV3/Node), preserving the cap as a best effort.
|
|
136
|
+
*/
|
|
137
|
+
private readCapped;
|
|
84
138
|
private get;
|
|
85
139
|
private post;
|
|
140
|
+
private getOk;
|
|
86
141
|
tip(): Promise<RpcTip>;
|
|
87
142
|
health(): Promise<any>;
|
|
88
143
|
blockByHeight(h: number): Promise<RpcBlock>;
|
|
89
144
|
blockByHash(hash: string): Promise<RpcBlock>;
|
|
90
|
-
tx(id: string): Promise<
|
|
91
|
-
ok: boolean;
|
|
92
|
-
txid: string;
|
|
93
|
-
block_hash?: string;
|
|
94
|
-
height?: number;
|
|
95
|
-
time?: number;
|
|
96
|
-
tx?: RpcTxJson;
|
|
97
|
-
err?: string;
|
|
98
|
-
}>;
|
|
145
|
+
tx(id: string): Promise<RpcTxInfo>;
|
|
99
146
|
utxos(addr: string): Promise<RpcUtxos>;
|
|
100
|
-
proposal(id: string): Promise<
|
|
101
|
-
proposals(domain: string, limit?: number): Promise<
|
|
102
|
-
topDomain(domain: string, epoch?: number): Promise<
|
|
103
|
-
domains(): Promise<
|
|
104
|
-
mempool(): Promise<
|
|
105
|
-
/**
|
|
147
|
+
proposal(id: string): Promise<RpcProposal>;
|
|
148
|
+
proposals(domain: string, limit?: number): Promise<RpcProposal[]>;
|
|
149
|
+
topDomain(domain: string, epoch?: number): Promise<unknown>;
|
|
150
|
+
domains(): Promise<string[]>;
|
|
151
|
+
mempool(): Promise<unknown>;
|
|
152
|
+
/**
|
|
153
|
+
* Await a txid reaching `confirmations` (default 1) — the submit-then-confirm flow every
|
|
154
|
+
* consumer was hand-rolling. Polls /tx + /tip; resolves {txid, height, confirmations};
|
|
155
|
+
* rejects on timeout (default 10 min — CSD blocks are ~2 min but the live miner is lumpy).
|
|
156
|
+
* A tx that drops OUT of the chain mid-wait (reorg) keeps polling until it re-confirms or
|
|
157
|
+
* times out — never resolves on a stale sighting.
|
|
158
|
+
*/
|
|
159
|
+
waitForTx(txid: string, opts?: {
|
|
160
|
+
confirmations?: number;
|
|
161
|
+
timeoutMs?: number;
|
|
162
|
+
pollMs?: number;
|
|
163
|
+
}): Promise<WaitForTxResult>;
|
|
164
|
+
/**
|
|
165
|
+
* Broadcast a node-JSON tx (from @inversealtruism/csd-tx `txToNodeJson`).
|
|
166
|
+
* ⚠ The node returns `{ok:false, err}` with HTTP 200 on REJECTION — and **`txid` is populated even
|
|
167
|
+
* then** (it's the computed id of the rejected tx). Callers MUST check `.ok`; reading `.txid`
|
|
168
|
+
* alone mistakes a rejected tx for a broadcast one. Use `submitOrThrow` if you want a hard failure.
|
|
169
|
+
*/
|
|
106
170
|
submit(nodeJsonTx: unknown): Promise<RpcSubmit>;
|
|
171
|
+
/** As `submit`, but throws on node rejection (`ok:false`) instead of returning a misleading txid. */
|
|
172
|
+
submitOrThrow(nodeJsonTx: unknown): Promise<RpcSubmit>;
|
|
107
173
|
templatePropose(body: unknown): Promise<any>;
|
|
108
174
|
templateAttest(body: unknown): Promise<any>;
|
|
109
175
|
}
|
|
110
176
|
/** Convert a node /tx or /block tx JSON back into the codec's Tx struct (for re-verification). */
|
|
111
177
|
declare function rpcTxToTx(j: RpcTxJson): Tx;
|
|
178
|
+
/** UTXO-VALUE-1 cure (audit). A CSD fee is implicit (Σin − Σout) and uncapped by consensus, so a
|
|
179
|
+
* builder that trusts a hostile RPC's /utxos `value` can compute too-small a change and silently
|
|
180
|
+
* BURN the difference as fee. This confirms each selected input's REAL value by fetching its source
|
|
181
|
+
* tx and RECOMPUTING its txid with the consensus codec — the txid commits to the output values, so
|
|
182
|
+
* a forged body whose recomputed txid still matches the prevout is impossible. Fail-CLOSED: any
|
|
183
|
+
* unreachable/forged/missing source aborts. Returns the verified input total (use it to compute
|
|
184
|
+
* change from REAL values, not the reported ones). RPC-facing builders (wallet, cairn-sdk) should
|
|
185
|
+
* call this before assembling a spend; csd-tx itself is pure and cannot fetch.
|
|
186
|
+
* (Mirrors the proven cairn-wallet `node.ts` implementation; the wallet's TXB-1 cure made canonical.) */
|
|
187
|
+
declare function verifyInputValues(client: {
|
|
188
|
+
tx(id: string): Promise<any>;
|
|
189
|
+
}, inputs: {
|
|
190
|
+
txid: string;
|
|
191
|
+
vout: number;
|
|
192
|
+
}[]): Promise<{
|
|
193
|
+
ok: boolean;
|
|
194
|
+
total: number;
|
|
195
|
+
}>;
|
|
112
196
|
/** Convert a node /block header JSON into the codec's BlockHeader. */
|
|
113
197
|
declare function rpcHeaderToHeader(h: RpcHeaderJson): BlockHeader;
|
|
114
198
|
|
|
115
|
-
export { type ClientOptions, CsdClient, type RpcBlock, type RpcHeaderJson, type RpcSubmit, type RpcTip, type RpcTxJson, type RpcUtxo, type RpcUtxos, rpcHeaderToHeader, rpcTxToTx };
|
|
199
|
+
export { type ClientOptions, CsdClient, type RpcBlock, type RpcHeaderJson, type RpcHealth, type RpcProposal, type RpcSubmit, type RpcTip, type RpcTxInfo, type RpcTxJson, type RpcUtxo, type RpcUtxos, type WaitForTxResult, rpcHeaderToHeader, rpcTxToTx, verifyInputValues };
|
package/dist/index.js
CHANGED
|
@@ -1,28 +1,95 @@
|
|
|
1
1
|
// src/index.ts
|
|
2
|
+
import { txid as codecTxid } from "@inversealtruism/csd-codec";
|
|
2
3
|
var CsdClient = class {
|
|
3
4
|
base;
|
|
4
5
|
f;
|
|
5
6
|
timeoutMs;
|
|
7
|
+
retries;
|
|
8
|
+
maxBytes;
|
|
6
9
|
constructor(opts) {
|
|
7
10
|
this.base = opts.baseUrl.replace(/\/+$/, "");
|
|
8
|
-
this.
|
|
11
|
+
this.maxBytes = Math.max(1, opts.maxResponseBytes ?? 16 * 1024 * 1024);
|
|
12
|
+
const gf = globalThis.fetch;
|
|
13
|
+
this.f = opts.fetch ?? (gf ? gf.bind(globalThis) : gf);
|
|
9
14
|
this.timeoutMs = opts.timeoutMs ?? 1e4;
|
|
15
|
+
this.retries = Math.max(0, opts.retries ?? 0);
|
|
10
16
|
if (!this.f) throw new Error("no fetch available \u2014 pass opts.fetch");
|
|
11
17
|
}
|
|
12
|
-
async
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
18
|
+
async req(path, init) {
|
|
19
|
+
let lastErr;
|
|
20
|
+
for (let attempt = 0; ; attempt++) {
|
|
21
|
+
try {
|
|
22
|
+
const r = await this.f(`${this.base}${path}`, { ...init, signal: AbortSignal.timeout(this.timeoutMs) });
|
|
23
|
+
if (r.status >= 500 && attempt < this.retries) {
|
|
24
|
+
lastErr = new Error(`HTTP ${r.status}`);
|
|
25
|
+
} else if (!r.ok) throw new Error(`${init?.method ?? "GET"} ${path} \u2192 HTTP ${r.status}`);
|
|
26
|
+
else return await this.readCapped(r, path);
|
|
27
|
+
} catch (e) {
|
|
28
|
+
if (attempt >= this.retries) throw e;
|
|
29
|
+
lastErr = e;
|
|
30
|
+
}
|
|
31
|
+
const cap = Math.min(5e3, 250 * 2 ** attempt);
|
|
32
|
+
await new Promise((res) => setTimeout(res, Math.floor(Math.random() * cap)));
|
|
33
|
+
void lastErr;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Read a response body as JSON with a hard byte ceiling (`maxResponseBytes`). Rejects an
|
|
38
|
+
* oversized `Content-Length` up front, and otherwise streams the body and aborts the moment
|
|
39
|
+
* it exceeds the cap — so a malicious node cannot make us buffer a giant body and OOM before
|
|
40
|
+
* we ever validate it (audit M2). Falls back to a size-checked `text()` on runtimes without a
|
|
41
|
+
* streaming body (older MV3/Node), preserving the cap as a best effort.
|
|
42
|
+
*/
|
|
43
|
+
async readCapped(r, path) {
|
|
44
|
+
const max = this.maxBytes;
|
|
45
|
+
const cl = r.headers.get("content-length");
|
|
46
|
+
if (cl && Number(cl) > max) throw new Error(`GET ${path} \u2192 response too large (${cl} > ${max} bytes)`);
|
|
47
|
+
const body = r.body;
|
|
48
|
+
if (!body || typeof body.getReader !== "function") {
|
|
49
|
+
const t = await r.text();
|
|
50
|
+
if (t.length > max) throw new Error(`GET ${path} \u2192 response too large (${t.length} > ${max} bytes)`);
|
|
51
|
+
return JSON.parse(t);
|
|
52
|
+
}
|
|
53
|
+
const reader = body.getReader();
|
|
54
|
+
const chunks = [];
|
|
55
|
+
let total = 0;
|
|
56
|
+
for (; ; ) {
|
|
57
|
+
const { value, done } = await reader.read();
|
|
58
|
+
if (done) break;
|
|
59
|
+
if (value) {
|
|
60
|
+
total += value.length;
|
|
61
|
+
if (total > max) {
|
|
62
|
+
try {
|
|
63
|
+
await reader.cancel();
|
|
64
|
+
} catch {
|
|
65
|
+
}
|
|
66
|
+
throw new Error(`GET ${path} \u2192 response exceeded ${max} bytes`);
|
|
67
|
+
}
|
|
68
|
+
chunks.push(value);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
const buf = new Uint8Array(total);
|
|
72
|
+
let off = 0;
|
|
73
|
+
for (const c of chunks) {
|
|
74
|
+
buf.set(c, off);
|
|
75
|
+
off += c.length;
|
|
76
|
+
}
|
|
77
|
+
return JSON.parse(new TextDecoder().decode(buf));
|
|
78
|
+
}
|
|
79
|
+
get(path) {
|
|
80
|
+
return this.req(path);
|
|
81
|
+
}
|
|
82
|
+
post(path, body) {
|
|
83
|
+
return this.req(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
|
84
|
+
}
|
|
85
|
+
// The node returns application errors as `{ok:false, err}` with HTTP **200**, so a bare `get()`
|
|
86
|
+
// can't see them. For endpoints whose `{ok:false}` result is useless to the caller (a missing
|
|
87
|
+
// block), surface it as a thrown error — otherwise a beyond-tip/not-found block flows downstream
|
|
88
|
+
// as a malformed object and crashes opaquely (e.g. the light client reading `header.prev`).
|
|
89
|
+
async getOk(path) {
|
|
90
|
+
const j = await this.get(path);
|
|
91
|
+
if (j && j.ok === false) throw new Error(`GET ${path} \u2192 node error: ${j.err ?? "ok:false"}`);
|
|
92
|
+
return j;
|
|
26
93
|
}
|
|
27
94
|
tip() {
|
|
28
95
|
return this.get("/tip");
|
|
@@ -31,10 +98,10 @@ var CsdClient = class {
|
|
|
31
98
|
return this.get("/health");
|
|
32
99
|
}
|
|
33
100
|
blockByHeight(h) {
|
|
34
|
-
return this.
|
|
101
|
+
return this.getOk(`/block/height/${h}`);
|
|
35
102
|
}
|
|
36
103
|
blockByHash(hash) {
|
|
37
|
-
return this.
|
|
104
|
+
return this.getOk(`/block/${hash}`);
|
|
38
105
|
}
|
|
39
106
|
tx(id) {
|
|
40
107
|
return this.get(`/tx/${id}`);
|
|
@@ -57,10 +124,46 @@ var CsdClient = class {
|
|
|
57
124
|
mempool() {
|
|
58
125
|
return this.get("/mempool");
|
|
59
126
|
}
|
|
60
|
-
/**
|
|
127
|
+
/**
|
|
128
|
+
* Await a txid reaching `confirmations` (default 1) — the submit-then-confirm flow every
|
|
129
|
+
* consumer was hand-rolling. Polls /tx + /tip; resolves {txid, height, confirmations};
|
|
130
|
+
* rejects on timeout (default 10 min — CSD blocks are ~2 min but the live miner is lumpy).
|
|
131
|
+
* A tx that drops OUT of the chain mid-wait (reorg) keeps polling until it re-confirms or
|
|
132
|
+
* times out — never resolves on a stale sighting.
|
|
133
|
+
*/
|
|
134
|
+
async waitForTx(txid, opts = {}) {
|
|
135
|
+
const want = Math.max(1, opts.confirmations ?? 1);
|
|
136
|
+
const deadline = Date.now() + (opts.timeoutMs ?? 6e5);
|
|
137
|
+
const poll = Math.max(500, opts.pollMs ?? 5e3);
|
|
138
|
+
for (; ; ) {
|
|
139
|
+
try {
|
|
140
|
+
const t = await this.tx(txid);
|
|
141
|
+
if (t.ok && t.height != null) {
|
|
142
|
+
const tip = await this.tip();
|
|
143
|
+
const conf = tip.height - t.height + 1;
|
|
144
|
+
if (conf >= want) return { txid, height: t.height, confirmations: conf };
|
|
145
|
+
}
|
|
146
|
+
} catch {
|
|
147
|
+
}
|
|
148
|
+
if (Date.now() > deadline) throw new Error(`waitForTx ${txid}: not at ${want} confirmation(s) within ${opts.timeoutMs ?? 6e5}ms`);
|
|
149
|
+
await new Promise((res) => setTimeout(res, poll));
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Broadcast a node-JSON tx (from @inversealtruism/csd-tx `txToNodeJson`).
|
|
154
|
+
* ⚠ The node returns `{ok:false, err}` with HTTP 200 on REJECTION — and **`txid` is populated even
|
|
155
|
+
* then** (it's the computed id of the rejected tx). Callers MUST check `.ok`; reading `.txid`
|
|
156
|
+
* alone mistakes a rejected tx for a broadcast one. Use `submitOrThrow` if you want a hard failure.
|
|
157
|
+
*/
|
|
61
158
|
submit(nodeJsonTx) {
|
|
62
159
|
return this.post("/tx/submit", { tx: nodeJsonTx });
|
|
63
160
|
}
|
|
161
|
+
/** As `submit`, but throws on node rejection (`ok:false`) instead of returning a misleading txid. */
|
|
162
|
+
async submitOrThrow(nodeJsonTx) {
|
|
163
|
+
const r = await this.submit(nodeJsonTx);
|
|
164
|
+
if (!r.ok) throw new Error(`tx rejected by node: ${r.err ?? "unknown error"}`);
|
|
165
|
+
return r;
|
|
166
|
+
}
|
|
64
167
|
templatePropose(body) {
|
|
65
168
|
return this.post("/tx/template/propose", body);
|
|
66
169
|
}
|
|
@@ -78,11 +181,40 @@ function rpcTxToTx(j) {
|
|
|
78
181
|
outputs: j.outputs.map((o) => ({ value: o.value, scriptPubkey: o.script_pubkey }))
|
|
79
182
|
};
|
|
80
183
|
}
|
|
184
|
+
async function verifyInputValues(client, inputs) {
|
|
185
|
+
const norm = (s) => String(s).toLowerCase().replace(/^0x/, "");
|
|
186
|
+
let total = 0;
|
|
187
|
+
for (const i of inputs) {
|
|
188
|
+
let info;
|
|
189
|
+
try {
|
|
190
|
+
info = await client.tx(i.txid);
|
|
191
|
+
} catch {
|
|
192
|
+
return { ok: false, total: 0 };
|
|
193
|
+
}
|
|
194
|
+
const body = info?.tx ?? info;
|
|
195
|
+
if (!body || !Array.isArray(body.outputs) || !Array.isArray(body.inputs)) return { ok: false, total: 0 };
|
|
196
|
+
let tx;
|
|
197
|
+
try {
|
|
198
|
+
tx = rpcTxToTx(body);
|
|
199
|
+
} catch {
|
|
200
|
+
return { ok: false, total: 0 };
|
|
201
|
+
}
|
|
202
|
+
if (norm(codecTxid(tx)) !== norm(i.txid)) return { ok: false, total: 0 };
|
|
203
|
+
const out = tx.outputs[i.vout];
|
|
204
|
+
if (!out) return { ok: false, total: 0 };
|
|
205
|
+
const v = Number(out.value);
|
|
206
|
+
if (!Number.isSafeInteger(v) || v <= 0) return { ok: false, total: 0 };
|
|
207
|
+
total += v;
|
|
208
|
+
if (!Number.isSafeInteger(total)) return { ok: false, total: 0 };
|
|
209
|
+
}
|
|
210
|
+
return { ok: true, total };
|
|
211
|
+
}
|
|
81
212
|
function rpcHeaderToHeader(h) {
|
|
82
213
|
return { version: h.version, prev: h.prev, merkle: h.merkle, time: h.time, bits: h.bits, nonce: h.nonce };
|
|
83
214
|
}
|
|
84
215
|
export {
|
|
85
216
|
CsdClient,
|
|
86
217
|
rpcHeaderToHeader,
|
|
87
|
-
rpcTxToTx
|
|
218
|
+
rpcTxToTx,
|
|
219
|
+
verifyInputValues
|
|
88
220
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inversealtruism/csd-client",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.8",
|
|
4
4
|
"description": "Typed HTTP RPC client for a Compute Substrate node (or the Cairn proxy / a discovered gateway) — tip/block/tx/utxos/proposals/top/domains/mempool/submit/templates.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -19,12 +19,12 @@
|
|
|
19
19
|
"README.md"
|
|
20
20
|
],
|
|
21
21
|
"dependencies": {
|
|
22
|
-
"@inversealtruism/csd-codec": "0.1.
|
|
22
|
+
"@inversealtruism/csd-codec": "0.1.8"
|
|
23
23
|
},
|
|
24
24
|
"license": "MIT",
|
|
25
25
|
"sideEffects": false,
|
|
26
26
|
"devDependencies": {
|
|
27
|
-
"@inversealtruism/csd-vectors": "0.1.
|
|
27
|
+
"@inversealtruism/csd-vectors": "0.1.8"
|
|
28
28
|
},
|
|
29
29
|
"publishConfig": {
|
|
30
30
|
"access": "public"
|