@ninsei-labs/sdk 0.61.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 (71) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +56 -5
  3. package/assets/vendors/MANIFEST.json +1 -1
  4. package/assets/vendors/sdk/sdk-browser.js +4 -4
  5. package/engine/atomic/halfenc.js +6 -6
  6. package/engine/core/config.js +17 -38
  7. package/engine/core/format.js +1 -1
  8. package/engine/core/sellWindow.js +1 -1
  9. package/engine/core/store.js +11 -3
  10. package/engine/core/swap.js +3 -3
  11. package/engine/evm/amounts.js +2 -2
  12. package/engine/evm/asyncRoute.js +3 -3
  13. package/engine/evm/dex.js +1 -1
  14. package/engine/evm/factory.js +1 -1
  15. package/engine/evm/fees.js +62 -0
  16. package/engine/evm/funding.js +71 -66
  17. package/engine/evm/gasReserve.js +10 -0
  18. package/engine/evm/index.js +2 -2
  19. package/engine/evm/prices.js +3 -0
  20. package/engine/evm/session.js +1 -1
  21. package/engine/monero/address.js +4 -2
  22. package/engine/monero/arrivalRead.js +15 -2
  23. package/engine/monero/keyImage.js +146 -0
  24. package/engine/monero/keys.js +1 -0
  25. package/engine/monero/mnemonic.js +2 -1
  26. package/engine/monero/node.js +1 -0
  27. package/engine/monero/scan.js +12 -2
  28. package/engine/recovery/recoveryFile.js +31 -85
  29. package/engine/sdk/bridge.js +21 -51
  30. package/index.d.ts +412 -19
  31. package/package.json +20 -2
  32. package/src/actions.mjs +72 -6
  33. package/src/addressGuard.mjs +16 -0
  34. package/src/codes.mjs +26 -9
  35. package/src/config.mjs +56 -3
  36. package/src/decline.mjs +23 -74
  37. package/src/firmRequest.mjs +80 -0
  38. package/src/index.mjs +17 -28
  39. package/src/legs/cow.mjs +2 -2
  40. package/src/legs/evm.mjs +20 -12
  41. package/src/legs/kyber-spec.mjs +2 -2
  42. package/src/legs/kyber.mjs +1 -1
  43. package/src/legs/shape.mjs +1 -1
  44. package/src/legs/uniswaprelay.mjs +16 -4
  45. package/src/legs/uniswapx.mjs +29 -7
  46. package/src/levelsWalkSpec.mjs +1 -1
  47. package/src/lock.mjs +18 -37
  48. package/src/provider/envFile.mjs +3 -3
  49. package/src/provider/sign.mjs +3 -3
  50. package/src/public/evm.d.ts +84 -0
  51. package/src/public/evm.mjs +20 -0
  52. package/src/public/order.mjs +1 -1
  53. package/src/public/provider.mjs +1 -1
  54. package/src/public/recovery.d.ts +3 -2
  55. package/src/public/recovery.mjs +1 -1
  56. package/src/public/xmr.d.ts +2 -2
  57. package/src/quoteEip712Spec.mjs +4 -4
  58. package/src/quotes.mjs +52 -11
  59. package/src/recovery-key.mjs +7 -3
  60. package/src/relayFirmClient.mjs +4 -0
  61. package/src/relayQuote.mjs +1 -0
  62. package/src/sim.mjs +1 -1
  63. package/src/swap-flow.mjs +22 -32
  64. package/src/swaps.mjs +63 -56
  65. package/src/sweep-inputs.mjs +61 -0
  66. package/src/sweep-reconcile.mjs +71 -0
  67. package/src/sweep-restore.mjs +38 -9
  68. package/src/sweep.mjs +164 -10
  69. package/src/version.mjs +1 -1
  70. package/src/wallet.mjs +1 -1
  71. package/src/xmr-arrival.mjs +1041 -43
@@ -313,7 +313,7 @@ export async function signMessage(message) {
313
313
  }
314
314
  // THE MESSAGE IS PASSED IN HEX, NOT AS TEXT. EIP-191 requires it: the first personal_sign argument is the
315
315
  // message bytes in hex. MetaMask accepts text too (which is why this never surfaced on a live wallet for
316
- // years), while a node refuses: "invalid value: string ..., expected a valid hex string". Verified by a call:
316
+ // years), while a node refuses: "invalid value: string..., expected a valid hex string". Verified by a call:
317
317
  // text - refusal -32602, hex - a signature. The argument order [data, address] is as in MetaMask and WalletConnect.
318
318
  // If the wallet answers with an error, we show it AS IS: the cause is visible from the text.
319
319
  const hex = "0x" + Array.from(new TextEncoder().encode(String(message)), (b) => b.toString(16).padStart(2, "0")).join("");
@@ -195,7 +195,8 @@ export async function checkAddress(addr, opts = {}) {
195
195
  }
196
196
  const shape = networkFromShape(a);
197
197
  if (opts.expectNetwork && shape && shape !== opts.expectNetwork) {
198
- return { ok: false, reason: `This is a ${shape} address, but the swap runs on ${opts.expectNetwork}` };
198
+ return { ok: false, reason: `This is a ${shape} address, but the swap runs on ${opts.expectNetwork}`,
199
+ network: shape, expectedNetwork: opts.expectNetwork };
199
200
  }
200
201
  try {
201
202
  const bytes = decodeMoneroBase58(a);
@@ -215,7 +216,8 @@ export async function checkAddress(addr, opts = {}) {
215
216
  const meta = PREFIXES[prefix] || { network: "unknown", kind: "unknown" };
216
217
  if (meta.network === "unknown") return { ok: false, reason: `Unsupported address prefix ${prefix}` };
217
218
  if (opts.expectNetwork && meta.network !== opts.expectNetwork) {
218
- return { ok: false, reason: `This is a ${meta.network} address, but the swap runs on ${opts.expectNetwork}` };
219
+ return { ok: false, reason: `This is a ${meta.network} address, but the swap runs on ${opts.expectNetwork}`,
220
+ network: meta.network, expectedNetwork: opts.expectNetwork };
219
221
  }
220
222
  return { ok: true, verified: true, network: meta.network, kind: meta.kind, bytes: bytes.length };
221
223
  } catch (e) {
@@ -13,10 +13,13 @@
13
13
  // THE NETWORK TABLE IS DERIVED from the package's own prefix table rather than written out with numbers: a prefix
14
14
  // typed from memory (stagenet is not 18) already produced an address that no wallet would open.
15
15
  import { decodeMoneroBase58, PREFIX_BY_NETWORK } from "./address.js";
16
+ import { keccak256 } from "../../src/primitives.mjs";
16
17
 
17
18
  const NETWORK_BY_PREFIX = Object.fromEntries(
18
19
  Object.entries(PREFIX_BY_NETWORK).map(([network, kinds]) => [kinds.primary, network]),
19
20
  );
21
+ const PRIMARY_BYTES = 69; // 1-byte prefix + 2 * 32-byte keys + 4-byte checksum
22
+ const INTEGRATED_BYTES = 77; // primary + 8-byte payment id
20
23
 
21
24
  const toHex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
22
25
 
@@ -26,7 +29,17 @@ const toHex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0"
26
29
  */
27
30
  export function decodeAddressKeys(address) {
28
31
  const raw = decodeMoneroBase58(String(address == null ? "" : address).trim());
29
- if (!raw || raw.length < 69) throw new Error("not a Monero address: " + (raw ? raw.length + " bytes" : "not base58"));
32
+ // THE LENGTH AND CHECKSUM ARE PART OF THE BINDING. A typo that still decodes to 69/77 bytes would otherwise
33
+ // produce public keys from a different address and be accepted as the watched identity.
34
+ if (raw.length !== PRIMARY_BYTES && raw.length !== INTEGRATED_BYTES) {
35
+ throw new Error("not a Monero address: " + raw.length + " bytes");
36
+ }
37
+ const payload = raw.slice(0, raw.length - 4);
38
+ const checksum = raw.slice(raw.length - 4);
39
+ const digest = Uint8Array.from(keccak256(payload));
40
+ if (!checksum.every((byte, index) => byte === digest[index])) {
41
+ throw new Error("not a Monero address: checksum mismatch");
42
+ }
30
43
  const netByte = raw[0];
31
44
  return {
32
45
  network: NETWORK_BY_PREFIX[netByte] || null,
@@ -71,6 +84,6 @@ export function viewKeyMatchesAddress(viewScalar, expectedViewPubHex, halves) {
71
84
  return got === want;
72
85
  }
73
86
 
74
- // THE UNLOCK RULE HAS ONE HOME: ./unlock.js. This module re-exports it for the public xmr entry instead of keeping
87
+ // THE UNLOCK RULE HAS ONE HOME:./unlock.js. This module re-exports it for the public xmr entry instead of keeping
75
88
  // a second copy; a second copy is a second truth about whether money can be spent.
76
89
  export { UNLOCK_TIME_BLOCK_MAX, unlockStateOf } from "./unlock.js";
@@ -0,0 +1,146 @@
1
+ // MONERO KEY IMAGES WITHOUT A WALLET. The spend key and the funding outputs are already in the SDK; this module
2
+ // turns each verified output into the image a node's `is_key_image_spent` call takes.
3
+ //
4
+ // THE FORMULAS COME FROM MONERO'S OWN SOURCE, NOT FROM A GUESS:
5
+ // u = fe_frombytes(keccak256(outputKey))
6
+ // P = ge_fromfe_frombytes_vartime(u)
7
+ // Hp(P) = 8 * P
8
+ // x = Hs(derivation || varint(index)) + b mod l
9
+ // keyImage = x * Hp(P)
10
+ //
11
+ // `ge_fromfe_frombytes_vartime` is CryptoNote's map from a field element to a curve point. It is NOT
12
+ // `Point.fromHex(hash)`: ref10's `fromfe` is an Elligator-style map and the cofactor multiply is part of the
13
+ // key-image rule. The constants below are the canonical values from Monero's `crypto-ops-data.c`; a wrong root
14
+ // here returns a valid-looking point and a wrong image, so the vectors in `tools/check-key-image.mjs` pin every
15
+ // branch.
16
+ import { ed25519 } from "@noble/curves/ed25519.js";
17
+ import { keccak_256 } from "@noble/hashes/sha3.js";
18
+ import { ED_ORDER, bytesToHex, hashToScalar, hexToBytes, scalarFromHexLE, varint } from "./scan.js";
19
+
20
+ const P = (1n << 255n) - 19n;
21
+ const A = 486662n;
22
+ const mod = (x) => ((x % P) + P) % P;
23
+ const pow = (b, e) => {
24
+ let result = 1n;
25
+ let base = mod(b);
26
+ let exponent = e;
27
+ while (exponent > 0n) {
28
+ if (exponent & 1n) result = result * base % P;
29
+ base = base * base % P;
30
+ exponent >>= 1n;
31
+ }
32
+ return result;
33
+ };
34
+ const invert = (x) => pow(x, P - 2n);
35
+ const MA = mod(-A);
36
+ const MA2 = mod(-A * A);
37
+ const SQRT_M1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n;
38
+ const FFFB1 = 57192811444617977854858898469001663971726463542204390960804972474891788632558n;
39
+ const FFFB2 = 34838897745748397871374137087405348832069628406613012804793447631241588021984n;
40
+ const FFFB3 = 46719087769223307720043111813545796356806574765024592941723029582131464514662n;
41
+ const FFFB4 = 11880190023474909848668974726140447524736946358411580136929581950889876492678n;
42
+
43
+ const pointHex = (value) => String(value == null ? "" : value).replace(/^0x/i, "").toLowerCase();
44
+ const isPoint = (value) => /^[0-9a-f]{64}$/.test(pointHex(value));
45
+
46
+ /** ref10 `ge_fromfe_frombytes_vartime`, returning the compressed Edwards point. */
47
+ export function hashToPoint(input) {
48
+ const bytes = typeof input === "string" ? hexToBytes(input) : Uint8Array.from(input);
49
+ if (bytes.length !== 32) throw new Error("hashToPoint: expected 32 bytes");
50
+ const u = BigInt("0x" + bytesToHex(Uint8Array.from(bytes).reverse()));
51
+ const v = 2n * u % P * u % P;
52
+ const w = (v + 1n) % P;
53
+ let x = mod(w * w + MA2 * v);
54
+ let X = pow(w * invert(x), (P + 3n) / 8n);
55
+ x = X * X % P * x % P;
56
+ let y = mod(w - x);
57
+ let z = MA;
58
+ let sign;
59
+
60
+ if (y !== 0n) {
61
+ const sum = (w + x) % P;
62
+ if (sum !== 0n) {
63
+ // The square root was the other one. Multiply by sqrt(-1) and look again.
64
+ x = x * SQRT_M1 % P;
65
+ y = mod(w - x);
66
+ X = X * (y !== 0n ? FFFB3 : FFFB4) % P;
67
+ sign = 1;
68
+ } else {
69
+ X = X * FFFB1 % P * u % P;
70
+ z = z * v % P;
71
+ sign = 0;
72
+ }
73
+ } else {
74
+ X = X * FFFB2 % P * u % P;
75
+ z = z * v % P;
76
+ sign = 0;
77
+ }
78
+
79
+ // THE SIGN IS CHOSEN ON X BEFORE THE PROJECTIVE MULTIPLICATION. Checking it on X/Z afterwards flips a valid
80
+ // point for some inputs; the first vectors happened to have Z with the same parity.
81
+ if ((X & 1n) !== BigInt(sign)) X = mod(-X);
82
+ const Z = (z + w) % P;
83
+ const Y = (z - w + P) % P;
84
+ X = X * Z % P;
85
+ const inverseZ = invert(Z);
86
+ const affineX = X * inverseZ % P;
87
+ const affineY = Y * inverseZ % P;
88
+ const out = scalarToBytes(affineY);
89
+ out[31] |= Number(affineX & 1n) << 7;
90
+ return bytesToHex(out);
91
+ }
92
+
93
+ function scalarToBytes(value, width = 32) {
94
+ const out = new Uint8Array(width);
95
+ let rest = value;
96
+ for (let i = 0; i < width; i++) {
97
+ out[i] = Number(rest & 0xffn);
98
+ rest >>= 8n;
99
+ }
100
+ return out;
101
+ }
102
+
103
+ /** Monero `biased_hash_to_ec`: keccak(P), the fromfe map, then the cofactor multiply by 8. */
104
+ export function biasedHashToEc(publicKey) {
105
+ if (!isPoint(publicKey)) throw new Error("biasedHashToEc: expected a compressed point");
106
+ return ed25519.Point.fromHex(hashToPoint(keccak_256(hexToBytes(pointHex(publicKey)))))
107
+ .multiply(8n).toHex();
108
+ }
109
+
110
+ /**
111
+ * THE RAW KEY IMAGE PRIMITIVE: `b * Hp(P)`. `keyImageFromOutput` uses this after deriving `x`; the Monero
112
+ * `generate_key_image` vectors call it with a known spend scalar. `requireOwnership` checks `b*G == P` and is on
113
+ * for callers that hold both values.
114
+ */
115
+ export function keyImageFromSpendKey({ outputKey, privateSpendKey, requireOwnership = true }) {
116
+ if (!isPoint(outputKey)) throw new Error("keyImage: outputKey is not a compressed point");
117
+ const spend = scalarFromHexLE(String(privateSpendKey || ""));
118
+ if (spend <= 0n || spend >= ED_ORDER) throw new Error("keyImage: private spend key is not a scalar");
119
+ const output = ed25519.Point.fromHex(pointHex(outputKey));
120
+ if (requireOwnership && output.toHex().toLowerCase() !== ed25519.Point.BASE.multiply(spend).toHex().toLowerCase()) {
121
+ throw new Error("keyImage: output does not belong to the private spend key");
122
+ }
123
+ return ed25519.Point.fromHex(biasedHashToEc(outputKey)).multiply(spend).toHex();
124
+ }
125
+
126
+ /**
127
+ * THE KEY IMAGE OF ONE VERIFIED OUTPUT. `derivation` is the per-output value `findOurOutputs` already carries;
128
+ * `privateSpendKey` is the little-endian hex `sweep.keys` returns. The `x*G == outputKey` check refuses a spend key
129
+ * from another address instead of producing an image that no node can match.
130
+ */
131
+ export function keyImageFromOutput({ outputKey, derivation, index, privateSpendKey }) {
132
+ if (!isPoint(outputKey)) throw new Error("keyImage: outputKey is not a compressed point");
133
+ if (!/^[0-9a-f]{64}$/i.test(String(derivation || "").replace(/^0x/i, ""))) {
134
+ throw new Error("keyImage: derivation is not 32 bytes");
135
+ }
136
+ if (!Number.isSafeInteger(Number(index)) || Number(index) < 0) throw new Error("keyImage: bad output index");
137
+ const spend = scalarFromHexLE(String(privateSpendKey || ""));
138
+ if (spend <= 0n || spend >= ED_ORDER) throw new Error("keyImage: private spend key is not a scalar");
139
+ const output = ed25519.Point.fromHex(pointHex(outputKey));
140
+ const scalar = hashToScalar(hexToBytes(derivation), varint(Number(index)));
141
+ const x = (scalar + spend) % ED_ORDER;
142
+ if (x === 0n || output.toHex().toLowerCase() !== ed25519.Point.BASE.multiply(x).toHex().toLowerCase()) {
143
+ throw new Error("keyImage: output does not belong to the private spend key");
144
+ }
145
+ return ed25519.Point.fromHex(biasedHashToEc(outputKey)).multiply(x).toHex();
146
+ }
@@ -32,6 +32,7 @@ function toBytesLE(value, width = SCALAR_BYTES) {
32
32
 
33
33
  function reduce(bytes) {
34
34
  if (bytes.length > 64) throw new Error("scalar is longer than 64 bytes");
35
+ // sc_reduce32 reads the zero-padded input as little-endian before reducing modulo l.
35
36
  const padded = new Uint8Array(64);
36
37
  padded.set(bytes);
37
38
  return toBytesLE(toBigIntLE(padded) % ORDER);
@@ -34,7 +34,7 @@ function wordsToChunk(one, two, three) {
34
34
  const b = WORD_INDEX.get(two);
35
35
  const c = WORD_INDEX.get(three);
36
36
  if (a === undefined || b === undefined || c === undefined) throw new Error("invalid mnemonic word");
37
- // The word order encodes a value in a mixed radix; the inverse is in chunkToWords.
37
+ // Three words encode one little-endian uint32. Both directions use the same base-N offsets.
38
38
  return a + n * (((b - a) % n + n) % n) + n * n * (((c - b) % n + n) % n);
39
39
  }
40
40
 
@@ -46,6 +46,7 @@ function chunkToWords(value) {
46
46
  return [WORDLIST[one], WORDLIST[two], WORDLIST[three]];
47
47
  }
48
48
 
49
+ // The checksum covers the three-letter prefixes of the 24 payload words. The checksum word is not included.
49
50
  function checksumWord(words) {
50
51
  const prefix = words.map((word) => word.slice(0, PREFIX)).join("");
51
52
  return words[crc32(new TextEncoder().encode(prefix)) % words.length];
@@ -75,6 +75,7 @@ export async function getInfo({ force = false } = {}) {
75
75
 
76
76
  function normalize(info) {
77
77
  return {
78
+ // monerod get_info.height is the next block height (top + 1), not the latest mined block.
78
79
  height: info.height,
79
80
  nettype: info.nettype || (info.mainnet ? "mainnet" : info.stagenet ? "stagenet" : "testnet"),
80
81
  offline: !!info.offline,
@@ -138,8 +138,10 @@ export function watchedAddressVerdict({ address, viewSecret, spendPub } = {}) {
138
138
  return { ok: false, code: "bad-input", why: "not-a-monero-address", field: "address" };
139
139
  }
140
140
  if (!keys.network) return { ok: false, code: "bad-input", why: "not-a-primary-address", field: "address" };
141
+ // ARRIVAL DOES NOT NEED THE PRIVATE SPEND KEY. The public spend key is in the address, so a caller that has only
142
+ // the address and the view secret still binds the watched identity; a supplied key is checked against it.
141
143
  const wantedSpend = String(spendPub === undefined || spendPub === null ? "" : spendPub).replace(/^0x/, "").toLowerCase();
142
- if (!wantedSpend || wantedSpend !== keys.spendPub.toLowerCase()) {
144
+ if (wantedSpend && wantedSpend !== keys.spendPub.toLowerCase()) {
143
145
  return { ok: false, code: "xmr-address-mismatch", field: "spendPub" };
144
146
  }
145
147
  const form = viewKeyFormForAddress(viewSecret, keys.viewPub);
@@ -483,7 +485,15 @@ function bindWatched(watched) {
483
485
  const bound = [];
484
486
  for (const entry of watched) {
485
487
  const verdict = watchedAddressVerdict(entry);
486
- if (verdict.ok) bound.push({ entry, bound: verdict });
488
+ // AN INVALID IDENTITY IS NOT AN EMPTY WATCH. Skipping it made scanRange return a complete zero row for an
489
+ // address whose key did not belong to it; the caller could not tell that from "no money".
490
+ if (!verdict.ok) {
491
+ const error = new Error("watched identity is invalid");
492
+ error.code = verdict.code || "bad-input";
493
+ error.params = verdict;
494
+ throw error;
495
+ }
496
+ bound.push({ entry, bound: verdict });
487
497
  }
488
498
  return bound;
489
499
  }
@@ -1,66 +1,31 @@
1
- // The deal recovery file: real cryptography in the browser (WebCrypto).
1
+ // The deal recovery file: WebCrypto AES-GCM, not a stub.
2
2
  //
3
- // Litepaper §5: without a saved recovery file a deal is not funded; if the tab is lost, this file is the only way
4
- // to claim the XMR or refund the ETH (including through a standalone client without the site). So it is real
5
- // AES-GCM, not a stub: the file can be decrypted only with the password the user knows.
3
+ // The file is the only way to claim the XMR or refund the ETH after the tab is lost. It decrypts only with the
4
+ // password the user knows.
6
5
  //
7
6
  // File format (Ninsei-swap-<id>.json.enc):
8
7
  // { v:2, alg:"AES-GCM-256/PBKDF2-SHA256", iter, salt, iv, ciphertext, meta:{id,side,createdAt} }
9
- // Inside ciphertext is the payload (see buildPayload), versioned separately: the envelope version (v) and the
10
- // payload version (version) change independently - encryption and deal content are different things.
8
+ // The envelope version (v) and the payload version (version) change independently.
11
9
  //
12
- // WHAT IS IN THE PAYLOAD, AND WHY EXACTLY THIS
13
- // v3: MY HALF of the spend key and MY HALF of the view key (spendHalf, viewHalf) plus the counterparty's PUBLIC
14
- // points (otherSpendPoint, otherViewPoint). No full spend key exists for ANYONE: the address is a sum of halves,
15
- // and only the holder of both can spend. The second half is given by the chain - hence the escrow address is in
16
- // the file too: the sweep reads the revealed half from it. The counterparty's points are public (they are in the
17
- // address and the order anyway), but without them the address cannot be assembled from the halves.
18
- // v2: the mnemonic is the single source of keys: both the spend key and the view key derive from it. Keys are NOT
19
- // duplicated in the payload: a copy of the secret in the file is one more way to lose it and one more reason for
20
- // the fields to drift (the file used to carry both seedHex and the two private keys).
21
- // publicSpendKey /
22
- // publicViewKey /
23
- // address - for checking: if the mnemonic derives another address, the file is corrupt or substituted, and a
24
- // wallet must not be restored from it.
25
- // restoreHeight - the height to start the scan from. Without it the wallet scans Monero history from zero,
26
- // which is tens of hours (measured ~35 blocks/s). The deal's creation height is a correct floor: the XMR lock
27
- // cannot happen earlier.
10
+ // Payload:
11
+ // v3: my spend half and my view half, plus the counterparty's public points. The escrow address is here too, because
12
+ // the sweep reads the revealed half from it.
13
+ // v2: the mnemonic is the single source of keys. The payload also carries the public spend key, the public view key,
14
+ // the address for checking and the scan start height. Without the height the wallet scans from zero.
28
15
  //
29
- // WHAT IS NOT IN THE FILE: the spend key in the clear (only inside the ciphertext), a card number, a withdrawal
30
- // address, and anything not needed to complete or roll back the deal.
31
- //
32
- // THERE IS NO QUOTE KIND IN THE PAYLOAD, and the payload key set is not checked: a file issued earlier with an
33
- // extra kind key is still read (the extra key just goes unread) and new files are issued without it. The format
34
- // does not change: PAYLOAD_VERSION stays 3 - the quote kind never had to do with the file version.
16
+ // The file does not carry the spend key in clear, a card number or a withdrawal address.
17
+ // A file with an extra kind key is still read. New files do not carry that key.
35
18
 
36
- // THE ENCRYPTION PARAMETERS ARE NAMED EXPLICITLY AND ARE NOT TAKEN FROM WEB-CRYPTO DEFAULTS.
37
- // The tag length and the key length are part of the FORMAT, not an implementation detail: a file issued today must
38
- // be readable years later, so both numbers stand in every call (encrypt/decrypt/deriveKey), live in frozen objects
39
- // and were confirmed by MEASUREMENT: the tag length (ciphertext minus plaintext = 16 bytes) and the derived key
40
- // length (256 bits - proven by decrypting with a key derived separately as 256 bits). The PBKDF2 iteration count
41
- // is also part of the format, but it is DELIBERATELY changeable: it grows with time, and old files are then read
42
- // by their own count (see ITER_MIN below).
43
- //
19
+ // The encryption parameters are explicit, not WebCrypto defaults. The tag length, key length and iteration count are
20
+ // part of the format. The iteration count can grow, and old files are read with their own count (see ITER_MIN).
44
21
  //
45
- // THE ITERATION COUNT: 600,000 - OWASP's recommendation for PBKDF2-HMAC-SHA256, i.e. when FIPS-140 requires
46
- // a "work factor of 600,000 or more" with an internal HMAC-SHA-256 (the numbers come from GPU measurements on an
47
- // RTX 4000, as of December 2022).
48
- // WHY PBKDF2 AND NOT Argon2id/scrypt, WHICH OWASP RANKS HIGHER: a browser offers only what WebCrypto gives, and
49
- // among password-hashing it has ONE - PBKDF2; Argon2id and scrypt are not in the standard. There is nothing to
50
- // choose from, so at least the number correct for PBKDF2 matters.
51
- // WHY 210,000 WAS WRONG: that number is in the OWASP table for PBKDF2-HMAC-SHA512 (220,000), while we use
52
- // HMAC-SHA256 - the count was three times below the recommendation for our own algorithm.
53
- // WHAT THIS DOES NOT GIVE, SO AS NOT TO BE MISLED: iterations raise the price of ONE guess (measured on the
54
- // development machine: 210k - 109 ms, 600k - 283 ms; noticeably more on a weak device in a browser) but do not
55
- // save a weak password: an offline brute force is bounded by the password ENTROPY, not by the count. The 12-char
56
- // minimum remains the weak spot.
22
+ // PBKDF2 is the only password KDF in WebCrypto. Argon2id and scrypt are not available. The count is 600,000 for
23
+ // PBKDF2-HMAC-SHA256. A weak password remains the weak point; iterations raise the cost of one guess.
57
24
  const ITER = 600_000;
58
- // A FLOOR FOR FOREIGN FILES. The iteration count comes FROM THE FILE (otherwise it could not be raised without
59
- // losing old files), so a weak value must meet a refusal: a file below the floor is not decrypted.
25
+ // The iteration count comes from the file, so a weak value must be refused.
60
26
  const ITER_MIN = 100_000;
61
27
  const ITER_MAX = 10_000_000;
62
- // The algorithm identifier is ONE string for the whole module: it used to be written twice (write and read), and a
63
- // divergence between the copies would surface only on a live file.
28
+ // One algorithm identifier for writes and reads.
64
29
  const ALG_ID = "AES-GCM-256/PBKDF2-SHA256";
65
30
  const AES = Object.freeze({ name: "AES-GCM", tagLength: 128, keyBits: 256 });
66
31
  const KDF = Object.freeze({ name: "PBKDF2", hash: "SHA-256" });
@@ -98,20 +63,12 @@ function unb64(str) {
98
63
  return Uint8Array.from(atob(str), (c) => c.charCodeAt(0));
99
64
  }
100
65
 
101
- // THE ITERATION COUNT IS A PARAMETER, NOT A CALL CONSTANT. On encryption it is ITER, on reading it is the number
102
- // FROM THE FILE: the format stores it precisely so the count can be raised without losing already issued files.
103
- // Reading used to take the constant and ignore the iter field entirely - so raising the count would have silently
104
- // broken all old files, and the field in the file would have been decoration.
105
- // AAD: THE HEADER IS UNDER AUTHENTICATION, NOT ONLY THE CIPHERTEXT. AES-GCM checks the integrity of what is passed
106
- // to it as additionalData. Without AAD (as in version 1) only the ciphertext was covered, while `meta` - the deal
107
- // id, side, time, terms hash - sits beside it and could be edited without a trace, and the reader would take the
108
- // substituted value. The string is built by both writer and reader FROM THE SAME FIELDS IN THE SAME ORDER: any
109
- // field edit changes the string and decryption is rejected.
110
- // WHY AN ARRAY, NOT AN OBJECT: key order in an object is a JSON implementation detail and an "identical" object
111
- // can yield different text. And why ?? null: a missing field in the array would give undefined, which is another
112
- // value.
113
- // EXPORTED ON PURPOSE: the string is part of the FORMAT, and checks must build it with the same code, not their
114
- // own copy (a copy would diverge from the format exactly where it costs most).
66
+ // The iteration count is a parameter, not a call constant. Encryption uses ITER; reading uses the count from the
67
+ // file. The format stores it so the count can grow without losing old files.
68
+ // AAD: the header is authenticated, not only the ciphertext. Version 1 has no AAD, so a version-1 file must decrypt
69
+ // without it. The string is built by both writer and reader from the same fields in the same order.
70
+ // An array, not an object: object key order is a JSON implementation detail. Missing fields become null.
71
+ // Exported so checks build the same string, not a copy.
115
72
  export function envelopeAad(envelope) {
116
73
  const m = envelope.meta || {};
117
74
  return JSON.stringify([
@@ -131,21 +88,13 @@ async function deriveKey(passphrase, salt, iterations) {
131
88
  );
132
89
  }
133
90
 
134
- // THE HEIGHT TO START THE RECOVERY SCAN FROM. A pure function: it goes nowhere, so it is checked without a node -
135
- // and that matters, because this is exactly where the height used to get lost.
91
+ // The recovery scan start height. This is a pure function, so a test can run it without a node.
136
92
  //
137
- // WHY TWO SOURCES. The height was taken ONLY from the Monero node, and when the node did not answer, null was
138
- // honestly written into the file. Recovery then scanned history from zero (tens of hours), although the exact deal
139
- // height was at hand: the escrow is created by a transaction and its block is in the receipt. The node is someone
140
- // else's service that may be down (a live proxy returned 502), while the deal is our own and already exists.
93
+ // The height has three sources: the escrow birth height from the receipt, the application's stored height and the
94
+ // Monero node height. The node is an external service and can be down. The deal height is ours and already exists.
141
95
  //
142
- // TAKE THE SMALLER AND STEP BACK A BLOCK. The XMR arrival may land a block earlier than the recorded height, and a
143
- // scan that starts below the money finds it; one that starts above never does. Hence Math.min and minus one, but
144
- // never below one.
145
- // THE THIRD SOURCE - THE APPLICATION. Old deal records have no birthHeight field (it appeared later), but the app
146
- // resolved and stored the height when it registered the watch; the page gets it from its server. This is OUR
147
- // source, so it does not depend on whether the Monero node answers now, and it is what saves already issued
148
- // files: their record has no height at all.
96
+ // Use the smallest source and subtract one block. The XMR arrival can land one block before the recorded height. A
97
+ // scan that starts too high never finds the money.
149
98
  export function scanStartHeight({ escrowBirthHeight = null, serverRestoreHeight = null, nodeHeight = null } = {}) {
150
99
  const known = [escrowBirthHeight, serverRestoreHeight, nodeHeight]
151
100
  .map((v) => Number(v))
@@ -154,15 +103,12 @@ export function scanStartHeight({ escrowBirthHeight = null, serverRestoreHeight
154
103
  return Math.max(1, Math.min(...known) - 1);
155
104
  }
156
105
 
157
- // The payload: everything needed to complete or roll back the deal without the site. restoreHeight is passed by
158
- // the caller - scanStartHeight puts it here, and the module does not go to the network itself so it can be tested
159
- // without a node.
106
+ // The payload. `restoreHeight` is passed by the caller; scanStartHeight computes it. This module never reads the
107
+ // network.
160
108
  export function buildPayload({ swap, swapWallet, escrow, receiveAddress, restoreHeight = null }) {
161
109
  return {
162
110
  magic: FILE_MAGIC,
163
- // THE VERSION REFLECTS THE CONTENT, NOT THE MODULE VERSION. It used to hold PAYLOAD_VERSION, so after halves
164
- // appeared a file built from a mnemonic got number 3 - claiming content it did not have, and the check rightly
165
- // rejected it. The number must tell the truth about the content: a halves file is three, a mnemonic file is two.
111
+ // The version reflects the content, not the module version. A halves file is 3. A mnemonic file is 2.
166
112
  version: swapWallet && swapWallet.spendHalf ? 3 : 2,
167
113
  swapId: swap.id,
168
114
  // The order terms hash FROM THE CONTRACT. It is the file's tie to the chain: knowing the terms, one can check
@@ -1,76 +1,46 @@
1
- // THE PAGE-TO-CORE SHIM: THE ONE PLACE WHERE SCREENS KNOW ABOUT THE SDK (sdk/).
1
+ // PAGE-TO-CORE SHIM.
2
2
  //
3
- // WHY IT EXISTS. The swap logic lives in the core (sdk/, the @ninsei-labs/sdk package) while the page should do
4
- // only markup, screen state and texts. Before this shim every screen called the engine itself and the logic
5
- // spread across two places. Now a screen calls the SHIM, and only it knows about the core.
3
+ // Screens use the SDK through this file. The shim passes the page storage, the chain read and the wallet adapter.
4
+ // It computes no thresholds, step order or escrow address.
6
5
  //
6
+ // The SDK is served as a built bundle at assets/vendors/sdk/sdk-browser.js. The version query resets the cache
7
+ // after a rebuild. The bundle exposes createNinsei and the browser adapters.
7
8
  //
8
- // WHAT THE SHIM PASSES TO THE CORE - exactly the seams the core asks for from outside and cannot get itself:
9
- // storage - the page's storage: deals and session are read from where the page puts them (core/store.js);
10
- // evmCall - chain reads WITH THE PAGE'S WALLET: the core has no provider of its own and must not;
11
- // wallet - the page wallet adapter (sdk/src/adapters/evm-wallet.mjs): signing happens only in it.
12
- //
13
- // WHAT THE SHIM DOES NOT DO. It computes neither thresholds nor step order nor the escrow address: method names
14
- // and paths are only those that EXIST in the core, and the decisions stay in the core.
15
- //
16
- // ABOUT THE CORE BEING AVAILABLE TO THE PAGE - IT IS NOW BUILT, NOT WAITING FOR A BUILD.
17
- // * sdk/src/primitives.mjs imports @noble/curves and @noble/hashes by BARE package names, so the page is
18
- // served not the sdk/ source but a BUILT BUNDLE (www/assets/vendors/sdk/sdk-browser.js, the same path as the
19
- // atomic-swap crypto bundle). The bundle exposes the WHOLE FACADE:
20
- // createNinsei (config/wallet/quotes/preflight/swaps/actions/order/sweep/recovery/sim) plus the browser
21
- // adapters (evmWallet, localStorageAdapter/memoryAdapter). So starting a swap (swaps.start) and facade
22
- // quotes ARE available to the page - a "facade not served to the page" refusal is no longer expected.
23
- // * The bundle link carries ?v=<hash>, so the edge cache resets itself after a rebuild.
24
- //
25
- //
26
- // THE ORDER ACTIONS HAVE NO FALLBACK PATH ANY MORE, AND THAT IS A CONSEQUENCE OF THE MOVE. The deal engine used
27
- // to sit on the page and, with the bundle unavailable, the order actions ran on it - "the same functions", as it
28
- // was written here. Now the deal engine is a module OF THE PACKAGE (sdk/src/swap-flow.mjs): there is no second
29
- // copy on the page, so no fallback can exist. The bundle did not load (missing file, old cache, network) - that
30
- // is a NAMED refusal with the cause in the console (sdkBundle below), not silence and not a substitution.
31
- //
9
+ // There is no page-side fallback. If the bundle does not load, sdkBundle returns null and the caller sees a named
10
+ // refusal.
32
11
 
33
12
  import { chainById, DEFAULT_CHAIN, MONERO, allowedProvidersFor, knownFactoryCodesFor, knownImplementationCodesFor } from "../core/config.js";
34
13
  import { storage as pageStorage } from "../core/store.js";
35
14
  import * as evm from "../evm/index.js";
36
- // ORDER TERMS FOR THE CORE ARE ASSEMBLED FROM DATA, NOT FROM RULES: the windows come from the finality policy
37
- // (core/finality.js), the salt from the engine's generator (evm/funding.js). No deadlines or numbers of its own here.
15
+ // Order terms come from data, not rules: the windows come from the finality policy and the salt from the engine's
16
+ // generator. This file has no deadlines or numbers of its own.
38
17
  import { orderWindows } from "../core/finality.js";
39
18
  import { newSecret } from "../evm/funding.js";
40
- // THE ORDER CALLS - ACTION AND READ - COME FROM THE CORE. The deal engine moved into the package, and the shim
41
- // exposes EXACTLY the same names (markReadyOrder/claimOrder/refundOrder/orderStatus/orderDeadlines), so a screen
42
- // changes only the import source, not the call expression - and the guard that fixes the call site sees the old call.
19
+ // Order actions and reads come from the core. The shim exposes the same names, so a screen changes only its import.
43
20
  //
44
- // THE DEAL LIST AND ITS UPKEEP (the #/swaps screen). States come from the CORE: swaps.list - display, swaps.forget -
45
- // dropping a record. The core needs only the page's storage, and the shim adds no rules of its own.
21
+ // The deal list and its upkeep use core state. The core needs only the page storage.
46
22
  //
47
- // WATCHING IS A PAGE MECHANISM, NOT THE CORE'S: the poll tick lives in app.js, so the focus stays in
48
- // core/swap.js and the screen only declares it to the shim.
23
+ // Watching is a page mechanism. The poll tick lives in app.js, and the screen declares it to the shim.
49
24
  import { setLiveFocus, dealSwapIds, serverRestoreHeightFor, STEP_LABELS,
50
25
  confirmReady as engineConfirmReady, refundEth as engineRefundEth, sweepNow as engineSweepNow,
51
26
  getSwap as engineGetSwap, saveSwap as engineSaveSwap } from "../core/swap.js";
52
- // THE FEE RATE AND THE ORDER STATE - CHAIN READS WITH THE PAGE'S WALLET: the reference panel ("how it works")
53
- // and recovery-file parsing take them. The page gets them FROM HERE, not directly from evm/*.
27
+ // Fee rate and order state are chain reads with the page wallet. The page gets them here, not from evm/*.
54
28
  import { cachedFeeRate } from "../evm/fees.js";
55
- // MONERO ADDRESS AND HEIGHT - DELIBERATE PAGE READS (the progress screen): checking the recipient address
56
- // format and the node height for the scan height in the recovery file. The address logic lives in the core
57
- // (swaps.addressNetwork), here a fallback by the same module; the node height is the page node's read.
29
+ // Monero address and height are deliberate page reads. The address logic lives in the core; the node height is the
30
+ // page node's read.
58
31
  import { networkFromShape } from "../monero/address.js";
59
32
  import { height as nodeHeightValue } from "../monero/node.js";
60
33
 
61
- // THE CORE ADDRESS AS A STRING - THE BUILT BUNDLE SHIPPED WITH THE PACKAGE. A relative URL resolves both in the
62
- // published `engine/` tree and in the page that serves this shim from `www/js/sdk/`; ?v=<hash> keeps the cache fresh.
34
+ // The built bundle shipped with the package. A relative URL resolves in the published engine tree and in the page.
35
+ // The version query keeps the cache fresh.
63
36
  const SDK_BUNDLE = new URL("../../assets/vendors/sdk/sdk-browser.js?v=fa7dc71a", import.meta.url).href;
64
37
 
65
- // A NAMED SEAM FOR CHECKS. The asynchronous path is driven against a
66
- // stand-in order book (the demo network has no provider), and the ordinary escrow funding that follows a settled
67
- // swap can be replaced while that runs, because deploying an escrow factory on a throwaway chain is the stand's
68
- // job, not a check's. The replacement is named, set only by a check, and unset by the same function; production
69
- // never calls it, so the real funding path is what ships.
38
+ // A named seam for checks. A check can replace the funding step while it drives a stand-in order book. Production
39
+ // never calls it, so the real funding path ships.
70
40
  let startSwapOverride = null;
71
41
  export function useStartSwap(fn = null) { startSwapOverride = typeof fn === "function" ? fn : null; return Boolean(startSwapOverride); }
72
42
 
73
- // ONE LOAD PER PAGE. A refusal is a state, not a breakdown: it is named in the console and the caller decides.
43
+ // One load per page. A refusal is a state: it is named in the console and the caller decides.
74
44
  let loading = null;
75
45
  export async function sdkBundle() {
76
46
  if (!loading) {
@@ -78,7 +48,7 @@ export async function sdkBundle() {
78
48
  try { return await import(SDK_BUNDLE); }
79
49
  catch (error) {
80
50
  console.warn("[bridge] the built SDK core was not served to the page (" + ((error && error.message) || error) +
81
- "): actions go by the previous engine call; see www/js/sdk/bridge.js");
51
+ "): no page-side fallback; see www/js/sdk/bridge.js");
82
52
  return null;
83
53
  }
84
54
  })();