@inversealtruism/csd-client 0.1.19 → 0.1.21
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 +11 -0
- package/dist/index.cjs +64 -9
- package/dist/index.d.cts +77 -19
- package/dist/index.d.ts +77 -19
- package/dist/index.js +63 -9
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -8,4 +8,15 @@ Part of the [Compute Substrate SDK](https://github.com/InverseAltruism/csd-sdk)
|
|
|
8
8
|
npm i @inversealtruism/csd-client
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
+
A non-2xx answer throws an `Error` whose message names the method, the path and the status, as before, and which
|
|
12
|
+
carries `status` and, when the body arrives within 1 second (or the request's remaining time, if less), `body`
|
|
13
|
+
(`HttpErrorFields`): the first `ERROR_BODY_MAX_BYTES` (4,096) bytes as text, decoded as UTF-8, never parsed and never
|
|
14
|
+
logged, so a caller can tell why a node or a proxy refused a request. A body that is late or cannot be read is not
|
|
15
|
+
waited for further, and the error has no `body`. A 4xx is not retried, `submit` never is, and a 5xx retried within
|
|
16
|
+
`retries` is retried without reading its body.
|
|
17
|
+
|
|
18
|
+
Node 22 or later (`engines`). `parseJsonExact`, the default body parser, keeps an integer above 2^53 - 1 exact only
|
|
19
|
+
where `JSON.parse` hands its reviver the source text, which Node 18 and 20 lack; there such a value (a Propose's
|
|
20
|
+
`expires_epoch`, which the node does not bound) comes back as a rounded number, and a txid recomputed from it fails.
|
|
21
|
+
|
|
11
22
|
See the [repo README](https://github.com/InverseAltruism/csd-sdk#readme) and [examples/quickstart.mjs](https://github.com/InverseAltruism/csd-sdk/blob/master/examples/quickstart.mjs) for usage. MIT.
|
package/dist/index.cjs
CHANGED
|
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
21
21
|
var index_exports = {};
|
|
22
22
|
__export(index_exports, {
|
|
23
23
|
CsdClient: () => CsdClient,
|
|
24
|
+
ERROR_BODY_MAX_BYTES: () => ERROR_BODY_MAX_BYTES,
|
|
24
25
|
parseJsonExact: () => parseJsonExact,
|
|
25
26
|
rpcHeaderToHeader: () => rpcHeaderToHeader,
|
|
26
27
|
rpcTxToTx: () => rpcTxToTx,
|
|
@@ -33,8 +34,57 @@ function parseJsonExact(text) {
|
|
|
33
34
|
return JSON.parse(text, exactIntReviver);
|
|
34
35
|
}
|
|
35
36
|
var DEFAULT_MAX_RESPONSE_BYTES = 16 * 1024 * 1024;
|
|
37
|
+
var ERROR_BODY_MAX_BYTES = 4096;
|
|
38
|
+
var ERROR_BODY_WAIT_MS = 1e3;
|
|
39
|
+
var LATE = /* @__PURE__ */ Symbol("late");
|
|
36
40
|
var DEFAULT_RETRIES = 0;
|
|
37
41
|
var finiteOr = (v, dflt) => v !== void 0 && Number.isFinite(v) ? v : dflt;
|
|
42
|
+
async function errorBody(r, ms) {
|
|
43
|
+
if (!(ms > 0)) return void 0;
|
|
44
|
+
let timer;
|
|
45
|
+
const late = new Promise((res) => {
|
|
46
|
+
timer = setTimeout(() => res(LATE), ms);
|
|
47
|
+
});
|
|
48
|
+
const within = (p) => {
|
|
49
|
+
p.catch(() => void 0);
|
|
50
|
+
return Promise.race([p, late]);
|
|
51
|
+
};
|
|
52
|
+
const cut = (b) => new TextDecoder().decode(b.subarray(0, ERROR_BODY_MAX_BYTES));
|
|
53
|
+
try {
|
|
54
|
+
const body = r.body;
|
|
55
|
+
if (!body || typeof body.getReader !== "function") {
|
|
56
|
+
const t = await within(r.text());
|
|
57
|
+
return t === LATE ? void 0 : cut(new TextEncoder().encode(t));
|
|
58
|
+
}
|
|
59
|
+
const reader = body.getReader();
|
|
60
|
+
const chunks = [];
|
|
61
|
+
let total = 0;
|
|
62
|
+
while (total < ERROR_BODY_MAX_BYTES) {
|
|
63
|
+
const step = await within(reader.read());
|
|
64
|
+
if (step === LATE) {
|
|
65
|
+
reader.cancel().catch(() => void 0);
|
|
66
|
+
return void 0;
|
|
67
|
+
}
|
|
68
|
+
if (step.done) break;
|
|
69
|
+
if (step.value) {
|
|
70
|
+
chunks.push(step.value);
|
|
71
|
+
total += step.value.length;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
if (total >= ERROR_BODY_MAX_BYTES) reader.cancel().catch(() => void 0);
|
|
75
|
+
const buf = new Uint8Array(total);
|
|
76
|
+
let off = 0;
|
|
77
|
+
for (const c of chunks) {
|
|
78
|
+
buf.set(c, off);
|
|
79
|
+
off += c.length;
|
|
80
|
+
}
|
|
81
|
+
return cut(buf);
|
|
82
|
+
} catch {
|
|
83
|
+
return void 0;
|
|
84
|
+
} finally {
|
|
85
|
+
clearTimeout(timer);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
38
88
|
var CsdClient = class {
|
|
39
89
|
base;
|
|
40
90
|
f;
|
|
@@ -57,11 +107,15 @@ var CsdClient = class {
|
|
|
57
107
|
let lastErr;
|
|
58
108
|
for (let attempt = 0; ; attempt++) {
|
|
59
109
|
try {
|
|
110
|
+
const sent = Date.now();
|
|
60
111
|
const r = await this.f(`${this.base}${path}`, { ...init, signal: AbortSignal.timeout(this.timeoutMs) });
|
|
61
112
|
if (r.status >= 500 && attempt < maxRetries) {
|
|
62
113
|
lastErr = new Error(`HTTP ${r.status}`);
|
|
63
|
-
} else if (!r.ok)
|
|
64
|
-
|
|
114
|
+
} else if (!r.ok) {
|
|
115
|
+
const body = await errorBody(r, Math.min(ERROR_BODY_WAIT_MS, this.timeoutMs - (Date.now() - sent)));
|
|
116
|
+
const fields = body === void 0 ? { status: r.status } : { status: r.status, body };
|
|
117
|
+
throw Object.assign(new Error(`${init?.method ?? "GET"} ${path} \u2192 HTTP ${r.status}`), { terminal: r.status < 500 }, fields);
|
|
118
|
+
} else return await this.readCapped(r, path);
|
|
65
119
|
} catch (e) {
|
|
66
120
|
if (attempt >= maxRetries || e?.terminal) throw e;
|
|
67
121
|
lastErr = e;
|
|
@@ -74,7 +128,7 @@ var CsdClient = class {
|
|
|
74
128
|
/**
|
|
75
129
|
* Read a response body as JSON with a hard byte ceiling (`maxResponseBytes`). Rejects an
|
|
76
130
|
* oversized `Content-Length` up front, and otherwise streams the body and aborts the moment
|
|
77
|
-
* it exceeds the cap
|
|
131
|
+
* it exceeds the cap: so a malicious node cannot make us buffer a giant body and OOM before
|
|
78
132
|
* we ever validate it (audit M2). Falls back to a size-checked `text()` on runtimes without a
|
|
79
133
|
* streaming body (older MV3/Node), preserving the cap as a best effort.
|
|
80
134
|
*/
|
|
@@ -123,7 +177,7 @@ var CsdClient = class {
|
|
|
123
177
|
}
|
|
124
178
|
// The node returns application errors as `{ok:false, err}` with HTTP **200**, so a bare `get()`
|
|
125
179
|
// can't see them. For endpoints whose `{ok:false}` result is useless to the caller (a missing
|
|
126
|
-
// block), surface it as a thrown error
|
|
180
|
+
// block), surface it as a thrown error: otherwise a beyond-tip/not-found block flows downstream
|
|
127
181
|
// as a malformed object and crashes opaquely (e.g. the light client reading `header.prev`).
|
|
128
182
|
async getOk(path) {
|
|
129
183
|
const j = await this.get(path);
|
|
@@ -152,7 +206,7 @@ var CsdClient = class {
|
|
|
152
206
|
return this.get(`/utxos/${addr}${opts.available === false ? "" : "?available=true"}`);
|
|
153
207
|
}
|
|
154
208
|
// getOk: a not-found proposal returns {ok:false}@200; without this the caller reads .domain/.uri off a
|
|
155
|
-
// malformed object instead of seeing the error (audit M6). (tx() deliberately keeps its bare get
|
|
209
|
+
// malformed object instead of seeing the error (audit M6). (tx() deliberately keeps its bare get: its
|
|
156
210
|
// {ok:false} is a documented VALID "not yet in a block" state that waitForTx/verifyInputValues handle.)
|
|
157
211
|
proposal(id) {
|
|
158
212
|
return this.getOk(`/proposal/${id}`);
|
|
@@ -170,11 +224,11 @@ var CsdClient = class {
|
|
|
170
224
|
return this.get("/mempool");
|
|
171
225
|
}
|
|
172
226
|
/**
|
|
173
|
-
* Await a txid reaching `confirmations` (default 1)
|
|
227
|
+
* Await a txid reaching `confirmations` (default 1): the submit-then-confirm flow every
|
|
174
228
|
* consumer was hand-rolling. Polls /tx + /tip; resolves {txid, height, confirmations};
|
|
175
|
-
* rejects on timeout (default 10 min
|
|
229
|
+
* rejects on timeout (default 10 min: CSD blocks are ~2 min but the live miner is lumpy).
|
|
176
230
|
* A tx that drops OUT of the chain mid-wait (reorg) keeps polling until it re-confirms or
|
|
177
|
-
* times out
|
|
231
|
+
* times out: never resolves on a stale sighting.
|
|
178
232
|
* The count is `tip.height - tx.height + 1` from the RPC's own /tx and /tip answers, with no PoW
|
|
179
233
|
* or inclusion check, so a lying RPC can over-state it. Gate funds on csd-light, not on this.
|
|
180
234
|
*/
|
|
@@ -198,7 +252,7 @@ var CsdClient = class {
|
|
|
198
252
|
}
|
|
199
253
|
/**
|
|
200
254
|
* Broadcast a node-JSON tx (from @inversealtruism/csd-tx `txToNodeJson`).
|
|
201
|
-
* ⚠ The node returns `{ok:false, err}` with HTTP 200 on REJECTION
|
|
255
|
+
* ⚠ The node returns `{ok:false, err}` with HTTP 200 on REJECTION, and **`txid` is populated even
|
|
202
256
|
* then** (it's the computed id of the rejected tx). Callers MUST check `.ok`; reading `.txid`
|
|
203
257
|
* alone mistakes a rejected tx for a broadcast one. Use `submitOrThrow` if you want a hard failure.
|
|
204
258
|
*/
|
|
@@ -263,6 +317,7 @@ function rpcHeaderToHeader(h) {
|
|
|
263
317
|
// Annotate the CommonJS export names for ESM import in node:
|
|
264
318
|
0 && (module.exports = {
|
|
265
319
|
CsdClient,
|
|
320
|
+
ERROR_BODY_MAX_BYTES,
|
|
266
321
|
parseJsonExact,
|
|
267
322
|
rpcHeaderToHeader,
|
|
268
323
|
rpcTxToTx,
|
package/dist/index.d.cts
CHANGED
|
@@ -72,17 +72,54 @@ interface RpcSubmit {
|
|
|
72
72
|
mempool_len?: number;
|
|
73
73
|
err?: string | null;
|
|
74
74
|
}
|
|
75
|
+
interface RpcProposalRecord {
|
|
76
|
+
proposal_id: string;
|
|
77
|
+
domain: string;
|
|
78
|
+
payload_hash: string;
|
|
79
|
+
uri: string;
|
|
80
|
+
proposer: string;
|
|
81
|
+
created_height: number;
|
|
82
|
+
created_epoch: number;
|
|
83
|
+
fee: number | bigint;
|
|
84
|
+
expires_epoch: number | bigint;
|
|
85
|
+
}
|
|
86
|
+
/** `/proposal/:id`. An unknown id answers `{ ok: false, err }`, which `proposal()` throws. */
|
|
75
87
|
interface RpcProposal {
|
|
76
|
-
ok
|
|
88
|
+
ok: boolean;
|
|
89
|
+
proposal: RpcProposalRecord;
|
|
90
|
+
err?: string;
|
|
91
|
+
}
|
|
92
|
+
/** One row of `/proposals/:domain/:limit`; the feed names no proposer. */
|
|
93
|
+
interface RpcProposalItem {
|
|
94
|
+
proposal_id: string;
|
|
77
95
|
txid: string;
|
|
96
|
+
block_hash: string;
|
|
97
|
+
height: number;
|
|
98
|
+
time: number;
|
|
78
99
|
domain: string;
|
|
79
100
|
payload_hash: string;
|
|
80
101
|
uri: string;
|
|
81
102
|
expires_epoch: number | bigint;
|
|
82
|
-
|
|
103
|
+
}
|
|
104
|
+
interface RpcProposals {
|
|
105
|
+
ok: boolean;
|
|
106
|
+
tip: string;
|
|
83
107
|
height: number;
|
|
84
|
-
|
|
85
|
-
|
|
108
|
+
scanned_blocks: number;
|
|
109
|
+
count: number;
|
|
110
|
+
proposals: RpcProposalItem[];
|
|
111
|
+
}
|
|
112
|
+
interface RpcDomain {
|
|
113
|
+
domain: string;
|
|
114
|
+
proposals: number;
|
|
115
|
+
attestations: number;
|
|
116
|
+
}
|
|
117
|
+
interface RpcDomains {
|
|
118
|
+
ok: boolean;
|
|
119
|
+
tip: string;
|
|
120
|
+
height: number;
|
|
121
|
+
count: number;
|
|
122
|
+
domains: RpcDomain[];
|
|
86
123
|
}
|
|
87
124
|
interface RpcTxInfo {
|
|
88
125
|
ok: boolean;
|
|
@@ -93,12 +130,23 @@ interface RpcTxInfo {
|
|
|
93
130
|
tx?: RpcTxJson;
|
|
94
131
|
err?: string;
|
|
95
132
|
}
|
|
133
|
+
/** `ok` is false while a node task has stopped. The last three are null until known and absent on nodes before
|
|
134
|
+
* overlay 0.1.7. */
|
|
96
135
|
interface RpcHealth {
|
|
97
136
|
ok: boolean;
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
137
|
+
tip: string;
|
|
138
|
+
height: number;
|
|
139
|
+
chainwork: string;
|
|
140
|
+
peer_count: number;
|
|
141
|
+
known_peers: number;
|
|
142
|
+
mempool_tx_count: number;
|
|
143
|
+
mempool_spent_outpoints: number;
|
|
144
|
+
mempool_bytes: number;
|
|
145
|
+
mempool_min_feerate_ppm: number | bigint | null;
|
|
146
|
+
mempool_max_feerate_ppm: number | bigint | null;
|
|
147
|
+
best_peer_height?: number | null;
|
|
148
|
+
blocks_behind?: number | null;
|
|
149
|
+
secs_since_tip_activity?: number | null;
|
|
102
150
|
}
|
|
103
151
|
interface WaitForTxResult {
|
|
104
152
|
txid: string;
|
|
@@ -110,12 +158,12 @@ interface ClientOptions {
|
|
|
110
158
|
fetch?: typeof fetch;
|
|
111
159
|
timeoutMs?: number;
|
|
112
160
|
/** retry NETWORK failures (timeouts, refused, 5xx) this many times with jittered backoff.
|
|
113
|
-
* NEVER retries an application result (`ok:false`) or 4xx
|
|
161
|
+
* NEVER retries an application result (`ok:false`) or 4xx: those are answers, not outages. */
|
|
114
162
|
retries?: number;
|
|
115
163
|
/**
|
|
116
164
|
* Hard ceiling (bytes) on a response body before it is parsed. A lying/malicious node can
|
|
117
165
|
* otherwise stream a multi-hundred-MB body that the verifier buffers (`await r.json()`) and
|
|
118
|
-
* OOM-crashes BEFORE any PoW/merkle/LWMA check runs
|
|
166
|
+
* OOM-crashes BEFORE any PoW/merkle/LWMA check runs: a remote DoS of the trusted light-client
|
|
119
167
|
* path (audit M2). Default 16 MiB ≫ any real block; raise it for an unusually large block source.
|
|
120
168
|
*/
|
|
121
169
|
maxResponseBytes?: number;
|
|
@@ -124,6 +172,16 @@ interface ClientOptions {
|
|
|
124
172
|
}
|
|
125
173
|
/** JSON.parse, except that an integer literal outside the safe JS range is returned as an exact bigint. */
|
|
126
174
|
declare function parseJsonExact(text: string): unknown;
|
|
175
|
+
/** The most bytes of a non-2xx body an HTTP error carries. The node's refusal texts run to a few hundred bytes (its
|
|
176
|
+
* longest error format, with 66-character arguments, is under 200 characters); a proxy's short HTML page fits too. */
|
|
177
|
+
declare const ERROR_BODY_MAX_BYTES = 4096;
|
|
178
|
+
/** What the error a request throws for a non-2xx answer carries besides its message: the HTTP status, and the first
|
|
179
|
+
* ERROR_BODY_MAX_BYTES bytes of the body, decoded as UTF-8 (an invalid byte reads as U+FFFD), never parsed, when the
|
|
180
|
+
* body arrives within ERROR_BODY_WAIT_MS (or the request's remaining time, if less); else no `body`. */
|
|
181
|
+
interface HttpErrorFields {
|
|
182
|
+
status: number;
|
|
183
|
+
body?: string;
|
|
184
|
+
}
|
|
127
185
|
declare class CsdClient {
|
|
128
186
|
private readonly base;
|
|
129
187
|
private readonly f;
|
|
@@ -136,7 +194,7 @@ declare class CsdClient {
|
|
|
136
194
|
/**
|
|
137
195
|
* Read a response body as JSON with a hard byte ceiling (`maxResponseBytes`). Rejects an
|
|
138
196
|
* oversized `Content-Length` up front, and otherwise streams the body and aborts the moment
|
|
139
|
-
* it exceeds the cap
|
|
197
|
+
* it exceeds the cap: so a malicious node cannot make us buffer a giant body and OOM before
|
|
140
198
|
* we ever validate it (audit M2). Falls back to a size-checked `text()` on runtimes without a
|
|
141
199
|
* streaming body (older MV3/Node), preserving the cap as a best effort.
|
|
142
200
|
*/
|
|
@@ -153,16 +211,16 @@ declare class CsdClient {
|
|
|
153
211
|
available?: boolean;
|
|
154
212
|
}): Promise<RpcUtxos>;
|
|
155
213
|
proposal(id: string): Promise<RpcProposal>;
|
|
156
|
-
proposals(domain: string, limit?: number): Promise<
|
|
214
|
+
proposals(domain: string, limit?: number): Promise<RpcProposals>;
|
|
157
215
|
topDomain(domain: string, epoch?: number): Promise<unknown>;
|
|
158
|
-
domains(): Promise<
|
|
216
|
+
domains(): Promise<RpcDomains>;
|
|
159
217
|
mempool(): Promise<unknown>;
|
|
160
218
|
/**
|
|
161
|
-
* Await a txid reaching `confirmations` (default 1)
|
|
219
|
+
* Await a txid reaching `confirmations` (default 1): the submit-then-confirm flow every
|
|
162
220
|
* consumer was hand-rolling. Polls /tx + /tip; resolves {txid, height, confirmations};
|
|
163
|
-
* rejects on timeout (default 10 min
|
|
221
|
+
* rejects on timeout (default 10 min: CSD blocks are ~2 min but the live miner is lumpy).
|
|
164
222
|
* A tx that drops OUT of the chain mid-wait (reorg) keeps polling until it re-confirms or
|
|
165
|
-
* times out
|
|
223
|
+
* times out: never resolves on a stale sighting.
|
|
166
224
|
* The count is `tip.height - tx.height + 1` from the RPC's own /tx and /tip answers, with no PoW
|
|
167
225
|
* or inclusion check, so a lying RPC can over-state it. Gate funds on csd-light, not on this.
|
|
168
226
|
*/
|
|
@@ -173,7 +231,7 @@ declare class CsdClient {
|
|
|
173
231
|
}): Promise<WaitForTxResult>;
|
|
174
232
|
/**
|
|
175
233
|
* Broadcast a node-JSON tx (from @inversealtruism/csd-tx `txToNodeJson`).
|
|
176
|
-
* ⚠ The node returns `{ok:false, err}` with HTTP 200 on REJECTION
|
|
234
|
+
* ⚠ The node returns `{ok:false, err}` with HTTP 200 on REJECTION, and **`txid` is populated even
|
|
177
235
|
* then** (it's the computed id of the rejected tx). Callers MUST check `.ok`; reading `.txid`
|
|
178
236
|
* alone mistakes a rejected tx for a broadcast one. Use `submitOrThrow` if you want a hard failure.
|
|
179
237
|
*/
|
|
@@ -188,7 +246,7 @@ declare function rpcTxToTx(j: RpcTxJson): Tx;
|
|
|
188
246
|
/** UTXO-VALUE-1 cure (audit). A CSD fee is implicit (Σin − Σout) and uncapped by consensus, so a
|
|
189
247
|
* builder that trusts a hostile RPC's /utxos `value` can compute too-small a change and silently
|
|
190
248
|
* BURN the difference as fee. This confirms each selected input's REAL value by fetching its source
|
|
191
|
-
* tx and RECOMPUTING its txid with the consensus codec
|
|
249
|
+
* tx and RECOMPUTING its txid with the consensus codec: the txid commits to the output values, so
|
|
192
250
|
* a forged body whose recomputed txid still matches the prevout is impossible. Fail-CLOSED: any
|
|
193
251
|
* unreachable/forged/missing source aborts. Returns the verified input total (use it to compute
|
|
194
252
|
* change from REAL values, not the reported ones). RPC-facing builders (wallet, cairn-sdk) should
|
|
@@ -209,4 +267,4 @@ declare function verifyInputValues(client: {
|
|
|
209
267
|
/** Convert a node /block header JSON into the codec's BlockHeader. */
|
|
210
268
|
declare function rpcHeaderToHeader(h: RpcHeaderJson): BlockHeader;
|
|
211
269
|
|
|
212
|
-
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, parseJsonExact, rpcHeaderToHeader, rpcTxToTx, verifyInputValues };
|
|
270
|
+
export { type ClientOptions, CsdClient, ERROR_BODY_MAX_BYTES, type HttpErrorFields, type RpcBlock, type RpcDomain, type RpcDomains, type RpcHeaderJson, type RpcHealth, type RpcProposal, type RpcProposalItem, type RpcProposalRecord, type RpcProposals, type RpcSubmit, type RpcTip, type RpcTxInfo, type RpcTxJson, type RpcUtxo, type RpcUtxos, type WaitForTxResult, parseJsonExact, rpcHeaderToHeader, rpcTxToTx, verifyInputValues };
|
package/dist/index.d.ts
CHANGED
|
@@ -72,17 +72,54 @@ interface RpcSubmit {
|
|
|
72
72
|
mempool_len?: number;
|
|
73
73
|
err?: string | null;
|
|
74
74
|
}
|
|
75
|
+
interface RpcProposalRecord {
|
|
76
|
+
proposal_id: string;
|
|
77
|
+
domain: string;
|
|
78
|
+
payload_hash: string;
|
|
79
|
+
uri: string;
|
|
80
|
+
proposer: string;
|
|
81
|
+
created_height: number;
|
|
82
|
+
created_epoch: number;
|
|
83
|
+
fee: number | bigint;
|
|
84
|
+
expires_epoch: number | bigint;
|
|
85
|
+
}
|
|
86
|
+
/** `/proposal/:id`. An unknown id answers `{ ok: false, err }`, which `proposal()` throws. */
|
|
75
87
|
interface RpcProposal {
|
|
76
|
-
ok
|
|
88
|
+
ok: boolean;
|
|
89
|
+
proposal: RpcProposalRecord;
|
|
90
|
+
err?: string;
|
|
91
|
+
}
|
|
92
|
+
/** One row of `/proposals/:domain/:limit`; the feed names no proposer. */
|
|
93
|
+
interface RpcProposalItem {
|
|
94
|
+
proposal_id: string;
|
|
77
95
|
txid: string;
|
|
96
|
+
block_hash: string;
|
|
97
|
+
height: number;
|
|
98
|
+
time: number;
|
|
78
99
|
domain: string;
|
|
79
100
|
payload_hash: string;
|
|
80
101
|
uri: string;
|
|
81
102
|
expires_epoch: number | bigint;
|
|
82
|
-
|
|
103
|
+
}
|
|
104
|
+
interface RpcProposals {
|
|
105
|
+
ok: boolean;
|
|
106
|
+
tip: string;
|
|
83
107
|
height: number;
|
|
84
|
-
|
|
85
|
-
|
|
108
|
+
scanned_blocks: number;
|
|
109
|
+
count: number;
|
|
110
|
+
proposals: RpcProposalItem[];
|
|
111
|
+
}
|
|
112
|
+
interface RpcDomain {
|
|
113
|
+
domain: string;
|
|
114
|
+
proposals: number;
|
|
115
|
+
attestations: number;
|
|
116
|
+
}
|
|
117
|
+
interface RpcDomains {
|
|
118
|
+
ok: boolean;
|
|
119
|
+
tip: string;
|
|
120
|
+
height: number;
|
|
121
|
+
count: number;
|
|
122
|
+
domains: RpcDomain[];
|
|
86
123
|
}
|
|
87
124
|
interface RpcTxInfo {
|
|
88
125
|
ok: boolean;
|
|
@@ -93,12 +130,23 @@ interface RpcTxInfo {
|
|
|
93
130
|
tx?: RpcTxJson;
|
|
94
131
|
err?: string;
|
|
95
132
|
}
|
|
133
|
+
/** `ok` is false while a node task has stopped. The last three are null until known and absent on nodes before
|
|
134
|
+
* overlay 0.1.7. */
|
|
96
135
|
interface RpcHealth {
|
|
97
136
|
ok: boolean;
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
137
|
+
tip: string;
|
|
138
|
+
height: number;
|
|
139
|
+
chainwork: string;
|
|
140
|
+
peer_count: number;
|
|
141
|
+
known_peers: number;
|
|
142
|
+
mempool_tx_count: number;
|
|
143
|
+
mempool_spent_outpoints: number;
|
|
144
|
+
mempool_bytes: number;
|
|
145
|
+
mempool_min_feerate_ppm: number | bigint | null;
|
|
146
|
+
mempool_max_feerate_ppm: number | bigint | null;
|
|
147
|
+
best_peer_height?: number | null;
|
|
148
|
+
blocks_behind?: number | null;
|
|
149
|
+
secs_since_tip_activity?: number | null;
|
|
102
150
|
}
|
|
103
151
|
interface WaitForTxResult {
|
|
104
152
|
txid: string;
|
|
@@ -110,12 +158,12 @@ interface ClientOptions {
|
|
|
110
158
|
fetch?: typeof fetch;
|
|
111
159
|
timeoutMs?: number;
|
|
112
160
|
/** retry NETWORK failures (timeouts, refused, 5xx) this many times with jittered backoff.
|
|
113
|
-
* NEVER retries an application result (`ok:false`) or 4xx
|
|
161
|
+
* NEVER retries an application result (`ok:false`) or 4xx: those are answers, not outages. */
|
|
114
162
|
retries?: number;
|
|
115
163
|
/**
|
|
116
164
|
* Hard ceiling (bytes) on a response body before it is parsed. A lying/malicious node can
|
|
117
165
|
* otherwise stream a multi-hundred-MB body that the verifier buffers (`await r.json()`) and
|
|
118
|
-
* OOM-crashes BEFORE any PoW/merkle/LWMA check runs
|
|
166
|
+
* OOM-crashes BEFORE any PoW/merkle/LWMA check runs: a remote DoS of the trusted light-client
|
|
119
167
|
* path (audit M2). Default 16 MiB ≫ any real block; raise it for an unusually large block source.
|
|
120
168
|
*/
|
|
121
169
|
maxResponseBytes?: number;
|
|
@@ -124,6 +172,16 @@ interface ClientOptions {
|
|
|
124
172
|
}
|
|
125
173
|
/** JSON.parse, except that an integer literal outside the safe JS range is returned as an exact bigint. */
|
|
126
174
|
declare function parseJsonExact(text: string): unknown;
|
|
175
|
+
/** The most bytes of a non-2xx body an HTTP error carries. The node's refusal texts run to a few hundred bytes (its
|
|
176
|
+
* longest error format, with 66-character arguments, is under 200 characters); a proxy's short HTML page fits too. */
|
|
177
|
+
declare const ERROR_BODY_MAX_BYTES = 4096;
|
|
178
|
+
/** What the error a request throws for a non-2xx answer carries besides its message: the HTTP status, and the first
|
|
179
|
+
* ERROR_BODY_MAX_BYTES bytes of the body, decoded as UTF-8 (an invalid byte reads as U+FFFD), never parsed, when the
|
|
180
|
+
* body arrives within ERROR_BODY_WAIT_MS (or the request's remaining time, if less); else no `body`. */
|
|
181
|
+
interface HttpErrorFields {
|
|
182
|
+
status: number;
|
|
183
|
+
body?: string;
|
|
184
|
+
}
|
|
127
185
|
declare class CsdClient {
|
|
128
186
|
private readonly base;
|
|
129
187
|
private readonly f;
|
|
@@ -136,7 +194,7 @@ declare class CsdClient {
|
|
|
136
194
|
/**
|
|
137
195
|
* Read a response body as JSON with a hard byte ceiling (`maxResponseBytes`). Rejects an
|
|
138
196
|
* oversized `Content-Length` up front, and otherwise streams the body and aborts the moment
|
|
139
|
-
* it exceeds the cap
|
|
197
|
+
* it exceeds the cap: so a malicious node cannot make us buffer a giant body and OOM before
|
|
140
198
|
* we ever validate it (audit M2). Falls back to a size-checked `text()` on runtimes without a
|
|
141
199
|
* streaming body (older MV3/Node), preserving the cap as a best effort.
|
|
142
200
|
*/
|
|
@@ -153,16 +211,16 @@ declare class CsdClient {
|
|
|
153
211
|
available?: boolean;
|
|
154
212
|
}): Promise<RpcUtxos>;
|
|
155
213
|
proposal(id: string): Promise<RpcProposal>;
|
|
156
|
-
proposals(domain: string, limit?: number): Promise<
|
|
214
|
+
proposals(domain: string, limit?: number): Promise<RpcProposals>;
|
|
157
215
|
topDomain(domain: string, epoch?: number): Promise<unknown>;
|
|
158
|
-
domains(): Promise<
|
|
216
|
+
domains(): Promise<RpcDomains>;
|
|
159
217
|
mempool(): Promise<unknown>;
|
|
160
218
|
/**
|
|
161
|
-
* Await a txid reaching `confirmations` (default 1)
|
|
219
|
+
* Await a txid reaching `confirmations` (default 1): the submit-then-confirm flow every
|
|
162
220
|
* consumer was hand-rolling. Polls /tx + /tip; resolves {txid, height, confirmations};
|
|
163
|
-
* rejects on timeout (default 10 min
|
|
221
|
+
* rejects on timeout (default 10 min: CSD blocks are ~2 min but the live miner is lumpy).
|
|
164
222
|
* A tx that drops OUT of the chain mid-wait (reorg) keeps polling until it re-confirms or
|
|
165
|
-
* times out
|
|
223
|
+
* times out: never resolves on a stale sighting.
|
|
166
224
|
* The count is `tip.height - tx.height + 1` from the RPC's own /tx and /tip answers, with no PoW
|
|
167
225
|
* or inclusion check, so a lying RPC can over-state it. Gate funds on csd-light, not on this.
|
|
168
226
|
*/
|
|
@@ -173,7 +231,7 @@ declare class CsdClient {
|
|
|
173
231
|
}): Promise<WaitForTxResult>;
|
|
174
232
|
/**
|
|
175
233
|
* Broadcast a node-JSON tx (from @inversealtruism/csd-tx `txToNodeJson`).
|
|
176
|
-
* ⚠ The node returns `{ok:false, err}` with HTTP 200 on REJECTION
|
|
234
|
+
* ⚠ The node returns `{ok:false, err}` with HTTP 200 on REJECTION, and **`txid` is populated even
|
|
177
235
|
* then** (it's the computed id of the rejected tx). Callers MUST check `.ok`; reading `.txid`
|
|
178
236
|
* alone mistakes a rejected tx for a broadcast one. Use `submitOrThrow` if you want a hard failure.
|
|
179
237
|
*/
|
|
@@ -188,7 +246,7 @@ declare function rpcTxToTx(j: RpcTxJson): Tx;
|
|
|
188
246
|
/** UTXO-VALUE-1 cure (audit). A CSD fee is implicit (Σin − Σout) and uncapped by consensus, so a
|
|
189
247
|
* builder that trusts a hostile RPC's /utxos `value` can compute too-small a change and silently
|
|
190
248
|
* BURN the difference as fee. This confirms each selected input's REAL value by fetching its source
|
|
191
|
-
* tx and RECOMPUTING its txid with the consensus codec
|
|
249
|
+
* tx and RECOMPUTING its txid with the consensus codec: the txid commits to the output values, so
|
|
192
250
|
* a forged body whose recomputed txid still matches the prevout is impossible. Fail-CLOSED: any
|
|
193
251
|
* unreachable/forged/missing source aborts. Returns the verified input total (use it to compute
|
|
194
252
|
* change from REAL values, not the reported ones). RPC-facing builders (wallet, cairn-sdk) should
|
|
@@ -209,4 +267,4 @@ declare function verifyInputValues(client: {
|
|
|
209
267
|
/** Convert a node /block header JSON into the codec's BlockHeader. */
|
|
210
268
|
declare function rpcHeaderToHeader(h: RpcHeaderJson): BlockHeader;
|
|
211
269
|
|
|
212
|
-
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, parseJsonExact, rpcHeaderToHeader, rpcTxToTx, verifyInputValues };
|
|
270
|
+
export { type ClientOptions, CsdClient, ERROR_BODY_MAX_BYTES, type HttpErrorFields, type RpcBlock, type RpcDomain, type RpcDomains, type RpcHeaderJson, type RpcHealth, type RpcProposal, type RpcProposalItem, type RpcProposalRecord, type RpcProposals, type RpcSubmit, type RpcTip, type RpcTxInfo, type RpcTxJson, type RpcUtxo, type RpcUtxos, type WaitForTxResult, parseJsonExact, rpcHeaderToHeader, rpcTxToTx, verifyInputValues };
|
package/dist/index.js
CHANGED
|
@@ -5,8 +5,57 @@ function parseJsonExact(text) {
|
|
|
5
5
|
return JSON.parse(text, exactIntReviver);
|
|
6
6
|
}
|
|
7
7
|
var DEFAULT_MAX_RESPONSE_BYTES = 16 * 1024 * 1024;
|
|
8
|
+
var ERROR_BODY_MAX_BYTES = 4096;
|
|
9
|
+
var ERROR_BODY_WAIT_MS = 1e3;
|
|
10
|
+
var LATE = /* @__PURE__ */ Symbol("late");
|
|
8
11
|
var DEFAULT_RETRIES = 0;
|
|
9
12
|
var finiteOr = (v, dflt) => v !== void 0 && Number.isFinite(v) ? v : dflt;
|
|
13
|
+
async function errorBody(r, ms) {
|
|
14
|
+
if (!(ms > 0)) return void 0;
|
|
15
|
+
let timer;
|
|
16
|
+
const late = new Promise((res) => {
|
|
17
|
+
timer = setTimeout(() => res(LATE), ms);
|
|
18
|
+
});
|
|
19
|
+
const within = (p) => {
|
|
20
|
+
p.catch(() => void 0);
|
|
21
|
+
return Promise.race([p, late]);
|
|
22
|
+
};
|
|
23
|
+
const cut = (b) => new TextDecoder().decode(b.subarray(0, ERROR_BODY_MAX_BYTES));
|
|
24
|
+
try {
|
|
25
|
+
const body = r.body;
|
|
26
|
+
if (!body || typeof body.getReader !== "function") {
|
|
27
|
+
const t = await within(r.text());
|
|
28
|
+
return t === LATE ? void 0 : cut(new TextEncoder().encode(t));
|
|
29
|
+
}
|
|
30
|
+
const reader = body.getReader();
|
|
31
|
+
const chunks = [];
|
|
32
|
+
let total = 0;
|
|
33
|
+
while (total < ERROR_BODY_MAX_BYTES) {
|
|
34
|
+
const step = await within(reader.read());
|
|
35
|
+
if (step === LATE) {
|
|
36
|
+
reader.cancel().catch(() => void 0);
|
|
37
|
+
return void 0;
|
|
38
|
+
}
|
|
39
|
+
if (step.done) break;
|
|
40
|
+
if (step.value) {
|
|
41
|
+
chunks.push(step.value);
|
|
42
|
+
total += step.value.length;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (total >= ERROR_BODY_MAX_BYTES) reader.cancel().catch(() => void 0);
|
|
46
|
+
const buf = new Uint8Array(total);
|
|
47
|
+
let off = 0;
|
|
48
|
+
for (const c of chunks) {
|
|
49
|
+
buf.set(c, off);
|
|
50
|
+
off += c.length;
|
|
51
|
+
}
|
|
52
|
+
return cut(buf);
|
|
53
|
+
} catch {
|
|
54
|
+
return void 0;
|
|
55
|
+
} finally {
|
|
56
|
+
clearTimeout(timer);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
10
59
|
var CsdClient = class {
|
|
11
60
|
base;
|
|
12
61
|
f;
|
|
@@ -29,11 +78,15 @@ var CsdClient = class {
|
|
|
29
78
|
let lastErr;
|
|
30
79
|
for (let attempt = 0; ; attempt++) {
|
|
31
80
|
try {
|
|
81
|
+
const sent = Date.now();
|
|
32
82
|
const r = await this.f(`${this.base}${path}`, { ...init, signal: AbortSignal.timeout(this.timeoutMs) });
|
|
33
83
|
if (r.status >= 500 && attempt < maxRetries) {
|
|
34
84
|
lastErr = new Error(`HTTP ${r.status}`);
|
|
35
|
-
} else if (!r.ok)
|
|
36
|
-
|
|
85
|
+
} else if (!r.ok) {
|
|
86
|
+
const body = await errorBody(r, Math.min(ERROR_BODY_WAIT_MS, this.timeoutMs - (Date.now() - sent)));
|
|
87
|
+
const fields = body === void 0 ? { status: r.status } : { status: r.status, body };
|
|
88
|
+
throw Object.assign(new Error(`${init?.method ?? "GET"} ${path} \u2192 HTTP ${r.status}`), { terminal: r.status < 500 }, fields);
|
|
89
|
+
} else return await this.readCapped(r, path);
|
|
37
90
|
} catch (e) {
|
|
38
91
|
if (attempt >= maxRetries || e?.terminal) throw e;
|
|
39
92
|
lastErr = e;
|
|
@@ -46,7 +99,7 @@ var CsdClient = class {
|
|
|
46
99
|
/**
|
|
47
100
|
* Read a response body as JSON with a hard byte ceiling (`maxResponseBytes`). Rejects an
|
|
48
101
|
* oversized `Content-Length` up front, and otherwise streams the body and aborts the moment
|
|
49
|
-
* it exceeds the cap
|
|
102
|
+
* it exceeds the cap: so a malicious node cannot make us buffer a giant body and OOM before
|
|
50
103
|
* we ever validate it (audit M2). Falls back to a size-checked `text()` on runtimes without a
|
|
51
104
|
* streaming body (older MV3/Node), preserving the cap as a best effort.
|
|
52
105
|
*/
|
|
@@ -95,7 +148,7 @@ var CsdClient = class {
|
|
|
95
148
|
}
|
|
96
149
|
// The node returns application errors as `{ok:false, err}` with HTTP **200**, so a bare `get()`
|
|
97
150
|
// can't see them. For endpoints whose `{ok:false}` result is useless to the caller (a missing
|
|
98
|
-
// block), surface it as a thrown error
|
|
151
|
+
// block), surface it as a thrown error: otherwise a beyond-tip/not-found block flows downstream
|
|
99
152
|
// as a malformed object and crashes opaquely (e.g. the light client reading `header.prev`).
|
|
100
153
|
async getOk(path) {
|
|
101
154
|
const j = await this.get(path);
|
|
@@ -124,7 +177,7 @@ var CsdClient = class {
|
|
|
124
177
|
return this.get(`/utxos/${addr}${opts.available === false ? "" : "?available=true"}`);
|
|
125
178
|
}
|
|
126
179
|
// getOk: a not-found proposal returns {ok:false}@200; without this the caller reads .domain/.uri off a
|
|
127
|
-
// malformed object instead of seeing the error (audit M6). (tx() deliberately keeps its bare get
|
|
180
|
+
// malformed object instead of seeing the error (audit M6). (tx() deliberately keeps its bare get: its
|
|
128
181
|
// {ok:false} is a documented VALID "not yet in a block" state that waitForTx/verifyInputValues handle.)
|
|
129
182
|
proposal(id) {
|
|
130
183
|
return this.getOk(`/proposal/${id}`);
|
|
@@ -142,11 +195,11 @@ var CsdClient = class {
|
|
|
142
195
|
return this.get("/mempool");
|
|
143
196
|
}
|
|
144
197
|
/**
|
|
145
|
-
* Await a txid reaching `confirmations` (default 1)
|
|
198
|
+
* Await a txid reaching `confirmations` (default 1): the submit-then-confirm flow every
|
|
146
199
|
* consumer was hand-rolling. Polls /tx + /tip; resolves {txid, height, confirmations};
|
|
147
|
-
* rejects on timeout (default 10 min
|
|
200
|
+
* rejects on timeout (default 10 min: CSD blocks are ~2 min but the live miner is lumpy).
|
|
148
201
|
* A tx that drops OUT of the chain mid-wait (reorg) keeps polling until it re-confirms or
|
|
149
|
-
* times out
|
|
202
|
+
* times out: never resolves on a stale sighting.
|
|
150
203
|
* The count is `tip.height - tx.height + 1` from the RPC's own /tx and /tip answers, with no PoW
|
|
151
204
|
* or inclusion check, so a lying RPC can over-state it. Gate funds on csd-light, not on this.
|
|
152
205
|
*/
|
|
@@ -170,7 +223,7 @@ var CsdClient = class {
|
|
|
170
223
|
}
|
|
171
224
|
/**
|
|
172
225
|
* Broadcast a node-JSON tx (from @inversealtruism/csd-tx `txToNodeJson`).
|
|
173
|
-
* ⚠ The node returns `{ok:false, err}` with HTTP 200 on REJECTION
|
|
226
|
+
* ⚠ The node returns `{ok:false, err}` with HTTP 200 on REJECTION, and **`txid` is populated even
|
|
174
227
|
* then** (it's the computed id of the rejected tx). Callers MUST check `.ok`; reading `.txid`
|
|
175
228
|
* alone mistakes a rejected tx for a broadcast one. Use `submitOrThrow` if you want a hard failure.
|
|
176
229
|
*/
|
|
@@ -234,6 +287,7 @@ function rpcHeaderToHeader(h) {
|
|
|
234
287
|
}
|
|
235
288
|
export {
|
|
236
289
|
CsdClient,
|
|
290
|
+
ERROR_BODY_MAX_BYTES,
|
|
237
291
|
parseJsonExact,
|
|
238
292
|
rpcHeaderToHeader,
|
|
239
293
|
rpcTxToTx,
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inversealtruism/csd-client",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.21",
|
|
4
4
|
"engines": {
|
|
5
|
-
"node": ">=
|
|
5
|
+
"node": ">=22"
|
|
6
6
|
},
|
|
7
7
|
"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.",
|
|
8
8
|
"type": "module",
|
|
@@ -27,12 +27,12 @@
|
|
|
27
27
|
"README.md"
|
|
28
28
|
],
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@inversealtruism/csd-codec": "0.1.
|
|
30
|
+
"@inversealtruism/csd-codec": "0.1.19"
|
|
31
31
|
},
|
|
32
32
|
"license": "MIT",
|
|
33
33
|
"sideEffects": false,
|
|
34
34
|
"devDependencies": {
|
|
35
|
-
"@inversealtruism/csd-vectors": "0.1.
|
|
35
|
+
"@inversealtruism/csd-vectors": "0.1.17"
|
|
36
36
|
},
|
|
37
37
|
"publishConfig": {
|
|
38
38
|
"access": "public"
|