@integraledger/profile-facilitator 0.1.0 → 0.2.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/dist/tron.js CHANGED
@@ -1,26 +1,29 @@
1
1
  /**
2
- * Rule 5 of `x402/exact/tron/lcp-trc20-memo` against one network's FullNode: `/verify` checks the signed transaction
3
- * against the requirements and simulates it; `/settle` repeats that, claims the transaction id, broadcasts, and polls
4
- * for the receipt.
2
+ * Rule 5 of `x402/exact/tron/lcp-trc20-memo` against one network's FullNode and Solidity node: `/verify` checks the
3
+ * signed transaction against the requirements, the owner's permission, its reference block and the ids already held,
4
+ * and simulates it; `/settle` repeats that, claims the transaction id, broadcasts, and reads the transaction's status
5
+ * until it is final.
5
6
  */
6
7
  import { secp256k1 } from "@noble/curves/secp256k1.js";
7
8
  import { keccak_256 } from "@noble/hashes/sha3.js";
9
+ import { isRefusal } from "@integraledger/lcp";
8
10
  import { decodeTronTx, pairingOf, tronAddress, tronCarrier, tronStatus, } from "@integraledger/lcp/tron";
9
11
  import { failed, invalid, isObject, isPending, operatorLog, pending, } from "./answers.js";
10
12
  import { base58check } from "./base58check.js";
11
- import { NODE_TIMEOUT_MS, NodeError, postJson, sleep } from "./http.js";
13
+ import { NodeError, postJson, sleep } from "./http.js";
12
14
  import { answerReserve, inTime } from "./store.js";
13
15
  const POLL_MS = 1_000;
14
16
  /** A verify reason as a settle answer's: a node that could not be read before submission is a settle error. */
15
17
  function settleReason(r) {
16
18
  return r === "unexpected_verify_error" ? "unexpected_settle_error" : r;
17
19
  }
18
- function refused(v) {
19
- return isObject(v) && v["refused"] === true;
20
- }
21
20
  function hexOf(b) {
22
21
  return Buffer.from(b).toString("hex");
23
22
  }
23
+ /** A permission's threshold or a key's weight: java-tron prints an int64 as a JSON number, read as a safe one ≥ 0. */
24
+ function int64(v) {
25
+ return typeof v === "number" && Number.isSafeInteger(v) && v >= 0 ? BigInt(v) : undefined;
26
+ }
24
27
  function sameBytes(a, b) {
25
28
  return a.length === b.length && a.every((x, i) => x === b[i]);
26
29
  }
@@ -69,14 +72,14 @@ export function createTron(nodes, s, settleWaitMs) {
69
72
  if (typeof hex !== "string")
70
73
  return "invalid_payload";
71
74
  const tx = decodeTronTx(hex);
72
- if (refused(tx))
75
+ if (isRefusal(tx))
73
76
  return "invalid_payload";
74
77
  const carried = await tronCarrier(tx);
75
- if (refused(carried))
78
+ if (isRefusal(carried))
76
79
  return "invalid_payload";
77
80
  const asset = await tronAddress(req.asset);
78
81
  const payTo = await tronAddress(req.payTo);
79
- if (refused(asset) || refused(payTo))
82
+ if (isRefusal(asset) || isRefusal(payTo))
80
83
  return "invalid_payment_requirements";
81
84
  if (!sameBytes(tx.raw.contractAddress, asset))
82
85
  return "invalid_payload";
@@ -97,26 +100,93 @@ export function createTron(nodes, s, settleWaitMs) {
97
100
  maxTimeoutSeconds: req.maxTimeoutSeconds,
98
101
  };
99
102
  }
100
- /** The expiration window, then the node's simulation of the call, within `timeoutMs`. */
101
- async function checkNow(c, timeoutMs = NODE_TIMEOUT_MS) {
102
- const now = BigInt(Date.now());
103
- const expiration = c.raw.expiration;
104
- if (expiration <= now || expiration > now + BigInt(c.maxTimeoutSeconds) * 1000n)
105
- return "invalid_payload";
106
- if (timeoutMs <= 0)
107
- return "unexpected_verify_error";
108
- let sim;
103
+ /** A FullNode call's JSON answer, bounded by `deadline` (a `performance.now()` time) and by the node call bound. */
104
+ async function ask(c, path, body, deadline) {
109
105
  try {
110
- sim = await postJson(`${byNetwork.get(c.network).fullNode}/wallet/triggerconstantcontract`, {
111
- owner_address: hexOf(c.raw.owner),
112
- contract_address: hexOf(c.raw.contractAddress),
113
- function_selector: "transfer(address,uint256)",
114
- parameter: hexOf(c.raw.callData.subarray(4)),
115
- }, timeoutMs);
106
+ return await postJson(`${byNetwork.get(c.network).fullNode}${path}`, body, deadline - performance.now());
116
107
  }
117
108
  catch {
109
+ return undefined;
110
+ }
111
+ }
112
+ /**
113
+ * The owner's permission accepts the one signature: the weight it gives the owner's own key is at least its
114
+ * threshold. An account the node does not hold, or one with no owner permission set, has java-tron's default owner
115
+ * permission: the address's own key, weight 1, threshold 1.
116
+ */
117
+ async function permitted(c, deadline) {
118
+ const account = await ask(c, "/wallet/getaccount", { address: hexOf(c.raw.owner) }, deadline);
119
+ if (!isObject(account))
120
+ return "unexpected_verify_error";
121
+ const permission = account["owner_permission"];
122
+ if (permission === undefined)
123
+ return null;
124
+ if (!isObject(permission) || !Array.isArray(permission["keys"]))
118
125
  return "unexpected_verify_error";
126
+ const threshold = int64(permission["threshold"]);
127
+ if (threshold === undefined)
128
+ return "unexpected_verify_error";
129
+ const owner = hexOf(c.raw.owner);
130
+ let weight = 0n;
131
+ for (const key of permission["keys"]) {
132
+ if (!isObject(key) || typeof key["address"] !== "string")
133
+ return "unexpected_verify_error";
134
+ const w = int64(key["weight"]);
135
+ if (w === undefined)
136
+ return "unexpected_verify_error";
137
+ if (key["address"].toLowerCase() === owner)
138
+ weight = w;
119
139
  }
140
+ return weight >= threshold ? null : "unsupported_permission";
141
+ }
142
+ /**
143
+ * TaPoS as the node checks it: `ref_block_bytes` are bytes 6–7 of a block number, and `ref_block_hash` must equal
144
+ * bytes 8–15 of the id of the latest block at or below the FullNode's head whose number ends in those two bytes.
145
+ */
146
+ async function tapos(c, deadline) {
147
+ const refBytes = c.raw.refBlockBytes;
148
+ const refHash = c.raw.refBlockHash;
149
+ if (refBytes.length !== 2 || refHash.length !== 8)
150
+ return "invalid_transaction";
151
+ const now = await ask(c, "/wallet/getnowblock", {}, deadline);
152
+ const header = isObject(now) ? now["block_header"] : undefined;
153
+ const raw = isObject(header) ? header["raw_data"] : undefined;
154
+ const head = isObject(raw) ? raw["number"] : undefined;
155
+ if (typeof head !== "number" || !Number.isSafeInteger(head) || head < 0)
156
+ return "unexpected_verify_error";
157
+ const low = (refBytes[0] << 8) | refBytes[1];
158
+ const number = head - ((head % 65_536) - low + 65_536) % 65_536;
159
+ if (number < 0)
160
+ return "invalid_transaction";
161
+ const block = await ask(c, "/wallet/getblock", { id_or_num: String(number), detail: false }, deadline);
162
+ if (!isObject(block))
163
+ return "unexpected_verify_error";
164
+ if (Object.keys(block).length === 0)
165
+ return "invalid_transaction";
166
+ const id = block["blockID"];
167
+ if (typeof id !== "string" || !/^[0-9a-f]{64}$/.test(id) || BigInt(`0x${id.slice(0, 16)}`) !== BigInt(number)) {
168
+ return "unexpected_verify_error";
169
+ }
170
+ return id.slice(16, 32) === hexOf(refHash) ? null : "invalid_transaction";
171
+ }
172
+ /**
173
+ * The FullNode does not hold the transaction id at `path`: `/wallet/gettransactionbyid` for its blocks, or
174
+ * `/wallet/gettransactionfrompending` for its pending pool. Each answers `{}` for an id it does not hold.
175
+ */
176
+ async function unheld(c, path, deadline) {
177
+ const tx = await ask(c, path, { value: c.txid }, deadline);
178
+ if (!isObject(tx))
179
+ return "unexpected_verify_error";
180
+ return Object.keys(tx).length === 0 ? null : "invalid_transaction_state";
181
+ }
182
+ /** The node's simulation of `transfer(payTo, amount)` from the owner on the asset. */
183
+ async function simulated(c, deadline) {
184
+ const sim = await ask(c, "/wallet/triggerconstantcontract", {
185
+ owner_address: hexOf(c.raw.owner),
186
+ contract_address: hexOf(c.raw.contractAddress),
187
+ function_selector: "transfer(address,uint256)",
188
+ parameter: hexOf(c.raw.callData.subarray(4)),
189
+ }, deadline);
120
190
  if (!isObject(sim) || !isObject(sim["result"]))
121
191
  return "unexpected_verify_error";
122
192
  if (sim["result"]["result"] !== true)
@@ -126,46 +196,43 @@ export function createTron(nodes, s, settleWaitMs) {
126
196
  return "invalid_transaction";
127
197
  return null;
128
198
  }
199
+ /**
200
+ * The expiration window, then the node reads, made together: the owner's permission, TaPoS, the ids the node holds
201
+ * in its blocks and in its pending pool, and the simulation. The first refusal in that order is the answer. Each call is bounded by the node call bound and
202
+ * by `deadline`.
203
+ */
204
+ async function checkNow(c, deadline = Infinity) {
205
+ const now = BigInt(Date.now());
206
+ const expiration = c.raw.expiration;
207
+ if (expiration <= now || expiration > now + BigInt(c.maxTimeoutSeconds) * 1000n)
208
+ return "invalid_payload";
209
+ if (deadline - performance.now() <= 0)
210
+ return "unexpected_verify_error";
211
+ const reads = await Promise.all([
212
+ permitted(c, deadline),
213
+ tapos(c, deadline),
214
+ unheld(c, "/wallet/gettransactionbyid", deadline),
215
+ unheld(c, "/wallet/gettransactionfrompending", deadline),
216
+ simulated(c, deadline),
217
+ ]);
218
+ return reads.find((r) => r !== null) ?? null;
219
+ }
220
+ /** Every check of `/verify`: the transaction, the store, which must not hold its id, and the node reads. */
129
221
  async function verify(r) {
130
222
  const c = await check(r);
131
223
  if (typeof c === "string")
132
224
  return invalid(c);
133
- const now = await checkNow(c);
134
- return now === null ? { isValid: true, payer: c.payer } : invalid(now, c.payer);
135
- }
136
- /** A receipt's block and result from `gettransactioninfobyid` at `url`; undefined when there is none or it is unreadable. */
137
- async function infoAt(url, c, deadline) {
138
- let info;
225
+ let stored;
139
226
  try {
140
- info = await postJson(`${url}/gettransactioninfobyid`, { value: c.txid }, deadline - performance.now());
227
+ stored = await inTime(s.read(c.network, c.txid), Infinity);
141
228
  }
142
229
  catch {
143
- return undefined;
230
+ return invalid("unexpected_verify_error", c.payer);
144
231
  }
145
- if (!isObject(info) || typeof info["blockNumber"] !== "number")
146
- return undefined;
147
- const result = isObject(info["receipt"]) ? info["receipt"]["result"] : undefined;
148
- return typeof result === "string" ? { result } : undefined;
149
- }
150
- /**
151
- * One read of the transaction's receipt: success once the FullNode shows it in a block with `SUCCESS`; a failure only
152
- * once the Solidity node, which serves solidified blocks alone, shows it with another result; else undefined.
153
- */
154
- async function receipt(c, deadline) {
155
- const node = byNetwork.get(c.network);
156
- const head = await infoAt(`${node.fullNode}/wallet`, c, deadline);
157
- if (head === undefined)
158
- return undefined;
159
- const success = { success: true, transaction: c.txid, network: c.network, payer: c.payer };
160
- if (head.result === "SUCCESS")
161
- return success;
162
- const solid = await infoAt(`${node.solidityNode}/walletsolidity`, c, deadline);
163
- if (solid === undefined)
164
- return undefined;
165
- if (solid.result === "SUCCESS")
166
- return success;
167
- operatorLog({ event: "settlement-failed", network: c.network, transaction: c.txid, result: solid.result });
168
- return failed("invalid_transaction_state", c.txid, c.network);
232
+ if (stored.state !== "none")
233
+ return invalid("invalid_transaction_state", c.payer);
234
+ const now = await checkNow(c);
235
+ return now === null ? { isValid: true, payer: c.payer } : invalid(now, c.payer);
169
236
  }
170
237
  /** The profile's reads at the Solidity node and the FullNode, each bounded by `deadline`. */
171
238
  function reader(c, deadline) {
@@ -205,46 +272,74 @@ export function createTron(nodes, s, settleWaitMs) {
205
272
  };
206
273
  }
207
274
  /**
208
- * True once the reads prove the transaction can never be included: the profile's status finds it at no node, with the
209
- * latest solidified block two slots past its expiration. Reads nothing while the local clock is before the expiration.
275
+ * One read of the transaction's status through the profile's `tronStatus`: settled, at the Solidity node or the
276
+ * FullNode, only with receipt result `SUCCESS` and a `Transfer` log from the asset, whatever the call returned (a
277
+ * TRC-20 token may return false from `transfer` and still transfer). A failed receipt, or one with no such log, is
278
+ * final only when the Solidity node, which serves solidified blocks alone, shows it. A transaction no node holds,
279
+ * with the latest solidified block two slots past its expiration, can never be included. Anything else gives
280
+ * undefined.
210
281
  */
211
- async function expired(c, deadline) {
212
- if (BigInt(Date.now()) < c.raw.expiration)
213
- return false;
214
- const ref = {
282
+ async function outcome(c, deadline) {
283
+ const reads = reader(c, deadline);
284
+ let found;
285
+ const st = await tronStatus({
215
286
  network: c.network,
216
287
  txid: `0x${c.txid}`,
217
288
  asset: `0x${hexOf(c.raw.contractAddress)}`,
218
289
  expiration: c.raw.expiration.toString(),
219
- };
220
- const st = await tronStatus(ref, reader(c, deadline));
221
- return st.state === "failed" && st.why === "expired";
290
+ }, {
291
+ ...reads,
292
+ async info(txid, level) {
293
+ const info = await reads.info(txid, level);
294
+ if (info !== null)
295
+ found = level;
296
+ return info;
297
+ },
298
+ });
299
+ if (st.state === "settled")
300
+ return { success: true, transaction: c.txid, network: c.network, payer: c.payer };
301
+ if (st.state === "pending")
302
+ return undefined;
303
+ if (st.why === "expired") {
304
+ operatorLog({ event: "settlement-expired", network: c.network, transaction: c.txid });
305
+ return failed("invalid_transaction_state", c.txid, c.network);
306
+ }
307
+ if (found !== "solid")
308
+ return undefined;
309
+ operatorLog({
310
+ event: "settlement-failed",
311
+ network: c.network,
312
+ transaction: c.txid,
313
+ why: st.why,
314
+ result: st.result,
315
+ });
316
+ return failed("invalid_transaction_state", c.txid, c.network);
317
+ }
318
+ /** The answer to a `/settle` of a payment whose success has already been answered: a consumed payment fails. */
319
+ function consumed(c) {
320
+ return failed("invalid_transaction_state", c.txid, c.network);
222
321
  }
223
322
  /**
224
- * Reads the receipt every second until `deadline`, and the stored answer too when `stored` is set, answering with the
225
- * first final answer either gives, or with `invalid_transaction_state` once the transaction can never be included.
226
- * Broadcasts nothing.
323
+ * Reads the transaction's status every second until `deadline`, and the stored answer too when `stored` is set,
324
+ * answering with the first final answer either gives. A stored success is another settle's, so it gives the consumed
325
+ * answer. Broadcasts nothing.
227
326
  */
228
327
  async function watch(c, deadline, stored) {
229
328
  for (;;) {
230
329
  if (stored) {
231
330
  const row = await inTime(s.read(c.network, c.txid), deadline).catch(() => undefined);
232
331
  if (row?.state === "answered" && !isPending(row.answer))
233
- return row.answer;
332
+ return row.answer.success ? consumed(c) : row.answer;
234
333
  }
235
- const final = await receipt(c, deadline);
334
+ const final = await outcome(c, deadline);
236
335
  if (final !== undefined)
237
336
  return final;
238
- if (await expired(c, deadline)) {
239
- operatorLog({ event: "settlement-expired", network: c.network, transaction: c.txid });
240
- return failed("invalid_transaction_state", c.txid, c.network);
241
- }
242
337
  if (performance.now() + POLL_MS > deadline)
243
338
  return pending(c.txid, c.network);
244
339
  await sleep(POLL_MS);
245
340
  }
246
341
  }
247
- /** Broadcasts, then reads the receipt until `deadline`. */
342
+ /** Broadcasts, then reads the transaction's status until `deadline`. */
248
343
  async function submit(c, deadline) {
249
344
  const node = byNetwork.get(c.network);
250
345
  let sent;
@@ -261,19 +356,31 @@ export function createTron(nodes, s, settleWaitMs) {
261
356
  return failed("unexpected_settle_error", "", c.network);
262
357
  return watch(c, deadline, false);
263
358
  }
264
- /** Stores the answer, unless the row holds a final one; a failed write leaves the row for a later read of the chain. */
359
+ /**
360
+ * Stores the answer unless the row holds a final one. A success is given only by the settle whose write stored it,
361
+ * so one payment is answered success once: a success another settle stored first gives the consumed answer, and a
362
+ * success whose write fails gives `settlement_pending` with the id. A failed write of any other answer leaves the row
363
+ * for a later read of the chain.
364
+ */
265
365
  async function keep(c, answer, deadline) {
266
- await inTime(s.answer(c.network, c.txid, answer), deadline).catch(() => {
366
+ let wrote;
367
+ try {
368
+ wrote = await inTime(s.answer(c.network, c.txid, answer), deadline);
369
+ }
370
+ catch {
267
371
  operatorLog({ event: "answer-not-stored", network: c.network, transaction: c.txid });
268
- });
269
- return answer;
372
+ return answer.success ? pending(c.txid, c.network) : answer;
373
+ }
374
+ return answer.success && !wrote ? consumed(c) : answer;
270
375
  }
271
376
  /**
272
- * Answers within `settleWaitMs`. A stored final answer is given as it is. A claimed id, or a stored pending answer, is
273
- * read again from the chain. An answer with no transaction says nothing was broadcast, so it is given only for an id
274
- * the store does not hold: a broadcast the node refused releases the claim, and when nothing is released the answer
275
- * is pending with its id. A refusal as a duplicate is read as broadcast. When the store cannot be read, the
276
- * facilitator cannot know whether the transaction was broadcast, so the answer is pending with its id.
377
+ * Answers within `settleWaitMs`. A stored success means the payment is consumed, and gives
378
+ * `invalid_transaction_state` with the id; any other stored final answer is given as it is. A claimed id, or a stored
379
+ * pending answer, is read again from the chain. An id the node already holds is consumed too. An answer with no
380
+ * transaction says nothing was broadcast, so it is given only for an id the store does not hold: a broadcast the node
381
+ * refused releases the claim, and when nothing is released the answer is pending with its id. A refusal as a
382
+ * duplicate is read as broadcast. When the store cannot be read, the facilitator cannot know whether the transaction
383
+ * was broadcast, so the answer is pending with its id.
277
384
  */
278
385
  async function settle(r) {
279
386
  const deadline = performance.now() + settleWaitMs;
@@ -289,12 +396,15 @@ export function createTron(nodes, s, settleWaitMs) {
289
396
  catch {
290
397
  return pending(c.txid, c.network);
291
398
  }
292
- if (stored.state === "answered" && !isPending(stored.answer))
293
- return stored.answer;
399
+ if (stored.state === "answered" && !isPending(stored.answer)) {
400
+ return stored.answer.success ? consumed(c) : stored.answer;
401
+ }
294
402
  const waitUntil = deadline - answerReserve(settleWaitMs);
295
403
  if (stored.state !== "none")
296
404
  return keep(c, await watch(c, waitUntil, true), deadline);
297
- const now = await checkNow(c, left());
405
+ const now = await checkNow(c, deadline);
406
+ if (now === "invalid_transaction_state")
407
+ return consumed(c);
298
408
  if (now !== null)
299
409
  return failed(settleReason(now), "", network);
300
410
  if (left() <= 0)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@integraledger/profile-facilitator",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "An x402 facilitator for the LCP profiles x402/exact/tron/lcp-trc20-memo and x402/exact/polkadot/lcp-assets-remark: verifies and settles payments whose signed transaction carries the ATR hash.",
5
5
  "license": "Apache-2.0",
6
6
  "engines": {
@@ -39,7 +39,7 @@
39
39
  "LICENSE"
40
40
  ],
41
41
  "dependencies": {
42
- "@integraledger/lcp": "0.1.0",
42
+ "@integraledger/lcp": "0.2.0",
43
43
  "@noble/curves": "2.4.0",
44
44
  "@noble/hashes": "2.4.0",
45
45
  "@polkadot/api": "17.0.1",