@ninsei-labs/sdk 0.60.0 → 0.62.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.
Files changed (96) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +81 -18
  3. package/assets/vendors/MANIFEST.json +1 -1
  4. package/assets/vendors/sdk/sdk-browser.js +4 -4
  5. package/engine/atomic/dleq2.js +0 -4
  6. package/engine/atomic/halfenc.js +6 -10
  7. package/engine/atomic/halves.js +0 -4
  8. package/engine/atomic/order.js +0 -4
  9. package/engine/atomic/orderContext.js +0 -4
  10. package/engine/atomic/orderHalfCommit.js +0 -4
  11. package/engine/core/chainSource.js +0 -4
  12. package/engine/core/clock.js +0 -4
  13. package/engine/core/config.js +17 -42
  14. package/engine/core/finality.js +0 -4
  15. package/engine/core/format.js +1 -5
  16. package/engine/core/preSignGuards.js +0 -4
  17. package/engine/core/rfqSource.js +0 -3
  18. package/engine/core/sellWindow.js +1 -5
  19. package/engine/core/store.js +11 -7
  20. package/engine/core/swap.js +3 -7
  21. package/engine/evm/amounts.js +2 -6
  22. package/engine/evm/asyncRoute.js +3 -7
  23. package/engine/evm/auth.js +0 -4
  24. package/engine/evm/claimGas.js +2 -6
  25. package/engine/evm/dex.js +1 -5
  26. package/engine/evm/escrow.js +0 -4
  27. package/engine/evm/factory.js +1 -5
  28. package/engine/evm/fees.js +62 -4
  29. package/engine/evm/funding.js +73 -71
  30. package/engine/evm/gasReserve.js +10 -4
  31. package/engine/evm/index.js +7 -11
  32. package/engine/evm/injected.js +0 -4
  33. package/engine/evm/permit.js +0 -4
  34. package/engine/evm/prices.js +3 -4
  35. package/engine/evm/session.js +1 -5
  36. package/engine/mock/chain.js +0 -4
  37. package/engine/monero/address.js +4 -5
  38. package/engine/monero/arrivalRead.js +15 -2
  39. package/engine/monero/halvesSweep.js +0 -4
  40. package/engine/monero/keyImage.js +146 -0
  41. package/engine/monero/keys.js +1 -0
  42. package/engine/monero/mnemonic.js +2 -1
  43. package/engine/monero/node.js +1 -4
  44. package/engine/monero/scan.js +12 -2
  45. package/engine/monero/swapKeys.js +0 -4
  46. package/engine/monero/unlock.js +2 -6
  47. package/engine/monero/wallet.js +0 -3
  48. package/engine/recovery/recoveryFile.js +31 -89
  49. package/engine/recovery/restore.js +0 -4
  50. package/engine/sdk/bridge.js +24 -58
  51. package/engine/ui/dom.js +0 -4
  52. package/engine/ui/walletModal.js +0 -4
  53. package/index.d.ts +436 -42
  54. package/package.json +22 -3
  55. package/src/actions.mjs +72 -6
  56. package/src/addressGuard.mjs +16 -0
  57. package/src/codes.mjs +26 -9
  58. package/src/config.mjs +56 -3
  59. package/src/decline.mjs +23 -74
  60. package/src/engine.mjs +17 -26
  61. package/src/firmRequest.mjs +80 -0
  62. package/src/index.mjs +17 -28
  63. package/src/legs/cow.mjs +2 -2
  64. package/src/legs/evm.mjs +20 -12
  65. package/src/legs/kyber-spec.mjs +2 -2
  66. package/src/legs/kyber.mjs +1 -1
  67. package/src/legs/shape.mjs +1 -1
  68. package/src/legs/uniswaprelay.mjs +16 -4
  69. package/src/legs/uniswapx.mjs +29 -7
  70. package/src/levelsWalkSpec.mjs +1 -1
  71. package/src/lock.mjs +18 -37
  72. package/src/provider/envFile.mjs +3 -3
  73. package/src/provider/sign.mjs +3 -3
  74. package/src/public/evm.d.ts +84 -0
  75. package/src/public/evm.mjs +20 -0
  76. package/src/public/order.mjs +1 -1
  77. package/src/public/provider.mjs +1 -1
  78. package/src/public/recovery.d.ts +4 -3
  79. package/src/public/recovery.mjs +1 -1
  80. package/src/public/xmr.d.ts +2 -2
  81. package/src/quoteEip712Spec.mjs +4 -4
  82. package/src/quotes.mjs +52 -11
  83. package/src/recovery-key.mjs +7 -3
  84. package/src/relayClaim.mjs +17 -3
  85. package/src/relayFirmClient.mjs +4 -0
  86. package/src/relayQuote.mjs +1 -0
  87. package/src/sim.mjs +1 -1
  88. package/src/swap-flow.mjs +28 -41
  89. package/src/swaps.mjs +217 -123
  90. package/src/sweep-inputs.mjs +61 -0
  91. package/src/sweep-reconcile.mjs +71 -0
  92. package/src/sweep-restore.mjs +38 -9
  93. package/src/sweep.mjs +164 -10
  94. package/src/version.mjs +1 -1
  95. package/src/wallet.mjs +1 -1
  96. package/src/xmr-arrival.mjs +1053 -57
@@ -14,10 +14,9 @@
14
14
  // and the screen says the nodes do not agree. When only one operator has confirmed, the core names that state
15
15
  // (`one-node`) instead of waiting silently.
16
16
  //
17
- // WHERE THE RULE LIVES. "Locked by unlock_time is not an arrival" is ONE rule (issue #84). It is not copied here:
18
- // it lives under www/js/monero/unlock.js, is mirrored byte-for-byte into the engine (sdk/engine/monero/unlock.js,
19
- // guarded by tools/check-sdk-engine.mjs) and is read through the engine seam. The block parser is mirrored the
20
- // same way (www/js/monero/scan.js) - a second copy would be a second truth about money.
17
+ // WHERE THE RULE LIVES. "Locked by unlock_time is not an arrival" is ONE rule. It lives in the
18
+ // SDK's engine (engine/monero/unlock.js) and is read through the engine seam. The block parser lives beside it
19
+ // (engine/monero/scan.js) - a second copy would be a second truth about money.
21
20
  //
22
21
  // PRIVACY. Public nodes are asked for the WHOLE BLOCK (get_block plus /get_transactions over all of the block's
23
22
  // hashes), never for a single transaction: otherwise a node links the user's IP to the trade. Requests carry
@@ -54,6 +53,11 @@ const failureOf = (error, node) => {
54
53
  const out = { url: node.url, operator: node.operator, code };
55
54
  if (params.status !== undefined && params.status !== null) out.status = params.status;
56
55
  if (why) out.why = why;
56
+ // A PARTIAL BATCH NAMES WHICH REQUEST FAILED. The outer failure list is what a caller sees; dropping the offset
57
+ // here would make a multi-batch block look like one anonymous partial answer.
58
+ for (const key of ["batchStart", "batchEnd", "total"]) {
59
+ if (params[key] !== undefined && params[key] !== null) out[key] = params[key];
60
+ }
57
61
  return out;
58
62
  };
59
63
 
@@ -88,14 +92,25 @@ export function normalizeNodes(nodes) {
88
92
 
89
93
  // ONE REQUEST. `text/plain` on purpose: the public nodes answer it without a preflight (verified on the whole
90
94
  // default list). The response body is JSON even though the content type is not.
91
- async function call(node, path, body, fetchImpl, timeoutMs) {
95
+ async function call(node, path, body, fetchImpl, timeoutMs, options = {}) {
92
96
  let res;
97
+ const timeout = typeof AbortSignal !== "undefined" && AbortSignal.timeout ? AbortSignal.timeout(timeoutMs) : null;
98
+ let signal = timeout;
99
+ const external = options.signal;
100
+ if (external && typeof external.addEventListener === "function") {
101
+ const controller = new AbortController();
102
+ const abort = () => controller.abort();
103
+ if (external.aborted) abort();
104
+ else external.addEventListener("abort", abort, { once: true });
105
+ if (timeout) timeout.addEventListener("abort", abort, { once: true });
106
+ signal = controller.signal;
107
+ }
93
108
  try {
94
109
  res = await fetchImpl(node.url + path, {
95
110
  method: "POST",
96
111
  headers: { "Content-Type": "text/plain" },
97
112
  body: JSON.stringify(body),
98
- signal: typeof AbortSignal !== "undefined" && AbortSignal.timeout ? AbortSignal.timeout(timeoutMs) : undefined,
113
+ signal: signal || undefined,
99
114
  });
100
115
  } catch (error) {
101
116
  // KEEP THE NAME: `AbortSignal.timeout` is "TimeoutError" in a browser and "AbortError" in Node; the message
@@ -104,6 +119,9 @@ async function call(node, path, body, fetchImpl, timeoutMs) {
104
119
  why: String((error && error.message) || error).slice(0, 120) });
105
120
  }
106
121
  if (!res || res.ok !== true) throw new SdkError("xmr-no-nodes", { node: node.url, status: res ? res.status : null });
122
+ if (typeof options.onBytes === "function") {
123
+ try { options.onBytes((await res.clone().arrayBuffer()).byteLength); } catch { /* the body is the answer */ }
124
+ }
107
125
  try { return await res.json(); } catch (error) {
108
126
  // A BODY CUT BY THE TIMEOUT IS STILL A TIMEOUT. `res.json()` rejects after the signal fired; in Node and in
109
127
  // browsers that is a TimeoutError/AbortError, not a malformed answer.
@@ -113,8 +131,8 @@ async function call(node, path, body, fetchImpl, timeoutMs) {
113
131
  }
114
132
  }
115
133
 
116
- async function getInfo(node, fetchImpl, timeoutMs) {
117
- const j = await call(node, "/json_rpc", { jsonrpc: "2.0", id: "info", method: "get_info" }, fetchImpl, timeoutMs);
134
+ async function getInfo(node, fetchImpl, timeoutMs, options = {}) {
135
+ const j = await call(node, "/json_rpc", { jsonrpc: "2.0", id: "info", method: "get_info" }, fetchImpl, timeoutMs, options);
118
136
  const r = j && j.result;
119
137
  if (!r || !Number.isFinite(Number(r.height))) throw new SdkError("xmr-no-nodes", { node: node.url, why: "no-height" });
120
138
  // A BUSY NODE HAS NOT FINISHED ITS OWN VIEW. Its height is not evidence that the walk was complete.
@@ -127,42 +145,55 @@ async function getInfo(node, fetchImpl, timeoutMs) {
127
145
  }
128
146
 
129
147
  // THE WHOLE BLOCK: its hash and ALL of its transaction hashes. This is the only form a public node is asked in.
130
- async function getBlock(node, height, fetchImpl, timeoutMs) {
131
- const j = await call(node, "/json_rpc", { jsonrpc: "2.0", id: "block", method: "get_block", params: { height } }, fetchImpl, timeoutMs);
148
+ async function getBlock(node, height, fetchImpl, timeoutMs, options = {}) {
149
+ const j = await call(node, "/json_rpc", { jsonrpc: "2.0", id: "block", method: "get_block", params: { height } }, fetchImpl, timeoutMs, options);
132
150
  const r = j && j.result;
133
151
  if (!r) throw new SdkError("xmr-no-nodes", { node: node.url, why: "no-block" });
134
152
  const hash = (r.block_header && r.block_header.hash) || null;
153
+ const parent = (r.block_header && r.block_header.prev_hash) || null;
154
+ const numTxes = r.block_header && Number.isFinite(Number(r.block_header.num_txes)) ? Number(r.block_header.num_txes) : null;
135
155
  let txHashes = Array.isArray(r.tx_hashes) ? r.tx_hashes : null;
136
156
  if (!txHashes) {
137
157
  const json = typeof r.json === "string" ? JSON.parse(r.json) : r.json;
138
158
  txHashes = (json && json.tx_hashes) || [];
139
159
  }
140
- return { hash, txHashes };
160
+ return { hash, parent, numTxes, txHashes };
141
161
  }
142
162
 
143
- // ALL THE BLOCK'S TRANSACTIONS in one request (never a single-hash request to a public node).
144
- async function getBlockTxs(node, hashes, fetchImpl, timeoutMs) {
163
+ // ALL THE BLOCK'S TRANSACTIONS in bounded requests. Public monerod runs restricted and refuses more than 100
164
+ // hashes per `/get_transactions`; batching keeps the request shape legal without changing which txids are named.
165
+ const RESTRICTED_TRANSACTIONS_COUNT = 100;
166
+
167
+ async function getBlockTxs(node, hashes, fetchImpl, timeoutMs, options = {}) {
145
168
  if (!hashes.length) return [];
146
- const j = await call(node, "/get_transactions", { txs_hashes: hashes, decode_as_json: true }, fetchImpl, timeoutMs);
147
- const wrappers = Array.isArray(j.txs) ? j.txs : [];
148
- const bodies = Array.isArray(j.txs_as_json) ? j.txs_as_json : [];
149
- // A PARTIAL ANSWER IS NOT AN EMPTY BLOCK. If the node returns fewer transactions than the block named, the walk
150
- // cannot conclude "no payment": that answer is unknown and must stop the refund path.
151
- if (bodies.length !== hashes.length || (wrappers.length && wrappers.length !== hashes.length)) {
152
- throw new SdkError("xmr-no-nodes", { node: node.url, why: "partial-transactions", want: hashes.length, got: bodies.length });
153
- }
154
- const out = bodies.map((s, i) => {
155
- let body;
156
- try { body = typeof s === "string" ? JSON.parse(s) : s; }
157
- catch { throw new SdkError("xmr-no-nodes", { node: node.url, why: "bad-json" }); }
158
- const w = wrappers[i] || {};
159
- body.tx_hash = String(w.tx_hash || body.tx_hash || "").replace(/^0x/, "").toLowerCase();
160
- body.block_height = w.block_height ?? null;
161
- body.confirmations = w.confirmations ?? null;
162
- return body;
163
- }).filter((body) => hashes.includes(String(body.tx_hash || "").toLowerCase()));
164
- if (out.length !== hashes.length) {
165
- throw new SdkError("xmr-no-nodes", { node: node.url, why: "partial-transactions", want: hashes.length, got: out.length });
169
+ const out = [];
170
+ for (let start = 0; start < hashes.length; start += RESTRICTED_TRANSACTIONS_COUNT) {
171
+ const batch = hashes.slice(start, start + RESTRICTED_TRANSACTIONS_COUNT);
172
+ const batchOffset = { batchStart: start, batchEnd: start + batch.length, total: hashes.length };
173
+ const j = await call(node, "/get_transactions", { txs_hashes: batch, decode_as_json: true }, fetchImpl, timeoutMs, options);
174
+ const wrappers = Array.isArray(j.txs) ? j.txs : [];
175
+ const bodies = Array.isArray(j.txs_as_json) ? j.txs_as_json : [];
176
+ // A PARTIAL ANSWER IS NOT AN EMPTY BLOCK. If the node returns fewer transactions than the batch named, the walk
177
+ // cannot conclude "no payment": that answer is unknown and must stop the refund path. The batch offset names the
178
+ // exact request, not only the tail's size.
179
+ if (bodies.length !== batch.length || (wrappers.length && wrappers.length !== batch.length)) {
180
+ throw new SdkError("xmr-no-nodes", { node: node.url, why: "partial-transactions", want: batch.length, got: bodies.length, ...batchOffset });
181
+ }
182
+ const wanted = new Set(batch.map((hash) => String(hash).toLowerCase()));
183
+ const parsed = bodies.map((s, i) => {
184
+ let body;
185
+ try { body = typeof s === "string" ? JSON.parse(s) : s; }
186
+ catch { throw new SdkError("xmr-no-nodes", { node: node.url, why: "bad-json" }); }
187
+ const w = wrappers[i] || {};
188
+ body.tx_hash = String(w.tx_hash || body.tx_hash || "").replace(/^0x/, "").toLowerCase();
189
+ body.block_height = w.block_height ?? null;
190
+ body.confirmations = w.confirmations ?? null;
191
+ return body;
192
+ }).filter((body) => wanted.has(String(body.tx_hash || "").toLowerCase()));
193
+ if (parsed.length !== batch.length) {
194
+ throw new SdkError("xmr-no-nodes", { node: node.url, why: "partial-transactions", want: batch.length, got: parsed.length, ...batchOffset });
195
+ }
196
+ out.push(...parsed);
166
197
  }
167
198
  return out;
168
199
  }
@@ -171,6 +202,36 @@ async function getBlockTxs(node, hashes, fetchImpl, timeoutMs) {
171
202
  // amount did not match its Pedersen commitment is NOT money: it contributes zero, and the caller names it.
172
203
  const sumOutputs = (hit) => hit.outputs.reduce((n, o) => n + (o.amountVerified ? (o.amountAtomic || 0n) : 0n), 0n);
173
204
 
205
+ // `Number(null)` IS 0. A missing confirmation count is not a mined transfer with zero confirmations; it is a
206
+ // missing field, so the block position supplies the fallback. This is used by every read that turns a daemon
207
+ // wrapper into a transfer.
208
+ const confirmationsOf = (tx, height, tipHeight) => {
209
+ const raw = tx && tx.confirmations;
210
+ if (raw === null || raw === undefined || raw === "") return Math.max(0, Number(tipHeight) - Number(height) + 1);
211
+ const value = Number(raw);
212
+ return Number.isFinite(value) ? value : Math.max(0, Number(tipHeight) - Number(height) + 1);
213
+ };
214
+
215
+ // A CALLER BUG IS NOT A NODE FAILURE. A throwing progress or checkpoint callback rejects the read with its own
216
+ // field; it must not appear in `failed` as if the daemon answered badly.
217
+ const callerFailure = (field, cause) => {
218
+ const error = new SdkError("bad-input", { field, why: "callback-failed" });
219
+ error.caller = true;
220
+ error.cause = cause;
221
+ return error;
222
+ };
223
+
224
+ // THE SAME TIE-BREAK IN THE EXACT AND THE SHADOW WALK. Score and amount decide first; two candidates that are
225
+ // equal on both are not interchangeable, because the report names one txid. The earlier block wins, and inside one
226
+ // block the lower txid wins - both walks see the same chain order.
227
+ const betterCandidate = (candidate, best) => {
228
+ if (!best) return true;
229
+ if (candidate.score !== best.score) return candidate.score > best.score;
230
+ if (candidate.amountAtomic !== best.amountAtomic) return candidate.amountAtomic > best.amountAtomic;
231
+ if (candidate.height !== best.height) return candidate.height < best.height;
232
+ return String(candidate.txid).toLowerCase() < String(best.txid).toLowerCase();
233
+ };
234
+
174
235
  /**
175
236
  * FIND THE BEST MATCHING TRANSFER. Blocks are walked from the swap's birth height upwards and the whole block is
176
237
  * asked for each height, so a public node never learns which transaction is ours. Every matching transfer is
@@ -201,16 +262,50 @@ async function locate(node, { expectedAtomic, address, viewSecret, spendPub, fro
201
262
  // one; a full unlocked payout wins over a full locked one. The verification step still compares the chosen
202
263
  // transaction across operators.
203
264
  const score = (amountAtomic >= expectedAtomic ? 4 : 0) + (amountVerified ? 2 : 0) + (locked ? 0 : 1);
204
- const candidate = { txid: tx.tx_hash, height: h };
205
- if (score === 7) return candidate;
206
- if (!best || score > best.score || (score === best.score && amountAtomic > best.amountAtomic)) {
207
- best = { ...candidate, score, amountAtomic };
208
- }
265
+ const candidate = { txid: tx.tx_hash, height: h, score, amountAtomic };
266
+ // A perfect score does not end the walk: another perfect candidate can tie on score and amount, and the
267
+ // deterministic tie-break must decide which txid the caller is told about.
268
+ if (betterCandidate(candidate, best)) best = candidate;
209
269
  }
210
270
  }
211
271
  return best;
212
272
  }
213
273
 
274
+ /**
275
+ * A MATCHING TRANSFER CAN BE IN THE POOL BEFORE IT IS IN A BLOCK. The exact walk cannot see it, so the site would
276
+ * say "waiting for the maker's XMR" with no txid for a whole block interval. The pool is read as a WHOLE (all
277
+ * hashes, then the existing batched `/get_transactions`), never by the caller's txid: a node must not learn which
278
+ * transfer is being watched.
279
+ *
280
+ * A pool match is INFORMATION ONLY. It never counts as seen or arrived, and it does not change the two-operator or
281
+ * confirmation rules; one synced node's pool is enough to show the txid while the block arrives.
282
+ */
283
+ async function findPoolTransfer(node, { expectedAtomic, watched, tip, nowSec, fetchImpl, timeoutMs }) {
284
+ const body = await call(node, "/get_transaction_pool_hashes", {}, fetchImpl, timeoutMs);
285
+ const hashes = Array.isArray(body.tx_hashes)
286
+ ? body.tx_hashes.map((hash) => String(hash).replace(/^0x/, "").toLowerCase()).filter((hash) => /^[0-9a-f]{64}$/.test(hash))
287
+ : [];
288
+ if (!hashes.length) return null;
289
+ const txs = await getBlockTxs(node, hashes, fetchImpl, timeoutMs);
290
+ let best = null;
291
+ for (const tx of txs) {
292
+ // `height: null` is right here: the transaction has no block yet. The tip still decides whether its unlock
293
+ // time has matured, exactly as the block walk does.
294
+ const hit = engine.xmrScan.matchTransaction(tx, [watched], { height: null, tipHeight: Math.max(0, tip), nowSec });
295
+ if (!hit.length) continue;
296
+ // AN UNVERIFIED AMOUNT IS NOT SHOWN AS A POOL PAYMENT. The same Pedersen check that guards `locate` must pass
297
+ // before the report names an amount; otherwise a node could invent one without a key.
298
+ if (!hit[0].outputs.every((o) => o.amountVerified === true)) continue;
299
+ const amountAtomic = sumOutputs(hit[0]);
300
+ const locked = hit[0].unlock && hit[0].unlock.locked === true;
301
+ const score = (amountAtomic >= expectedAtomic ? 4 : 0) + 2 + (locked ? 0 : 1);
302
+ // A POOL HAS NO HEIGHT. The deterministic tie-break still uses the lower txid, so two answers name one transfer.
303
+ const candidate = { txid: tx.tx_hash, height: 0, score, amountAtomic, locked };
304
+ if (betterCandidate(candidate, best)) best = { ...candidate, node, unlock: hit[0].unlock || null };
305
+ }
306
+ return best;
307
+ }
308
+
214
309
  /**
215
310
  * VERIFY THE ARRIVAL. Returns a verdict, and refuses WITH A CODE where the money cannot be declared an arrival:
216
311
  * xmr-locked - the outputs are barred by the transaction's unlock_time (until a height or a date);
@@ -222,10 +317,11 @@ async function locate(node, { expectedAtomic, address, viewSecret, spendPub, fro
222
317
  */
223
318
  export async function verifyArrival(request) {
224
319
  if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
320
+ if (request.amountRule !== undefined && request.amountRule !== null) return verifyArrivalFromRead(request);
225
321
  const nodes = normalizeNodes(request.nodes);
226
322
  if (!isStr(request.address)) throw new SdkError("bad-input", { field: "address" });
227
323
  if (request.viewSecret === undefined || request.viewSecret === null) throw new SdkError("bad-input", { field: "viewSecret" });
228
- if (!isStr(request.spendPub)) throw new SdkError("bad-input", { field: "spendPub" });
324
+ if (request.spendPub !== undefined && request.spendPub !== null && !isStr(request.spendPub)) throw new SdkError("bad-input", { field: "spendPub" });
229
325
  let expectedAtomic;
230
326
  try { expectedAtomic = BigInt(request.expectedAtomic); } catch { throw new SdkError("bad-input", { field: "expectedAtomic" }); }
231
327
  if (expectedAtomic <= 0n) throw new SdkError("bad-input", { field: "expectedAtomic" });
@@ -287,9 +383,44 @@ export async function verifyArrival(request) {
287
383
  if (located) break;
288
384
  }
289
385
  if (!located) {
386
+ // A POOL TRANSFER IS NOT AN ARRIVAL, BUT ITS TXID IS REAL INFORMATION. Read the whole pool on every synced
387
+ // node and return the match before the absence path: one node's pool is enough to show the id, while `seen`
388
+ // stays false and the confirmation rule stays untouched.
389
+ let poolHit = null;
390
+ const poolFailed = [];
391
+ const poolChecked = new Set();
392
+ for (const { node, info } of live) {
393
+ if (!info.synced) { continue; }
394
+ try {
395
+ const hit = await findPoolTransfer(node, {
396
+ expectedAtomic, watched, tip: top, nowSec, fetchImpl, timeoutMs,
397
+ });
398
+ poolChecked.add(node.operator);
399
+ if (hit) { poolHit = hit; break; }
400
+ } catch (error) {
401
+ poolFailed.push({ ...failureOf(error, node), why: "pool-read" });
402
+ }
403
+ }
404
+ if (poolHit) {
405
+ return {
406
+ seen: false, state: "pool", absent: false, txid: poolHit.txid, height: null,
407
+ amountAtomic: poolHit.amountAtomic.toString(), amountVerified: true,
408
+ confirmations: 0, locked: poolHit.locked, unlock: poolHit.unlock,
409
+ tip, operators: [poolHit.node.operator], poolFrom: { url: poolHit.node.url, operator: poolHit.node.operator },
410
+ checked: live.map((l) => ({
411
+ url: l.node.url, operator: l.node.operator, height: l.info.height, synchronized: l.info.synced,
412
+ state: l.node === poolHit.node ? "pool" : "pool-no-match",
413
+ })),
414
+ failed: [...failed, ...poolFailed],
415
+ };
416
+ }
417
+ failed.push(...poolFailed);
290
418
  failed.push(...staleWitnesses);
291
419
  // ABSENCE IS A CLAIM ABOUT MONEY, SO IT NEEDS TWO OPERATORS. One node can withhold a transaction and make
292
420
  // this walk look empty; a refund signed on that answer would take the depositor's ETH from a maker who paid.
421
+ // ONLY A NODE WHOSE POOL WAS ALSO READ COUNTS. A completed block walk with a failed pool read is unknown
422
+ // about the mempool, and a transfer relayed only there must not become `absent: true`.
423
+ const absenceOperators = [...completedOperators].filter((operator) => poolChecked.has(operator));
293
424
  // Only when no node finished the walk is every node unreachable.
294
425
  if (!completedOperators.size) {
295
426
  // A LIVE BUT UNSYNCHRONIZED NODE IS UNKNOWN, NOT ABSENT. Returning pending keeps the refund closed while
@@ -300,7 +431,7 @@ export async function verifyArrival(request) {
300
431
  }
301
432
  throw new SdkError("xmr-no-nodes", { tried: nodes.map((n) => n.url), nodes: failed });
302
433
  }
303
- return { seen: false, state: "pending", absent: completedOperators.size >= 2, txid: txidHint, tip, completedOperators: [...completedOperators], checked: live.map((l) => ({ url: l.node.url, operator: l.node.operator, height: l.info.height, synchronized: l.info.synced })), failed };
434
+ return { seen: false, state: "pending", absent: absenceOperators.length >= 2, txid: txidHint, tip, completedOperators: absenceOperators, checked: live.map((l) => ({ url: l.node.url, operator: l.node.operator, height: l.info.height, synchronized: l.info.synced })), failed };
304
435
  }
305
436
 
306
437
  // 3. VERIFY ON EVERY NODE: the SAME block hash, the SAME transaction inside it, the confirmations and the money.
@@ -341,10 +472,11 @@ export async function verifyArrival(request) {
341
472
  key: String(o.key || "").replace(/^0x/, "").toLowerCase(),
342
473
  amountAtomic: o.amountVerified ? String(o.amountAtomic ?? null) : null,
343
474
  amountVerified: o.amountVerified === true,
475
+ derivation: String(o.derivation || "").replace(/^0x/, "").toLowerCase(),
344
476
  }));
345
477
  record.unlock = hit[0].unlock;
346
478
  // Confirmations of a block: top - height + 1, and top = info.height - 1 (see above), so this is height - located.
347
- record.confirmations = Number.isFinite(Number(body.confirmations)) ? Number(body.confirmations) : (info.height - located.height);
479
+ record.confirmations = confirmationsOf(body, located.height, info.height);
348
480
  // A NODE THAT CHANGED THE AMOUNT IS A DISAGREEMENT, NOT A WITNESS. The commitment check above is what
349
481
  // makes this observable: without it an altered ecdhInfo.amount would still look like a valid output.
350
482
  if (!record.amountVerified) { record.state = "amount-unverified"; seen.push(record); continue; }
@@ -402,7 +534,7 @@ export async function verifyArrival(request) {
402
534
  const amountAtomic = best.nodes[0].amountAtomic;
403
535
  const agreedBy = best.nodes.map((r) => ({ url: r.url, operator: r.operator, blockHash: r.blockHash, confirmations: r.confirmations }));
404
536
 
405
- // LOCKED IS NOT AN ARRIVAL, and the rule for that is the shared one (issue #84), mirrored from www/js.
537
+ // LOCKED IS NOT AN ARRIVAL, and the rule for that is the shared one, in the SDK engine.
406
538
  const locked = best.nodes.find((r) => r.unlock && r.unlock.locked);
407
539
  if (locked) {
408
540
  const until = locked.unlock;
@@ -418,17 +550,882 @@ export async function verifyArrival(request) {
418
550
 
419
551
  if (best.operators.size < 2) {
420
552
  return { seen: false, state: "one-node", txid: located.txid, height: located.height, blockHash: best.observation.blockHash,
421
- amountAtomic: amountAtomic.toString(), confirmations, operators: [...best.operators], agreedBy, checked: seen, failed };
553
+ amountAtomic: amountAtomic.toString(), outputs: best.observation.outputs, confirmations, operators: [...best.operators], agreedBy, checked: seen, failed };
422
554
  }
423
555
  if (confirmations < minConfirmations) {
424
556
  return { seen: false, state: "pending", why: "confirmations", txid: located.txid, height: located.height, blockHash: best.observation.blockHash,
425
- amountAtomic: amountAtomic.toString(), confirmations, needConfirmations: minConfirmations, agreedBy, checked: seen, failed };
557
+ amountAtomic: amountAtomic.toString(), outputs: best.observation.outputs, confirmations, needConfirmations: minConfirmations, agreedBy, checked: seen, failed };
426
558
  }
427
559
  return { seen: true, state: "arrived", txid: located.txid, height: located.height, blockHash: best.observation.blockHash,
428
- amountAtomic: amountAtomic.toString(), confirmations, needConfirmations: minConfirmations,
560
+ amountAtomic: amountAtomic.toString(), outputs: best.observation.outputs, confirmations, needConfirmations: minConfirmations,
429
561
  operators: [...best.operators], agreedBy, checked: seen, failed };
430
562
  }
431
563
 
564
+ /**
565
+ * RECOVERY READ CANNOT USE THE QUOTE'S AMOUNT. A seller may send less than the quote (an exchange fee), more, or
566
+ * several transfers. The recovery path therefore walks the same whole blocks and returns EVERY matching transfer
567
+ * with its verified outputs, instead of choosing one candidate shaped by `expectedAtomic`.
568
+ */
569
+ function recoveryObservation(tx, hit, node, { height, blockHash, confirmations, pool = false }) {
570
+ const outputs = hit[0].outputs.map((o) => ({
571
+ index: o.index,
572
+ key: String(o.key || "").replace(/^0x/, "").toLowerCase(),
573
+ amountAtomic: o.amountVerified ? String(o.amountAtomic ?? null) : null,
574
+ amountVerified: o.amountVerified === true,
575
+ derivation: String(o.derivation || "").replace(/^0x/, "").toLowerCase(),
576
+ }));
577
+ const amountAtomic = sumOutputs(hit[0]);
578
+ return {
579
+ txid: String(tx.tx_hash || "").replace(/^0x/, "").toLowerCase(),
580
+ height, blockHash, confirmations, pool,
581
+ outputs,
582
+ amountAtomic: amountAtomic.toString(),
583
+ amountVerified: hit[0].outputs.every((o) => o.amountVerified === true),
584
+ locked: !!(hit[0].unlock && hit[0].unlock.locked),
585
+ unlock: hit[0].unlock || null,
586
+ url: node.url, operator: node.operator,
587
+ };
588
+ }
589
+
590
+ // KEY IMAGES OF THE FUNDING OUTPUTS, SUPPLIED BY THE CALLER. A recovery read carries the view key and the public
591
+ // spend key, not the private spend key: it must not derive key images itself. `sweep.keyImages` returns these from
592
+ // an arrival; mapping them back to output keys is what makes a spend local instead of a `is_key_image_spent` call.
593
+ function normalizeKeyImages(value) {
594
+ const empty = { provided: false, byImage: new Map(), byOutput: new Map() };
595
+ if (value === undefined || value === null) return empty;
596
+ if (!Array.isArray(value)) throw new SdkError("bad-input", { field: "keyImages" });
597
+ const byImage = new Map();
598
+ const byOutput = new Map();
599
+ value.forEach((entry, position) => {
600
+ const raw = typeof entry === "string" ? entry : entry && entry.keyImage;
601
+ const keyImage = typeof raw === "string" ? raw.replace(/^0x/, "").toLowerCase() : "";
602
+ if (!hash64(keyImage)) throw new SdkError("bad-input", { field: "keyImages", why: "key-image", position });
603
+ if (byImage.has(keyImage)) throw new SdkError("bad-input", { field: "keyImages", why: "duplicate", position });
604
+ const outputKey = entry && typeof entry === "object" && typeof entry.outputKey === "string"
605
+ ? entry.outputKey.replace(/^0x/, "").toLowerCase() : null;
606
+ if (outputKey !== null && !hash64(outputKey)) throw new SdkError("bad-input", { field: "keyImages", why: "output-key", position });
607
+ const record = { keyImage, outputKey };
608
+ byImage.set(keyImage, record);
609
+ if (outputKey) byOutput.set(outputKey, keyImage);
610
+ });
611
+ return { provided: true, byImage, byOutput };
612
+ }
613
+
614
+ function spendsOfTx(tx, tracked, node, { height, blockHash, pool = false }) {
615
+ if (!tracked.provided) return [];
616
+ const records = [];
617
+ const vin = Array.isArray(tx.vin) ? tx.vin : [];
618
+ for (const entry of vin) {
619
+ const raw = entry && entry.key && entry.key.k_image;
620
+ const keyImage = typeof raw === "string" ? raw.replace(/^0x/, "").toLowerCase() : "";
621
+ if (!hash64(keyImage) || !tracked.byImage.has(keyImage)) continue;
622
+ records.push({
623
+ keyImage, outputKey: tracked.byImage.get(keyImage).outputKey,
624
+ txid: String(tx.tx_hash || "").replace(/^0x/, "").toLowerCase(),
625
+ height, blockHash, pool,
626
+ });
627
+ }
628
+ return records;
629
+ }
630
+
631
+ function addSpends(target, records) {
632
+ for (const spend of records) {
633
+ const previous = target.get(spend.keyImage);
634
+ if (!previous || (previous.pool && !spend.pool)) target.set(spend.keyImage, spend);
635
+ }
636
+ }
637
+
638
+ function availableAtomicOf(transfers, tracked, spends, minConfirmations = 1) {
639
+ if (!tracked.provided) return null;
640
+ const spent = new Set(spends.map((spend) => spend.keyImage));
641
+ let total = 0n;
642
+ let complete = true;
643
+ for (const transfer of transfers) {
644
+ if (transfer.pool || transfer.locked || Number(transfer.confirmations) < minConfirmations) continue;
645
+ for (const output of transfer.outputs || []) {
646
+ if (!output.amountVerified || output.amountAtomic === null || output.amountAtomic === undefined) continue;
647
+ const keyImage = tracked.byOutput.get(String(output.key || "").toLowerCase());
648
+ if (!keyImage) { complete = false; continue; }
649
+ if (!spent.has(keyImage)) total += BigInt(output.amountAtomic);
650
+ }
651
+ }
652
+ return complete ? total.toString() : null;
653
+ }
654
+
655
+ async function scanRecoveryBlocks(node, { watched, fromHeight, toHeight, nowSec, fetchImpl, timeoutMs }) {
656
+ const transfers = [];
657
+ const failures = [];
658
+ let complete = true;
659
+ for (let height = fromHeight; height <= toHeight; height++) {
660
+ let block;
661
+ try { block = await getBlock(node, height, fetchImpl, timeoutMs); }
662
+ catch (error) { failures.push({ ...failureOf(error, node), height }); complete = false; break; }
663
+ if (!block.txHashes.length) continue;
664
+ let txs;
665
+ try { txs = await getBlockTxs(node, block.txHashes, fetchImpl, timeoutMs); }
666
+ catch (error) { failures.push({ ...failureOf(error, node), height }); complete = false; break; }
667
+ for (const tx of txs) {
668
+ const hit = engine.xmrScan.matchTransaction(tx, [watched], {
669
+ height, tipHeight: Math.max(0, toHeight), nowSec,
670
+ });
671
+ if (!hit.length) continue;
672
+ const confirmations = confirmationsOf(tx, height, toHeight);
673
+ transfers.push(recoveryObservation(tx, hit, node, { height, blockHash: block.hash, confirmations }));
674
+ }
675
+ }
676
+ return { transfers, failures, complete };
677
+ }
678
+
679
+ async function scanRecoveryPoolState(node, { watched, tracked, tip, nowSec, fetchImpl, timeoutMs, txid = null }) {
680
+ const body = await call(node, "/get_transaction_pool_hashes", {}, fetchImpl, timeoutMs);
681
+ const hashes = Array.isArray(body.tx_hashes)
682
+ ? body.tx_hashes.map((hash) => String(hash).replace(/^0x/, "").toLowerCase()).filter((hash) => /^[0-9a-f]{64}$/.test(hash))
683
+ : [];
684
+ if (!hashes.length) return { transfers: [], spends: [], target: null };
685
+ const txs = await getBlockTxs(node, hashes, fetchImpl, timeoutMs);
686
+ const transfers = [];
687
+ const spends = [];
688
+ let target = null;
689
+ for (const tx of txs) {
690
+ if (txid !== null && target === null && String(tx.tx_hash || "").replace(/^0x/, "").toLowerCase() === txid) {
691
+ target = { txid, height: null, blockHash: null, pool: true };
692
+ }
693
+ spends.push(...spendsOfTx(tx, tracked, node, { height: null, blockHash: null, pool: true }));
694
+ const hit = engine.xmrScan.matchTransaction(tx, [watched], { height: null, tipHeight: Math.max(0, tip), nowSec });
695
+ if (!hit.length) continue;
696
+ transfers.push(recoveryObservation(tx, hit, node, { height: null, blockHash: null, confirmations: 0, pool: true }));
697
+ }
698
+ return { transfers, spends, target };
699
+ }
700
+
701
+ async function scanRecoveryPool(node, { watched, tip, nowSec, fetchImpl, timeoutMs }) {
702
+ const state = await scanRecoveryPoolState(node, { watched, tracked: normalizeKeyImages(null), tip, nowSec, fetchImpl, timeoutMs });
703
+ return state.transfers;
704
+ }
705
+
706
+ // ---------------------------------------------------------------------------
707
+ // THE PRIMARY RECOVERY READ.
708
+ //
709
+ // One chosen node walks the whole range. The checkpoint is caller-owned storage; the SDK never persists it and never
710
+ // silently trusts it. A checkpoint is a claim about a block hash, not a claim about money: an anchor that moved, a
711
+ // digest that does not describe its own contents, or a chain that does not connect is a replay from the start.
712
+ //
713
+ // The walk is deliberately independent of `verifyRecovery`'s two-node decision. This function returns one node's
714
+ // complete history and its progress; independent confirmation stays a separate, later step.
715
+ const CHECKPOINT_VERSION = 1;
716
+ const HASH64 = /^[0-9a-f]{64}$/;
717
+ const hash64 = (value) => typeof value === "string" && HASH64.test(value.replace(/^0x/, "").toLowerCase());
718
+ const normalizedHash = (value) => String(value || "").replace(/^0x/, "").toLowerCase();
719
+
720
+ function checkpointDigest(record) {
721
+ const text = JSON.stringify({
722
+ version: record.version, network: record.network, address: record.address, fromHeight: record.fromHeight,
723
+ through: record.through, transfers: record.transfers, outputs: record.outputs, spends: record.spends,
724
+ });
725
+ return engine.xmrScan.bytesToHex(engine.xmrScan.keccak(new TextEncoder().encode(text)));
726
+ }
727
+
728
+ function checkpointRecord({ network, address, fromHeight, through, transfers, spends = [], kind = null }) {
729
+ const record = {
730
+ version: CHECKPOINT_VERSION, network, address, fromHeight, through,
731
+ transfers,
732
+ outputs: transfers.flatMap((transfer) => transfer.outputs.map((output) => ({
733
+ txid: transfer.txid, height: transfer.height, blockHash: transfer.blockHash, ...output,
734
+ }))),
735
+ spends,
736
+ };
737
+ if (kind) record.kind = kind;
738
+ if (kind === "witness") record.grid = WITNESS_SLICE_BLOCKS;
739
+ record.digest = checkpointDigest(record);
740
+ return record;
741
+ }
742
+
743
+ function validCheckpoint(record, identity) {
744
+ if (!record || typeof record !== "object" || record.version !== CHECKPOINT_VERSION) return null;
745
+ if (record.kind && record.kind !== "primary") return null;
746
+ if (record.network !== identity.network || record.address !== identity.address || record.fromHeight !== identity.fromHeight) return null;
747
+ if (!Array.isArray(record.transfers) || !Array.isArray(record.outputs) || !Array.isArray(record.spends)) return null;
748
+ if (!record.through || !Number.isSafeInteger(record.through.height) || !hash64(record.through.hash)) return null;
749
+ if (record.through.height < identity.fromHeight) return null;
750
+ if (record.digest !== checkpointDigest(record)) return null;
751
+ return record;
752
+ }
753
+
754
+ function validWitnessCheckpoint(record, identity) {
755
+ if (!record || typeof record !== "object" || record.version !== CHECKPOINT_VERSION) return null;
756
+ if (record.kind !== "witness" || record.grid !== WITNESS_SLICE_BLOCKS) return null;
757
+ if (record.network !== identity.network || record.address !== identity.address || record.fromHeight !== identity.fromHeight) return null;
758
+ if (!Array.isArray(record.transfers) || !Array.isArray(record.outputs) || !Array.isArray(record.spends)) return null;
759
+ if (!record.through || !Number.isSafeInteger(record.through.height) || !hash64(record.through.hash)) return null;
760
+ if (record.through.height < identity.fromHeight) return null;
761
+ if (record.digest !== checkpointDigest(record)) return null;
762
+ return record;
763
+ }
764
+
765
+ /**
766
+ * READ ONE NODE FROM `fromHeight` TO ITS HEAD.
767
+ *
768
+ * The checkpoint object is `{ read(), save(record), discard() }` or omitted. `onProgress` receives
769
+ * `{ phase, through, blocksVerified, blocksTotal, bytes, operator }`. `signal` cancels the read; `idleTimeoutMs`
770
+ * bounds a request, not the whole walk, so a long range may take as long as it keeps advancing. A failed body,
771
+ * a short transaction list, a moved anchor or a broken parent link makes the answer incomplete, never empty.
772
+ */
773
+ export async function readRecovery(request) {
774
+ if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
775
+ const nodes = request.node !== undefined ? normalizeNodes([request.node]) : normalizeNodes(request.nodes);
776
+ const node = nodes[0];
777
+ if (!isStr(request.address)) throw new SdkError("bad-input", { field: "address" });
778
+ if (request.viewSecret === undefined || request.viewSecret === null) throw new SdkError("bad-input", { field: "viewSecret" });
779
+ if (!isStr(request.spendPub)) throw new SdkError("bad-input", { field: "spendPub" });
780
+ const fromHeight = request.fromHeight === null || request.fromHeight === undefined ? 0 : intOf(request.fromHeight);
781
+ if (fromHeight === null || fromHeight < 0) throw new SdkError("bad-input", { field: "fromHeight" });
782
+ const fetchImpl = typeof request.fetch === "function" ? request.fetch : globalThis.fetch;
783
+ if (typeof fetchImpl !== "function") throw new SdkError("bad-input", { field: "fetch" });
784
+ const idleRaw = request.idleTimeoutMs === null || request.idleTimeoutMs === undefined ? null : Number(request.idleTimeoutMs);
785
+ const totalRaw = request.timeoutMs === null || request.timeoutMs === undefined ? null : Number(request.timeoutMs);
786
+ const timeoutMs = idleRaw !== null && Number.isFinite(idleRaw) && idleRaw > 0
787
+ ? idleRaw
788
+ : (totalRaw !== null && Number.isFinite(totalRaw) && totalRaw > 0 ? totalRaw : 20000);
789
+ const minConfirmationsRaw = request.minConfirmations === null || request.minConfirmations === undefined ? null : Number(request.minConfirmations);
790
+ const minConfirmations = minConfirmationsRaw !== null && Number.isFinite(minConfirmationsRaw)
791
+ ? Math.max(1, Math.trunc(minConfirmationsRaw))
792
+ : 1;
793
+ const signal = request.signal && typeof request.signal.addEventListener === "function" ? request.signal : null;
794
+ const checkpoint = request.checkpoint && typeof request.checkpoint === "object" ? request.checkpoint : null;
795
+ const onProgress = typeof request.onProgress === "function" ? request.onProgress : () => {};
796
+ const bound = engine.xmrScan.watchedAddressVerdict({ address: request.address, viewSecret: request.viewSecret, spendPub: request.spendPub });
797
+ if (!bound.ok) {
798
+ if (bound.code === "bad-input") throw new SdkError("bad-input", { field: bound.field || "address", why: bound.why });
799
+ throw new SdkError(bound.code, { field: bound.field || "address", address: request.address });
800
+ }
801
+ const addressNetwork = bound.keys && bound.keys.network ? bound.keys.network : null;
802
+ if (request.network !== undefined && request.network !== null && addressNetwork && request.network !== addressNetwork) {
803
+ throw new SdkError("bad-input", { field: "network", why: "address-network-mismatch" });
804
+ }
805
+ const watched = { address: request.address, viewSecret: bound.viewSecret, spendPub: bound.spendPub };
806
+ const tracked = normalizeKeyImages(request.keyImages);
807
+ const targetTxid = request.txid === undefined || request.txid === null ? null : normalizedHash(request.txid);
808
+ if (targetTxid !== null && !hash64(targetTxid)) throw new SdkError("bad-input", { field: "txid" });
809
+ let target = null;
810
+ let info;
811
+ try { info = await getInfo(node, fetchImpl, timeoutMs, { signal }); }
812
+ catch (error) {
813
+ return { transfers: [], tip: null, fromHeight, minConfirmations,
814
+ target, complete: false, through: null, checkpoint: null, blocked: false, failed: [failureOf(error, node)] };
815
+ }
816
+ const network = isStr(request.network) ? request.network : info.nettype;
817
+ if (!isStr(network)) throw new SdkError("bad-input", { field: "network" });
818
+ if (addressNetwork && info.nettype && addressNetwork !== info.nettype) {
819
+ throw new SdkError("bad-input", { field: "node", why: "node-network-mismatch" });
820
+ }
821
+ if (!info.synced) {
822
+ return { transfers: [], tip: info.height, fromHeight, minConfirmations,
823
+ target, complete: false, through: null, checkpoint: null, blocked: true,
824
+ failed: [{ url: node.url, operator: node.operator, code: "stale", why: "not-synchronized" }] };
825
+ }
826
+ const top = Math.max(0, info.height - 1);
827
+ if (top < fromHeight) {
828
+ // A RANGE ABOVE THE TIP HAS NO BLOCKS, BUT THE POOL IS STILL READ. The old early return called an empty
829
+ // block range complete without asking the pool, so a withdrawal already waiting there looked absent.
830
+ let transfers = [];
831
+ let spends = [];
832
+ let poolFailure = null;
833
+ try {
834
+ const pool = await scanRecoveryPoolState(node, {
835
+ watched, tracked, tip: top, nowSec: request.nowSec, fetchImpl, timeoutMs, txid: targetTxid,
836
+ });
837
+ if (pool.target) target = pool.target;
838
+ transfers = pool.transfers;
839
+ spends = pool.spends;
840
+ } catch (error) {
841
+ poolFailure = { ...failureOf(error, node), why: "pool-read" };
842
+ }
843
+ return { transfers, tip: info.height, fromHeight, minConfirmations, target,
844
+ complete: poolFailure === null, through: null, spends, checkpoint: null, blocked: false,
845
+ ...(poolFailure
846
+ ? { failed: [poolFailure] }
847
+ : { availableAtomic: availableAtomicOf(transfers, tracked, spends, minConfirmations),
848
+ availableSource: { url: node.url, operator: node.operator }, failed: [] }) };
849
+ }
850
+ const identity = { network, address: request.address, fromHeight };
851
+ let bytes = 0;
852
+ const countBytes = (n) => { if (Number.isFinite(n) && n > 0) bytes += n; };
853
+ let prior = null;
854
+ if (checkpoint && typeof checkpoint.read === "function") {
855
+ try { prior = validCheckpoint(checkpoint.read(), identity); }
856
+ catch (error) { throw callerFailure("checkpoint.read", error); }
857
+ if (!prior && typeof checkpoint.discard === "function") {
858
+ try { checkpoint.discard(); }
859
+ catch (error) { throw callerFailure("checkpoint.discard", error); }
860
+ }
861
+ }
862
+ let replay = 0;
863
+ const run = async (startRecord) => {
864
+ target = null;
865
+ let transfers = [];
866
+ let spends = [];
867
+ const spendMap = new Map();
868
+ let through = null;
869
+ let blocksVerified = 0;
870
+ let previousHash = null;
871
+ if (startRecord) {
872
+ transfers = startRecord.transfers.slice();
873
+ spends = startRecord.spends.slice();
874
+ addSpends(spendMap, spends);
875
+ through = { height: startRecord.through.height, hash: normalizedHash(startRecord.through.hash) };
876
+ blocksVerified = through.height - fromHeight + 1;
877
+ previousHash = through.hash;
878
+ // A stored height is a claim. The block at that height must still carry the same hash, or the chain moved.
879
+ let anchor;
880
+ try {
881
+ anchor = await getBlock(node, through.height, fetchImpl, timeoutMs, { signal, onBytes: countBytes });
882
+ } catch (error) {
883
+ const failure = failureOf(error, node);
884
+ failure.height = through.height;
885
+ return { transfers, tip: info.height, fromHeight, minConfirmations, complete: false, through,
886
+ target, spends: [...spendMap.values()],
887
+ checkpoint: checkpointRecord({ ...identity, through, transfers, spends: [...spendMap.values()] }), blocked: false, failed: [failure] };
888
+ }
889
+ if (!anchor.hash || normalizedHash(anchor.hash) !== through.hash) throw new Error("reorg");
890
+ }
891
+ const total = top - fromHeight + 1;
892
+ const emit = () => {
893
+ try {
894
+ onProgress({
895
+ phase: "blocks", through: through ? through.height : null, blocksVerified, blocksTotal: total,
896
+ bytes, operator: node.operator,
897
+ });
898
+ } catch (error) { throw callerFailure("onProgress", error); }
899
+ };
900
+ emit();
901
+ for (let height = through ? through.height + 1 : fromHeight; height <= top; height += 1) {
902
+ if (signal && signal.aborted) throw new SdkError("xmr-no-nodes", { node: node.url, name: "AbortError", why: "cancelled" });
903
+ let block;
904
+ let txs = [];
905
+ try {
906
+ block = await getBlock(node, height, fetchImpl, timeoutMs, { signal, onBytes: countBytes });
907
+ if (!hash64(block.hash)) throw new SdkError("xmr-no-nodes", { node: node.url, why: "no-block", height });
908
+ if (block.numTxes !== null && block.txHashes.length !== block.numTxes) throw new SdkError("xmr-no-nodes", { node: node.url, why: "block-incomplete", height });
909
+ if (previousHash && (!block.parent || normalizedHash(block.parent) !== previousHash)) throw new Error("reorg");
910
+ if (!block.txHashes.every((hash) => hash64(hash))) throw new SdkError("xmr-no-nodes", { node: node.url, why: "block-incomplete", height });
911
+ if (block.txHashes.length) txs = await getBlockTxs(node, block.txHashes, fetchImpl, timeoutMs, { signal, onBytes: countBytes });
912
+ } catch (error) {
913
+ if (String(error && error.message) === "reorg") throw error;
914
+ const failure = failureOf(error, node);
915
+ failure.height = height;
916
+ return { transfers, tip: info.height, fromHeight, minConfirmations, complete: false, through,
917
+ target, spends: [...spendMap.values()],
918
+ checkpoint: through ? checkpointRecord({ ...identity, through, transfers, spends: [...spendMap.values()] }) : null, blocked: false, failed: [failure] };
919
+ }
920
+ for (const tx of txs) {
921
+ if (targetTxid !== null && target === null && normalizedHash(tx.tx_hash) === targetTxid) {
922
+ target = { txid: targetTxid, height, blockHash: normalizedHash(block.hash), pool: false };
923
+ }
924
+ addSpends(spendMap, spendsOfTx(tx, tracked, node, { height, blockHash: block.hash }));
925
+ const hit = engine.xmrScan.matchTransaction(tx, [watched], { height, tipHeight: top, nowSec: request.nowSec });
926
+ if (!hit.length) continue;
927
+ const confirmations = confirmationsOf(tx, height, top);
928
+ transfers.push(recoveryObservation(tx, hit, node, { height, blockHash: block.hash, confirmations }));
929
+ }
930
+ through = { height, hash: normalizedHash(block.hash) };
931
+ previousHash = through.hash;
932
+ blocksVerified += 1;
933
+ if (checkpoint && typeof checkpoint.save === "function") {
934
+ try { checkpoint.save(checkpointRecord({ ...identity, through, transfers, spends: [...spendMap.values()] })); }
935
+ catch (error) { throw callerFailure("checkpoint.save", error); }
936
+ }
937
+ emit();
938
+ }
939
+ let poolFailure = null;
940
+ try {
941
+ const pool = await scanRecoveryPoolState(node, {
942
+ watched, tracked, tip: top, nowSec: request.nowSec, fetchImpl, timeoutMs, txid: targetTxid,
943
+ });
944
+ if (target === null && pool.target) target = pool.target;
945
+ const known = new Set(transfers.map((transfer) => transfer.txid));
946
+ for (const transfer of pool.transfers) {
947
+ if (known.has(transfer.txid)) continue;
948
+ known.add(transfer.txid);
949
+ transfers.push(transfer);
950
+ }
951
+ addSpends(spendMap, pool.spends);
952
+ } catch (error) {
953
+ poolFailure = { ...failureOf(error, node), why: "pool-read" };
954
+ }
955
+ spends = [...spendMap.values()];
956
+ const confirmedSpends = spends.filter((spend) => spend.pool !== true);
957
+ const confirmedTransfers = transfers.filter((transfer) => transfer.pool !== true);
958
+ if (poolFailure) {
959
+ return { transfers, tip: info.height, fromHeight, minConfirmations, complete: false, through,
960
+ target, spends,
961
+ checkpoint: through ? checkpointRecord({ ...identity, through, transfers: confirmedTransfers, spends: confirmedSpends }) : null,
962
+ blocked: false, failed: [poolFailure] };
963
+ }
964
+ return { transfers, tip: info.height, fromHeight, minConfirmations, complete: true, through,
965
+ target, spends, availableAtomic: availableAtomicOf(transfers, tracked, spends, minConfirmations),
966
+ availableSource: { url: node.url, operator: node.operator },
967
+ checkpoint: through ? checkpointRecord({ ...identity, through, transfers: confirmedTransfers, spends: confirmedSpends }) : null,
968
+ blocked: false, failed: [] };
969
+ };
970
+ for (;;) {
971
+ try {
972
+ return await run(prior);
973
+ } catch (error) {
974
+ if (error && error.caller) throw error;
975
+ if (String(error && error.message) === "reorg" && replay === 0) {
976
+ replay += 1;
977
+ prior = null;
978
+ if (checkpoint && typeof checkpoint.discard === "function") {
979
+ try { checkpoint.discard(); }
980
+ catch (discardError) { throw callerFailure("checkpoint.discard", discardError); }
981
+ }
982
+ continue;
983
+ }
984
+ const failure = failureOf(error, node);
985
+ return { transfers: [], tip: info.height, fromHeight, minConfirmations, complete: false, through: null,
986
+ target, checkpoint: null, blocked: false, failed: [failure] };
987
+ }
988
+ }
989
+ }
990
+
991
+ /**
992
+ * THE WITNESS READ ON A PLAIN MONEROD.
993
+ *
994
+ * The witness is asked for whole fixed windows of the zero-aligned grid, never for the order's exact start, a payout
995
+ * height, a single transaction or a key image. Every height of a window is read, then every transaction hash in those
996
+ * blocks; a matching transfer never stops the walk. The residual leak is the grid bucket that contains the start.
997
+ *
998
+ * `tipHeight` is the top the primary read reached. When it is above this witness, the witness is behind and the
999
+ * answer is incomplete; when it is omitted, the witness's own top is the target. A checkpoint re-reads the whole
1000
+ * window that contains it, so a cold and a resumed read of the same window issue the same requests.
1001
+ */
1002
+ export async function readRecoveryWitness(request) {
1003
+ if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
1004
+ const nodes = request.node !== undefined ? normalizeNodes([request.node]) : normalizeNodes(request.nodes);
1005
+ const node = nodes[0];
1006
+ if (!isStr(request.address)) throw new SdkError("bad-input", { field: "address" });
1007
+ if (request.viewSecret === undefined || request.viewSecret === null) throw new SdkError("bad-input", { field: "viewSecret" });
1008
+ if (!isStr(request.spendPub)) throw new SdkError("bad-input", { field: "spendPub" });
1009
+ const fromHeight = request.fromHeight === null || request.fromHeight === undefined ? null : intOf(request.fromHeight);
1010
+ if (fromHeight === null || fromHeight < 0) throw new SdkError("bad-input", { field: "fromHeight" });
1011
+ const tipHeightRaw = request.tipHeight === null || request.tipHeight === undefined ? null : intOf(request.tipHeight);
1012
+ if (request.tipHeight !== null && request.tipHeight !== undefined && (tipHeightRaw === null || tipHeightRaw < 0)) {
1013
+ throw new SdkError("bad-input", { field: "tipHeight" });
1014
+ }
1015
+ const minConfirmationsRaw = request.minConfirmations === null || request.minConfirmations === undefined ? null : Number(request.minConfirmations);
1016
+ const minConfirmations = minConfirmationsRaw !== null && Number.isFinite(minConfirmationsRaw)
1017
+ ? Math.max(1, Math.trunc(minConfirmationsRaw))
1018
+ : 1;
1019
+ const fetchImpl = typeof request.fetch === "function" ? request.fetch : globalThis.fetch;
1020
+ if (typeof fetchImpl !== "function") throw new SdkError("bad-input", { field: "fetch" });
1021
+ const idleRaw = request.idleTimeoutMs === null || request.idleTimeoutMs === undefined ? null : Number(request.idleTimeoutMs);
1022
+ const totalRaw = request.timeoutMs === null || request.timeoutMs === undefined ? null : Number(request.timeoutMs);
1023
+ const timeoutMs = idleRaw !== null && Number.isFinite(idleRaw) && idleRaw > 0
1024
+ ? idleRaw
1025
+ : (totalRaw !== null && Number.isFinite(totalRaw) && totalRaw > 0 ? totalRaw : 20000);
1026
+ const signal = request.signal && typeof request.signal.addEventListener === "function" ? request.signal : null;
1027
+ const checkpoint = request.checkpoint && typeof request.checkpoint === "object" ? request.checkpoint : null;
1028
+ const onProgress = typeof request.onProgress === "function" ? request.onProgress : () => {};
1029
+ const bound = engine.xmrScan.watchedAddressVerdict({ address: request.address, viewSecret: request.viewSecret, spendPub: request.spendPub });
1030
+ if (!bound.ok) {
1031
+ if (bound.code === "bad-input") throw new SdkError("bad-input", { field: bound.field || "address", why: bound.why });
1032
+ throw new SdkError(bound.code, { field: bound.field || "address", address: request.address });
1033
+ }
1034
+ const addressNetwork = bound.keys && bound.keys.network ? bound.keys.network : null;
1035
+ if (request.network !== undefined && request.network !== null && addressNetwork && request.network !== addressNetwork) {
1036
+ throw new SdkError("bad-input", { field: "network", why: "address-network-mismatch" });
1037
+ }
1038
+ const watched = { address: request.address, viewSecret: bound.viewSecret, spendPub: bound.spendPub };
1039
+ const tracked = normalizeKeyImages(request.keyImages);
1040
+ let info;
1041
+ try { info = await getInfo(node, fetchImpl, timeoutMs, { signal }); }
1042
+ catch (error) {
1043
+ return { transfers: [], tip: null, fromHeight, through: null, complete: false, checkpoint: null, blocked: false, failed: [failureOf(error, node)] };
1044
+ }
1045
+ const network = isStr(request.network) ? request.network : info.nettype;
1046
+ if (!isStr(network)) throw new SdkError("bad-input", { field: "network" });
1047
+ if (addressNetwork && info.nettype && addressNetwork !== info.nettype) {
1048
+ throw new SdkError("bad-input", { field: "node", why: "node-network-mismatch" });
1049
+ }
1050
+ if (!info.synced) {
1051
+ return { transfers: [], tip: info.height, fromHeight, through: null, complete: false, checkpoint: null, blocked: true,
1052
+ failed: [{ url: node.url, operator: node.operator, code: "stale", why: "not-synchronized" }] };
1053
+ }
1054
+ const top = Math.max(0, info.height - 1);
1055
+ if (tipHeightRaw !== null && tipHeightRaw > top) {
1056
+ return { transfers: [], tip: info.height, fromHeight, through: null, complete: false, checkpoint: null, blocked: false,
1057
+ failed: [{ url: node.url, operator: node.operator, code: "stale", why: "witness-behind", height: top, wanted: tipHeightRaw }] };
1058
+ }
1059
+ const targetTop = tipHeightRaw === null ? top : Math.min(tipHeightRaw, top);
1060
+ if (targetTop < fromHeight) {
1061
+ return { transfers: [], tip: info.height, fromHeight, through: null, complete: true, checkpoint: null, blocked: false, failed: [] };
1062
+ }
1063
+ const identity = { network, address: request.address, fromHeight };
1064
+ let prior = null;
1065
+ if (checkpoint && typeof checkpoint.read === "function") {
1066
+ try { prior = validWitnessCheckpoint(checkpoint.read(), identity); }
1067
+ catch (error) { throw callerFailure("checkpoint.read", error); }
1068
+ if (!prior && typeof checkpoint.discard === "function") {
1069
+ try { checkpoint.discard(); }
1070
+ catch (error) { throw callerFailure("checkpoint.discard", error); }
1071
+ }
1072
+ }
1073
+ const firstWindow = witnessSliceIndex(fromHeight);
1074
+ const startWindow = prior ? witnessSliceIndex(prior.through.height) : firstWindow;
1075
+ const lastWindow = witnessSliceIndex(targetTop);
1076
+ if (startWindow > lastWindow) {
1077
+ return { transfers: prior ? prior.transfers : [], tip: info.height, fromHeight, through: prior ? prior.through : null,
1078
+ complete: true, checkpoint: prior ? checkpointRecord({ ...identity, through: prior.through, transfers: prior.transfers, spends: prior.spends, kind: "witness" }) : null,
1079
+ blocked: false, failed: [] };
1080
+ }
1081
+ let bytes = 0;
1082
+ const countBytes = (n) => { if (Number.isFinite(n) && n > 0) bytes += n; };
1083
+ const total = targetTop - witnessSliceStart(firstWindow) + 1;
1084
+ let replay = 0;
1085
+ const run = async (startRecord) => {
1086
+ const fromWindow = startRecord ? witnessSliceIndex(startRecord.through.height) : firstWindow;
1087
+ const windowStart = witnessSliceStart(fromWindow);
1088
+ let transfers = startRecord ? startRecord.transfers.filter((transfer) => transfer.height < windowStart) : [];
1089
+ let spends = [];
1090
+ const spendMap = new Map();
1091
+ if (startRecord) {
1092
+ spends = startRecord.spends.filter((spend) => spend.height === null || spend.height < windowStart);
1093
+ addSpends(spendMap, spends);
1094
+ }
1095
+ let through = null;
1096
+ let previousHash = null;
1097
+ let blocksVerified = 0;
1098
+ const priorThrough = startRecord ? startRecord.through : null;
1099
+ const emit = () => {
1100
+ try {
1101
+ onProgress({ phase: "witness", through: through ? through.height : null, blocksVerified, blocksTotal: total,
1102
+ bytes, operator: node.operator, window: through ? witnessSliceIndex(through.height) : fromWindow });
1103
+ } catch (error) { throw callerFailure("onProgress", error); }
1104
+ };
1105
+ emit();
1106
+ for (let window = fromWindow; window <= lastWindow; window += 1) {
1107
+ const start = witnessSliceStart(window);
1108
+ const end = Math.min(witnessSliceEnd(window), targetTop);
1109
+ for (let height = start; height <= end; height += 1) {
1110
+ if (signal && signal.aborted) throw new SdkError("xmr-no-nodes", { node: node.url, name: "AbortError", why: "cancelled" });
1111
+ let block;
1112
+ let txs = [];
1113
+ try {
1114
+ block = await getBlock(node, height, fetchImpl, timeoutMs, { signal, onBytes: countBytes });
1115
+ if (!hash64(block.hash)) throw new SdkError("xmr-no-nodes", { node: node.url, why: "no-block", height });
1116
+ if (block.numTxes !== null && block.txHashes.length !== block.numTxes) throw new SdkError("xmr-no-nodes", { node: node.url, why: "block-incomplete", height });
1117
+ if (previousHash && (!block.parent || normalizedHash(block.parent) !== previousHash)) throw new Error("reorg");
1118
+ if (!block.txHashes.every((hash) => hash64(hash))) throw new SdkError("xmr-no-nodes", { node: node.url, why: "block-incomplete", height });
1119
+ if (block.txHashes.length) txs = await getBlockTxs(node, block.txHashes, fetchImpl, timeoutMs, { signal, onBytes: countBytes });
1120
+ } catch (error) {
1121
+ if (String(error && error.message) === "reorg") throw error;
1122
+ const failure = failureOf(error, node);
1123
+ failure.height = height;
1124
+ const keptThrough = through || (startRecord ? startRecord.through : null);
1125
+ const keptTransfers = through ? transfers : (startRecord ? startRecord.transfers : transfers);
1126
+ const keptSpends = through ? [...spendMap.values()] : (startRecord ? startRecord.spends : []);
1127
+ return { transfers: keptTransfers, tip: info.height, fromHeight, complete: false, through: keptThrough,
1128
+ spends: keptSpends,
1129
+ checkpoint: keptThrough ? checkpointRecord({ ...identity, through: keptThrough, transfers: keptTransfers, spends: keptSpends, kind: "witness" }) : null,
1130
+ blocked: false, failed: [failure] };
1131
+ }
1132
+ if (priorThrough && height === priorThrough.height && normalizedHash(block.hash) !== priorThrough.hash) throw new Error("reorg");
1133
+ for (const tx of txs) {
1134
+ addSpends(spendMap, spendsOfTx(tx, tracked, node, { height, blockHash: block.hash }));
1135
+ const hit = engine.xmrScan.matchTransaction(tx, [watched], { height, tipHeight: targetTop, nowSec: request.nowSec });
1136
+ if (!hit.length || height < fromHeight) continue;
1137
+ const confirmations = confirmationsOf(tx, height, targetTop);
1138
+ transfers.push(recoveryObservation(tx, hit, node, { height, blockHash: block.hash, confirmations }));
1139
+ }
1140
+ through = { height, hash: normalizedHash(block.hash) };
1141
+ previousHash = through.hash;
1142
+ blocksVerified += 1;
1143
+ if (checkpoint && typeof checkpoint.save === "function") {
1144
+ try { checkpoint.save(checkpointRecord({ ...identity, through, transfers, spends: [...spendMap.values()], kind: "witness" })); }
1145
+ catch (error) { throw callerFailure("checkpoint.save", error); }
1146
+ }
1147
+ emit();
1148
+ }
1149
+ }
1150
+ spends = [...spendMap.values()];
1151
+ return { transfers, tip: info.height, fromHeight, complete: true, through, spends,
1152
+ availableAtomic: availableAtomicOf(transfers, tracked, spends, minConfirmations),
1153
+ checkpoint: through ? checkpointRecord({ ...identity, through, transfers, spends, kind: "witness" }) : null,
1154
+ blocked: false, failed: [] };
1155
+ };
1156
+ for (;;) {
1157
+ try {
1158
+ return await run(prior);
1159
+ } catch (error) {
1160
+ if (error && error.caller) throw error;
1161
+ if (String(error && error.message) === "reorg" && replay === 0) {
1162
+ replay += 1;
1163
+ prior = null;
1164
+ if (checkpoint && typeof checkpoint.discard === "function") {
1165
+ try { checkpoint.discard(); }
1166
+ catch (discardError) { throw callerFailure("checkpoint.discard", discardError); }
1167
+ }
1168
+ continue;
1169
+ }
1170
+ const failure = failureOf(error, node);
1171
+ return { transfers: [], tip: info.height, fromHeight, complete: false, through: null, checkpoint: null, blocked: false, failed: [failure] };
1172
+ }
1173
+ }
1174
+ }
1175
+
1176
+ /**
1177
+ * THE ARRIVAL DECISION OVER ONE READ. It uses `verifyRecovery` (primary read plus plain-daemon witnesses) and applies
1178
+ * the owner's amount rule to the same observations:
1179
+ * - `at-least` (buy): the sum of distinct verified outputs across confirmed, unlocked transfers must reach the quote;
1180
+ * - `exact` (sale): the sum of confirmed, unlocked transfers must equal the signed amount.
1181
+ * An incomplete read is unknown; a one-node transfer is not an arrival.
1182
+ */
1183
+ export async function verifyArrivalFromRead(request) {
1184
+ if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
1185
+ const rule = request.amountRule === undefined || request.amountRule === null ? "at-least" : request.amountRule;
1186
+ if (rule !== "at-least" && rule !== "exact") throw new SdkError("bad-input", { field: "amountRule" });
1187
+ let expectedAtomic;
1188
+ try { expectedAtomic = BigInt(request.expectedAtomic); } catch { throw new SdkError("bad-input", { field: "expectedAtomic" }); }
1189
+ if (expectedAtomic <= 0n) throw new SdkError("bad-input", { field: "expectedAtomic" });
1190
+ const fromHeight = request.fromHeight === null || request.fromHeight === undefined ? 0 : intOf(request.fromHeight);
1191
+ if (fromHeight === null || fromHeight < 0) throw new SdkError("bad-input", { field: "fromHeight" });
1192
+ const recovery = await verifyRecovery({
1193
+ nodes: request.nodes, address: request.address, viewSecret: request.viewSecret, spendPub: request.spendPub,
1194
+ fromHeight, minConfirmations: request.minConfirmations, nowSec: request.nowSec, timeoutMs: request.timeoutMs,
1195
+ fetch: request.fetch, keyImages: request.keyImages,
1196
+ });
1197
+ const usable = recovery.transfers.filter((transfer) => transfer.agreed && transfer.confirmed
1198
+ && !transfer.pool && !transfer.locked);
1199
+ const chosen = [];
1200
+ const seenOutputs = new Set();
1201
+ let total = 0n;
1202
+ if (rule === "exact") {
1203
+ for (const transfer of usable) {
1204
+ total += BigInt(transfer.amountAtomic);
1205
+ chosen.push(transfer);
1206
+ }
1207
+ } else {
1208
+ for (const transfer of usable) {
1209
+ let contributed = false;
1210
+ for (const output of transfer.outputs || []) {
1211
+ if (!output.amountVerified || output.amountAtomic === null || output.amountAtomic === undefined) continue;
1212
+ const id = transfer.txid + ":" + output.index;
1213
+ if (seenOutputs.has(id)) continue;
1214
+ seenOutputs.add(id);
1215
+ total += BigInt(output.amountAtomic);
1216
+ contributed = true;
1217
+ }
1218
+ if (contributed) chosen.push(transfer);
1219
+ }
1220
+ }
1221
+ const seenByAmount = rule === "exact" ? total === expectedAtomic : total >= expectedAtomic;
1222
+ const seen = seenByAmount && recovery.complete === true;
1223
+ const poolHit = recovery.transfers.find((transfer) => transfer.pool);
1224
+ const completedOperators = recovery.completedOperators || [];
1225
+ const absent = recovery.complete === true && chosen.length === 0 && !poolHit && completedOperators.length >= 2;
1226
+ const outputs = [];
1227
+ const outputKeys = new Set();
1228
+ for (const transfer of chosen) {
1229
+ for (const output of transfer.outputs || []) {
1230
+ const id = transfer.txid + ":" + output.index;
1231
+ if (outputKeys.has(id)) continue;
1232
+ outputKeys.add(id);
1233
+ outputs.push({ ...output, txid: transfer.txid, height: transfer.height, blockHash: transfer.blockHash });
1234
+ }
1235
+ }
1236
+ const first = chosen[0] || poolHit || null;
1237
+ return {
1238
+ seen, state: seen ? "arrived" : (poolHit ? "pool" : "pending"),
1239
+ absent,
1240
+ completedOperators: absent ? completedOperators : undefined,
1241
+ txid: first ? first.txid : txidOf(request.txid),
1242
+ height: first ? first.height : null,
1243
+ blockHash: first ? first.blockHash : null,
1244
+ amountAtomic: total.toString(),
1245
+ amountVerified: outputs.every((output) => output.amountVerified === true),
1246
+ amountRule: rule,
1247
+ confirmations: chosen.length ? Math.min(...chosen.map((transfer) => Number(transfer.confirmations))) : 0,
1248
+ needConfirmations: recovery.minConfirmations,
1249
+ tip: recovery.tip,
1250
+ operators: [...new Set(chosen.flatMap((transfer) => transfer.operators || []))],
1251
+ checked: recovery.checked,
1252
+ failed: recovery.failed,
1253
+ outputs,
1254
+ transfers: chosen,
1255
+ locked: false,
1256
+ unlock: null,
1257
+ agreedBy: chosen.flatMap((transfer) => transfer.agreedBy || []),
1258
+ };
1259
+ }
1260
+
1261
+ /**
1262
+ * THE RECOVERY READ. Unlike `verifyArrival`, it has no expected amount and never calls a short transfer a refusal:
1263
+ * it returns every matching transfer from the order's start height, including a transfer still in the pool. Each
1264
+ * transfer carries its verified outputs and the operators that agreed on the same observation. A transfer seen by
1265
+ * one operator is returned with `agreed: false`; a recovery UI must decide whether to wait for the second operator.
1266
+ */
1267
+ export async function verifyRecovery(request) {
1268
+ if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
1269
+ const nodes = normalizeNodes(request.nodes);
1270
+ if (!isStr(request.address)) throw new SdkError("bad-input", { field: "address" });
1271
+ if (request.viewSecret === undefined || request.viewSecret === null) throw new SdkError("bad-input", { field: "viewSecret" });
1272
+ if (request.spendPub !== undefined && request.spendPub !== null && !isStr(request.spendPub)) throw new SdkError("bad-input", { field: "spendPub" });
1273
+ const fromHeight = intOf(request.fromHeight);
1274
+ if (fromHeight === null || fromHeight < 0) throw new SdkError("bad-input", { field: "fromHeight" });
1275
+ const minConfirmations = Math.max(1, intOf(request.minConfirmations) ?? 1);
1276
+ const fetchImpl = typeof request.fetch === "function" ? request.fetch : globalThis.fetch;
1277
+ if (typeof fetchImpl !== "function") throw new SdkError("bad-input", { field: "fetch" });
1278
+ const nowSec = Number.isFinite(Number(request.nowSec)) ? Number(request.nowSec) : Math.floor(Date.now() / 1000);
1279
+ const timeoutMs = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0 ? Number(request.timeoutMs) : 20000;
1280
+ const bound = engine.xmrScan.watchedAddressVerdict({
1281
+ address: request.address, viewSecret: request.viewSecret, spendPub: request.spendPub,
1282
+ });
1283
+ if (!bound.ok) {
1284
+ if (bound.code === "bad-input") throw new SdkError("bad-input", { field: bound.field || "address", why: bound.why });
1285
+ throw new SdkError(bound.code, { field: bound.field || "address", address: request.address });
1286
+ }
1287
+ const watched = { address: request.address, viewSecret: bound.viewSecret, spendPub: bound.spendPub };
1288
+ const spendPub = bound.spendPub;
1289
+
1290
+ const tracked = normalizeKeyImages(request.keyImages);
1291
+ const live = [];
1292
+ const failed = [];
1293
+ for (const node of nodes) {
1294
+ try { live.push({ node, info: await getInfo(node, fetchImpl, timeoutMs) }); }
1295
+ catch (error) { failed.push(failureOf(error, node)); }
1296
+ }
1297
+ if (!live.length) throw new SdkError("xmr-no-nodes", { tried: nodes.map((n) => n.url), nodes: failed });
1298
+ const tip = Math.max(...live.map((entry) => entry.info.height));
1299
+ const top = Math.max(0, tip - 1);
1300
+ const observations = new Map();
1301
+ const spendMap = new Map();
1302
+ const checked = [];
1303
+ let complete = true;
1304
+ const completedOperators = new Set();
1305
+ let availableAtomic = null;
1306
+ let primarySpends = [];
1307
+
1308
+ for (let index = 0; index < live.length; index += 1) {
1309
+ const { node, info } = live[index];
1310
+ checked.push({ url: node.url, operator: node.operator, height: info.height, synchronized: info.synced });
1311
+ if (!info.synced) {
1312
+ failed.push({ url: node.url, operator: node.operator, code: "stale", why: "not-synchronized" });
1313
+ complete = false;
1314
+ continue;
1315
+ }
1316
+ const nodeTop = Math.max(0, Math.min(top, info.height - 1));
1317
+ let read;
1318
+ let poolComplete = true;
1319
+ try {
1320
+ const common = {
1321
+ address: request.address, viewSecret: request.viewSecret, spendPub,
1322
+ fromHeight, minConfirmations, network: request.network, keyImages: request.keyImages,
1323
+ nowSec, timeoutMs, idleTimeoutMs: request.idleTimeoutMs ?? request.timeoutMs, fetch: fetchImpl,
1324
+ };
1325
+ read = index === 0
1326
+ ? await readRecovery({ ...common, node })
1327
+ : await readRecoveryWitness({ ...common, node, tipHeight: nodeTop });
1328
+ } catch (error) {
1329
+ failed.push(failureOf(error, node));
1330
+ complete = false;
1331
+ continue;
1332
+ }
1333
+ if (index > 0) {
1334
+ try {
1335
+ const pool = await scanRecoveryPoolState(node, {
1336
+ watched, tracked, tip: nodeTop, nowSec, fetchImpl, timeoutMs,
1337
+ });
1338
+ for (const transfer of pool.transfers) {
1339
+ if (!observations.has(transfer.txid)) observations.set(transfer.txid, []);
1340
+ observations.get(transfer.txid).push(transfer);
1341
+ }
1342
+ addSpends(spendMap, pool.spends);
1343
+ } catch (error) {
1344
+ failed.push({ ...failureOf(error, node), why: "pool-read" });
1345
+ complete = false;
1346
+ poolComplete = false;
1347
+ }
1348
+ }
1349
+ for (const transfer of read.transfers) {
1350
+ if (!observations.has(transfer.txid)) observations.set(transfer.txid, []);
1351
+ observations.get(transfer.txid).push(transfer);
1352
+ }
1353
+ if (index === 0) primarySpends = read.spends || [];
1354
+ addSpends(spendMap, read.spends || []);
1355
+ if (availableAtomic === null && read.availableAtomic !== null && read.availableAtomic !== undefined) {
1356
+ availableAtomic = read.availableAtomic;
1357
+ }
1358
+ failed.push(...(read.failed || []));
1359
+ if (read.complete !== true) complete = false;
1360
+ else if (poolComplete) completedOperators.add(node.operator);
1361
+ }
1362
+
1363
+ const transfers = [];
1364
+ for (const [txid, list] of observations) {
1365
+ // A TRANSFER IS AGREED ONLY ON THE SAME OBSERVATION. Different blocks, outputs, amounts or unlock states are
1366
+ // separate observations, not a majority vote that hides a lie.
1367
+ const groups = new Map();
1368
+ for (const observation of list) {
1369
+ const key = JSON.stringify({
1370
+ height: observation.height, blockHash: observation.blockHash, outputs: observation.outputs,
1371
+ amountAtomic: observation.amountAtomic, amountVerified: observation.amountVerified,
1372
+ locked: observation.locked, pool: observation.pool,
1373
+ unlock: observation.unlock ? { locked: observation.unlock.locked, untilHeight: observation.unlock.untilHeight ?? null, untilTime: observation.unlock.untilTime ?? null } : null,
1374
+ });
1375
+ if (!groups.has(key)) groups.set(key, { observation, nodes: [] });
1376
+ groups.get(key).nodes.push(observation);
1377
+ }
1378
+ const ranked = [...groups.values()].sort((a, b) => b.nodes.length - a.nodes.length
1379
+ || String(a.observation.operator).localeCompare(String(b.observation.operator)));
1380
+ const best = ranked[0];
1381
+ const operators = [...new Set(best.nodes.map((entry) => entry.operator))];
1382
+ const confirmations = Math.min(...best.nodes.map((entry) => Number(entry.confirmations)));
1383
+ transfers.push({
1384
+ txid,
1385
+ height: best.observation.height,
1386
+ blockHash: best.observation.blockHash,
1387
+ pool: best.observation.pool,
1388
+ confirmations,
1389
+ confirmed: confirmations >= minConfirmations && !best.observation.pool,
1390
+ amountAtomic: best.observation.amountAtomic,
1391
+ amountVerified: best.observation.amountVerified,
1392
+ outputs: best.observation.outputs,
1393
+ locked: best.observation.locked,
1394
+ unlock: best.observation.unlock,
1395
+ operators,
1396
+ agreed: operators.length >= 2,
1397
+ agreedBy: best.nodes.map((entry) => ({ url: entry.url, operator: entry.operator, confirmations: entry.confirmations })),
1398
+ disagreements: ranked.length > 1
1399
+ ? ranked.slice(1).map((entry) => ({ operators: [...new Set(entry.nodes.map((node) => node.operator))], amountAtomic: entry.observation.amountAtomic }))
1400
+ : [],
1401
+ });
1402
+ }
1403
+ transfers.sort((a, b) => (a.height === null ? Number.MAX_SAFE_INTEGER : a.height) - (b.height === null ? Number.MAX_SAFE_INTEGER : b.height)
1404
+ || String(a.txid).localeCompare(String(b.txid)));
1405
+
1406
+ const spends = [...spendMap.values()];
1407
+ const primarySpendSet = new Set(primarySpends.map((spend) => spend.keyImage));
1408
+ const spendsDisagreements = spends.filter((spend) => !primarySpendSet.has(spend.keyImage));
1409
+ const availableForVerdict = spendsDisagreements.length ? null : availableAtomic;
1410
+ const ready = transfers.some((transfer) => transfer.agreed && transfer.confirmed && !transfer.locked);
1411
+ const agreed = transfers.some((transfer) => transfer.agreed);
1412
+ return {
1413
+ state: ready ? "ready" : (agreed ? "pending" : (transfers.length ? "one-node" : "none")),
1414
+ transfers,
1415
+ tip,
1416
+ fromHeight,
1417
+ minConfirmations,
1418
+ complete: spendsDisagreements.length ? false : complete,
1419
+ completedOperators: [...completedOperators],
1420
+ spends,
1421
+ spendsDisagreements,
1422
+ availableAtomic: availableForVerdict,
1423
+ availableSource: live.length ? { url: live[0].node.url, operator: live[0].node.operator } : null,
1424
+ checked,
1425
+ failed,
1426
+ };
1427
+ }
1428
+
432
1429
  // ---------------------------------------------------------------------------
433
1430
  // WITNESS-V1: FIXED BLOCK SLICES FOR THE SHADOW CHECK
434
1431
  // ---------------------------------------------------------------------------
@@ -527,17 +1524,13 @@ async function locateInSlices(node, { expectedAtomic, address, viewSecret, spend
527
1524
  const locked = hit[0].unlock && hit[0].unlock.locked === true;
528
1525
  const score = (amountAtomic >= expectedAtomic ? 4 : 0) + (amountVerified ? 2 : 0) + (locked ? 0 : 1);
529
1526
  const candidate = { txid, height: block.height, blockHash: block.hash, amountAtomic, locked, score };
530
- if (!best || score > best.score || (score === best.score && amountAtomic > best.amountAtomic)) best = candidate;
1527
+ if (betterCandidate(candidate, best)) best = candidate;
531
1528
  }
532
1529
  }
533
- // THE WHOLE SLICE WAS READ. A perfect candidate lets the walk stop after this slice, not after a block:
534
- // the last witness request is still a fixed slice, never the payout height. Completion is judged by the
535
- // LAST BLOCK the witness actually served, not by the slice index: a witness can stop inside the same
536
- // 20-block window as the target and still be behind it.
537
- if (best && best.score === 7) {
538
- completed = slice.to >= target;
539
- break;
540
- }
1530
+ // THE WHOLE SLICE WAS READ. A perfect candidate does not end the walk: a later slice can contain a newer tip,
1531
+ // and the witness must still prove it reached the common target. Completion is judged by the LAST BLOCK the
1532
+ // witness actually served, not by the slice index: a witness can stop inside the same 20-block window as the
1533
+ // target and still be behind it.
541
1534
  if (index === last) completed = slice.to >= target;
542
1535
  }
543
1536
  return { located: best, completed, servedTop, failure };
@@ -674,9 +1667,6 @@ export async function verifyArrivalShadow(request) {
674
1667
  if (!located) failed.push(...staleWitnesses);
675
1668
  const completedOperators = [...completedWitnessOperators];
676
1669
  const independentOperators = completedOperators.filter((operator) => String(operator).toLowerCase() !== "ninsei");
677
- const required = 2;
678
- const witnessQuorum = { required, completed: completedOperators, independent: independentOperators,
679
- ok: (network === "mainnet" ? independentOperators.length : completedOperators.length) >= required };
680
1670
 
681
1671
  // ONE OPINION PER OPERATOR, THEN COMPARE THE OPINIONS. A second instance of the same operator may repeat the
682
1672
  // first, but it may not silently contradict it; a different operator that reports another block, amount or
@@ -718,6 +1708,12 @@ export async function verifyArrivalShadow(request) {
718
1708
  const field = observationField(representatives[0], representatives[i]);
719
1709
  if (field) witnessDisagreements.push({ operators: [representatives[0].operator, representatives[i].operator], field });
720
1710
  }
1711
+ // A QUORUM OF WALKERS IS NOT A QUORUM OF ANSWERS. Compute this after the witness-to-witness comparison: two
1712
+ // completed operators that disagree have not agreed on anything, even though each reached the target.
1713
+ const required = 2;
1714
+ const witnessQuorum = { required, completed: completedOperators, independent: independentOperators,
1715
+ ok: (network === "mainnet" ? independentOperators.length : completedOperators.length) >= required
1716
+ && witnessDisagreements.length === 0 };
721
1717
  const witnessEvidence = { observations: representatives, disagreements: witnessDisagreements };
722
1718
 
723
1719
  const witness = located