@integraledger/profile-facilitator 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +157 -69
- package/dist/answers.d.ts +23 -2
- package/dist/answers.js +43 -3
- package/dist/http.d.ts +22 -5
- package/dist/http.js +41 -20
- package/dist/index.d.ts +15 -1
- package/dist/index.js +25 -11
- package/dist/polkadot.d.ts +2 -2
- package/dist/polkadot.js +266 -103
- package/dist/store.d.ts +6 -4
- package/dist/store.js +17 -15
- package/dist/tron.d.ts +2 -2
- package/dist/tron.js +243 -106
- package/dist/unexpected.d.ts +21 -0
- package/dist/unexpected.js +27 -0
- package/package.json +9 -6
package/dist/polkadot.js
CHANGED
|
@@ -5,13 +5,19 @@
|
|
|
5
5
|
*/
|
|
6
6
|
import { ApiPromise } from "@polkadot/api";
|
|
7
7
|
import { blake2b } from "@noble/hashes/blake2.js";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
8
|
+
import { pairingOf } from "@integraledger/lcp";
|
|
9
|
+
import { isRefusal } from "@integraledger/lcp/core";
|
|
10
|
+
import { decodeProfileCall, exactPolkadotRemark, extrinsicHash, ss58Decode, } from "@integraledger/lcp/polkadot";
|
|
11
|
+
import { failed, invalid, isObject, isPending, pending, } from "./answers.js";
|
|
12
|
+
import { NODE_MAX_BYTES, NODE_TIMEOUT_MS, NodeError, Slots, isSpent, postJson, sleep, within } from "./http.js";
|
|
12
13
|
import { answerReserve, inTime } from "./store.js";
|
|
14
|
+
import { settleReason, unexpectedSettle, unexpectedVerify } from "./unexpected.js";
|
|
13
15
|
const POLL_MS = 1_000;
|
|
14
|
-
/**
|
|
16
|
+
/**
|
|
17
|
+
* The longest a metadata load may take. Each of its calls is bounded by the node call bound and by the time the load
|
|
18
|
+
* has left, and a call the load has no time left for is not sent: a load given up at this bound has no call in flight
|
|
19
|
+
* and sends no further call.
|
|
20
|
+
*/
|
|
15
21
|
const INIT_TIMEOUT_MS = 30_000;
|
|
16
22
|
/** Milliseconds per block, used to turn the era's last block into the row's `until`. */
|
|
17
23
|
const SLOW_BLOCK_MS = 12_000;
|
|
@@ -48,7 +54,7 @@ class RpcError extends Error {
|
|
|
48
54
|
}
|
|
49
55
|
/**
|
|
50
56
|
* True when a refused submission says the node has already seen the extrinsic or its nonce (already in the pool,
|
|
51
|
-
* temporarily banned, or an outdated nonce),
|
|
57
|
+
* temporarily banned, or an outdated nonce): the payment's replay primitive, the payer's nonce, is consumed.
|
|
52
58
|
*/
|
|
53
59
|
function seenBefore(e) {
|
|
54
60
|
if (e.code === ALREADY_IMPORTED || e.code === TEMPORARILY_BANNED)
|
|
@@ -66,14 +72,20 @@ async function rpc(url, method, params, timeoutMs, maxBytes) {
|
|
|
66
72
|
}
|
|
67
73
|
return answer["result"];
|
|
68
74
|
}
|
|
69
|
-
/**
|
|
70
|
-
|
|
75
|
+
/**
|
|
76
|
+
* A provider for `@polkadot/api`, with no subscriptions, for one metadata load that ends at `deadline` (on
|
|
77
|
+
* `performance.now()`). Every call is one JSON-RPC POST bounded by the node call bound and by the time left before
|
|
78
|
+
* `deadline`; once `deadline` has passed, a call is not sent and fails as `spent`. `@polkadot/api` goes on with a
|
|
79
|
+
* load's calls once its caller stops waiting for the load; this bound ends them, so a load given up at its deadline has
|
|
80
|
+
* no call in flight and sends no further call.
|
|
81
|
+
*/
|
|
82
|
+
function boundedProvider(url, deadline) {
|
|
71
83
|
const provider = {
|
|
72
84
|
hasSubscriptions: false,
|
|
73
85
|
isClonable: false,
|
|
74
86
|
isConnected: true,
|
|
75
87
|
clone() {
|
|
76
|
-
return boundedProvider(url);
|
|
88
|
+
return boundedProvider(url, deadline);
|
|
77
89
|
},
|
|
78
90
|
async connect() { },
|
|
79
91
|
async disconnect() { },
|
|
@@ -81,7 +93,10 @@ function boundedProvider(url) {
|
|
|
81
93
|
return () => { };
|
|
82
94
|
},
|
|
83
95
|
send(method, params) {
|
|
84
|
-
|
|
96
|
+
const left = deadline - performance.now();
|
|
97
|
+
if (left <= 0)
|
|
98
|
+
return Promise.reject(new NodeError("spent", false, method));
|
|
99
|
+
return rpc(url, method, params, left);
|
|
85
100
|
},
|
|
86
101
|
subscribe() {
|
|
87
102
|
return Promise.reject(new Error("subscriptions are not used"));
|
|
@@ -124,35 +139,95 @@ function runtimeBounds(api) {
|
|
|
124
139
|
const body = Math.max(...classes);
|
|
125
140
|
return { blockAnswerBytes: NODE_MAX_BYTES + Math.ceil((9 * body) / 2) + 7 * headerBytes, blockHashCount: count };
|
|
126
141
|
}
|
|
127
|
-
export function createPolkadot(nodes, s, settleWaitMs) {
|
|
142
|
+
export function createPolkadot(nodes, s, settleWaitMs, log) {
|
|
128
143
|
const byNetwork = new Map(nodes.map((n) => [n.network, n]));
|
|
129
144
|
const apis = new Map();
|
|
130
|
-
/** The
|
|
131
|
-
|
|
145
|
+
/** The fields that name a payment in an operator entry: the payer once the extrinsic is decoded. */
|
|
146
|
+
const about = (c) => ({
|
|
147
|
+
network: c.network,
|
|
148
|
+
...(c.payer === undefined ? {} : { payer: c.payer }),
|
|
149
|
+
transaction: c.id,
|
|
150
|
+
});
|
|
151
|
+
/**
|
|
152
|
+
* `unexpected_verify_error` for an answer to `call` this facilitator cannot read: a `node-call-failed` entry whose
|
|
153
|
+
* cause is a `malformed` NodeError naming the part it cannot read.
|
|
154
|
+
*/
|
|
155
|
+
const malformed = (c, call, part) => unexpectedVerify(log, { event: "node-call-failed", ...about(c), call }, new NodeError("malformed", true, `${call}: ${part}`));
|
|
156
|
+
/** The entry for a settle whose deadline, `settleWaitMs` after its request, passed before `before`. */
|
|
157
|
+
const deadlinePassed = (c, before) => ({
|
|
158
|
+
event: "settle-deadline-passed",
|
|
159
|
+
...about(c),
|
|
160
|
+
before,
|
|
161
|
+
settleWaitMs,
|
|
162
|
+
});
|
|
163
|
+
/**
|
|
164
|
+
* `unexpected_verify_error` for a `/verify` step whose own bound left no time for its call `call`: the call was not
|
|
165
|
+
* sent, and the entry is a failed call's, its cause a `spent` NodeError.
|
|
166
|
+
*/
|
|
167
|
+
const notSent = (c, call) => unexpectedVerify(log, { event: "node-call-failed", ...about(c), call }, new NodeError("spent", false, call));
|
|
168
|
+
/** The stored row, or undefined when the store does not answer by `deadline`; the failure goes to the operator log. */
|
|
169
|
+
const readStored = (c, deadline) => inTime(s.read(c.network, c.id), deadline).catch((e) => {
|
|
170
|
+
log({ event: "store-call-failed", ...about(c), call: "read" }, e);
|
|
171
|
+
return undefined;
|
|
172
|
+
});
|
|
173
|
+
/**
|
|
174
|
+
* The network's metadata, loaded once and loaded again when the node's runtime version changes, within `timeoutMs`:
|
|
175
|
+
* the version read, the wait for a load another request started, and the wait for a new load. One failed load is one
|
|
176
|
+
* failure, with one operator entry. A load that fails while the request that started it waits is that request's
|
|
177
|
+
* failure, which it reports; one that fails once that request has stopped waiting goes to the operator log from the
|
|
178
|
+
* handler below, with that request's payment `fields` and the load's cause. Once `timeoutMs` is spent, a new load is
|
|
179
|
+
* not started and a load in flight is not waited for: that is a `spent` NodeError.
|
|
180
|
+
*/
|
|
181
|
+
async function apiFor(node, fields, timeoutMs) {
|
|
182
|
+
const deadline = performance.now() + timeoutMs;
|
|
183
|
+
const left = () => deadline - performance.now();
|
|
132
184
|
const version = await rpc(node.rpc, "state_getRuntimeVersion", [], timeoutMs);
|
|
133
185
|
const spec = isObject(version) ? version["specVersion"] : undefined;
|
|
134
186
|
if (typeof spec !== "number")
|
|
135
187
|
throw new NodeError("malformed", true, "state_getRuntimeVersion: no specVersion");
|
|
136
188
|
let loading = apis.get(node.network);
|
|
137
189
|
if (loading !== undefined) {
|
|
138
|
-
|
|
190
|
+
// A load that failed has gone to the operator log, from the request that started it or from the handler below;
|
|
191
|
+
// a new one is made.
|
|
192
|
+
// With no time left, a load in flight ends the wait at once: this request sends nothing.
|
|
193
|
+
const spent = left() <= 0;
|
|
194
|
+
const api = await within(loading.catch(() => undefined), left()).catch((e) => {
|
|
195
|
+
throw spent ? new NodeError("spent", false, "metadata") : e;
|
|
196
|
+
});
|
|
139
197
|
if (api !== undefined && api.runtimeVersion.specVersion.toNumber() === spec)
|
|
140
198
|
return api;
|
|
141
199
|
apis.delete(node.network);
|
|
142
200
|
void api?.disconnect();
|
|
143
201
|
}
|
|
202
|
+
if (left() <= 0)
|
|
203
|
+
throw new NodeError("spent", false, "metadata");
|
|
144
204
|
const fresh = load(node);
|
|
145
205
|
apis.set(node.network, fresh);
|
|
146
|
-
|
|
206
|
+
let waiting = true;
|
|
207
|
+
// Registered before the wait below, so a failure that ends the wait reaches this handler while `waiting` holds.
|
|
208
|
+
fresh.catch((e) => {
|
|
147
209
|
if (apis.get(node.network) === fresh)
|
|
148
210
|
apis.delete(node.network);
|
|
211
|
+
if (!waiting)
|
|
212
|
+
log({ event: "node-call-failed", ...fields, call: "metadata" }, e);
|
|
149
213
|
});
|
|
150
|
-
|
|
214
|
+
try {
|
|
215
|
+
return await within(fresh, left());
|
|
216
|
+
}
|
|
217
|
+
finally {
|
|
218
|
+
waiting = false;
|
|
219
|
+
}
|
|
151
220
|
}
|
|
221
|
+
/**
|
|
222
|
+
* The network's metadata, loaded through a provider whose calls end at the load's deadline, `INIT_TIMEOUT_MS` after
|
|
223
|
+
* the load starts. The load is given up at that deadline: it has no call in flight then and sends none after it, and
|
|
224
|
+
* a later request starts a fresh load.
|
|
225
|
+
*/
|
|
152
226
|
async function load(node) {
|
|
153
|
-
const
|
|
227
|
+
const deadline = performance.now() + INIT_TIMEOUT_MS;
|
|
228
|
+
const api = new ApiPromise({ provider: boundedProvider(node.rpc, deadline), noInitWarn: true, initWasm: false });
|
|
154
229
|
try {
|
|
155
|
-
await within(api.isReadyOrError,
|
|
230
|
+
await within(api.isReadyOrError, deadline - performance.now());
|
|
156
231
|
}
|
|
157
232
|
catch (e) {
|
|
158
233
|
void api.disconnect();
|
|
@@ -170,7 +245,7 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
170
245
|
const node = byNetwork.get(req.network);
|
|
171
246
|
if (node === undefined)
|
|
172
247
|
return "invalid_network";
|
|
173
|
-
if (
|
|
248
|
+
if (pairingOf(req) !== "x402/exact/polkadot/lcp-assets-remark")
|
|
174
249
|
return "invalid_payment_requirements";
|
|
175
250
|
const { extrinsic, call } = r.paymentPayload.payload;
|
|
176
251
|
if (!isLowerHex(extrinsic) || !isLowerHex(call))
|
|
@@ -195,20 +270,27 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
195
270
|
remarkHash: `0x${hexOf(blake2b(profile.remark, { dkLen: 32 }))}`,
|
|
196
271
|
};
|
|
197
272
|
}
|
|
198
|
-
/**
|
|
273
|
+
/**
|
|
274
|
+
* The checks of rule 5 that decode the extrinsic with the network's metadata, within `timeoutMs`. A metadata read that
|
|
275
|
+
* `timeoutMs` leaves no time for is not made, and the answer is `{ spent: "metadata" }`.
|
|
276
|
+
*/
|
|
199
277
|
async function decode(l, timeoutMs) {
|
|
278
|
+
const fields = about({ network: l.node.network, id: l.id });
|
|
200
279
|
let api;
|
|
201
280
|
try {
|
|
202
|
-
api = await
|
|
281
|
+
api = await apiFor(l.node, fields, timeoutMs);
|
|
203
282
|
}
|
|
204
|
-
catch {
|
|
205
|
-
|
|
283
|
+
catch (e) {
|
|
284
|
+
if (isSpent(e))
|
|
285
|
+
return { spent: "metadata" };
|
|
286
|
+
return unexpectedVerify(log, { event: "node-call-failed", ...fields, call: "metadata" }, e);
|
|
206
287
|
}
|
|
207
288
|
let xt;
|
|
208
289
|
try {
|
|
209
290
|
xt = api.createType("Extrinsic", l.extrinsic);
|
|
210
291
|
}
|
|
211
292
|
catch {
|
|
293
|
+
// The payer's own extrinsic bytes do not decode: refused `invalid_payload` to the client that sent them.
|
|
212
294
|
return "invalid_payload";
|
|
213
295
|
}
|
|
214
296
|
if (!xt.isSigned || xt.type !== 4 || xt.toHex() !== l.extrinsic || xt.method.toHex() !== l.call)
|
|
@@ -226,16 +308,20 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
226
308
|
}
|
|
227
309
|
if (!xt.era.isMortalEra)
|
|
228
310
|
return "invalid_payload";
|
|
311
|
+
const payer = xt.signer.toString();
|
|
312
|
+
const decoded = { network: l.node.network, id: l.id, payer };
|
|
229
313
|
const eventsKey = api.query["system"]?.["events"]?.key();
|
|
314
|
+
if (eventsKey === undefined)
|
|
315
|
+
return malformed(decoded, "metadata", "System.Events");
|
|
230
316
|
const bounds = runtimeBounds(api);
|
|
231
|
-
if (
|
|
232
|
-
return "
|
|
317
|
+
if (bounds === undefined)
|
|
318
|
+
return malformed(decoded, "metadata", "System.BlockLength, System.BlockHashCount");
|
|
233
319
|
return {
|
|
234
320
|
network: l.node.network,
|
|
235
321
|
api,
|
|
236
322
|
hex: l.extrinsic,
|
|
237
323
|
id: l.id,
|
|
238
|
-
payer
|
|
324
|
+
payer,
|
|
239
325
|
assetId: l.assetId,
|
|
240
326
|
remarkHash: l.remarkHash,
|
|
241
327
|
era: xt.era.asMortalEra,
|
|
@@ -255,7 +341,8 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
255
341
|
}
|
|
256
342
|
/**
|
|
257
343
|
* `TaggedTransactionQueue_validate_transaction` at the best block, within `timeoutMs`: the best block's height, and
|
|
258
|
-
* when the last block that can include the extrinsic ends.
|
|
344
|
+
* when the last block that can include the extrinsic ends. A call `timeoutMs` leaves no time for is not sent, and the
|
|
345
|
+
* answer names it.
|
|
259
346
|
*/
|
|
260
347
|
async function validate(c, timeoutMs = 3 * NODE_TIMEOUT_MS) {
|
|
261
348
|
const url = byNetwork.get(c.network).rpc;
|
|
@@ -264,19 +351,26 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
264
351
|
let best;
|
|
265
352
|
let header;
|
|
266
353
|
let validity;
|
|
354
|
+
let call = "chain_getBlockHash";
|
|
267
355
|
try {
|
|
268
|
-
best = await rpc(url,
|
|
356
|
+
best = await rpc(url, call, [], left());
|
|
269
357
|
if (!isLowerHex(best) || best.length !== 66)
|
|
270
|
-
return "
|
|
271
|
-
|
|
272
|
-
|
|
358
|
+
return malformed(c, call, "the block hash");
|
|
359
|
+
call = "chain_getHeader";
|
|
360
|
+
header = await rpc(url, call, [best], left());
|
|
361
|
+
call = "state_call";
|
|
362
|
+
validity = await rpc(url, call, ["TaggedTransactionQueue_validate_transaction", `0x${EXTERNAL}${c.hex.slice(2)}${best.slice(2)}`, best], left());
|
|
273
363
|
}
|
|
274
|
-
catch {
|
|
275
|
-
|
|
364
|
+
catch (e) {
|
|
365
|
+
if (isSpent(e))
|
|
366
|
+
return { spent: call };
|
|
367
|
+
return unexpectedVerify(log, { event: "node-call-failed", ...about(c), call }, e);
|
|
276
368
|
}
|
|
277
369
|
const height = blockNumber(header);
|
|
278
|
-
if (height === undefined
|
|
279
|
-
return "
|
|
370
|
+
if (height === undefined)
|
|
371
|
+
return malformed(c, "chain_getHeader", "number");
|
|
372
|
+
if (typeof validity !== "string")
|
|
373
|
+
return malformed(c, "state_call", "the validity");
|
|
280
374
|
if (!validity.startsWith("0x00"))
|
|
281
375
|
return "invalid_transaction";
|
|
282
376
|
const blocksLeft = Math.max(0, lastBlock(c, height) + 1 - height);
|
|
@@ -289,8 +383,14 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
289
383
|
const c = await decode(l, INIT_TIMEOUT_MS);
|
|
290
384
|
if (typeof c === "string")
|
|
291
385
|
return invalid(c);
|
|
386
|
+
if ("spent" in c)
|
|
387
|
+
return invalid(notSent({ network: l.node.network, id: l.id }, c.spent));
|
|
292
388
|
const v = await validate(c);
|
|
293
|
-
|
|
389
|
+
if (typeof v === "string")
|
|
390
|
+
return invalid(v, c.payer);
|
|
391
|
+
if ("spent" in v)
|
|
392
|
+
return invalid(notSent(c, v.spent), c.payer);
|
|
393
|
+
return { isValid: true, payer: c.payer };
|
|
294
394
|
}
|
|
295
395
|
/**
|
|
296
396
|
* The answer for the extrinsic at `index` of block `hash`, from that block's events. A failure is logged for the
|
|
@@ -309,25 +409,46 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
309
409
|
return { success: true, transaction: timepoint, network: c.network, payer: c.payer };
|
|
310
410
|
const seen = mine.map((r) => `${r.event.section}.${r.event.method}`);
|
|
311
411
|
if (final)
|
|
312
|
-
|
|
412
|
+
log({ event: "settlement-failed", ...about(c), transaction: timepoint, events: seen });
|
|
313
413
|
return failed("invalid_transaction_state", timepoint, c.network);
|
|
314
414
|
}
|
|
315
|
-
/**
|
|
316
|
-
|
|
415
|
+
/**
|
|
416
|
+
* The finalized head's height, read before `deadline`. Undefined when a read fails or the header names no number, a
|
|
417
|
+
* node answer this facilitator cannot read; either is a `node-call-failed` entry with the call. A read `deadline`
|
|
418
|
+
* leaves no time for is not sent, and the answer names it.
|
|
419
|
+
*/
|
|
420
|
+
async function finalizedHeight(c, url, deadline) {
|
|
421
|
+
let call = "chain_getFinalizedHead";
|
|
317
422
|
try {
|
|
318
|
-
const hash = await rpc(url,
|
|
319
|
-
|
|
423
|
+
const hash = await rpc(url, call, [], deadline - performance.now());
|
|
424
|
+
call = "chain_getHeader";
|
|
425
|
+
const height = blockNumber(await rpc(url, call, [hash], deadline - performance.now()));
|
|
426
|
+
if (height === undefined)
|
|
427
|
+
throw new NodeError("malformed", true, `${call}: number`);
|
|
428
|
+
return height;
|
|
320
429
|
}
|
|
321
|
-
catch {
|
|
430
|
+
catch (e) {
|
|
431
|
+
if (isSpent(e))
|
|
432
|
+
return { spent: call };
|
|
433
|
+
log({ event: "node-call-failed", ...about(c), call }, e);
|
|
322
434
|
return undefined;
|
|
323
435
|
}
|
|
324
436
|
}
|
|
325
|
-
/**
|
|
326
|
-
|
|
437
|
+
/**
|
|
438
|
+
* The head's height. Undefined when the read fails or the header names no number, a node answer this facilitator
|
|
439
|
+
* cannot read; either is a `node-call-failed` entry with the call. Undefined too, with no entry, when `left()` leaves
|
|
440
|
+
* no time for the read, which is not sent.
|
|
441
|
+
*/
|
|
442
|
+
async function headHeight(c, url, left) {
|
|
327
443
|
try {
|
|
328
|
-
|
|
444
|
+
const height = blockNumber(await rpc(url, "chain_getHeader", [], left()));
|
|
445
|
+
if (height === undefined)
|
|
446
|
+
throw new NodeError("malformed", true, "chain_getHeader: number");
|
|
447
|
+
return height;
|
|
329
448
|
}
|
|
330
|
-
catch {
|
|
449
|
+
catch (e) {
|
|
450
|
+
if (!isSpent(e))
|
|
451
|
+
log({ event: "node-call-failed", ...about(c), call: "chain_getHeader" }, e);
|
|
331
452
|
return undefined;
|
|
332
453
|
}
|
|
333
454
|
}
|
|
@@ -356,7 +477,9 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
356
477
|
/**
|
|
357
478
|
* Block `n` read for the extrinsic: the answer when the block holds it, `absent` when it does not, `unreadable` (with
|
|
358
479
|
* the reason) when the node gives neither the block nor, for the block that holds it, its events, or when no block
|
|
359
|
-
* read slot comes free before the deadline, and `stopped` when the deadline ends a read that started.
|
|
480
|
+
* read slot comes free before the deadline, and `stopped` when the deadline ends a read that started. A call the
|
|
481
|
+
* deadline leaves no time for is not sent, and the read is `stopped` with no entry; each other read that gives no
|
|
482
|
+
* block goes to the operator log, with what stopped it.
|
|
360
483
|
*/
|
|
361
484
|
async function readBlock(c, url, n, left, final) {
|
|
362
485
|
try {
|
|
@@ -366,9 +489,15 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
366
489
|
return await included(c, url, found.hash, found.index, left(), final);
|
|
367
490
|
}
|
|
368
491
|
catch (e) {
|
|
369
|
-
if (
|
|
492
|
+
if (isSpent(e))
|
|
493
|
+
return "stopped";
|
|
494
|
+
if (!(e instanceof NoBlockReadSlot) && left() <= 0) {
|
|
495
|
+
log({ event: "block-read-stopped", ...about(c), block: n }, e);
|
|
370
496
|
return "stopped";
|
|
371
|
-
|
|
497
|
+
}
|
|
498
|
+
const reason = e instanceof Error ? e.message : String(e);
|
|
499
|
+
log({ event: "block-unreadable", ...about(c), block: n, final, reason }, e);
|
|
500
|
+
return { unreadable: reason };
|
|
372
501
|
}
|
|
373
502
|
}
|
|
374
503
|
/**
|
|
@@ -378,8 +507,8 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
378
507
|
* success is an answer: a failure there waits until its block is final, and a block that cannot be read is skipped,
|
|
379
508
|
* since it is read again at finality. Then, with the time left, the blocks recorded as unread before this pass are
|
|
380
509
|
* read again. Once every block to the last is read at finality, and none is unread, the extrinsic can never be
|
|
381
|
-
* included, and the answer is `invalid_transaction_state` with its hash.
|
|
382
|
-
* got to.
|
|
510
|
+
* included, and the answer is `invalid_transaction_state` with its hash. The head is not read once `deadline` has
|
|
511
|
+
* passed. Gives the final answer, or where the scan has got to.
|
|
383
512
|
*/
|
|
384
513
|
async function scanOnce(c, since, at, deadline) {
|
|
385
514
|
const url = byNetwork.get(c.network).rpc;
|
|
@@ -389,14 +518,14 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
389
518
|
const unread = new Set(at.unread);
|
|
390
519
|
const resolved = new Set(at.resolved);
|
|
391
520
|
const position = () => ({ proven, next, unread: [...unread].sort((a, b) => a - b), resolved: [...resolved] });
|
|
392
|
-
const
|
|
521
|
+
const read = await finalizedHeight(c, url, deadline);
|
|
522
|
+
const finalized = typeof read === "number" ? read : undefined;
|
|
393
523
|
while (finalized !== undefined && proven <= Math.min(finalized, last) && left() > 0) {
|
|
394
524
|
const read = await readBlock(c, url, proven, left, true);
|
|
395
525
|
if (read === "stopped")
|
|
396
526
|
return position();
|
|
397
527
|
if (typeof read === "object" && "unreadable" in read) {
|
|
398
528
|
unread.add(proven);
|
|
399
|
-
operatorLog({ event: "block-unreadable", network: c.network, transaction: c.id, block: proven, reason: read.unreadable });
|
|
400
529
|
}
|
|
401
530
|
else if (read !== "absent") {
|
|
402
531
|
return { answer: read };
|
|
@@ -404,7 +533,7 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
404
533
|
proven += 1;
|
|
405
534
|
}
|
|
406
535
|
next = Math.max(next, proven);
|
|
407
|
-
const head = await headHeight(url, left);
|
|
536
|
+
const head = left() > 0 ? await headHeight(c, url, left) : undefined;
|
|
408
537
|
while (head !== undefined && next <= Math.min(head, last) && left() > 0) {
|
|
409
538
|
const read = await readBlock(c, url, next, left, false);
|
|
410
539
|
if (read === "stopped")
|
|
@@ -430,32 +559,37 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
430
559
|
return { answer: read };
|
|
431
560
|
}
|
|
432
561
|
if (proven > last && unread.size === 0) {
|
|
433
|
-
|
|
562
|
+
log({ event: "settlement-expired", ...about(c) });
|
|
434
563
|
return { answer: failed("invalid_transaction_state", c.id, c.network) };
|
|
435
564
|
}
|
|
436
565
|
return position();
|
|
437
566
|
}
|
|
438
567
|
/**
|
|
439
568
|
* Scans for the extrinsic from `since`, with the stored `unread` blocks, every second until `deadline`, reading the
|
|
440
|
-
* stored answer too when `stored` is set, and answers with the first final answer either gives.
|
|
441
|
-
*
|
|
569
|
+
* stored answer too when `stored` is set, and answers with the first final answer either gives. Once `deadline` has
|
|
570
|
+
* passed, no pass is made: the answer is the one the wait's end gives. Where the scan got to at finality is stored:
|
|
571
|
+
* `since` moves on, and the blocks it could not read are recorded. Submits nothing.
|
|
442
572
|
*/
|
|
443
573
|
async function scan(c, since, unread, deadline, stored) {
|
|
444
574
|
let at = { proven: since, next: since, unread, resolved: [] };
|
|
445
575
|
for (;;) {
|
|
446
576
|
if (stored) {
|
|
447
|
-
const row = await
|
|
577
|
+
const row = await readStored(c, deadline);
|
|
448
578
|
if (row?.state === "answered" && !isPending(row.answer))
|
|
449
579
|
return row.answer;
|
|
450
580
|
}
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
581
|
+
if (deadline - performance.now() > 0) {
|
|
582
|
+
const step = await scanOnce(c, since, at, deadline);
|
|
583
|
+
if ("answer" in step)
|
|
584
|
+
return step.answer;
|
|
585
|
+
at = step;
|
|
586
|
+
}
|
|
455
587
|
if (performance.now() + POLL_MS > deadline) {
|
|
456
588
|
if (at.proven > since || at.unread.length > 0 || at.resolved.length > 0) {
|
|
457
589
|
const to = Math.min(at.proven, lastBlock(c, since));
|
|
458
|
-
void s
|
|
590
|
+
void s
|
|
591
|
+
.advance(c.network, c.id, { from: since, to, unread: at.unread, resolved: at.resolved })
|
|
592
|
+
.catch((e) => log({ event: "store-call-failed", ...about(c), call: "advance" }, e));
|
|
459
593
|
}
|
|
460
594
|
return pending(c.id, c.network);
|
|
461
595
|
}
|
|
@@ -464,7 +598,10 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
464
598
|
}
|
|
465
599
|
/**
|
|
466
600
|
* Submits, then scans for the extrinsic until `deadline`. A refusal that says the node has already seen the extrinsic
|
|
467
|
-
* or its nonce is
|
|
601
|
+
* or its nonce is a consumed payment: `invalid_transaction_state` with the extrinsic's hash, and no scan. Any other
|
|
602
|
+
* refusal, or a request that cannot have reached the node, gives `unexpected_settle_error` with no transaction:
|
|
603
|
+
* nothing was submitted. So does a submission `deadline` leaves no time for, as after a claim that answers late: it
|
|
604
|
+
* is not sent, and its entry is `settle-deadline-passed`.
|
|
468
605
|
*/
|
|
469
606
|
async function submit(c, since, deadline) {
|
|
470
607
|
const url = byNetwork.get(c.network).rpc;
|
|
@@ -472,12 +609,14 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
472
609
|
await rpc(url, "author_submitExtrinsic", [c.hex], deadline - performance.now());
|
|
473
610
|
}
|
|
474
611
|
catch (e) {
|
|
475
|
-
if (
|
|
476
|
-
return
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
if (
|
|
480
|
-
return
|
|
612
|
+
if (isSpent(e))
|
|
613
|
+
return unexpectedSettle(log, deadlinePassed(c, "author_submitExtrinsic"));
|
|
614
|
+
const entry = { event: "node-call-failed", ...about(c), call: "author_submitExtrinsic" };
|
|
615
|
+
const notSubmitted = e instanceof RpcError ? !seenBefore(e) : e instanceof NodeError && !e.sent;
|
|
616
|
+
if (notSubmitted)
|
|
617
|
+
return unexpectedSettle(log, entry, e);
|
|
618
|
+
log(entry, e);
|
|
619
|
+
return e instanceof RpcError ? failed("invalid_transaction_state", c.id, c.network) : pending(c.id, c.network);
|
|
481
620
|
}
|
|
482
621
|
return scan(c, since, [], deadline, false);
|
|
483
622
|
}
|
|
@@ -489,55 +628,66 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
489
628
|
function repeatOf(stored) {
|
|
490
629
|
if (!stored.success)
|
|
491
630
|
return stored;
|
|
492
|
-
|
|
631
|
+
log({ event: "settlement-consumed", network: stored.network, payer: stored.payer, transaction: stored.transaction });
|
|
493
632
|
return failed("invalid_transaction_state", stored.transaction, stored.network);
|
|
494
633
|
}
|
|
495
634
|
/**
|
|
496
635
|
* Stores the answer, unless the row holds a final one. A success is given only by the settle whose write stored it:
|
|
497
636
|
* when the row already holds a final answer, the answer is what a repeat gets for it, and when the write fails, it is
|
|
498
|
-
* pending with the hash, for a later read of the chain.
|
|
499
|
-
*
|
|
637
|
+
* pending with the hash, for a later read of the chain. An answer with no transaction, a refused submission or one
|
|
638
|
+
* that cannot have reached the node, is given the same way: only once it is the stored answer. Any other answer is
|
|
639
|
+
* given whether or not it is stored; a failed write leaves the row for a later read of the chain.
|
|
500
640
|
*/
|
|
501
641
|
async function keep(c, answer, deadline) {
|
|
502
642
|
let wrote;
|
|
503
643
|
try {
|
|
504
644
|
wrote = await inTime(s.answer(c.network, c.id, answer), deadline);
|
|
505
645
|
}
|
|
506
|
-
catch {
|
|
507
|
-
|
|
508
|
-
return answer.success ? pending(c.id, c.network) : answer;
|
|
646
|
+
catch (e) {
|
|
647
|
+
log({ event: "answer-not-stored", ...about(c) }, e);
|
|
648
|
+
return answer.success || answer.transaction === "" ? pending(c.id, c.network) : answer;
|
|
509
649
|
}
|
|
510
|
-
if (!answer.success
|
|
650
|
+
if (wrote || (!answer.success && answer.transaction !== ""))
|
|
511
651
|
return answer;
|
|
512
|
-
const row = await
|
|
652
|
+
const row = await readStored(c, deadline);
|
|
513
653
|
return row?.state === "answered" && !isPending(row.answer) ? repeatOf(row.answer) : pending(c.id, c.network);
|
|
514
654
|
}
|
|
515
655
|
/**
|
|
516
656
|
* Reads a claimed id, or a stored pending answer, again from the chain until the answer's reserve before `deadline`,
|
|
517
|
-
* from the stored `since` and `unread`, then stores what it read.
|
|
657
|
+
* from the stored `since` and `unread`, then stores what it read. The decode is bounded by that wait too. Once that
|
|
658
|
+
* wait has ended, the node is asked nothing: the answer is the stored one, as a repeat gets it, or pending with the
|
|
659
|
+
* hash.
|
|
518
660
|
*/
|
|
519
661
|
async function follow(l, since, unread, deadline) {
|
|
520
|
-
const
|
|
521
|
-
|
|
522
|
-
|
|
662
|
+
const waitUntil = deadline - answerReserve(settleWaitMs);
|
|
663
|
+
const c = waitUntil - performance.now() > 0 ? await decode(l, waitUntil - performance.now()) : undefined;
|
|
664
|
+
const decoded = typeof c === "object" && !("spent" in c) ? c : undefined;
|
|
665
|
+
if (decoded === undefined || since === null) {
|
|
666
|
+
const row = await readStored(decoded ?? { network: l.node.network, id: l.id }, deadline);
|
|
523
667
|
return row?.state === "answered" ? repeatOf(row.answer) : pending(l.id, l.node.network);
|
|
524
668
|
}
|
|
525
|
-
return keep(
|
|
669
|
+
return keep(decoded, await scan(decoded, since, unread, waitUntil, true), deadline);
|
|
526
670
|
}
|
|
527
671
|
/**
|
|
528
672
|
* Answers within `settleWaitMs`. The stored answer is read before the node is asked anything, and a final one is
|
|
529
|
-
* given as a repeat gets it. A claimed id, or a stored pending answer, is read again from the chain.
|
|
530
|
-
*
|
|
531
|
-
* refused
|
|
532
|
-
*
|
|
533
|
-
*
|
|
534
|
-
*
|
|
673
|
+
* given as a repeat gets it. A claimed id, or a stored pending answer, is read again from the chain. A claimed id is
|
|
674
|
+
* never released: a submission the node refused as one it has already seen is a consumed payment, and any other
|
|
675
|
+
* refused submission, or a submission request that cannot have reached the node, gives `unexpected_settle_error`
|
|
676
|
+
* with no transaction, which says nothing was submitted. Each is stored final, and every repeat gets the stored
|
|
677
|
+
* answer. When the store cannot be read, the facilitator cannot know whether the extrinsic was submitted, so the
|
|
678
|
+
* answer is pending with its hash. For a hash the store does not hold, the deadline is checked before each node read:
|
|
679
|
+
* the decode, the finalized head read and the validation. A deadline spent there sends no node call, and gives
|
|
680
|
+
* `unexpected_settle_error`; so does a call inside one of them that the deadline leaves no time for, which is not sent,
|
|
681
|
+
* with its entry naming the call. A refusal the client's own bytes give comes first, so the decode's refusals, which
|
|
682
|
+
* need the metadata, are given when the deadline leaves time for it. The scan starts after the finalized head read before
|
|
683
|
+
* validation (never before the era's birth): validation at the best block shows the extrinsic absent from that
|
|
684
|
+
* block's ancestry, and the finalized head is in every later best chain. No hash is claimed once the wait for the
|
|
685
|
+
* chain has ended: its submission would have no time left.
|
|
535
686
|
*/
|
|
536
687
|
async function settle(r) {
|
|
537
688
|
const deadline = performance.now() + settleWaitMs;
|
|
538
689
|
const left = () => deadline - performance.now();
|
|
539
690
|
const network = r.paymentRequirements.network;
|
|
540
|
-
const settleReason = (v) => (v === "unexpected_verify_error" ? "unexpected_settle_error" : v);
|
|
541
691
|
const l = await local(r);
|
|
542
692
|
if (typeof l === "string")
|
|
543
693
|
return failed(l, "", network);
|
|
@@ -545,46 +695,59 @@ export function createPolkadot(nodes, s, settleWaitMs) {
|
|
|
545
695
|
try {
|
|
546
696
|
stored = await inTime(s.read(l.node.network, l.id), deadline);
|
|
547
697
|
}
|
|
548
|
-
catch {
|
|
698
|
+
catch (e) {
|
|
699
|
+
log({ event: "store-call-failed", ...about({ network: l.node.network, id: l.id }), call: "read" }, e);
|
|
549
700
|
return pending(l.id, l.node.network);
|
|
550
701
|
}
|
|
551
702
|
if (stored.state === "answered" && !isPending(stored.answer))
|
|
552
703
|
return repeatOf(stored.answer);
|
|
553
704
|
if (stored.state !== "none")
|
|
554
705
|
return follow(l, stored.since, stored.unread, deadline);
|
|
706
|
+
const hashed = { network: l.node.network, id: l.id };
|
|
707
|
+
if (left() <= 0)
|
|
708
|
+
return unexpectedSettle(log, deadlinePassed(hashed, "node reads"));
|
|
555
709
|
const c = await decode(l, left());
|
|
556
710
|
if (typeof c === "string")
|
|
557
711
|
return failed(settleReason(c), "", network);
|
|
558
|
-
|
|
712
|
+
if ("spent" in c)
|
|
713
|
+
return unexpectedSettle(log, deadlinePassed(hashed, c.spent));
|
|
714
|
+
if (left() <= 0)
|
|
715
|
+
return unexpectedSettle(log, deadlinePassed(c, "finalized head"));
|
|
716
|
+
const finalized = await finalizedHeight(c, l.node.rpc, deadline);
|
|
717
|
+
if (typeof finalized === "object")
|
|
718
|
+
return unexpectedSettle(log, deadlinePassed(c, finalized.spent));
|
|
719
|
+
if (left() <= 0)
|
|
720
|
+
return unexpectedSettle(log, deadlinePassed(c, "validation"));
|
|
559
721
|
const v = await validate(c, left());
|
|
560
722
|
if (typeof v === "string")
|
|
561
723
|
return failed(settleReason(v), "", network);
|
|
562
|
-
if (
|
|
563
|
-
return
|
|
724
|
+
if ("spent" in v)
|
|
725
|
+
return unexpectedSettle(log, deadlinePassed(c, v.spent));
|
|
726
|
+
const waitUntil = deadline - answerReserve(settleWaitMs);
|
|
727
|
+
if (waitUntil - performance.now() <= 0)
|
|
728
|
+
return unexpectedSettle(log, deadlinePassed(c, "claim"));
|
|
564
729
|
const birth = c.era.birth(v.best);
|
|
565
730
|
const since = Math.min(finalized === undefined ? birth : Math.max(birth, finalized + 1), lastBlock(c, v.best));
|
|
566
731
|
let won;
|
|
567
732
|
try {
|
|
568
733
|
won = await inTime(s.claim(c.network, c.id, v.until, since), deadline);
|
|
569
734
|
}
|
|
570
|
-
catch {
|
|
735
|
+
catch (e) {
|
|
736
|
+
log({ event: "store-call-failed", ...about(c), call: "claim" }, e);
|
|
571
737
|
return pending(c.id, c.network);
|
|
572
738
|
}
|
|
573
739
|
if (!won) {
|
|
574
|
-
const row = await
|
|
740
|
+
const row = await readStored(c, deadline);
|
|
575
741
|
const claimed = row !== undefined && row.state !== "none" ? row : undefined;
|
|
576
742
|
return follow(l, claimed?.since ?? null, claimed?.unread ?? [], deadline);
|
|
577
743
|
}
|
|
578
|
-
|
|
579
|
-
if (answer.success || answer.transaction !== "")
|
|
580
|
-
return keep(c, answer, deadline);
|
|
581
|
-
const released = await inTime(s.release(c.network, c.id), deadline).catch(() => false);
|
|
582
|
-
return released ? answer : pending(c.id, c.network);
|
|
744
|
+
return keep(c, await submit(c, since, waitUntil), deadline);
|
|
583
745
|
}
|
|
584
746
|
async function close() {
|
|
585
|
-
const all = [...apis
|
|
747
|
+
const all = [...apis];
|
|
586
748
|
apis.clear();
|
|
587
|
-
|
|
749
|
+
// A load that failed has gone to the operator log from `decode` or `apiFor`; a failed disconnect goes there here.
|
|
750
|
+
await Promise.all(all.map(([network, p]) => p.then((api) => api.disconnect().catch((e) => log({ event: "node-call-failed", network, call: "disconnect" }, e)), () => undefined)));
|
|
588
751
|
}
|
|
589
752
|
return { verify, settle, close, networks: nodes.map((n) => n.network) };
|
|
590
753
|
}
|