@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.
- package/CHANGELOG.md +57 -0
- package/README.md +81 -18
- package/assets/vendors/MANIFEST.json +1 -1
- package/assets/vendors/sdk/sdk-browser.js +4 -4
- package/engine/atomic/dleq2.js +0 -4
- package/engine/atomic/halfenc.js +6 -10
- package/engine/atomic/halves.js +0 -4
- package/engine/atomic/order.js +0 -4
- package/engine/atomic/orderContext.js +0 -4
- package/engine/atomic/orderHalfCommit.js +0 -4
- package/engine/core/chainSource.js +0 -4
- package/engine/core/clock.js +0 -4
- package/engine/core/config.js +17 -42
- package/engine/core/finality.js +0 -4
- package/engine/core/format.js +1 -5
- package/engine/core/preSignGuards.js +0 -4
- package/engine/core/rfqSource.js +0 -3
- package/engine/core/sellWindow.js +1 -5
- package/engine/core/store.js +11 -7
- package/engine/core/swap.js +3 -7
- package/engine/evm/amounts.js +2 -6
- package/engine/evm/asyncRoute.js +3 -7
- package/engine/evm/auth.js +0 -4
- package/engine/evm/claimGas.js +2 -6
- package/engine/evm/dex.js +1 -5
- package/engine/evm/escrow.js +0 -4
- package/engine/evm/factory.js +1 -5
- package/engine/evm/fees.js +62 -4
- package/engine/evm/funding.js +73 -71
- package/engine/evm/gasReserve.js +10 -4
- package/engine/evm/index.js +7 -11
- package/engine/evm/injected.js +0 -4
- package/engine/evm/permit.js +0 -4
- package/engine/evm/prices.js +3 -4
- package/engine/evm/session.js +1 -5
- package/engine/mock/chain.js +0 -4
- package/engine/monero/address.js +4 -5
- package/engine/monero/arrivalRead.js +15 -2
- package/engine/monero/halvesSweep.js +0 -4
- package/engine/monero/keyImage.js +146 -0
- package/engine/monero/keys.js +1 -0
- package/engine/monero/mnemonic.js +2 -1
- package/engine/monero/node.js +1 -4
- package/engine/monero/scan.js +12 -2
- package/engine/monero/swapKeys.js +0 -4
- package/engine/monero/unlock.js +2 -6
- package/engine/monero/wallet.js +0 -3
- package/engine/recovery/recoveryFile.js +31 -89
- package/engine/recovery/restore.js +0 -4
- package/engine/sdk/bridge.js +24 -58
- package/engine/ui/dom.js +0 -4
- package/engine/ui/walletModal.js +0 -4
- package/index.d.ts +436 -42
- package/package.json +22 -3
- package/src/actions.mjs +72 -6
- package/src/addressGuard.mjs +16 -0
- package/src/codes.mjs +26 -9
- package/src/config.mjs +56 -3
- package/src/decline.mjs +23 -74
- package/src/engine.mjs +17 -26
- package/src/firmRequest.mjs +80 -0
- package/src/index.mjs +17 -28
- package/src/legs/cow.mjs +2 -2
- package/src/legs/evm.mjs +20 -12
- package/src/legs/kyber-spec.mjs +2 -2
- package/src/legs/kyber.mjs +1 -1
- package/src/legs/shape.mjs +1 -1
- package/src/legs/uniswaprelay.mjs +16 -4
- package/src/legs/uniswapx.mjs +29 -7
- package/src/levelsWalkSpec.mjs +1 -1
- package/src/lock.mjs +18 -37
- package/src/provider/envFile.mjs +3 -3
- package/src/provider/sign.mjs +3 -3
- package/src/public/evm.d.ts +84 -0
- package/src/public/evm.mjs +20 -0
- package/src/public/order.mjs +1 -1
- package/src/public/provider.mjs +1 -1
- package/src/public/recovery.d.ts +4 -3
- package/src/public/recovery.mjs +1 -1
- package/src/public/xmr.d.ts +2 -2
- package/src/quoteEip712Spec.mjs +4 -4
- package/src/quotes.mjs +52 -11
- package/src/recovery-key.mjs +7 -3
- package/src/relayClaim.mjs +17 -3
- package/src/relayFirmClient.mjs +4 -0
- package/src/relayQuote.mjs +1 -0
- package/src/sim.mjs +1 -1
- package/src/swap-flow.mjs +28 -41
- package/src/swaps.mjs +217 -123
- package/src/sweep-inputs.mjs +61 -0
- package/src/sweep-reconcile.mjs +71 -0
- package/src/sweep-restore.mjs +38 -9
- package/src/sweep.mjs +164 -10
- package/src/version.mjs +1 -1
- package/src/wallet.mjs +1 -1
- package/src/xmr-arrival.mjs +1053 -57
package/engine/evm/funding.js
CHANGED
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
// GENERATED FILE - a byte-for-byte copy of the engine module www/js/evm/funding.js for the SDK package.
|
|
2
|
-
// Edit the source under www/js and regenerate the mirror; a drift guard reddens on any difference.
|
|
3
|
-
// Everything below this header is identical to the source.
|
|
4
|
-
|
|
5
1
|
// Funding an order in the escrow contract: real transactions, not a simulation.
|
|
6
2
|
//
|
|
7
3
|
// Roles and why:
|
|
@@ -44,13 +40,14 @@ export function newSecret() {
|
|
|
44
40
|
// TWO DEADLINES THAT DO NOT COINCIDE: until readyBy the depositor marks readiness ("I see the XMR"), from t1 a
|
|
45
41
|
// claim is closed and anyone may refund. Coincidence would restore a window where both paths are valid and gas
|
|
46
42
|
// would decide the dispute.
|
|
47
|
-
export function testOrderTerms({ locker, claimer, commitHalfLocker, commitHalfClaimer, edPointLocker, edPointClaimer, edViewPointLocker, amountWei, salt, claimWindowSeconds = 3600, readyWindowSeconds = 14400, readyBy, t1 }) {
|
|
43
|
+
export function testOrderTerms({ locker, claimer, commitHalfLocker, commitHalfClaimer, edPointLocker, edPointClaimer, edViewPointLocker, amountWei, salt, claimWindowSeconds = 3600, readyWindowSeconds = 14400, readyBy, t1, nowSec = null }) {
|
|
48
44
|
// THE VIEW POINT IS ON THE REQUIRED LIST: without it the Monero address cannot be assembled from the order
|
|
49
45
|
// fields, and the one who learns about it would be the claimer, after funding.
|
|
50
46
|
for (const [k, v] of Object.entries({ commitHalfLocker, commitHalfClaimer, edPointLocker, edPointClaimer, edViewPointLocker })) {
|
|
51
47
|
if (!v) throw new Error("order term not set: " + k);
|
|
52
48
|
}
|
|
53
|
-
const now =
|
|
49
|
+
const now = Number.isSafeInteger(Number(nowSec)) && Number(nowSec) > 0
|
|
50
|
+
? Number(nowSec) : Math.floor(Date.now() / 1000);
|
|
54
51
|
// DEADLINES MAY BE PASSED IN READY-MADE, AND THAT IS NECESSITY, NOT CONVENIENCE. They enter the canonical order
|
|
55
52
|
// context the proof is bound to, and the proof is computed BEFORE funding. Computing the deadlines here and now
|
|
56
53
|
// would put them AFTER the proof, so the proof would bind one set of deadlines while the contract gets another.
|
|
@@ -92,11 +89,23 @@ export function testOrderTerms({ locker, claimer, commitHalfLocker, commitHalfCl
|
|
|
92
89
|
};
|
|
93
90
|
}
|
|
94
91
|
|
|
95
|
-
// Amount in wei from a human value
|
|
92
|
+
// Amount in wei from a human decimal value and the token decimals.
|
|
93
|
+
//
|
|
94
|
+
// The value must carry its exact digits. A significant digit beyond `decimals` is a refusal; it is never sliced
|
|
95
|
+
// away, because that would fund a different amount from the signed one. Trailing zeroes beyond the decimals are
|
|
96
|
+
// not significant and are accepted.
|
|
96
97
|
export function toWei(human, decimals = 18) {
|
|
97
|
-
const
|
|
98
|
-
const
|
|
99
|
-
|
|
98
|
+
const text = String(human);
|
|
99
|
+
const match = /^(?:0|[1-9]\d*)(?:\.(\d+))?$/.exec(text);
|
|
100
|
+
if (!match) throw new Error("the amount is not a decimal number");
|
|
101
|
+
const dec = Number(decimals);
|
|
102
|
+
if (!Number.isInteger(dec) || dec < 0) throw new Error("the decimals are not a whole number");
|
|
103
|
+
const fraction = match[1] || "";
|
|
104
|
+
if (fraction.length > dec && /[1-9]/.test(fraction.slice(dec))) {
|
|
105
|
+
throw new Error("the amount has more decimal digits than the token");
|
|
106
|
+
}
|
|
107
|
+
const kept = fraction.slice(0, dec).padEnd(dec, "0");
|
|
108
|
+
return BigInt(text.split(".")[0]) * 10n ** BigInt(dec) + BigInt(kept || "0");
|
|
100
109
|
}
|
|
101
110
|
|
|
102
111
|
// THE ONE NATIVE AMOUNT OF A TOKEN-FUNDED ORDER.
|
|
@@ -115,13 +124,16 @@ export function escrowNativeWei({ quote = null, nativeDecimals = 18 } = {}) {
|
|
|
115
124
|
if (!Number.isFinite(n) || n <= 0) {
|
|
116
125
|
return { ok: false, code: "native-amount-unread", reason: "the quote's native amount is not a positive number" };
|
|
117
126
|
}
|
|
127
|
+
// A number at or above the safe-integer range has already lost digits before this function sees it.
|
|
128
|
+
if (typeof raw === "number" && Math.abs(raw) > Number.MAX_SAFE_INTEGER) {
|
|
129
|
+
return { ok: false, code: "native-amount-unread", reason: "the quote's native amount is not a safe number" };
|
|
130
|
+
}
|
|
118
131
|
const dec = Number(nativeDecimals);
|
|
119
132
|
if (!Number.isInteger(dec) || dec < 0) {
|
|
120
133
|
return { ok: false, code: "native-amount-unread", reason: "the native decimals are not a whole number" };
|
|
121
134
|
}
|
|
122
|
-
// THE QUOTE'S OWN DIGITS
|
|
123
|
-
|
|
124
|
-
const text = /e/i.test(String(raw)) ? n.toFixed(18) : String(raw);
|
|
135
|
+
// THE QUOTE'S OWN DIGITS. A canonical decimal string keeps them; exponent form is not a canonical amount.
|
|
136
|
+
const text = String(raw);
|
|
125
137
|
// DECIMAL DIGITS ONLY. BigInt accepts "0x10", and a native amount read as a hex literal would silently become
|
|
126
138
|
// sixteen times the token amount; a quote carries decimal text.
|
|
127
139
|
if (!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(text)) {
|
|
@@ -148,17 +160,12 @@ export function escrowNativeWei({ quote = null, nativeDecimals = 18 } = {}) {
|
|
|
148
160
|
// its gas is part of what the wallet has to be able to afford. One constant, one source (the check ties the
|
|
149
161
|
// reserve's copy to this declaration).
|
|
150
162
|
export const GAS_CREATE_ORDER_AND_FUND = 700_000n;
|
|
151
|
-
//
|
|
152
|
-
//
|
|
153
|
-
// only knows createOrderAndFund. The old lock(bytes) call and its gas constant are gone: the deposit rides in the
|
|
154
|
-
// same transaction.
|
|
163
|
+
// There is no separate "create without a deposit" constant. Each order escrow is an EIP-1167 clone, the terms live in
|
|
164
|
+
// the clone code, and the factory only has createOrderAndFund. The deposit rides in the same transaction.
|
|
155
165
|
|
|
156
|
-
// The OrderCreated event: topic0
|
|
157
|
-
//
|
|
158
|
-
//
|
|
159
|
-
// second copy here, which caused a real defect: after the OrderCreated field set changed, the stale copy failed to
|
|
160
|
-
// find the event and the escrow address silently fell back to the prediction - so the "address from the receipt"
|
|
161
|
-
// check stopped working without a word.
|
|
166
|
+
// The OrderCreated event: topic0 comes from the actual signature. Topics are [topic0, escrow, locker, claimer].
|
|
167
|
+
// Data carries both commitments, both points, the amount, readyBy, t1 and the salt.
|
|
168
|
+
// The event topic comes from the factory module, not a second copy here.
|
|
162
169
|
|
|
163
170
|
// The ACTUAL escrow address from the receipt. Returns null when the event is absent (the transaction is not in a
|
|
164
171
|
// block, or the factory is another) - then the caller must say so aloud rather than substitute a guess.
|
|
@@ -213,49 +220,54 @@ async function waitReceipt(receiptReader, hash, { tries = 12, delayMs = 1500 } =
|
|
|
213
220
|
|
|
214
221
|
// The full funding path. Steps are returned outward so the interface can show each one: predict is a free call,
|
|
215
222
|
// createOrder and lock are transactions in the user's wallet.
|
|
216
|
-
export async function fundOrder({ factory, locker, claimer, commitHalfLocker, commitHalfClaimer, edPointLocker, edPointClaimer, edViewPointLocker, salt: providedSalt, amountWei, amountLabel, claimWindowSeconds, readyWindowSeconds, readyBy, t1, quote, call, send, receipt, onStep, onPredicted }) {
|
|
223
|
+
export async function fundOrder({ factory, locker, claimer, commitHalfLocker, commitHalfClaimer, edPointLocker, edPointClaimer, edViewPointLocker, salt: providedSalt, amountWei, amountLabel, claimWindowSeconds, readyWindowSeconds, readyBy, t1, quote, call, send, receipt, onStep, onPredicted, nowSec = null }) {
|
|
217
224
|
if (!factory) throw new Error("no escrow factory address set for this network");
|
|
218
225
|
if (!locker) throw new Error("no EVM wallet connected: there is nobody to deposit");
|
|
219
226
|
if (!claimer) throw new Error("the order recipient (claimer) is not set");
|
|
220
227
|
if (locker.toLowerCase() === claimer.toLowerCase()) {
|
|
221
228
|
throw new Error("locker and claimer must not coincide: the contract rejects such an order");
|
|
222
229
|
}
|
|
223
|
-
// A
|
|
224
|
-
//
|
|
225
|
-
// quote is a NAMED refusal, not a silent funding of the wrong amount.
|
|
230
|
+
// A signed quote is mandatory. It carries the fee, the registry address and the provider. Without it, the order
|
|
231
|
+
// cannot be created, and funding would use the wrong amount.
|
|
226
232
|
if (!quote || typeof quote !== "object") throw new Error("a signed quote is required: the factory takes a quote, not bare order terms");
|
|
233
|
+
// THE QUOTE'S EXPIRY IS JUDGED AT THE FUNDING BOUNDARY. A device clock behind the chain lets an expired quote
|
|
234
|
+
// reach createOrderAndFund, which reverts after the fee is paid. The caller passes the chain time; when it is
|
|
235
|
+
// absent this is a test seam and the device clock remains the only clock available.
|
|
236
|
+
const fundingNowSec = Number.isSafeInteger(Number(nowSec)) && Number(nowSec) > 0
|
|
237
|
+
? Number(nowSec) : Math.floor(Date.now() / 1000);
|
|
238
|
+
const validUntil = Number(quote.validUntil);
|
|
239
|
+
if (Number.isSafeInteger(validUntil) && validUntil > 0 && validUntil <= fundingNowSec) {
|
|
240
|
+
const error = new Error("the signed quote has expired at the funding boundary");
|
|
241
|
+
error.code = "quote-expired";
|
|
242
|
+
error.params = { validUntil, now: fundingNowSec, step: "lock" };
|
|
243
|
+
throw error;
|
|
244
|
+
}
|
|
227
245
|
|
|
228
|
-
//
|
|
229
|
-
//
|
|
230
|
-
// The salt determines the escrow address and must exist
|
|
246
|
+
// Commitments and points are mandatory. Without them the order can be created but cannot be claimed, and its link
|
|
247
|
+
// to the Monero address cannot be proven.
|
|
248
|
+
// The salt determines the escrow address and must exist before the terms are assembled. The terms also go to predict.
|
|
231
249
|
const salt = providedSalt || newSecret(); // CREATE2 salt: determines the escrow address
|
|
232
250
|
const terms = testOrderTerms({
|
|
233
251
|
locker, claimer, commitHalfLocker, commitHalfClaimer, edPointLocker, edPointClaimer, edViewPointLocker,
|
|
234
|
-
amountWei, salt, claimWindowSeconds, readyWindowSeconds, readyBy, t1,
|
|
252
|
+
amountWei, salt, claimWindowSeconds, readyWindowSeconds, readyBy, t1, nowSec,
|
|
235
253
|
});
|
|
236
|
-
//
|
|
237
|
-
//
|
|
238
|
-
//
|
|
239
|
-
//
|
|
240
|
-
// escrow. The parameters are destructured, so there is no `order` variable here; the local is named `salt` and
|
|
241
|
-
// the input `providedSalt` to avoid a temporal-dead-zone self-reference.
|
|
242
|
-
// 1) the escrow address is visible BEFORE creation - that is the point of the factory
|
|
254
|
+
// Reuse the salt from the deal when it already has one. The salt determines the escrow address, so a new salt
|
|
255
|
+
// creates a new escrow while the record keeps the old address. Reuse also makes a retry hit the same address.
|
|
256
|
+
// The parameters are destructured, so the local is `salt` and the input is `providedSalt`.
|
|
257
|
+
// 1) the escrow address is visible before creation. That is the point of the factory.
|
|
243
258
|
onStep?.("computing the escrow address");
|
|
244
|
-
//
|
|
245
|
-
//
|
|
246
|
-
//
|
|
247
|
-
//
|
|
248
|
-
// THE DEPOSITOR'S FIELDS GO AS SEPARATE FACTORY ARGUMENTS, BUT THEY ARE IN THE SIGNED SET. Since quote protocol v10
|
|
249
|
-
// the factory signs them; the overwrite below must reproduce the signed values, or the digest check rejects the
|
|
250
|
-
// creation.
|
|
259
|
+
// The prediction fields must match the creation fields byte for byte. Both paths use the same terms, so they can
|
|
260
|
+
// diverge only when one place is edited alone. Keep one source of fields.
|
|
261
|
+
// The depositor's fields go as separate factory arguments, but they are in the signed set. The overwrite below must
|
|
262
|
+
// reproduce the signed values, or the digest check rejects the order.
|
|
251
263
|
const quoteEnc = { ...quote, commitHalfLocker: terms.commitHalfLocker, edPointLocker: terms.edPointLocker, edViewPointLocker: terms.edViewPointLocker };
|
|
252
|
-
//
|
|
253
|
-
//
|
|
254
|
-
//
|
|
255
|
-
// point can be funded beside a proof for another, and the claim reveals a half that does not open the address.
|
|
264
|
+
// Quote and terms must agree. A divergence moves the escrow address and signs the wrong order.
|
|
265
|
+
// The counterparty's spend half is part of that check. The proof is checked against the counterparty side, while
|
|
266
|
+
// the factory encodes the signed quote.
|
|
256
267
|
const sameValue = (a, b) => String(a === undefined || a === null ? "" : a).replace(/^0x/i, "").toLowerCase()
|
|
257
268
|
=== String(b === undefined || b === null ? "" : b).replace(/^0x/i, "").toLowerCase();
|
|
258
|
-
for (const name of ["locker", "claimer", "amount", "readyBy", "t1", "salt", "commitHalfClaimer", "edPointClaimer"
|
|
269
|
+
for (const name of ["locker", "claimer", "amount", "readyBy", "t1", "salt", "commitHalfClaimer", "edPointClaimer",
|
|
270
|
+
"commitHalfLocker", "edPointLocker", "edViewPointLocker"]) {
|
|
259
271
|
if (!sameValue(quote[name], terms[name])) {
|
|
260
272
|
throw new Error("the quote and the order terms diverge on field " + name);
|
|
261
273
|
}
|
|
@@ -286,21 +298,14 @@ export async function fundOrder({ factory, locker, claimer, commitHalfLocker, co
|
|
|
286
298
|
}
|
|
287
299
|
const escrowState = escrowStateVerdict({ status: stateRead.status, error: stateRead.error, address: escrow });
|
|
288
300
|
if (escrowState.blocks) throw new Error("signature not started: " + escrowState.reason);
|
|
289
|
-
// 2)
|
|
301
|
+
// 2) One transaction creates the order and funds it.
|
|
290
302
|
//
|
|
291
|
-
//
|
|
292
|
-
//
|
|
293
|
-
//
|
|
294
|
-
//
|
|
295
|
-
//
|
|
296
|
-
//
|
|
297
|
-
// one place in the project, and a second formatter here would diverge from it. The label is short on purpose: it
|
|
298
|
-
// is printed ON A BUTTON and must fit one line.
|
|
299
|
-
// THE FEE IS PART OF VALUE, AND THAT IS THE MAIN CONSEQUENCE OF ITS INTRODUCTION. The contract requires
|
|
300
|
-
// depositing EXACTLY `amount + fee`, so funding for the order amount alone is rejected - and rejected after
|
|
301
|
-
// signing, because the check lives in the contract. The order amount (`amount` in the terms) does NOT change: it
|
|
302
|
-
// is exactly what the claimer receives and what enters the terms hash. The fee is added on top, taken at claim,
|
|
303
|
-
// returned on refund.
|
|
303
|
+
// A failure rolls back creation, and one signature is enough. The sender becomes the locker, so the refund address
|
|
304
|
+
// always belongs to the payer.
|
|
305
|
+
// The amount is shown in ETH, not wei, and arrives as a ready string. Formatting lives in one place.
|
|
306
|
+
// The fee is part of the value. The contract requires exactly `amount + fee`, so funding the order amount alone is
|
|
307
|
+
// rejected after signing. The order amount is what the claimer receives and what enters the terms hash. The fee is
|
|
308
|
+
// added on top, taken at claim and returned on refund.
|
|
304
309
|
onStep?.("reading the escrow fee from the signed quote");
|
|
305
310
|
// THE FEE COMES FROM THE QUOTE AND IS MIRROR-CHECKED. Direction is already accounted for: a buy is amount + fee
|
|
306
311
|
// (on top), a sell is amount (the fee is deducted from the claimer's payout).
|
|
@@ -325,14 +330,11 @@ export async function fundOrder({ factory, locker, claimer, commitHalfLocker, co
|
|
|
325
330
|
gas: GAS_CREATE_ORDER_AND_FUND,
|
|
326
331
|
});
|
|
327
332
|
|
|
328
|
-
// 2b)
|
|
329
|
-
// and the factory code match
|
|
330
|
-
// the old one - and the deal looks broken (deadlines unreadable, no refund button). That is exactly what
|
|
331
|
-
// happened. A divergence from the prediction is named aloud: it is a sign of a real error.
|
|
333
|
+
// 2b) The escrow address comes from the receipt, not from the prediction. The prediction is right only when the
|
|
334
|
+
// salt and the factory code match. A divergence is a sign of a real error and must be named.
|
|
332
335
|
let actualEscrow = null;
|
|
333
|
-
//
|
|
334
|
-
// independent of the Monero node.
|
|
335
|
-
// not visible outside, and it must always be returned.
|
|
336
|
+
// The escrow birth block is the height where the deal exists on chain. It is the only source of that height
|
|
337
|
+
// independent of the Monero node. Declare it outside the branch so every path can return it.
|
|
336
338
|
let birthBlock = null;
|
|
337
339
|
let verdict = { status: "pending", reason: "no-receipt-reader" };
|
|
338
340
|
if (typeof receipt === "function") {
|
package/engine/evm/gasReserve.js
CHANGED
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
// GENERATED FILE - a byte-for-byte copy of the engine module www/js/evm/gasReserve.js for the SDK package.
|
|
2
|
-
// Edit the source under www/js and regenerate the mirror; a drift guard reddens on any difference.
|
|
3
|
-
// Everything below this header is identical to the source.
|
|
4
|
-
|
|
5
1
|
// THE BUYER GAS RESERVE FOR ORDER ACTIONS: THE READINESS MARK AND A POSSIBLE REFUND.
|
|
6
2
|
//
|
|
7
3
|
// THE POINT. In a direct swap the person deposits into the escrow, and after the XMR arrives calls markReady itself
|
|
@@ -67,6 +63,16 @@ export function orderGasReserveWei({ gasPriceWei, readyGasLimit = ORDER_READY_GA
|
|
|
67
63
|
return gp * (ready + refund + deposit) + extra;
|
|
68
64
|
}
|
|
69
65
|
|
|
66
|
+
// THE FUNDING RESERVE FOR MAX. The deposit is a separate transaction (`createOrderAndFund`) with its own gas limit;
|
|
67
|
+
// the balance must keep that limit times the maximum fee per gas. `orderGasReserveWei` remains the mark/refund
|
|
68
|
+
// reserve and does NOT include this deposit by default.
|
|
69
|
+
export function fundingGasReserveWei({ gasLimit = GAS_CREATE_ORDER_AND_FUND, maxFeePerGasWei } = {}) {
|
|
70
|
+
const limit = toBig(gasLimit);
|
|
71
|
+
const maxFee = toBig(maxFeePerGasWei);
|
|
72
|
+
if (limit === null || limit <= 0n || maxFee === null || maxFee <= 0n) return null;
|
|
73
|
+
return limit * maxFee;
|
|
74
|
+
}
|
|
75
|
+
|
|
70
76
|
// DISPLAY IN BOTH UNITS. A person coming from USDC has no sense of ETH scale, so the reserve is shown both
|
|
71
77
|
// in ETH and in dollars. The dollar is an estimate at the live native rate; no rate - no estimate (null), not a made-up one.
|
|
72
78
|
export function gasReserveDisplay({ reserveWei, nativeUsd, decimals = 18 } = {}) {
|
package/engine/evm/index.js
CHANGED
|
@@ -1,9 +1,5 @@
|
|
|
1
|
-
// GENERATED FILE - a byte-for-byte copy of the engine module www/js/evm/index.js for the SDK package.
|
|
2
|
-
// Edit the source under www/js and regenerate the mirror; a drift guard reddens on any difference.
|
|
3
|
-
// Everything below this header is identical to the source.
|
|
4
|
-
|
|
5
1
|
// The wallet used by the demo interface.
|
|
6
|
-
// One implementation: the injected EIP-1193 browser wallet (
|
|
2
|
+
// One implementation: the injected EIP-1193 browser wallet (engine/evm/session.js) - the user's real wallet,
|
|
7
3
|
// real balances. Mobile connectors are loaded by the host page and passed in as the same provider.
|
|
8
4
|
// The built-in demo wallet and its mode switch were removed: we are heading to a real product, not a mockup.
|
|
9
5
|
// Still NO transfers: there is no escrow contract yet and the address is mocked (mock/chain.js), so funding
|
|
@@ -27,7 +23,7 @@ import {
|
|
|
27
23
|
restoreInjected,
|
|
28
24
|
} from "./session.js";
|
|
29
25
|
import { discoverWallets } from "./injected.js";
|
|
30
|
-
// fundOrder needs a LOCAL name: `export * from
|
|
26
|
+
// fundOrder needs a LOCAL name: `export * from./funding.js` only re-exports and does not create a local
|
|
31
27
|
// variable, so fundOrderLive called a missing name and crashed.
|
|
32
28
|
import { fundOrder } from "./funding.js";
|
|
33
29
|
export * from "./factory.js";
|
|
@@ -37,16 +33,16 @@ export * from "./funding.js";
|
|
|
37
33
|
// protocol code, not two lookalikes.
|
|
38
34
|
export * from "./permit.js";
|
|
39
35
|
// THE ASYNCHRONOUS ROUTE, EXECUTED - through the same engine seam as the decision that chooses it. The page reaches
|
|
40
|
-
// it through the bridge; the SDK
|
|
36
|
+
// it through the bridge; the SDK owns this module.
|
|
41
37
|
export * from "./asyncRoute.js";
|
|
42
|
-
// THE EXECUTOR IS THE PACKAGE'S PROVIDER LAYER (src/legs/cow.mjs and its siblings). The
|
|
43
|
-
//
|
|
38
|
+
// THE EXECUTOR IS THE PACKAGE'S PROVIDER LAYER (src/legs/cow.mjs and its siblings). The old copy that used to
|
|
39
|
+
// execute the route here carried a second submit/status path; it was removed with the order worker.
|
|
44
40
|
|
|
45
41
|
// currentProvider - the wallet provider goes OUT to the SDK core (evm-wallet.mjs) so signing uses the same
|
|
46
42
|
// key as the page. Screens do not need it; they read status()/isConnected().
|
|
47
43
|
export { address, balanceOf, chainIdOf, connect, disconnect, isConnected, refreshBalances, restore, status, subscribe, switchChain, currentProvider };
|
|
48
44
|
export { connectInjected, restoreInjected };
|
|
49
|
-
// IMPORTANT: this is an import, not a re-export. `export { X } from
|
|
45
|
+
// IMPORTANT: this is an import, not a re-export. `export { X } from...` only re-exports and does NOT create
|
|
50
46
|
// a local name, while fundOrderLive uses sendTransaction/readContract directly - this already broke twice.
|
|
51
47
|
import { sendTransaction, readContract, readReceipt, readCode } from "./session.js";
|
|
52
48
|
export { sendTransaction, readContract, readReceipt, readCode };
|
|
@@ -74,7 +70,7 @@ export async function simulateEscrowFunding(tx) {
|
|
|
74
70
|
// Replaces simulateEscrowFunding. The difference is fundamental: the simulation invented a hash, here two
|
|
75
71
|
// real transactions go out - createOrder to the factory and lock(sealedHalf) to the new escrow.
|
|
76
72
|
//
|
|
77
|
-
// Separation is deliberate: cryptography (halves, DLEQ, envelope) lives in
|
|
73
|
+
// Separation is deliberate: cryptography (halves, DLEQ, envelope) lives in engine/atomic/ and does NOT reach
|
|
78
74
|
// here. This function gets the ready sealedCommitment and sealedHalf - exactly what goes to the contract.
|
|
79
75
|
// The caller sets the order of steps: verify the counterparty first, then lock.
|
|
80
76
|
//
|
package/engine/evm/injected.js
CHANGED
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
// GENERATED FILE - a byte-for-byte copy of the engine module www/js/evm/injected.js for the SDK package.
|
|
2
|
-
// Edit the source under www/js and regenerate the mirror; a drift guard reddens on any difference.
|
|
3
|
-
// Everything below this header is identical to the source.
|
|
4
|
-
|
|
5
1
|
// BROWSER WALLETS: detection by EIP-6963 and connection by EIP-1193.
|
|
6
2
|
// WHY EIP-6963, NOT window.ethereum.isMetaMask. With two extensions installed, window.ethereum is "whoever was
|
|
7
3
|
// last", and guessing by flags gives wrong names and icons. EIP-6963 solves this: a wallet announces itself with
|
package/engine/evm/permit.js
CHANGED
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
// GENERATED FILE - a byte-for-byte copy of the engine module www/js/evm/permit.js for the SDK package.
|
|
2
|
-
// Edit the source under www/js and regenerate the mirror; a drift guard reddens on any difference.
|
|
3
|
-
// Everything below this header is identical to the source.
|
|
4
|
-
|
|
5
1
|
// TOKEN ALLOWANCE FOR BUYING WITHOUT OWN ETH: what the token supports and what is missing.
|
|
6
2
|
//
|
|
7
3
|
// WHAT IS HERE AND WHAT IS NOT. Only selectors, calldata assembly and an HONEST verdict on whether a signature
|
package/engine/evm/prices.js
CHANGED
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
// GENERATED FILE - a byte-for-byte copy of the engine module www/js/evm/prices.js for the SDK package.
|
|
2
|
-
// Edit the source under www/js and regenerate the mirror; a drift guard reddens on any difference.
|
|
3
|
-
// Everything below this header is identical to the source.
|
|
4
|
-
|
|
5
1
|
// LIVE MARKET NUMBERS FOR THE EVM LEG: the native price (Chainlink on-chain) and the gas cost (RPC).
|
|
6
2
|
// WHY ON-CHAIN, NOT AN API: the price is a contract call over the same RPC already allowed by the CSP
|
|
7
3
|
// (connect-src), so no new external domain appears, there are no keys or rate limits, and the feed address is
|
|
@@ -42,6 +38,7 @@ async function rpc(chain, method, params = []) {
|
|
|
42
38
|
return j.result;
|
|
43
39
|
}
|
|
44
40
|
|
|
41
|
+
// ABI words are positional 32-byte values.
|
|
45
42
|
const word = (data, i) => BigInt("0x" + String(data).slice(2).slice(i * 64, (i + 1) * 64));
|
|
46
43
|
|
|
47
44
|
// ABI string decode: [offset][length][bytes]. Needed to tell the ETH/USD feed from another one. TextDecoder,
|
|
@@ -72,12 +69,14 @@ export async function nativeUsd(chain, { force = false } = {}) {
|
|
|
72
69
|
]);
|
|
73
70
|
const desc = decodeString(descHex);
|
|
74
71
|
const answer = word(roundHex, 1);
|
|
72
|
+
// Chainlink timestamps are seconds. Date.now() below is milliseconds.
|
|
75
73
|
const updatedAt = Number(word(roundHex, 3)) * 1000;
|
|
76
74
|
const decimals = Number(feed.decimals || 8);
|
|
77
75
|
const value = Number(answer) / 10 ** decimals;
|
|
78
76
|
const fresh = updatedAt > 0 && Date.now() - updatedAt < MAX_AGE_MS;
|
|
79
77
|
const sane = value >= (feed.min || 0.01) && value <= (feed.max || 1e7);
|
|
80
78
|
if (desc !== feed.pair || !fresh || !sane) {
|
|
79
|
+
// A failed or stale read is cached as null for CACHE_MS. That avoids a retry storm on a healthy feed.
|
|
81
80
|
return put(key, null); // null, not "roughly this": silence is more honest than a guess
|
|
82
81
|
}
|
|
83
82
|
return put(key, { usd: value, updatedAt, source: "chainlink", pair: desc });
|
package/engine/evm/session.js
CHANGED
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
// GENERATED FILE - a byte-for-byte copy of the engine module www/js/evm/session.js for the SDK package.
|
|
2
|
-
// Edit the source under www/js and regenerate the mirror; a drift guard reddens on any difference.
|
|
3
|
-
// Everything below this header is identical to the source.
|
|
4
|
-
|
|
5
1
|
// The EVM wallet: state, balances, network switching and the injected connector.
|
|
6
2
|
|
|
7
3
|
// A browser wallet (MetaMask, Rabby, Coinbase...) found by EIP-6963 connects directly over EIP-1193. The SDK
|
|
@@ -317,7 +313,7 @@ export async function signMessage(message) {
|
|
|
317
313
|
}
|
|
318
314
|
// THE MESSAGE IS PASSED IN HEX, NOT AS TEXT. EIP-191 requires it: the first personal_sign argument is the
|
|
319
315
|
// message bytes in hex. MetaMask accepts text too (which is why this never surfaced on a live wallet for
|
|
320
|
-
// years), while a node refuses: "invalid value: string
|
|
316
|
+
// years), while a node refuses: "invalid value: string..., expected a valid hex string". Verified by a call:
|
|
321
317
|
// text - refusal -32602, hex - a signature. The argument order [data, address] is as in MetaMask and WalletConnect.
|
|
322
318
|
// If the wallet answers with an error, we show it AS IS: the cause is visible from the text.
|
|
323
319
|
const hex = "0x" + Array.from(new TextEncoder().encode(String(message)), (b) => b.toString(16).padStart(2, "0")).join("");
|
package/engine/mock/chain.js
CHANGED
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
// GENERATED FILE - a byte-for-byte copy of the engine module www/js/mock/chain.js for the SDK package.
|
|
2
|
-
// Edit the source under www/js and regenerate the mirror; a drift guard reddens on any difference.
|
|
3
|
-
// Everything below this header is identical to the source.
|
|
4
|
-
|
|
5
1
|
// Mock chain: the escrow contract on EVM and the Monero leg.
|
|
6
2
|
//
|
|
7
3
|
// There are NO real transactions here. Everything returned is marked mock, and the hashes
|
package/engine/monero/address.js
CHANGED
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
// SDK ENGINE MODULE - the demo's sdk/ mirror copies this file byte for byte (tools/build-sdk-engine.mjs).
|
|
2
|
-
// The page's own www/js module is a separate copy; edit this package source and regenerate the mirror.
|
|
3
|
-
|
|
4
1
|
// Monero address checks and assembly: format + real checksum + network prefixes.
|
|
5
2
|
// A detail easy to get wrong: Monero has its OWN base58 - block-based (8 bytes -> 11 chars, the remainder last).
|
|
6
3
|
// It is NOT compatible with bitcoin-base58, where a leading '1' means a zero byte; here a block is a NUMBER and
|
|
@@ -198,7 +195,8 @@ export async function checkAddress(addr, opts = {}) {
|
|
|
198
195
|
}
|
|
199
196
|
const shape = networkFromShape(a);
|
|
200
197
|
if (opts.expectNetwork && shape && shape !== opts.expectNetwork) {
|
|
201
|
-
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 };
|
|
202
200
|
}
|
|
203
201
|
try {
|
|
204
202
|
const bytes = decodeMoneroBase58(a);
|
|
@@ -218,7 +216,8 @@ export async function checkAddress(addr, opts = {}) {
|
|
|
218
216
|
const meta = PREFIXES[prefix] || { network: "unknown", kind: "unknown" };
|
|
219
217
|
if (meta.network === "unknown") return { ok: false, reason: `Unsupported address prefix ${prefix}` };
|
|
220
218
|
if (opts.expectNetwork && meta.network !== opts.expectNetwork) {
|
|
221
|
-
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 };
|
|
222
221
|
}
|
|
223
222
|
return { ok: true, verified: true, network: meta.network, kind: meta.kind, bytes: bytes.length };
|
|
224
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
|
-
|
|
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
|
|
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";
|
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
// GENERATED FILE - a byte-for-byte copy of the engine module www/js/monero/halvesSweep.js for the SDK package.
|
|
2
|
-
// Edit the source under www/js and regenerate the mirror; a drift guard reddens on any difference.
|
|
3
|
-
// Everything below this header is identical to the source.
|
|
4
|
-
|
|
5
1
|
// KEYS FOR SWEEPING FROM A HALVES FILE. One logic for two consumers: the sweep page (sweep.js) and the
|
|
6
2
|
// check, so the two cannot drift.
|
|
7
3
|
// This is the main check of the whole sweep: the contract only verifies that the HASH of the revealed half
|
|
@@ -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
|
+
}
|