@cloak.dev/sdk 0.2.5 → 0.2.6-staging.2c9931c
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 +171 -0
- package/README.md +195 -43
- package/dist/index.cjs +2510 -252
- package/dist/index.d.cts +822 -155
- package/dist/index.d.ts +822 -155
- package/dist/index.js +2490 -257
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -676,7 +676,7 @@ function parseStrictViewingKeyChallenge(response, userPubkey, viewingKeyHex) {
|
|
|
676
676
|
|
|
677
677
|
// src/config/relay.ts
|
|
678
678
|
var CLOAK_PRODUCTION_RELAY_URL = "https://api.cloak.ag";
|
|
679
|
-
var RELAY_ORIGIN_ALLOWLIST = [
|
|
679
|
+
var RELAY_ORIGIN_ALLOWLIST = ["https://staging-api.cloak.ag"];
|
|
680
680
|
var ABSOLUTE_URL = /^[a-z][a-z0-9+.-]*:\/\//i;
|
|
681
681
|
var LOOPBACK_IPV4 = /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
|
|
682
682
|
var THIS_NETWORK_IPV4 = /^0\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
|
|
@@ -753,6 +753,44 @@ function isLoopbackHost(value) {
|
|
|
753
753
|
}
|
|
754
754
|
var BUILD_ALLOWS_LOCAL_ENDPOINTS = RELAY_ORIGIN_ALLOWLIST.some(isLoopbackHost);
|
|
755
755
|
|
|
756
|
+
// src/relay/clock.ts
|
|
757
|
+
var RELAY_SERVER_TIME_HEADER = "x-cloak-server-time";
|
|
758
|
+
var MAX_CLOCK_DIVERGENCE_MS = 2e3;
|
|
759
|
+
var MAX_PLAUSIBLE_OFFSET_MS = 24 * 60 * 60 * 1e3;
|
|
760
|
+
var sample = null;
|
|
761
|
+
function monotonicNowMs() {
|
|
762
|
+
const perf = globalThis.performance;
|
|
763
|
+
return typeof perf?.now === "function" ? perf.now() : Date.now();
|
|
764
|
+
}
|
|
765
|
+
function observeRelayClock(response) {
|
|
766
|
+
const raw = response?.headers?.get?.(RELAY_SERVER_TIME_HEADER);
|
|
767
|
+
if (typeof raw !== "string" || !/^\d{1,16}$/.test(raw.trim())) return;
|
|
768
|
+
const serverMs = Number(raw.trim());
|
|
769
|
+
const wallMs = Date.now();
|
|
770
|
+
const offsetMs = serverMs - wallMs;
|
|
771
|
+
if (!Number.isSafeInteger(serverMs) || Math.abs(offsetMs) > MAX_PLAUSIBLE_OFFSET_MS) return;
|
|
772
|
+
sample = { offsetMs, wallAtSampleMs: wallMs, monoAtSampleMs: monotonicNowMs() };
|
|
773
|
+
}
|
|
774
|
+
function relayNowMs() {
|
|
775
|
+
const wallMs = Date.now();
|
|
776
|
+
if (!sample) return wallMs;
|
|
777
|
+
const wallElapsed = wallMs - sample.wallAtSampleMs;
|
|
778
|
+
const monoElapsed = monotonicNowMs() - sample.monoAtSampleMs;
|
|
779
|
+
if (Math.abs(wallElapsed - monoElapsed) > MAX_CLOCK_DIVERGENCE_MS) {
|
|
780
|
+
sample = null;
|
|
781
|
+
return wallMs;
|
|
782
|
+
}
|
|
783
|
+
return wallMs + sample.offsetMs;
|
|
784
|
+
}
|
|
785
|
+
function hasRelayClockSample() {
|
|
786
|
+
if (!sample) return false;
|
|
787
|
+
relayNowMs();
|
|
788
|
+
return sample !== null;
|
|
789
|
+
}
|
|
790
|
+
function relayNowSeconds() {
|
|
791
|
+
return Math.floor(relayNowMs() / 1e3);
|
|
792
|
+
}
|
|
793
|
+
|
|
756
794
|
// src/relay/endpoint.ts
|
|
757
795
|
var ALLOWED_ORIGINS = new Set(
|
|
758
796
|
RELAY_ORIGIN_ALLOWLIST.map((entry) => {
|
|
@@ -801,9 +839,48 @@ function assertAllowedRelayOrigin(value) {
|
|
|
801
839
|
}
|
|
802
840
|
return trimmed.replace(/\/$/, "");
|
|
803
841
|
}
|
|
804
|
-
async function relayFetch(url, init) {
|
|
842
|
+
async function relayFetch(url, init, options) {
|
|
805
843
|
assertAllowedRelayOrigin(url);
|
|
806
|
-
|
|
844
|
+
const extra = sanitizeExtraHeaders(options?.extraHeaders);
|
|
845
|
+
const response = extra ? await fetch(url, { ...init, headers: mergeRelayHeaders(init?.headers, extra) }) : await fetch(url, init);
|
|
846
|
+
if (options?.observeClock !== false) observeRelayClock(response);
|
|
847
|
+
return response;
|
|
848
|
+
}
|
|
849
|
+
var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
850
|
+
var FORBIDDEN_HEADER_VALUE_CHARS = /[\r\n\0]/;
|
|
851
|
+
function sanitizeExtraHeaders(extra) {
|
|
852
|
+
if (!extra || typeof extra !== "object") return void 0;
|
|
853
|
+
const out = {};
|
|
854
|
+
let any = false;
|
|
855
|
+
for (const [name, value] of Object.entries(extra)) {
|
|
856
|
+
if (typeof name !== "string" || !HEADER_NAME.test(name)) continue;
|
|
857
|
+
if (typeof value !== "string" || FORBIDDEN_HEADER_VALUE_CHARS.test(value)) continue;
|
|
858
|
+
out[name] = value;
|
|
859
|
+
any = true;
|
|
860
|
+
}
|
|
861
|
+
return any ? out : void 0;
|
|
862
|
+
}
|
|
863
|
+
function mergeRelayHeaders(base, extraHeaders) {
|
|
864
|
+
const extra = sanitizeExtraHeaders(extraHeaders);
|
|
865
|
+
if (!extra) return base;
|
|
866
|
+
const merged = {};
|
|
867
|
+
const taken = /* @__PURE__ */ new Set();
|
|
868
|
+
const put = (name, value) => {
|
|
869
|
+
merged[name] = value;
|
|
870
|
+
taken.add(name.toLowerCase());
|
|
871
|
+
};
|
|
872
|
+
if (typeof Headers !== "undefined" && base instanceof Headers) {
|
|
873
|
+
base.forEach((value, name) => put(name, value));
|
|
874
|
+
} else if (Array.isArray(base)) {
|
|
875
|
+
for (const [name, value] of base) put(name, value);
|
|
876
|
+
} else if (base) {
|
|
877
|
+
for (const [name, value] of Object.entries(base)) put(name, value);
|
|
878
|
+
}
|
|
879
|
+
for (const [name, value] of Object.entries(extra)) {
|
|
880
|
+
if (taken.has(name.toLowerCase())) continue;
|
|
881
|
+
put(name, value);
|
|
882
|
+
}
|
|
883
|
+
return merged;
|
|
807
884
|
}
|
|
808
885
|
function assertAllowedRpcEndpoint(endpoint) {
|
|
809
886
|
if (BUILD_ALLOWS_LOCAL_ENDPOINTS) return;
|
|
@@ -1176,6 +1253,7 @@ var TRANSACT_SWAP_AUTH_FIELDS = [
|
|
|
1176
1253
|
"slippage_bps",
|
|
1177
1254
|
"swap_max_retries"
|
|
1178
1255
|
];
|
|
1256
|
+
var RELAY_AUTH_FIELDS_SIGNED_WHEN_PRESENT = ["affiliate_code"];
|
|
1179
1257
|
var UTF8 = new TextEncoder();
|
|
1180
1258
|
function compareKeysBytewise(a, b) {
|
|
1181
1259
|
if (a === b) return 0;
|
|
@@ -1239,6 +1317,11 @@ function buildAuthRequest(body, sender, fields) {
|
|
|
1239
1317
|
}
|
|
1240
1318
|
out[k] = value;
|
|
1241
1319
|
}
|
|
1320
|
+
for (const k of RELAY_AUTH_FIELDS_SIGNED_WHEN_PRESENT) {
|
|
1321
|
+
const value = body[k];
|
|
1322
|
+
if (value === void 0 || value === null) continue;
|
|
1323
|
+
out[k] = value;
|
|
1324
|
+
}
|
|
1242
1325
|
return out;
|
|
1243
1326
|
}
|
|
1244
1327
|
function buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request) {
|
|
@@ -1254,7 +1337,7 @@ ${digest}`
|
|
|
1254
1337
|
}
|
|
1255
1338
|
function buildRelayAuthPreimage(endpoint, programId, body, sender, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
|
|
1256
1339
|
const senderB58 = sender;
|
|
1257
|
-
const issuedAt = String(nowSeconds ??
|
|
1340
|
+
const issuedAt = String(nowSeconds ?? relayNowSeconds());
|
|
1258
1341
|
const nonce = randomNonceUuid();
|
|
1259
1342
|
const request = buildAuthRequest({ ...body, sender: senderB58 }, senderB58, fields);
|
|
1260
1343
|
const message = buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request);
|
|
@@ -1333,7 +1416,7 @@ function assertApprovalWithinFreshnessWindow(elapsedMs, maxAgeSeconds = REQUEST_
|
|
|
1333
1416
|
`The wallet approval took ${Math.round(elapsedSeconds)} seconds, and Cloak requests stay valid for ${maxAgeSeconds} seconds from the moment they are signed (${RELAY_AUTH_APPROVAL_MARGIN_SECONDS} of those are held back for the request to reach the network). The timestamp is inside the signature, so it cannot be refreshed without your approval again. NOTHING WAS SUBMITTED and no funds moved. Start the same operation again and approve the prompt when it appears.`
|
|
1334
1417
|
);
|
|
1335
1418
|
}
|
|
1336
|
-
function explainRelayAuthRejection(responseText) {
|
|
1419
|
+
function explainRelayAuthRejection(responseText, context) {
|
|
1337
1420
|
const text = String(responseText);
|
|
1338
1421
|
const has = (needle) => text.includes(needle);
|
|
1339
1422
|
if (has("issued too far in the future")) {
|
|
@@ -1343,7 +1426,9 @@ function explainRelayAuthRejection(responseText) {
|
|
|
1343
1426
|
return `The request was signed more than ${REQUEST_AUTH_MAX_AGE_SECONDS} seconds before it arrived, usually because a wallet approval was left waiting, or because this computer's clock is running behind. The signed timestamp cannot be refreshed on its own. Start the operation again. Nothing was submitted.`;
|
|
1344
1427
|
}
|
|
1345
1428
|
if (has("does not match the exact request")) {
|
|
1346
|
-
|
|
1429
|
+
const base = `The request body changed after it was signed, so the relay's digest and this one disagree. Sign the exact body that is POSTed, and re-POST a retry byte for byte rather than rebuilding it. If this is a hand-built swap call, check that every field in TRANSACT_SWAP_AUTH_FIELDS is present, including \`slippage_bps\`.`;
|
|
1430
|
+
if (!context?.carriedAffiliateCode) return base;
|
|
1431
|
+
return `${base} This request carried \`affiliate_code\`, which is signed with the rest of the body. A relay that predates the affiliate release (REL-010/REL-011) ignores that field and leaves it out of its digest, which produces exactly this mismatch. Upgrade the relay, or send the request without \`affiliateCode\`.`;
|
|
1347
1432
|
}
|
|
1348
1433
|
if (has("has no registered viewing key")) {
|
|
1349
1434
|
return `The signature was accepted, so this is not a signing problem: the wallet that signed has no viewing key registered with Cloak yet. Register one first, or let the SDK do it by leaving \`enforceViewingKeyRegistration\` on and supplying the viewing key.`;
|
|
@@ -3885,6 +3970,27 @@ function isRootAccepted(data, rootHex) {
|
|
|
3885
3970
|
const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
|
|
3886
3971
|
return readRootHistory(data).some((r) => r === want);
|
|
3887
3972
|
}
|
|
3973
|
+
function treeAccountAcceptsRoot(data, rootHex) {
|
|
3974
|
+
const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
|
|
3975
|
+
if (data.length >= ROOT_OFFSET + 32) {
|
|
3976
|
+
const current = Buffer.from(data.subarray(ROOT_OFFSET, ROOT_OFFSET + 32)).toString("hex");
|
|
3977
|
+
if (current === want) return true;
|
|
3978
|
+
}
|
|
3979
|
+
return isRootAccepted(data, want);
|
|
3980
|
+
}
|
|
3981
|
+
function readTreeAccountFrontier(data) {
|
|
3982
|
+
if (!data || data.length < ROOT_INDEX_OFFSET + 8) return null;
|
|
3983
|
+
const buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
|
|
3984
|
+
const next = readBigUInt64LE(buf, 32);
|
|
3985
|
+
if (next > 2n ** BigInt(MERKLE_TREE_HEIGHT)) return null;
|
|
3986
|
+
const subtrees = [];
|
|
3987
|
+
for (let level = 0; level < MERKLE_TREE_HEIGHT; level++) {
|
|
3988
|
+
const offset = SUBTREES_OFFSET + level * 32;
|
|
3989
|
+
subtrees.push(BigInt("0x" + buf.subarray(offset, offset + 32).toString("hex")));
|
|
3990
|
+
}
|
|
3991
|
+
const root = BigInt("0x" + buf.subarray(ROOT_OFFSET, ROOT_OFFSET + 32).toString("hex"));
|
|
3992
|
+
return { nextIndex: Number(next), subtrees, root };
|
|
3993
|
+
}
|
|
3888
3994
|
|
|
3889
3995
|
// src/proving/merkle.ts
|
|
3890
3996
|
import { buildPoseidon } from "circomlibjs";
|
|
@@ -4044,6 +4150,89 @@ var MerkleTree = class _MerkleTree {
|
|
|
4044
4150
|
async function buildMerkleTree(commitments, height = MERKLE_TREE_HEIGHT2) {
|
|
4045
4151
|
return MerkleTree.create(height, commitments);
|
|
4046
4152
|
}
|
|
4153
|
+
var MerkleFrontier = class _MerkleFrontier {
|
|
4154
|
+
constructor(levels, zeros, poseidon2, count, left) {
|
|
4155
|
+
this.levels = levels;
|
|
4156
|
+
this.zeros = zeros;
|
|
4157
|
+
this.poseidon = poseidon2;
|
|
4158
|
+
this.count = count;
|
|
4159
|
+
this.left = left;
|
|
4160
|
+
}
|
|
4161
|
+
static async create(state, levels = MERKLE_TREE_HEIGHT2) {
|
|
4162
|
+
const zeros = await getZeroValues();
|
|
4163
|
+
const poseidon2 = await getPoseidon();
|
|
4164
|
+
const left = new Array(levels).fill(null);
|
|
4165
|
+
let count = 0;
|
|
4166
|
+
if (state) {
|
|
4167
|
+
if (!Number.isSafeInteger(state.nextIndex) || state.nextIndex < 0 || state.nextIndex > 2 ** levels) {
|
|
4168
|
+
throw new Error("MerkleFrontierState.nextIndex out of range");
|
|
4169
|
+
}
|
|
4170
|
+
if (!Array.isArray(state.left) || state.left.length !== levels) {
|
|
4171
|
+
throw new Error(`MerkleFrontierState.left must have ${levels} entries`);
|
|
4172
|
+
}
|
|
4173
|
+
count = state.nextIndex;
|
|
4174
|
+
for (let l = 0; l < levels; l++) {
|
|
4175
|
+
const odd = Math.floor(count / 2 ** l) % 2 === 1;
|
|
4176
|
+
const entry = state.left[l];
|
|
4177
|
+
if (odd !== (entry !== "")) throw new Error(`MerkleFrontierState.left[${l}] disagrees with nextIndex`);
|
|
4178
|
+
if (odd) {
|
|
4179
|
+
if (!/^[0-9a-f]{64}$/.test(entry)) throw new Error(`MerkleFrontierState.left[${l}] is not 32-byte hex`);
|
|
4180
|
+
left[l] = BigInt("0x" + entry);
|
|
4181
|
+
}
|
|
4182
|
+
}
|
|
4183
|
+
}
|
|
4184
|
+
return new _MerkleFrontier(levels, zeros, poseidon2, count, left);
|
|
4185
|
+
}
|
|
4186
|
+
get nextIndex() {
|
|
4187
|
+
return this.count;
|
|
4188
|
+
}
|
|
4189
|
+
/**
|
|
4190
|
+
* The complete LEFT node held at `level`: the node at index `floor(nextIndex / 2^level) - 1`,
|
|
4191
|
+
* present only while that index is even (bit `level` of `nextIndex` is set), else `null`.
|
|
4192
|
+
* With every set bit of `nextIndex`, these nodes cover leaves `[0, nextIndex)` exactly.
|
|
4193
|
+
*/
|
|
4194
|
+
leftAt(level) {
|
|
4195
|
+
if (!Number.isInteger(level) || level < 0 || level >= this.levels) return null;
|
|
4196
|
+
return this.left[level];
|
|
4197
|
+
}
|
|
4198
|
+
hash(a, b) {
|
|
4199
|
+
return this.poseidon.F.toObject(this.poseidon([a, b]));
|
|
4200
|
+
}
|
|
4201
|
+
/** Append leaves at indices `nextIndex .. nextIndex + leaves.length - 1`. */
|
|
4202
|
+
append(leaves) {
|
|
4203
|
+
if (leaves.length === 0) return;
|
|
4204
|
+
if (this.count + leaves.length > 2 ** this.levels) throw new Error("Tree is full");
|
|
4205
|
+
let nodes = leaves;
|
|
4206
|
+
for (let l = 0; l < this.levels && nodes.length > 0; l++) {
|
|
4207
|
+
const before = Math.floor(this.count / 2 ** l);
|
|
4208
|
+
const seq = before % 2 === 1 ? [this.left[l], ...nodes] : nodes;
|
|
4209
|
+
const parents = [];
|
|
4210
|
+
for (let i = 0; i + 1 < seq.length; i += 2) parents.push(this.hash(seq[i], seq[i + 1]));
|
|
4211
|
+
this.left[l] = (before + nodes.length) % 2 === 1 ? seq[seq.length - 1] : null;
|
|
4212
|
+
nodes = parents;
|
|
4213
|
+
}
|
|
4214
|
+
this.count += leaves.length;
|
|
4215
|
+
}
|
|
4216
|
+
/** The root of the first `nextIndex` leaves, zero-padded to the right. */
|
|
4217
|
+
root() {
|
|
4218
|
+
let partial = this.zeros[0];
|
|
4219
|
+
for (let l = 0; l < this.levels; l++) {
|
|
4220
|
+
const odd = Math.floor(this.count / 2 ** l) % 2 === 1;
|
|
4221
|
+
if (odd) partial = this.hash(this.left[l], partial);
|
|
4222
|
+
else partial = partial === this.zeros[l] ? this.zeros[l + 1] : this.hash(partial, this.zeros[l]);
|
|
4223
|
+
}
|
|
4224
|
+
return partial;
|
|
4225
|
+
}
|
|
4226
|
+
toState() {
|
|
4227
|
+
return {
|
|
4228
|
+
nextIndex: this.count,
|
|
4229
|
+
left: this.left.map((v) => v === null ? "" : v.toString(16).padStart(64, "0"))
|
|
4230
|
+
};
|
|
4231
|
+
}
|
|
4232
|
+
clone() {
|
|
4233
|
+
return new _MerkleFrontier(this.levels, this.zeros, this.poseidon, this.count, [...this.left]);
|
|
4234
|
+
}
|
|
4235
|
+
};
|
|
4047
4236
|
|
|
4048
4237
|
// src/config/transaction-version.ts
|
|
4049
4238
|
var MAX_SUPPORTED_TRANSACTION_VERSION = 1;
|
|
@@ -4192,6 +4381,7 @@ async function fetchWithRetry(url, options = {}) {
|
|
|
4192
4381
|
try {
|
|
4193
4382
|
const response = await fetch(url, { signal: controller.signal });
|
|
4194
4383
|
clearTimeout(timeoutId);
|
|
4384
|
+
observeRelayClock(response);
|
|
4195
4385
|
return response;
|
|
4196
4386
|
} finally {
|
|
4197
4387
|
clearTimeout(timeoutId);
|
|
@@ -4555,38 +4745,77 @@ async function aesGcmDecrypt2(ciphertext, keyBytes, nonce) {
|
|
|
4555
4745
|
const plaintext = await subtle.decrypt({ name: "AES-GCM", iv: toArrayBuffer2(nonce) }, key, toArrayBuffer2(ciphertext));
|
|
4556
4746
|
return new Uint8Array(plaintext);
|
|
4557
4747
|
}
|
|
4558
|
-
async function
|
|
4748
|
+
async function importNkHkdfKey(nk) {
|
|
4559
4749
|
if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
|
|
4560
4750
|
throw new Error("nk must be 32 bytes");
|
|
4561
4751
|
}
|
|
4752
|
+
return getSubtleCrypto2().importKey("raw", toArrayBuffer2(nk), "HKDF", false, ["deriveBits"]);
|
|
4753
|
+
}
|
|
4754
|
+
async function deriveAesKeyAndNonceFromIkm(ikm, salt) {
|
|
4562
4755
|
const subtle = getSubtleCrypto2();
|
|
4563
|
-
const
|
|
4564
|
-
|
|
4565
|
-
|
|
4566
|
-
|
|
4567
|
-
|
|
4568
|
-
|
|
4569
|
-
|
|
4570
|
-
|
|
4571
|
-
|
|
4572
|
-
|
|
4573
|
-
|
|
4574
|
-
|
|
4575
|
-
|
|
4576
|
-
|
|
4577
|
-
|
|
4578
|
-
|
|
4579
|
-
|
|
4580
|
-
|
|
4581
|
-
|
|
4582
|
-
|
|
4583
|
-
|
|
4584
|
-
);
|
|
4756
|
+
const [keyBits, nonceBits] = await Promise.all([
|
|
4757
|
+
subtle.deriveBits(
|
|
4758
|
+
{
|
|
4759
|
+
name: "HKDF",
|
|
4760
|
+
hash: "SHA-256",
|
|
4761
|
+
salt: toArrayBuffer2(salt),
|
|
4762
|
+
info: toArrayBuffer2(CHAIN_NOTE_KEY_INFO)
|
|
4763
|
+
},
|
|
4764
|
+
ikm,
|
|
4765
|
+
256
|
|
4766
|
+
),
|
|
4767
|
+
subtle.deriveBits(
|
|
4768
|
+
{
|
|
4769
|
+
name: "HKDF",
|
|
4770
|
+
hash: "SHA-256",
|
|
4771
|
+
salt: toArrayBuffer2(salt),
|
|
4772
|
+
info: toArrayBuffer2(CHAIN_NOTE_NONCE_INFO)
|
|
4773
|
+
},
|
|
4774
|
+
ikm,
|
|
4775
|
+
96
|
|
4776
|
+
)
|
|
4777
|
+
]);
|
|
4585
4778
|
return {
|
|
4586
4779
|
key: new Uint8Array(keyBits),
|
|
4587
4780
|
nonce: new Uint8Array(nonceBits)
|
|
4588
4781
|
};
|
|
4589
4782
|
}
|
|
4783
|
+
async function deriveAesKeyAndNonce(nk, commitmentHex) {
|
|
4784
|
+
const ikm = await importNkHkdfKey(nk);
|
|
4785
|
+
return deriveAesKeyAndNonceFromIkm(ikm, hexToBytes32(commitmentHex));
|
|
4786
|
+
}
|
|
4787
|
+
function decodeChainNotePlaintext(version, plaintext, commitmentHex) {
|
|
4788
|
+
if (version === NOTE_VERSION_V4) {
|
|
4789
|
+
if (plaintext.length !== PLAINTEXT_LEN_V4) {
|
|
4790
|
+
throw new Error(`Invalid v4 chain note plaintext length: ${plaintext.length}`);
|
|
4791
|
+
}
|
|
4792
|
+
return {
|
|
4793
|
+
timestamp: readU64LE(plaintext, 0),
|
|
4794
|
+
commitment: commitmentHex.toLowerCase(),
|
|
4795
|
+
noteSalt: readU256BE(plaintext, TIMESTAMP_LEN),
|
|
4796
|
+
outAmount0: readU64LE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN),
|
|
4797
|
+
outPubkey0: readU256BE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN + OUT_AMOUNT_LEN),
|
|
4798
|
+
isSendToSelfKey0: BigInt(plaintext[PLAINTEXT_LEN_V4 - 1])
|
|
4799
|
+
};
|
|
4800
|
+
}
|
|
4801
|
+
if (version === NOTE_VERSION_V3) {
|
|
4802
|
+
if (plaintext.length !== PLAINTEXT_LEN_V3) {
|
|
4803
|
+
throw new Error(`Invalid v3 chain note plaintext length: ${plaintext.length}`);
|
|
4804
|
+
}
|
|
4805
|
+
return {
|
|
4806
|
+
timestamp: readU64LE(plaintext, 0),
|
|
4807
|
+
commitment: commitmentHex.toLowerCase(),
|
|
4808
|
+
noteSalt: readU256BE(plaintext, TIMESTAMP_LEN)
|
|
4809
|
+
};
|
|
4810
|
+
}
|
|
4811
|
+
if (plaintext.length !== PLAINTEXT_LEN_V2) {
|
|
4812
|
+
throw new Error(`Invalid v2 chain note plaintext length: ${plaintext.length}`);
|
|
4813
|
+
}
|
|
4814
|
+
return {
|
|
4815
|
+
timestamp: readU64LE(plaintext, 0),
|
|
4816
|
+
commitment: commitmentHex.toLowerCase()
|
|
4817
|
+
};
|
|
4818
|
+
}
|
|
4590
4819
|
async function encryptCompactChainNote(timestamp, nk, commitmentHex, noteSalt, semantics) {
|
|
4591
4820
|
if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
|
|
4592
4821
|
throw new Error("nk must be 32 bytes");
|
|
@@ -4650,36 +4879,7 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
|
|
|
4650
4879
|
try {
|
|
4651
4880
|
const { key, nonce } = await deriveAesKeyAndNonce(nk, commitment);
|
|
4652
4881
|
const plaintext = await aesGcmDecrypt2(ciphertext, key, nonce);
|
|
4653
|
-
|
|
4654
|
-
if (plaintext.length !== PLAINTEXT_LEN_V4) {
|
|
4655
|
-
throw new Error(`Invalid v4 chain note plaintext length: ${plaintext.length}`);
|
|
4656
|
-
}
|
|
4657
|
-
return {
|
|
4658
|
-
timestamp: readU64LE(plaintext, 0),
|
|
4659
|
-
commitment: commitment.toLowerCase(),
|
|
4660
|
-
noteSalt: readU256BE(plaintext, TIMESTAMP_LEN),
|
|
4661
|
-
outAmount0: readU64LE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN),
|
|
4662
|
-
outPubkey0: readU256BE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN + OUT_AMOUNT_LEN),
|
|
4663
|
-
isSendToSelfKey0: BigInt(plaintext[PLAINTEXT_LEN_V4 - 1])
|
|
4664
|
-
};
|
|
4665
|
-
}
|
|
4666
|
-
if (version === NOTE_VERSION_V3) {
|
|
4667
|
-
if (plaintext.length !== PLAINTEXT_LEN_V3) {
|
|
4668
|
-
throw new Error(`Invalid v3 chain note plaintext length: ${plaintext.length}`);
|
|
4669
|
-
}
|
|
4670
|
-
return {
|
|
4671
|
-
timestamp: readU64LE(plaintext, 0),
|
|
4672
|
-
commitment: commitment.toLowerCase(),
|
|
4673
|
-
noteSalt: readU256BE(plaintext, TIMESTAMP_LEN)
|
|
4674
|
-
};
|
|
4675
|
-
}
|
|
4676
|
-
if (plaintext.length !== PLAINTEXT_LEN_V2) {
|
|
4677
|
-
throw new Error(`Invalid v2 chain note plaintext length: ${plaintext.length}`);
|
|
4678
|
-
}
|
|
4679
|
-
return {
|
|
4680
|
-
timestamp: readU64LE(plaintext, 0),
|
|
4681
|
-
commitment: commitment.toLowerCase()
|
|
4682
|
-
};
|
|
4882
|
+
return decodeChainNotePlaintext(version, plaintext, commitment);
|
|
4683
4883
|
} catch (error) {
|
|
4684
4884
|
lastError = error;
|
|
4685
4885
|
}
|
|
@@ -4688,6 +4888,26 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
|
|
|
4688
4888
|
`Failed to decrypt compact chain note with provided commitments: ${lastError instanceof Error ? lastError.message : String(lastError)}`
|
|
4689
4889
|
);
|
|
4690
4890
|
}
|
|
4891
|
+
async function createCompactChainNoteDecryptor(nk) {
|
|
4892
|
+
const ikm = await importNkHkdfKey(nk);
|
|
4893
|
+
return async (noteBytes, commitment) => {
|
|
4894
|
+
if (!(noteBytes instanceof Uint8Array) || noteBytes.length <= 1) return null;
|
|
4895
|
+
if (!(commitment instanceof Uint8Array) || commitment.length !== 32) return null;
|
|
4896
|
+
const version = noteBytes[0];
|
|
4897
|
+
if (version !== NOTE_VERSION_V4 && version !== NOTE_VERSION_V3 && version !== NOTE_VERSION_V2) {
|
|
4898
|
+
return null;
|
|
4899
|
+
}
|
|
4900
|
+
try {
|
|
4901
|
+
const { key, nonce } = await deriveAesKeyAndNonceFromIkm(ikm, commitment);
|
|
4902
|
+
const plaintext = await aesGcmDecrypt2(noteBytes.subarray(1), key, nonce);
|
|
4903
|
+
let hex = "";
|
|
4904
|
+
for (let i = 0; i < 32; i++) hex += commitment[i].toString(16).padStart(2, "0");
|
|
4905
|
+
return decodeChainNotePlaintext(version, plaintext, hex);
|
|
4906
|
+
} catch {
|
|
4907
|
+
return null;
|
|
4908
|
+
}
|
|
4909
|
+
};
|
|
4910
|
+
}
|
|
4691
4911
|
function chainNoteToBase64(noteBytes) {
|
|
4692
4912
|
return Buffer.from(noteBytes).toString("base64");
|
|
4693
4913
|
}
|
|
@@ -4784,6 +5004,80 @@ function openRecipientDeliveryNote(envelope, viewingSecretKey) {
|
|
|
4784
5004
|
return null;
|
|
4785
5005
|
}
|
|
4786
5006
|
}
|
|
5007
|
+
var X25519_PKCS8_PREFIX = Uint8Array.from([
|
|
5008
|
+
48,
|
|
5009
|
+
46,
|
|
5010
|
+
2,
|
|
5011
|
+
1,
|
|
5012
|
+
0,
|
|
5013
|
+
48,
|
|
5014
|
+
5,
|
|
5015
|
+
6,
|
|
5016
|
+
3,
|
|
5017
|
+
43,
|
|
5018
|
+
101,
|
|
5019
|
+
110,
|
|
5020
|
+
4,
|
|
5021
|
+
34,
|
|
5022
|
+
4,
|
|
5023
|
+
32
|
|
5024
|
+
]);
|
|
5025
|
+
var HSALSA_SIGMA = new TextEncoder().encode("expand 32-byte k");
|
|
5026
|
+
function decodeOpened(plaintext) {
|
|
5027
|
+
if (!plaintext || plaintext.length !== RECIPIENT_DELIVERY_PLAINTEXT_LEN) return null;
|
|
5028
|
+
return { amount: readU64LE2(plaintext, 0), blinding: readU256BE2(plaintext, 8) };
|
|
5029
|
+
}
|
|
5030
|
+
async function createRecipientDeliveryOpener(viewingSecretKey) {
|
|
5031
|
+
if (!(viewingSecretKey instanceof Uint8Array) || viewingSecretKey.length !== 32) {
|
|
5032
|
+
throw new Error("viewingSecretKey must be 32 bytes");
|
|
5033
|
+
}
|
|
5034
|
+
const slow = async (envelope) => openRecipientDeliveryNote(envelope, viewingSecretKey);
|
|
5035
|
+
const subtle = globalThis.crypto?.subtle;
|
|
5036
|
+
const hsalsa = nacl4.lowlevel?.crypto_core_hsalsa20;
|
|
5037
|
+
if (!subtle || typeof hsalsa !== "function") return slow;
|
|
5038
|
+
let privateKey;
|
|
5039
|
+
const sharedKey = async (ephemeralPk) => {
|
|
5040
|
+
const publicKey = await subtle.importKey("raw", new Uint8Array(ephemeralPk), { name: "X25519" }, false, []);
|
|
5041
|
+
const shared = new Uint8Array(
|
|
5042
|
+
await subtle.deriveBits({ name: "X25519", public: publicKey }, privateKey, 256)
|
|
5043
|
+
);
|
|
5044
|
+
const key = new Uint8Array(32);
|
|
5045
|
+
hsalsa(key, new Uint8Array(16), shared, HSALSA_SIGMA);
|
|
5046
|
+
return key;
|
|
5047
|
+
};
|
|
5048
|
+
try {
|
|
5049
|
+
const pkcs8 = new Uint8Array(X25519_PKCS8_PREFIX.length + 32);
|
|
5050
|
+
pkcs8.set(X25519_PKCS8_PREFIX);
|
|
5051
|
+
pkcs8.set(viewingSecretKey, X25519_PKCS8_PREFIX.length);
|
|
5052
|
+
privateKey = await subtle.importKey("pkcs8", pkcs8, { name: "X25519" }, false, ["deriveBits"]);
|
|
5053
|
+
const probe = nacl4.box.keyPair().publicKey;
|
|
5054
|
+
const fast = await sharedKey(probe);
|
|
5055
|
+
const reference = nacl4.box.before(probe, viewingSecretKey);
|
|
5056
|
+
if (fast.length !== reference.length || fast.some((b, i) => b !== reference[i])) return slow;
|
|
5057
|
+
} catch {
|
|
5058
|
+
return slow;
|
|
5059
|
+
}
|
|
5060
|
+
return async (envelope) => {
|
|
5061
|
+
if (!(envelope instanceof Uint8Array) || envelope.length !== RECIPIENT_DELIVERY_NOTE_BYTES) return null;
|
|
5062
|
+
const ephemeralPk = envelope.subarray(0, RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN);
|
|
5063
|
+
const nonce = envelope.subarray(
|
|
5064
|
+
RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
|
|
5065
|
+
RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN
|
|
5066
|
+
);
|
|
5067
|
+
const ciphertext = envelope.subarray(RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN);
|
|
5068
|
+
let key;
|
|
5069
|
+
try {
|
|
5070
|
+
key = await sharedKey(ephemeralPk);
|
|
5071
|
+
} catch {
|
|
5072
|
+
return openRecipientDeliveryNote(envelope, viewingSecretKey);
|
|
5073
|
+
}
|
|
5074
|
+
try {
|
|
5075
|
+
return decodeOpened(nacl4.secretbox.open(ciphertext, nonce, key));
|
|
5076
|
+
} catch {
|
|
5077
|
+
return null;
|
|
5078
|
+
}
|
|
5079
|
+
};
|
|
5080
|
+
}
|
|
4787
5081
|
function recipientDeliveryNoteToBase64(envelope) {
|
|
4788
5082
|
return Buffer.from(envelope).toString("base64");
|
|
4789
5083
|
}
|
|
@@ -4836,9 +5130,41 @@ function parseDeliveryCarrierMemo(data) {
|
|
|
4836
5130
|
// src/notes/swap-refund.ts
|
|
4837
5131
|
import { blake3 as blake33 } from "@noble/hashes/blake3";
|
|
4838
5132
|
import _bs582 from "bs58";
|
|
5133
|
+
|
|
5134
|
+
// src/notes/owner-key.ts
|
|
5135
|
+
var FIELD_MODULUS = BigInt(
|
|
5136
|
+
"21888242871839275222246405745257275088548364400416034343698204186575808495617"
|
|
5137
|
+
);
|
|
5138
|
+
async function assertOwnerUtxoKeypair(keypair, label = "ownerUtxoKeypair") {
|
|
5139
|
+
if (!keypair || typeof keypair !== "object") {
|
|
5140
|
+
throw new Error(
|
|
5141
|
+
`${label} is required: pass the wallet's long-lived UTXO keypair (deriveUtxoKeypairFromSpendKey(skSpend)). Self-owned notes are never owned by a key derived from the viewing key nk.`
|
|
5142
|
+
);
|
|
5143
|
+
}
|
|
5144
|
+
const { privateKey, publicKey } = keypair;
|
|
5145
|
+
if (typeof privateKey !== "bigint" || privateKey <= 0n || privateKey >= FIELD_MODULUS) {
|
|
5146
|
+
throw new Error(`${label}.privateKey must be a non-zero field element (bigint)`);
|
|
5147
|
+
}
|
|
5148
|
+
if (typeof publicKey !== "bigint" || publicKey === 0n) {
|
|
5149
|
+
throw new Error(`${label}.publicKey must be a non-zero bigint`);
|
|
5150
|
+
}
|
|
5151
|
+
if (await derivePublicKey(privateKey) !== publicKey) {
|
|
5152
|
+
throw new Error(`${label}.publicKey is not derived from ${label}.privateKey`);
|
|
5153
|
+
}
|
|
5154
|
+
return { privateKey, publicKey };
|
|
5155
|
+
}
|
|
5156
|
+
function normalizeOwnerPublicKey(publicKey, label) {
|
|
5157
|
+
if (publicKey === void 0 || publicKey === null) return void 0;
|
|
5158
|
+
if (typeof publicKey !== "bigint" || publicKey <= 0n || publicKey >= FIELD_MODULUS) {
|
|
5159
|
+
throw new Error(`${label} must be a non-zero field element (bigint)`);
|
|
5160
|
+
}
|
|
5161
|
+
return publicKey;
|
|
5162
|
+
}
|
|
5163
|
+
|
|
5164
|
+
// src/notes/swap-refund.ts
|
|
4839
5165
|
var bs582 = _bs582.default || _bs582;
|
|
4840
5166
|
var REFUND_SEED_DOMAIN = new TextEncoder().encode("cloak_swap_refund_v1");
|
|
4841
|
-
var
|
|
5167
|
+
var LEGACY_REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
|
|
4842
5168
|
var REFUND_BLINDING_INFO = new TextEncoder().encode("blinding");
|
|
4843
5169
|
function normalizeNullifier(inputNullifier) {
|
|
4844
5170
|
if (inputNullifier instanceof Uint8Array) {
|
|
@@ -4872,13 +5198,29 @@ function derive(nk, nullifier, info) {
|
|
|
4872
5198
|
preimage.set(info, off);
|
|
4873
5199
|
return blake33(preimage);
|
|
4874
5200
|
}
|
|
4875
|
-
|
|
5201
|
+
function assertNk(viewingKeyNk) {
|
|
4876
5202
|
if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
|
|
4877
5203
|
throw new Error("viewingKeyNk must be 32 bytes");
|
|
4878
5204
|
}
|
|
5205
|
+
return viewingKeyNk;
|
|
5206
|
+
}
|
|
5207
|
+
function deriveSwapRefundBlinding(viewingKeyNk, inputNullifier) {
|
|
5208
|
+
const nk = assertNk(viewingKeyNk);
|
|
5209
|
+
return toFieldSecret(derive(nk, normalizeNullifier(inputNullifier), REFUND_BLINDING_INFO));
|
|
5210
|
+
}
|
|
5211
|
+
async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier, ownerUtxoKeypair) {
|
|
5212
|
+
const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
|
|
5213
|
+
const blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
|
|
5214
|
+
if (owner.publicKey === 0n || blinding === 0n) {
|
|
5215
|
+
throw new Error("refund authorization is degenerate");
|
|
5216
|
+
}
|
|
5217
|
+
return { privateKey: owner.privateKey, publicKey: owner.publicKey, blinding };
|
|
5218
|
+
}
|
|
5219
|
+
async function deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier) {
|
|
5220
|
+
const nk = assertNk(viewingKeyNk);
|
|
4879
5221
|
const nullifier = normalizeNullifier(inputNullifier);
|
|
4880
|
-
const privateKey = toFieldSecret(derive(
|
|
4881
|
-
const blinding = toFieldSecret(derive(
|
|
5222
|
+
const privateKey = toFieldSecret(derive(nk, nullifier, LEGACY_REFUND_PRIVATE_KEY_INFO));
|
|
5223
|
+
const blinding = toFieldSecret(derive(nk, nullifier, REFUND_BLINDING_INFO));
|
|
4882
5224
|
const publicKey = await derivePublicKey(privateKey);
|
|
4883
5225
|
if (publicKey === 0n || blinding === 0n) {
|
|
4884
5226
|
throw new Error("derived refund authorization is degenerate");
|
|
@@ -4896,19 +5238,39 @@ async function computeSwapRefundCommitment(amountAfterFee, refundPublicKey, refu
|
|
|
4896
5238
|
async function matchSwapRefundLeaf(params) {
|
|
4897
5239
|
const { viewingKeyNk, inputNullifier, amountAfterFee } = params;
|
|
4898
5240
|
const expected = params.commitment instanceof Uint8Array ? BigInt("0x" + Buffer.from(params.commitment).toString("hex")) : params.commitment;
|
|
4899
|
-
let
|
|
5241
|
+
let blinding;
|
|
5242
|
+
try {
|
|
5243
|
+
blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
|
|
5244
|
+
} catch {
|
|
5245
|
+
return null;
|
|
5246
|
+
}
|
|
5247
|
+
const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
|
|
5248
|
+
if (ownerPub !== void 0) {
|
|
5249
|
+
const candidate = await computeSwapRefundCommitment(amountAfterFee, ownerPub, blinding);
|
|
5250
|
+
if (candidate === expected) {
|
|
5251
|
+
return {
|
|
5252
|
+
keypair: { privateKey: params.ownerUtxoKeypair?.privateKey ?? 0n, publicKey: ownerPub },
|
|
5253
|
+
blinding,
|
|
5254
|
+
amount: amountAfterFee,
|
|
5255
|
+
commitment: candidate,
|
|
5256
|
+
legacyExposed: false
|
|
5257
|
+
};
|
|
5258
|
+
}
|
|
5259
|
+
}
|
|
5260
|
+
let legacy;
|
|
4900
5261
|
try {
|
|
4901
|
-
|
|
5262
|
+
legacy = await deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier);
|
|
4902
5263
|
} catch {
|
|
4903
5264
|
return null;
|
|
4904
5265
|
}
|
|
4905
|
-
const
|
|
4906
|
-
if (
|
|
5266
|
+
const legacyCandidate = await computeSwapRefundCommitment(amountAfterFee, legacy.publicKey, legacy.blinding);
|
|
5267
|
+
if (legacyCandidate !== expected) return null;
|
|
4907
5268
|
return {
|
|
4908
|
-
keypair: { privateKey:
|
|
4909
|
-
blinding:
|
|
5269
|
+
keypair: { privateKey: legacy.privateKey, publicKey: legacy.publicKey },
|
|
5270
|
+
blinding: legacy.blinding,
|
|
4910
5271
|
amount: amountAfterFee,
|
|
4911
|
-
commitment:
|
|
5272
|
+
commitment: legacyCandidate,
|
|
5273
|
+
legacyExposed: true
|
|
4912
5274
|
};
|
|
4913
5275
|
}
|
|
4914
5276
|
var TRANSACT_SWAP_TAG2 = 1;
|
|
@@ -4972,10 +5334,16 @@ function instructionsForProgram(tx, accountKeys, programIdBase58) {
|
|
|
4972
5334
|
if (Array.isArray(inner)) for (const block of inner) take(block?.instructions);
|
|
4973
5335
|
return out;
|
|
4974
5336
|
}
|
|
4975
|
-
async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
|
|
5337
|
+
async function discoverSwapRefunds(connection, programId, viewingKeyNk, options) {
|
|
4976
5338
|
if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
|
|
4977
5339
|
throw new Error("viewingKeyNk must be 32 bytes");
|
|
4978
5340
|
}
|
|
5341
|
+
if (!options || normalizeOwnerPublicKey(options.ownerUtxoKeypair?.publicKey, "options.ownerUtxoKeypair.publicKey") === void 0) {
|
|
5342
|
+
throw new Error(
|
|
5343
|
+
"discoverSwapRefunds requires options.ownerUtxoKeypair (the wallet's long-lived UTXO keypair): refund leaves are owned by it, and nk alone can only find legacy refunds."
|
|
5344
|
+
);
|
|
5345
|
+
}
|
|
5346
|
+
const ownerUtxoKeypair = options.ownerUtxoKeypair;
|
|
4979
5347
|
const { limit = 0, untilSignature, batchSize = 50, onStatus } = options;
|
|
4980
5348
|
const poolMint = options.poolMint ?? NATIVE_SOL_MINT;
|
|
4981
5349
|
const programIdBase58 = programId;
|
|
@@ -5050,7 +5418,8 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
|
|
|
5050
5418
|
viewingKeyNk,
|
|
5051
5419
|
inputNullifier: candidate.nullifier,
|
|
5052
5420
|
amountAfterFee: event.amountAfterFee,
|
|
5053
|
-
commitment: event.commitmentField
|
|
5421
|
+
commitment: event.commitmentField,
|
|
5422
|
+
ownerUtxoKeypair
|
|
5054
5423
|
});
|
|
5055
5424
|
if (!recovered) continue;
|
|
5056
5425
|
const dedupe = `${close.signature}:${event.leafIndex}`;
|
|
@@ -5074,7 +5443,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
|
|
|
5074
5443
|
// src/notes/deposit-note.ts
|
|
5075
5444
|
import { blake3 as blake34 } from "@noble/hashes/blake3";
|
|
5076
5445
|
var DEPOSIT_NOTE_DOMAIN = new TextEncoder().encode("cloak_deposit_note_v1");
|
|
5077
|
-
var
|
|
5446
|
+
var LEGACY_DEPOSIT_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
|
|
5078
5447
|
var DEPOSIT_BLINDING_INFO = new TextEncoder().encode("blinding");
|
|
5079
5448
|
var CHAIN_NOTE_SALT_BITS = 96;
|
|
5080
5449
|
var MAX_CHAIN_NOTE_SALT = (1n << BigInt(CHAIN_NOTE_SALT_BITS)) - 1n;
|
|
@@ -5110,30 +5479,47 @@ function derive2(nk, salt, info) {
|
|
|
5110
5479
|
preimage.set(info, off);
|
|
5111
5480
|
return blake34(preimage);
|
|
5112
5481
|
}
|
|
5482
|
+
function assertNk2(viewingKeyNk) {
|
|
5483
|
+
if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
|
|
5484
|
+
throw new Error("viewingKeyNk must be 32 bytes");
|
|
5485
|
+
}
|
|
5486
|
+
return viewingKeyNk;
|
|
5487
|
+
}
|
|
5113
5488
|
function randomDepositNoteSalt() {
|
|
5114
5489
|
const bytes = randomBytes(12);
|
|
5115
5490
|
let v = 0n;
|
|
5116
5491
|
for (const b of bytes) v = v << 8n | BigInt(b);
|
|
5117
5492
|
return v === 0n ? 1n : v;
|
|
5118
5493
|
}
|
|
5119
|
-
|
|
5120
|
-
|
|
5121
|
-
|
|
5122
|
-
|
|
5494
|
+
function deriveDepositNoteBlinding(viewingKeyNk, noteSalt) {
|
|
5495
|
+
const nk = assertNk2(viewingKeyNk);
|
|
5496
|
+
return toFieldSecret2(derive2(nk, saltToBytes(noteSalt), DEPOSIT_BLINDING_INFO));
|
|
5497
|
+
}
|
|
5498
|
+
async function deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt) {
|
|
5499
|
+
const nk = assertNk2(viewingKeyNk);
|
|
5123
5500
|
const salt = saltToBytes(noteSalt);
|
|
5124
|
-
const privateKey = toFieldSecret2(derive2(
|
|
5125
|
-
const blinding = toFieldSecret2(derive2(
|
|
5501
|
+
const privateKey = toFieldSecret2(derive2(nk, salt, LEGACY_DEPOSIT_PRIVATE_KEY_INFO));
|
|
5502
|
+
const blinding = toFieldSecret2(derive2(nk, salt, DEPOSIT_BLINDING_INFO));
|
|
5126
5503
|
const publicKey = await derivePublicKey(privateKey);
|
|
5127
5504
|
if (publicKey === 0n || blinding === 0n) {
|
|
5128
5505
|
throw new Error("derived deposit note secrets are degenerate");
|
|
5129
5506
|
}
|
|
5130
5507
|
return { keypair: { privateKey, publicKey }, blinding };
|
|
5131
5508
|
}
|
|
5132
|
-
async function createRecoverableDepositUtxo(
|
|
5509
|
+
async function createRecoverableDepositUtxo(params) {
|
|
5510
|
+
if (!params || typeof params !== "object" || params instanceof Uint8Array) {
|
|
5511
|
+
throw new Error(
|
|
5512
|
+
"createRecoverableDepositUtxo takes one options object: { amount, viewingKeyNk, ownerUtxoKeypair, mintAddress?, noteSalt? }"
|
|
5513
|
+
);
|
|
5514
|
+
}
|
|
5515
|
+
const { amount, viewingKeyNk } = params;
|
|
5133
5516
|
if (typeof amount !== "bigint" || amount <= 0n) {
|
|
5134
5517
|
throw new Error("amount must be a positive bigint");
|
|
5135
5518
|
}
|
|
5136
|
-
const
|
|
5519
|
+
const keypair = await assertOwnerUtxoKeypair(params.ownerUtxoKeypair);
|
|
5520
|
+
const mintAddress = params.mintAddress ?? NATIVE_SOL_MINT;
|
|
5521
|
+
const noteSalt = params.noteSalt ?? randomDepositNoteSalt();
|
|
5522
|
+
const blinding = deriveDepositNoteBlinding(viewingKeyNk, noteSalt);
|
|
5137
5523
|
const utxo = { amount, keypair, blinding, mintAddress };
|
|
5138
5524
|
utxo.commitment = await computeCommitment(utxo);
|
|
5139
5525
|
return { utxo, noteSalt };
|
|
@@ -5148,21 +5534,46 @@ function normalizeCommitment(value) {
|
|
|
5148
5534
|
async function matchDepositNote(params) {
|
|
5149
5535
|
const { viewingKeyNk, noteSalt, amount, mintAddress, outputCommitments } = params;
|
|
5150
5536
|
if (typeof amount !== "bigint" || amount <= 0n) return null;
|
|
5151
|
-
let
|
|
5537
|
+
let blinding;
|
|
5152
5538
|
try {
|
|
5153
|
-
|
|
5539
|
+
blinding = deriveDepositNoteBlinding(viewingKeyNk, noteSalt);
|
|
5154
5540
|
} catch {
|
|
5155
5541
|
return null;
|
|
5156
5542
|
}
|
|
5157
|
-
const
|
|
5543
|
+
const published = (outputCommitments ?? []).map(normalizeCommitment).filter((value) => value !== null);
|
|
5544
|
+
if (published.length === 0) return null;
|
|
5545
|
+
const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
|
|
5546
|
+
if (ownerPub !== void 0) {
|
|
5547
|
+
const keypair = {
|
|
5548
|
+
privateKey: params.ownerUtxoKeypair?.privateKey ?? 0n,
|
|
5549
|
+
publicKey: ownerPub
|
|
5550
|
+
};
|
|
5551
|
+
const candidate = await computeCommitment({ amount, keypair, blinding, mintAddress });
|
|
5552
|
+
if (published.some((value) => value === candidate)) {
|
|
5553
|
+
return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt, legacyExposed: false };
|
|
5554
|
+
}
|
|
5555
|
+
}
|
|
5556
|
+
let legacy;
|
|
5557
|
+
try {
|
|
5558
|
+
legacy = await deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt);
|
|
5559
|
+
} catch {
|
|
5560
|
+
return null;
|
|
5561
|
+
}
|
|
5562
|
+
const legacyCandidate = await computeCommitment({
|
|
5158
5563
|
amount,
|
|
5159
|
-
keypair:
|
|
5160
|
-
blinding:
|
|
5564
|
+
keypair: legacy.keypair,
|
|
5565
|
+
blinding: legacy.blinding,
|
|
5161
5566
|
mintAddress
|
|
5162
5567
|
});
|
|
5163
|
-
|
|
5164
|
-
|
|
5165
|
-
|
|
5568
|
+
if (!published.some((value) => value === legacyCandidate)) return null;
|
|
5569
|
+
return {
|
|
5570
|
+
...legacy,
|
|
5571
|
+
amount,
|
|
5572
|
+
mintAddress,
|
|
5573
|
+
commitment: legacyCandidate,
|
|
5574
|
+
noteSalt,
|
|
5575
|
+
legacyExposed: true
|
|
5576
|
+
};
|
|
5166
5577
|
}
|
|
5167
5578
|
|
|
5168
5579
|
// src/notes/change-note.ts
|
|
@@ -5218,10 +5629,11 @@ function deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex) {
|
|
|
5218
5629
|
preimage.set(CHANGE_BLINDING_INFO, off);
|
|
5219
5630
|
return toFieldSecret3(blake35(preimage));
|
|
5220
5631
|
}
|
|
5221
|
-
async function createRecoverableChangeUtxo(amount,
|
|
5632
|
+
async function createRecoverableChangeUtxo(amount, ownerUtxoKeypair, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomChangeNoteSalt(), outputIndex = 0) {
|
|
5222
5633
|
if (typeof amount !== "bigint" || amount <= 0n) {
|
|
5223
5634
|
throw new Error("amount must be a positive bigint");
|
|
5224
5635
|
}
|
|
5636
|
+
const keypair = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
|
|
5225
5637
|
const blinding = deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex);
|
|
5226
5638
|
const utxo = { amount, keypair, blinding, mintAddress };
|
|
5227
5639
|
utxo.commitment = await computeCommitment(utxo);
|
|
@@ -5247,13 +5659,27 @@ async function matchChangeNote(params) {
|
|
|
5247
5659
|
const candidate = await computeCommitment({ amount, keypair, blinding, mintAddress });
|
|
5248
5660
|
const published = (outputCommitments ?? []).map(normalizeCommitment2).filter((value) => value !== null);
|
|
5249
5661
|
if (!published.some((value) => value === candidate)) return null;
|
|
5250
|
-
|
|
5662
|
+
const walletKey = normalizeOwnerPublicKey(params.ownerUtxoPublicKey, "ownerUtxoPublicKey");
|
|
5663
|
+
const legacyExposed = walletKey !== void 0 && keypair.publicKey !== walletKey;
|
|
5664
|
+
return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt, legacyExposed };
|
|
5251
5665
|
}
|
|
5252
5666
|
|
|
5253
5667
|
// src/flows/transact.ts
|
|
5254
5668
|
import { buildPoseidon as buildPoseidon2 } from "circomlibjs";
|
|
5255
5669
|
import nacl5 from "tweetnacl";
|
|
5256
5670
|
|
|
5671
|
+
// src/relay/chain-note-time.ts
|
|
5672
|
+
async function relayChainNoteTimestampMs(relayUrl) {
|
|
5673
|
+
if (relayUrl && !hasRelayClockSample()) {
|
|
5674
|
+
try {
|
|
5675
|
+
const response = await relayFetch(`${relayUrl.replace(/\/$/, "")}/health`);
|
|
5676
|
+
await response.body?.cancel?.().catch(() => void 0);
|
|
5677
|
+
} catch {
|
|
5678
|
+
}
|
|
5679
|
+
}
|
|
5680
|
+
return BigInt(relayNowMs());
|
|
5681
|
+
}
|
|
5682
|
+
|
|
5257
5683
|
// src/proving/artifacts.ts
|
|
5258
5684
|
import { sha256 as sha2564 } from "@noble/hashes/sha2";
|
|
5259
5685
|
|
|
@@ -5874,6 +6300,9 @@ function assertInputMints(inputUtxos, expectedMint) {
|
|
|
5874
6300
|
);
|
|
5875
6301
|
}
|
|
5876
6302
|
}
|
|
6303
|
+
function affiliateCodeOrUndefined(code) {
|
|
6304
|
+
return typeof code === "string" && code.length > 0 ? code : void 0;
|
|
6305
|
+
}
|
|
5877
6306
|
function parseNkInput(input) {
|
|
5878
6307
|
if (typeof input !== "string") {
|
|
5879
6308
|
if (input.length !== 32) {
|
|
@@ -5887,6 +6316,33 @@ function parseNkInput(input) {
|
|
|
5887
6316
|
}
|
|
5888
6317
|
return Uint8Array.from(Buffer.from(clean, "hex"));
|
|
5889
6318
|
}
|
|
6319
|
+
async function resolveWalletNk(options) {
|
|
6320
|
+
const explicit = await resolveChainNoteNk(options);
|
|
6321
|
+
if (explicit) return explicit;
|
|
6322
|
+
if (options.ownerUtxoKeypair) {
|
|
6323
|
+
const owner = await assertOwnerUtxoKeypair(options.ownerUtxoKeypair);
|
|
6324
|
+
return getNkFromUtxoPrivateKey(owner.privateKey);
|
|
6325
|
+
}
|
|
6326
|
+
return null;
|
|
6327
|
+
}
|
|
6328
|
+
function missingWalletNkError(flow) {
|
|
6329
|
+
return new Error(
|
|
6330
|
+
`${flow} requires the wallet's viewing key: pass chainNoteViewingKeyNk (or getChainNoteViewingKeyNk), or ownerUtxoKeypair to use its canonical nk. The SDK no longer infers nk from a note's own key.`
|
|
6331
|
+
);
|
|
6332
|
+
}
|
|
6333
|
+
async function requireWalletNk(options, flow) {
|
|
6334
|
+
const nk = await resolveWalletNk(options);
|
|
6335
|
+
if (nk) return nk;
|
|
6336
|
+
throw missingWalletNkError(flow);
|
|
6337
|
+
}
|
|
6338
|
+
async function requireOwnerUtxoKeypair(options, flow) {
|
|
6339
|
+
if (!options.ownerUtxoKeypair) {
|
|
6340
|
+
throw new Error(
|
|
6341
|
+
`${flow} requires options.ownerUtxoKeypair, the wallet's long-lived UTXO keypair (deriveUtxoKeypairFromSpendKey(skSpend)). It owns the change and refund notes this flow creates; the SDK no longer inherits that owner from inputUtxos[0].`
|
|
6342
|
+
);
|
|
6343
|
+
}
|
|
6344
|
+
return assertOwnerUtxoKeypair(options.ownerUtxoKeypair, "options.ownerUtxoKeypair");
|
|
6345
|
+
}
|
|
5890
6346
|
async function resolveChainNoteNk(options) {
|
|
5891
6347
|
if (options.chainNoteViewingKeyNk) {
|
|
5892
6348
|
return parseNkInput(options.chainNoteViewingKeyNk);
|
|
@@ -5904,7 +6360,7 @@ function shouldDefaultUseUniqueNullifiers(_connection) {
|
|
|
5904
6360
|
function toHex(bytes) {
|
|
5905
6361
|
return Buffer.from(bytes).toString("hex");
|
|
5906
6362
|
}
|
|
5907
|
-
async function ensureViewingKeyRegistered(options, onProgress,
|
|
6363
|
+
async function ensureViewingKeyRegistered(options, onProgress, walletNk) {
|
|
5908
6364
|
if (options.enforceViewingKeyRegistration === false) {
|
|
5909
6365
|
return;
|
|
5910
6366
|
}
|
|
@@ -5918,7 +6374,7 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
|
|
|
5918
6374
|
"Viewing key registration is mandatory: walletPublicKey or depositor public key is required."
|
|
5919
6375
|
);
|
|
5920
6376
|
}
|
|
5921
|
-
const nk =
|
|
6377
|
+
const nk = walletNk;
|
|
5922
6378
|
if (!nk || nk.length !== 32) {
|
|
5923
6379
|
throw new Error(
|
|
5924
6380
|
"Viewing key registration is mandatory: provide a chain-note viewing key (nk)."
|
|
@@ -6060,10 +6516,10 @@ function buildPublicInputsBytesFromSignals(publicSignals) {
|
|
|
6060
6516
|
result.set(bigintToBytes322(BigInt(publicSignals[0])), offset);
|
|
6061
6517
|
offset += 32;
|
|
6062
6518
|
let amount = BigInt(publicSignals[1]);
|
|
6063
|
-
const
|
|
6064
|
-
const HALF_FIELD =
|
|
6519
|
+
const FIELD_MODULUS2 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
|
|
6520
|
+
const HALF_FIELD = FIELD_MODULUS2 / BigInt(2);
|
|
6065
6521
|
if (amount > HALF_FIELD) {
|
|
6066
|
-
amount = amount -
|
|
6522
|
+
amount = amount - FIELD_MODULUS2;
|
|
6067
6523
|
}
|
|
6068
6524
|
const amountBytes = new Uint8Array(8);
|
|
6069
6525
|
let amountValue = amount;
|
|
@@ -7010,8 +7466,9 @@ function chargeWalletApproval(used, budget, lastError) {
|
|
|
7010
7466
|
}
|
|
7011
7467
|
return used + 1;
|
|
7012
7468
|
}
|
|
7013
|
-
function relayFailureMessage(prefix, responseText) {
|
|
7014
|
-
const
|
|
7469
|
+
function relayFailureMessage(prefix, responseText, requestBody) {
|
|
7470
|
+
const carriedAffiliateCode = typeof requestBody?.affiliate_code === "string";
|
|
7471
|
+
const explanation = explainRelayAuthRejection(responseText, { carriedAffiliateCode });
|
|
7015
7472
|
return explanation ? `${prefix}: ${responseText}
|
|
7016
7473
|
|
|
7017
7474
|
${explanation}` : `${prefix}: ${responseText}`;
|
|
@@ -7217,6 +7674,39 @@ function buildTransactRequestBody(params) {
|
|
|
7217
7674
|
if (params.recipientDeliveryNotes && params.recipientDeliveryNotes.length > 0 && params.externalAmount === BigInt(0) && !params.recipient) {
|
|
7218
7675
|
body.recipient_delivery_notes = params.recipientDeliveryNotes;
|
|
7219
7676
|
}
|
|
7677
|
+
const affiliateCode = affiliateCodeOrUndefined(params.affiliateCode);
|
|
7678
|
+
if (affiliateCode && params.externalAmount < BigInt(0) && params.recipient) {
|
|
7679
|
+
body.affiliate_code = affiliateCode;
|
|
7680
|
+
}
|
|
7681
|
+
return body;
|
|
7682
|
+
}
|
|
7683
|
+
function buildTransactSwapRequestBody(params) {
|
|
7684
|
+
const body = {
|
|
7685
|
+
proof_bytes: params.proofB64,
|
|
7686
|
+
public_inputs: params.publicInputsB64,
|
|
7687
|
+
output_mint: params.outputMint,
|
|
7688
|
+
recipient_ata: params.recipientAta,
|
|
7689
|
+
recipient: params.recipientWallet,
|
|
7690
|
+
// The relay parses this as a u64 and rejects a JSON number ("invalid type: integer,
|
|
7691
|
+
// expected a string"). A string also removes the old 2^53 ceiling instead of guarding it.
|
|
7692
|
+
min_output_amount: params.minOutputAmount.toString(),
|
|
7693
|
+
// Proof-bound live PoolConfig snapshot; decimal string avoids JSON number precision loss.
|
|
7694
|
+
max_fee: params.maxFee.toString(),
|
|
7695
|
+
slippage_bps: params.slippageBps,
|
|
7696
|
+
dexes: params.dexes && params.dexes.length > 0 ? params.dexes : void 0,
|
|
7697
|
+
exclude_dexes: params.excludeDexes && params.excludeDexes.length > 0 ? params.excludeDexes : void 0,
|
|
7698
|
+
route_retry_attempts: params.routeRetryAttempts !== void 0 ? Math.max(0, Math.min(5, Math.floor(params.routeRetryAttempts))) : void 0,
|
|
7699
|
+
swap_max_retries: params.swapMaxRetries !== void 0 ? Math.max(1, Math.min(10, Math.floor(params.swapMaxRetries))) : void 0,
|
|
7700
|
+
encrypted_notes: params.encryptedNotes,
|
|
7701
|
+
risk_quote: params.riskQuote,
|
|
7702
|
+
// V3-04: refund-fallback owner authorization (two BN254 field elements, base64, 32 bytes each),
|
|
7703
|
+
// bound into the proof's ext_data_hash. The relay forwards both verbatim into the swap
|
|
7704
|
+
// params; the program builds the amount-bound R_fb from them at close.
|
|
7705
|
+
refund_pubkey: params.refundPubkeyB64,
|
|
7706
|
+
refund_blinding: params.refundBlindingB64
|
|
7707
|
+
};
|
|
7708
|
+
const affiliateCode = affiliateCodeOrUndefined(params.affiliateCode);
|
|
7709
|
+
if (affiliateCode) body.affiliate_code = affiliateCode;
|
|
7220
7710
|
return body;
|
|
7221
7711
|
}
|
|
7222
7712
|
function resolveUserWallet(options) {
|
|
@@ -7352,10 +7842,11 @@ async function submitTransactToRelay(args) {
|
|
|
7352
7842
|
try {
|
|
7353
7843
|
response = await doFetch(`${relayUrl}/transact`, {
|
|
7354
7844
|
method: "POST",
|
|
7355
|
-
headers: { "Content-Type": "application/json" },
|
|
7845
|
+
headers: mergeRelayHeaders({ "Content-Type": "application/json" }, args.extraHeaders),
|
|
7356
7846
|
body: requestPayload,
|
|
7357
7847
|
signal: controller.signal
|
|
7358
7848
|
});
|
|
7849
|
+
observeRelayClock(response);
|
|
7359
7850
|
} finally {
|
|
7360
7851
|
clearTimeout(timeoutId);
|
|
7361
7852
|
}
|
|
@@ -7386,7 +7877,9 @@ async function submitTransactToRelay(args) {
|
|
|
7386
7877
|
onProgress?.("Root not found (stale), will regenerate proof with fresh tree...");
|
|
7387
7878
|
return { kind: "stale-root", error: new Error(`Relay error: ${responseText}`) };
|
|
7388
7879
|
}
|
|
7389
|
-
return await resolveFailure(
|
|
7880
|
+
return await resolveFailure(
|
|
7881
|
+
new Error(relayFailureMessage("Relay error", responseText, requestBody))
|
|
7882
|
+
);
|
|
7390
7883
|
}
|
|
7391
7884
|
const apiResponse = JSON.parse(responseText);
|
|
7392
7885
|
if (!apiResponse.success || !apiResponse.data) {
|
|
@@ -7403,7 +7896,7 @@ async function submitTransactToRelay(args) {
|
|
|
7403
7896
|
return { kind: "stale-root", error: new Error(`Relay returned error: ${errorStr}`) };
|
|
7404
7897
|
}
|
|
7405
7898
|
return await resolveFailure(
|
|
7406
|
-
new Error(relayFailureMessage("Relay returned error", errorStr))
|
|
7899
|
+
new Error(relayFailureMessage("Relay returned error", errorStr, requestBody))
|
|
7407
7900
|
);
|
|
7408
7901
|
}
|
|
7409
7902
|
const result = apiResponse.data;
|
|
@@ -7511,34 +8004,37 @@ async function transact(params, options) {
|
|
|
7511
8004
|
);
|
|
7512
8005
|
}
|
|
7513
8006
|
onProgress?.("Validating transaction parameters...");
|
|
7514
|
-
const
|
|
7515
|
-
const
|
|
7516
|
-
|
|
7517
|
-
const explicitChainNoteNk = await resolveChainNoteNk(options);
|
|
7518
|
-
if (options.chainNoteSalt !== void 0 && !explicitChainNoteNk) {
|
|
8007
|
+
const walletNk = await resolveWalletNk(options);
|
|
8008
|
+
const ownerUtxoKeypair = options.ownerUtxoKeypair ? await assertOwnerUtxoKeypair(options.ownerUtxoKeypair) : void 0;
|
|
8009
|
+
if (options.chainNoteSalt !== void 0 && !walletNk) {
|
|
7519
8010
|
throw new Error(
|
|
7520
|
-
"options.chainNoteSalt requires
|
|
8011
|
+
"options.chainNoteSalt requires the wallet's viewing key: chainNoteViewingKeyNk (or getChainNoteViewingKeyNk), or ownerUtxoKeypair. The salt anchors a note derived from that nk, and the chain note has to be encrypted under the same key or the note is undiscoverable."
|
|
7521
8012
|
);
|
|
7522
8013
|
}
|
|
7523
8014
|
const chainNoteSalt = options.chainNoteSalt !== void 0 ? assertChainNoteSalt(options.chainNoteSalt) : randomChainNoteSalt();
|
|
7524
8015
|
const chainNoteWillCarrySalt = !options.disableChainNotes && !(options.encryptedNotes && options.encryptedNotes.length > 0);
|
|
7525
|
-
if (
|
|
7526
|
-
|
|
8016
|
+
if (!walletNk && (chainNoteWillCarrySalt || options.enforceViewingKeyRegistration !== false)) {
|
|
8017
|
+
throw missingWalletNkError("transact");
|
|
8018
|
+
}
|
|
8019
|
+
if (walletNk && chainNoteWillCarrySalt) {
|
|
8020
|
+
const selfOwners = new Set(inputUtxos.map((u) => u.keypair.publicKey));
|
|
8021
|
+
if (ownerUtxoKeypair) selfOwners.add(ownerUtxoKeypair.publicKey);
|
|
8022
|
+
const depositBlinding = deriveDepositNoteBlinding(walletNk, chainNoteSalt);
|
|
7527
8023
|
for (let i = 0; i < outputUtxos.length; i++) {
|
|
7528
8024
|
const out = outputUtxos[i];
|
|
7529
8025
|
if (!out || out.amount <= BigInt(0)) continue;
|
|
7530
|
-
if (!
|
|
7531
|
-
if (out.blinding !== deriveChangeNoteBlinding(
|
|
8026
|
+
if (!selfOwners.has(out.keypair.publicKey)) continue;
|
|
8027
|
+
if (out.blinding !== deriveChangeNoteBlinding(walletNk, chainNoteSalt, i) && out.blinding !== depositBlinding) {
|
|
7532
8028
|
throw new Error(
|
|
7533
|
-
`Output ${i} is change (amount ${out.amount}, owned by an input's keypair) but its blinding is not the one derivable from this wallet's viewing key. It was almost certainly built with \`createUtxo\`, whose blinding is random and is written nowhere on chain \u2014 if the caller ever drops the returned note, the funds are unspendable forever. Build change with \`createRecoverableChangeUtxo(amount, keypair, nk, mint, salt, outputIndex)\` and pass the same salt as \`options.chainNoteSalt\`, or use \`partialWithdraw\` / \`transfer\` / \`swapWithChange\`, which do it for you.`
|
|
8029
|
+
`Output ${i} is change (amount ${out.amount}, owned by an input's or the wallet's keypair) but its blinding is not the one derivable from this wallet's viewing key. It was almost certainly built with \`createUtxo\`, whose blinding is random and is written nowhere on chain \u2014 if the caller ever drops the returned note, the funds are unspendable forever. Build change with \`createRecoverableChangeUtxo(amount, keypair, nk, mint, salt, outputIndex)\` and pass the same salt as \`options.chainNoteSalt\`, or use \`partialWithdraw\` / \`transfer\` / \`swapWithChange\`, which do it for you.`
|
|
7534
8030
|
);
|
|
7535
8031
|
}
|
|
7536
8032
|
}
|
|
7537
8033
|
}
|
|
7538
8034
|
assertAllowedRpcConnection(connection);
|
|
7539
8035
|
assertInputMints(inputUtxos, options.expectedMint);
|
|
7540
|
-
await ensureViewingKeyRegistered(options, onProgress,
|
|
7541
|
-
const resolvedChainNoteNk =
|
|
8036
|
+
await ensureViewingKeyRegistered(options, onProgress, walletNk);
|
|
8037
|
+
const resolvedChainNoteNk = walletNk;
|
|
7542
8038
|
if (inputUtxos.length > 2) {
|
|
7543
8039
|
throw new Error("Maximum 2 input UTXOs allowed");
|
|
7544
8040
|
}
|
|
@@ -7912,7 +8408,7 @@ async function transact(params, options) {
|
|
|
7912
8408
|
}
|
|
7913
8409
|
const maxFee = isWithdrawal ? protocolFeeSnapshot : BigInt(0);
|
|
7914
8410
|
const extDataHash = await computeExtDataHash(recipient ?? null, relayerFee, relayer ?? null, maxFee);
|
|
7915
|
-
const chainNoteTimestamp =
|
|
8411
|
+
const chainNoteTimestamp = await relayChainNoteTimestampMs(relayUrl);
|
|
7916
8412
|
const mintField = pubkeyToFieldElement(mint);
|
|
7917
8413
|
let signature = "pending-" + Date.now().toString();
|
|
7918
8414
|
let commitmentIndices = [-1, -1];
|
|
@@ -8008,9 +8504,9 @@ async function transact(params, options) {
|
|
|
8008
8504
|
]));
|
|
8009
8505
|
const noteTailHash = poseidonHasher.F.toObject(poseidonHasher([chainNoteTimestamp, noteCommitment, chainNoteSalt, noteSemantics]));
|
|
8010
8506
|
const chainNoteHash = poseidonHasher.F.toObject(poseidonHasher([CHAIN_NOTE_DOMAIN_TAG, CHAIN_NOTE_TAG, amountDataHash, noteTailHash]));
|
|
8011
|
-
const
|
|
8012
|
-
if (chainNoteHash >=
|
|
8013
|
-
throw new Error(`chainNoteHash out of range: ${chainNoteHash.toString()} >= ${
|
|
8507
|
+
const FIELD_MODULUS2 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
|
|
8508
|
+
if (chainNoteHash >= FIELD_MODULUS2) {
|
|
8509
|
+
throw new Error(`chainNoteHash out of range: ${chainNoteHash.toString()} >= ${FIELD_MODULUS2.toString()}`);
|
|
8014
8510
|
}
|
|
8015
8511
|
const pathElementsTotal = inPathElements.reduce((sum, arr) => sum + arr.length, 0);
|
|
8016
8512
|
const totalInputs = 1 + // root
|
|
@@ -8375,7 +8871,10 @@ async function transact(params, options) {
|
|
|
8375
8871
|
// For Send (shield-to-shield): always include sender so relay can enforce sanctions checks.
|
|
8376
8872
|
sender: externalAmount === BigInt(0) && !recipient ? depositorPubkey : void 0,
|
|
8377
8873
|
externalAmount,
|
|
8378
|
-
recipientDeliveryNotes
|
|
8874
|
+
recipientDeliveryNotes,
|
|
8875
|
+
// SDK-002: attached only to a withdrawal / send to a public address; the builder ignores it
|
|
8876
|
+
// for deposits and shield-to-shield sends.
|
|
8877
|
+
affiliateCode: options.affiliateCode
|
|
8379
8878
|
});
|
|
8380
8879
|
void metadataBundle;
|
|
8381
8880
|
const relaySubmission = await submitTransactToRelay({
|
|
@@ -8396,7 +8895,8 @@ async function transact(params, options) {
|
|
|
8396
8895
|
inputNullifiers
|
|
8397
8896
|
},
|
|
8398
8897
|
canRetryStaleRoot: submissionAttempts < maxRootRetries,
|
|
8399
|
-
onProgress
|
|
8898
|
+
onProgress,
|
|
8899
|
+
extraHeaders: options.relayHeaders
|
|
8400
8900
|
});
|
|
8401
8901
|
if (relaySubmission.kind === "stale-root") {
|
|
8402
8902
|
lastError = relaySubmission.error;
|
|
@@ -8428,7 +8928,8 @@ async function transact(params, options) {
|
|
|
8428
8928
|
throw lastError;
|
|
8429
8929
|
}
|
|
8430
8930
|
const classified = classifyRelayError(lastError.message);
|
|
8431
|
-
const
|
|
8931
|
+
const isDepositSubmission = externalAmount > BigInt(0);
|
|
8932
|
+
const isMerkleClass = !isDepositSubmission && !(classified instanceof UtxoAlreadySpentError) && !(classified instanceof SanctionsQuoteError) && !isRootNotFoundError2(lastError);
|
|
8432
8933
|
if (canRebuildMerkleTreeFromChain() && isMerkleClass && relayUrl) {
|
|
8433
8934
|
onProgress?.(
|
|
8434
8935
|
"All relay-tree attempts failed. Rebuilding merkle tree from chain as last resort..."
|
|
@@ -8577,54 +9078,83 @@ async function transact(params, options) {
|
|
|
8577
9078
|
};
|
|
8578
9079
|
}
|
|
8579
9080
|
async function transfer(inputUtxos, recipientPubkey, amount, options) {
|
|
9081
|
+
const owner = await requireOwnerUtxoKeypair(options, "transfer");
|
|
9082
|
+
const transferNk = await requireWalletNk(options, "transfer");
|
|
8580
9083
|
const inputSum = sumUtxoAmounts(inputUtxos);
|
|
8581
9084
|
if (inputSum < amount) {
|
|
8582
9085
|
throw new Error(`Insufficient funds: have ${inputSum}, need ${amount}`);
|
|
8583
9086
|
}
|
|
8584
9087
|
const change = inputSum - amount;
|
|
8585
|
-
const myKeypair = inputUtxos[0].keypair;
|
|
8586
9088
|
const mint = inputUtxos[0].mintAddress;
|
|
8587
|
-
|
|
8588
|
-
|
|
8589
|
-
|
|
9089
|
+
let spendInputs = [
|
|
9090
|
+
...inputUtxos.filter((u) => u.keypair.publicKey === owner.publicKey),
|
|
9091
|
+
...inputUtxos.filter((u) => u.keypair.publicKey !== owner.publicKey)
|
|
9092
|
+
];
|
|
9093
|
+
let spendOptions = options;
|
|
9094
|
+
if (change > BigInt(0) && spendInputs[0].keypair.publicKey !== owner.publicKey) {
|
|
9095
|
+
if (spendInputs.length > 2) {
|
|
9096
|
+
throw new Error(
|
|
9097
|
+
`transfer: none of the ${spendInputs.length} inputs is owned by ownerUtxoKeypair (they are notes from before SDK 0.2.6), so they must first be moved under the wallet key, and one transaction moves at most 2 notes. Consolidate the older notes first (send them to yourself, ownerUtxoKeypair.publicKey, at most 2 per transfer) or withdraw them, then retry this transfer with at most 2 inputs.`
|
|
9098
|
+
);
|
|
9099
|
+
}
|
|
9100
|
+
if (options.relayAuthBatch) {
|
|
9101
|
+
throw new Error(
|
|
9102
|
+
"transfer: no input is owned by ownerUtxoKeypair, so the inputs must first be moved under the wallet key in a separate transaction, which a single batch item cannot carry. Spend them to yourself first, or run this transfer outside the batch."
|
|
9103
|
+
);
|
|
9104
|
+
}
|
|
9105
|
+
options.onProgress?.("Moving notes under the wallet key before the transfer...");
|
|
9106
|
+
const migrationSalt = randomChangeNoteSalt();
|
|
9107
|
+
const migrated = (await createRecoverableChangeUtxo(inputSum, owner, transferNk, mint, migrationSalt, 0)).utxo;
|
|
9108
|
+
const { recipientViewingPublicKey: _recipientViewingPublicKey, ...migrationOptions } = options;
|
|
9109
|
+
void _recipientViewingPublicKey;
|
|
9110
|
+
const migration = await transact(
|
|
9111
|
+
{ inputUtxos: spendInputs, outputUtxos: [migrated], externalAmount: BigInt(0) },
|
|
9112
|
+
{ ...migrationOptions, chainNoteSalt: migrationSalt }
|
|
9113
|
+
);
|
|
9114
|
+
const migratedNote = migration.outputUtxos?.[0] ?? migrated;
|
|
9115
|
+
if (migration.commitmentIndices?.[0] >= 0) {
|
|
9116
|
+
migratedNote.index = migration.commitmentIndices[0];
|
|
9117
|
+
}
|
|
9118
|
+
spendInputs = [migratedNote];
|
|
9119
|
+
spendOptions = { ...options, cachedMerkleTree: migration.merkleTree };
|
|
9120
|
+
}
|
|
9121
|
+
const changeNoteSalt = randomChangeNoteSalt();
|
|
9122
|
+
const isSendToSelf = recipientPubkey === owner.publicKey || inputUtxos.some((u) => u.keypair.publicKey === recipientPubkey);
|
|
8590
9123
|
const recipientKeypair = {
|
|
8591
9124
|
privateKey: BigInt(0),
|
|
8592
9125
|
// Recipient's private key unknown
|
|
8593
9126
|
publicKey: recipientPubkey
|
|
8594
9127
|
};
|
|
8595
|
-
const recipientUtxo =
|
|
9128
|
+
const recipientUtxo = isSendToSelf ? (await createRecoverableChangeUtxo(amount, owner, transferNk, mint, changeNoteSalt, 0)).utxo : await createUtxo(amount, recipientKeypair, mint);
|
|
8596
9129
|
const outputUtxos = [recipientUtxo];
|
|
8597
9130
|
if (change > BigInt(0)) {
|
|
8598
|
-
|
|
8599
|
-
|
|
8600
|
-
|
|
8601
|
-
|
|
8602
|
-
|
|
8603
|
-
|
|
8604
|
-
|
|
8605
|
-
|
|
8606
|
-
|
|
8607
|
-
outputUtxos.push(utxo);
|
|
8608
|
-
} else {
|
|
8609
|
-
outputUtxos.push(await createUtxo(change, myKeypair, mint));
|
|
8610
|
-
}
|
|
9131
|
+
const { utxo } = await createRecoverableChangeUtxo(
|
|
9132
|
+
change,
|
|
9133
|
+
owner,
|
|
9134
|
+
transferNk,
|
|
9135
|
+
mint,
|
|
9136
|
+
changeNoteSalt,
|
|
9137
|
+
1
|
|
9138
|
+
);
|
|
9139
|
+
outputUtxos.push(utxo);
|
|
8611
9140
|
}
|
|
8612
9141
|
return transact(
|
|
8613
9142
|
{
|
|
8614
|
-
inputUtxos,
|
|
9143
|
+
inputUtxos: spendInputs,
|
|
8615
9144
|
outputUtxos,
|
|
8616
9145
|
externalAmount: BigInt(0)
|
|
8617
9146
|
// Pure shield-to-shield
|
|
8618
9147
|
},
|
|
8619
|
-
|
|
9148
|
+
{ ...spendOptions, chainNoteSalt: changeNoteSalt }
|
|
8620
9149
|
);
|
|
8621
9150
|
}
|
|
8622
9151
|
async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
|
|
9152
|
+
const owner = await requireOwnerUtxoKeypair(options, "partialWithdraw");
|
|
9153
|
+
const walletNk = await requireWalletNk(options, "partialWithdraw");
|
|
8623
9154
|
const inputSum = sumUtxoAmounts(inputUtxos);
|
|
8624
9155
|
if (inputSum < withdrawAmount) {
|
|
8625
9156
|
throw new Error(`Insufficient funds: have ${inputSum}, need ${withdrawAmount}`);
|
|
8626
9157
|
}
|
|
8627
|
-
const myKeypair = inputUtxos[0].keypair;
|
|
8628
9158
|
const mint = inputUtxos[0].mintAddress;
|
|
8629
9159
|
let utxos = [...inputUtxos];
|
|
8630
9160
|
let cachedTree = options.cachedMerkleTree;
|
|
@@ -8633,9 +9163,8 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
|
|
|
8633
9163
|
utxos.sort((a, b) => a.amount > b.amount ? 1 : a.amount < b.amount ? -1 : 0);
|
|
8634
9164
|
const [small1, small2, ...rest] = utxos;
|
|
8635
9165
|
const mergedAmount = small1.amount + small2.amount;
|
|
8636
|
-
const
|
|
8637
|
-
const
|
|
8638
|
-
const mergedOutput = mergeNk ? (await createRecoverableChangeUtxo(mergedAmount, myKeypair, mergeNk, mint, mergeSalt, 0)).utxo : await createUtxo(mergedAmount, myKeypair, mint);
|
|
9166
|
+
const mergeSalt = randomChangeNoteSalt();
|
|
9167
|
+
const mergedOutput = (await createRecoverableChangeUtxo(mergedAmount, owner, walletNk, mint, mergeSalt, 0)).utxo;
|
|
8639
9168
|
const mergeResult = await transact(
|
|
8640
9169
|
{
|
|
8641
9170
|
inputUtxos: [small1, small2],
|
|
@@ -8646,7 +9175,7 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
|
|
|
8646
9175
|
{
|
|
8647
9176
|
...options,
|
|
8648
9177
|
cachedMerkleTree: cachedTree,
|
|
8649
|
-
|
|
9178
|
+
chainNoteSalt: mergeSalt
|
|
8650
9179
|
}
|
|
8651
9180
|
);
|
|
8652
9181
|
cachedTree = mergeResult.merkleTree;
|
|
@@ -8661,23 +9190,18 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
|
|
|
8661
9190
|
const outputUtxos = [];
|
|
8662
9191
|
let changeNoteSalt;
|
|
8663
9192
|
if (change > BigInt(0)) {
|
|
8664
|
-
const
|
|
8665
|
-
|
|
8666
|
-
|
|
8667
|
-
|
|
8668
|
-
|
|
8669
|
-
|
|
8670
|
-
|
|
8671
|
-
|
|
8672
|
-
|
|
8673
|
-
|
|
8674
|
-
|
|
8675
|
-
|
|
8676
|
-
outputUtxos.push(utxo);
|
|
8677
|
-
changeNoteSalt = salt;
|
|
8678
|
-
} else {
|
|
8679
|
-
outputUtxos.push(await createUtxo(change, myKeypair, mint));
|
|
8680
|
-
}
|
|
9193
|
+
const salt = randomChangeNoteSalt();
|
|
9194
|
+
const { utxo } = await createRecoverableChangeUtxo(
|
|
9195
|
+
change,
|
|
9196
|
+
owner,
|
|
9197
|
+
walletNk,
|
|
9198
|
+
mint,
|
|
9199
|
+
salt,
|
|
9200
|
+
0
|
|
9201
|
+
// partialWithdraw puts change at output 0
|
|
9202
|
+
);
|
|
9203
|
+
outputUtxos.push(utxo);
|
|
9204
|
+
changeNoteSalt = salt;
|
|
8681
9205
|
}
|
|
8682
9206
|
return transact(
|
|
8683
9207
|
{
|
|
@@ -8800,6 +9324,8 @@ async function swapUtxo(params, options) {
|
|
|
8800
9324
|
if (relayUrl) {
|
|
8801
9325
|
assertRelayAuthAvailable(relayAuthPlan, "private swap");
|
|
8802
9326
|
}
|
|
9327
|
+
const swapOwner = await requireOwnerUtxoKeypair(options, "swapUtxo");
|
|
9328
|
+
const resolvedSwapChainNoteNk = await requireWalletNk(options, "swapUtxo");
|
|
8803
9329
|
if (inputUtxos.length === 0) {
|
|
8804
9330
|
throw new Error("At least one input UTXO required");
|
|
8805
9331
|
}
|
|
@@ -8825,15 +9351,12 @@ async function swapUtxo(params, options) {
|
|
|
8825
9351
|
throw new Error(`Amount mismatch: input(${totalInputAmount}) != swap(${swapAmount}) + change(${changeAmount})`);
|
|
8826
9352
|
}
|
|
8827
9353
|
onProgress?.("Validating transaction parameters...");
|
|
8828
|
-
|
|
8829
|
-
await ensureViewingKeyRegistered(options, onProgress, swapFallbackNk);
|
|
8830
|
-
const explicitSwapChainNoteNk = await resolveChainNoteNk(options);
|
|
8831
|
-
const resolvedSwapChainNoteNk = explicitSwapChainNoteNk ?? swapFallbackNk;
|
|
9354
|
+
await ensureViewingKeyRegistered(options, onProgress, resolvedSwapChainNoteNk);
|
|
8832
9355
|
const chainNoteSalt = options.chainNoteSalt !== void 0 ? assertChainNoteSalt(options.chainNoteSalt) : randomChainNoteSalt();
|
|
8833
|
-
if (
|
|
8834
|
-
if (changeUtxo.blinding !== deriveChangeNoteBlinding(
|
|
9356
|
+
if (changeUtxo && changeUtxo.amount > BigInt(0) && (changeUtxo.keypair.publicKey === swapOwner.publicKey || inputUtxos.some((u) => u.keypair.publicKey === changeUtxo.keypair.publicKey))) {
|
|
9357
|
+
if (changeUtxo.blinding !== deriveChangeNoteBlinding(resolvedSwapChainNoteNk, chainNoteSalt, 0)) {
|
|
8835
9358
|
throw new Error(
|
|
8836
|
-
`Swap change (amount ${changeUtxo.amount}, owned by an input's keypair) has a blinding that is not derivable from this wallet's viewing key. It was almost certainly built with \`createUtxo\`, whose blinding is random and is written nowhere on chain \u2014 if the caller ever drops the returned note, the funds are unspendable forever. Build it with \`createRecoverableChangeUtxo(amount, keypair, nk, mint, salt, 0)\` and pass the same salt as \`options.chainNoteSalt\`, or use \`swapWithChange\`, which does it for you.`
|
|
9359
|
+
`Swap change (amount ${changeUtxo.amount}, owned by an input's or the wallet's keypair) has a blinding that is not derivable from this wallet's viewing key. It was almost certainly built with \`createUtxo\`, whose blinding is random and is written nowhere on chain \u2014 if the caller ever drops the returned note, the funds are unspendable forever. Build it with \`createRecoverableChangeUtxo(amount, keypair, nk, mint, salt, 0)\` and pass the same salt as \`options.chainNoteSalt\`, or use \`swapWithChange\`, which does it for you.`
|
|
8837
9360
|
);
|
|
8838
9361
|
}
|
|
8839
9362
|
}
|
|
@@ -8857,24 +9380,18 @@ async function swapUtxo(params, options) {
|
|
|
8857
9380
|
);
|
|
8858
9381
|
}
|
|
8859
9382
|
const externalAmount = -swapAmount;
|
|
8860
|
-
|
|
8861
|
-
|
|
8862
|
-
|
|
8863
|
-
|
|
8864
|
-
|
|
8865
|
-
|
|
8866
|
-
|
|
8867
|
-
|
|
8868
|
-
|
|
8869
|
-
|
|
8870
|
-
|
|
8871
|
-
|
|
8872
|
-
refundBlinding = randomFieldElement();
|
|
8873
|
-
}
|
|
8874
|
-
} else {
|
|
8875
|
-
refundKeypair = await generateUtxoKeypair();
|
|
8876
|
-
refundBlinding = randomFieldElement();
|
|
8877
|
-
}
|
|
9383
|
+
const refundNullifier = bigintToBytes322(await computeNullifier(paddedInputs[0]));
|
|
9384
|
+
const refundAuthorization = await deriveSwapRefundAuthorization(
|
|
9385
|
+
resolvedSwapChainNoteNk,
|
|
9386
|
+
refundNullifier,
|
|
9387
|
+
swapOwner
|
|
9388
|
+
);
|
|
9389
|
+
const refundKeypair = {
|
|
9390
|
+
privateKey: refundAuthorization.privateKey,
|
|
9391
|
+
publicKey: refundAuthorization.publicKey
|
|
9392
|
+
};
|
|
9393
|
+
const refundBlinding = refundAuthorization.blinding;
|
|
9394
|
+
const refundDerivedFromNk = true;
|
|
8878
9395
|
if (refundKeypair.publicKey === BigInt(0) || refundBlinding === BigInt(0)) {
|
|
8879
9396
|
throw new Error(
|
|
8880
9397
|
"Refund authorization derivation produced a zero pubkey/blinding \u2014 aborting swap to avoid an unclaimable timeout refund. Retry; a persistent failure indicates a keygen/RNG fault."
|
|
@@ -9200,7 +9717,7 @@ async function swapUtxo(params, options) {
|
|
|
9200
9717
|
for (const utxo of paddedOutputs) {
|
|
9201
9718
|
outputCommitments.push(await computeCommitment(utxo));
|
|
9202
9719
|
}
|
|
9203
|
-
const chainNoteTimestamp =
|
|
9720
|
+
const chainNoteTimestamp = await relayChainNoteTimestampMs(relayUrl);
|
|
9204
9721
|
onProgress?.("Computing external data hash...");
|
|
9205
9722
|
const mint = swapPoolMint;
|
|
9206
9723
|
const mintField = pubkeyToFieldElement(mint);
|
|
@@ -9443,30 +9960,27 @@ async function swapUtxo(params, options) {
|
|
|
9443
9960
|
const [ssp] = await findProgramAddress(["swap_state", addressBytes(pdas.pool), new Uint8Array(nBytes)], programId);
|
|
9444
9961
|
await options.onSwapStatePredicted(ssp);
|
|
9445
9962
|
}
|
|
9446
|
-
const requestBody = {
|
|
9447
|
-
|
|
9448
|
-
|
|
9449
|
-
|
|
9450
|
-
|
|
9451
|
-
|
|
9452
|
-
|
|
9453
|
-
|
|
9454
|
-
|
|
9455
|
-
|
|
9456
|
-
|
|
9457
|
-
|
|
9458
|
-
|
|
9459
|
-
|
|
9460
|
-
|
|
9461
|
-
|
|
9462
|
-
|
|
9463
|
-
|
|
9464
|
-
//
|
|
9465
|
-
|
|
9466
|
-
|
|
9467
|
-
refund_pubkey: Buffer.from(bigintToBytes322(refundKeypair.publicKey)).toString("base64"),
|
|
9468
|
-
refund_blinding: Buffer.from(bigintToBytes322(refundBlinding)).toString("base64")
|
|
9469
|
-
};
|
|
9963
|
+
const requestBody = buildTransactSwapRequestBody({
|
|
9964
|
+
proofB64,
|
|
9965
|
+
publicInputsB64,
|
|
9966
|
+
outputMint,
|
|
9967
|
+
recipientAta,
|
|
9968
|
+
recipientWallet,
|
|
9969
|
+
minOutputAmount,
|
|
9970
|
+
maxFee: swapMaxFee,
|
|
9971
|
+
slippageBps: swapSlippageBps,
|
|
9972
|
+
dexes: swapDexes,
|
|
9973
|
+
excludeDexes: swapExcludeDexes,
|
|
9974
|
+
routeRetryAttempts: options.swapRouteRetryAttempts,
|
|
9975
|
+
swapMaxRetries: options.swapMaxRetries,
|
|
9976
|
+
encryptedNotes,
|
|
9977
|
+
riskQuote: riskQuoteData,
|
|
9978
|
+
refundPubkeyB64: Buffer.from(bigintToBytes322(refundKeypair.publicKey)).toString("base64"),
|
|
9979
|
+
refundBlindingB64: Buffer.from(bigintToBytes322(refundBlinding)).toString("base64"),
|
|
9980
|
+
// SDK-001/002: a swap intake is fee-bearing. Every attempt of this loop is a new intake with
|
|
9981
|
+
// a fresh proof, so each one carries the code; none of them is a `retry_request_id` retry.
|
|
9982
|
+
affiliateCode: options.affiliateCode
|
|
9983
|
+
});
|
|
9470
9984
|
try {
|
|
9471
9985
|
if (relayAuthPlan.kind === "wallet") {
|
|
9472
9986
|
walletApprovals = chargeWalletApproval(walletApprovals, walletApprovalBudget, lastError);
|
|
@@ -9485,11 +9999,16 @@ async function swapUtxo(params, options) {
|
|
|
9485
9999
|
TRANSACT_SWAP_AUTH_FIELDS
|
|
9486
10000
|
);
|
|
9487
10001
|
if (swapAuthFields) Object.assign(requestBody, swapAuthFields);
|
|
9488
|
-
const response = await relayFetch(
|
|
9489
|
-
|
|
9490
|
-
|
|
9491
|
-
|
|
9492
|
-
|
|
10002
|
+
const response = await relayFetch(
|
|
10003
|
+
`${relayUrl}/transact_swap`,
|
|
10004
|
+
{
|
|
10005
|
+
method: "POST",
|
|
10006
|
+
headers: { "Content-Type": "application/json" },
|
|
10007
|
+
body: JSON.stringify(requestBody)
|
|
10008
|
+
},
|
|
10009
|
+
// SDK-004: e.g. the mobile app's `X-Cloak-Client`. Omitted, this is the old call exactly.
|
|
10010
|
+
{ extraHeaders: options.relayHeaders }
|
|
10011
|
+
);
|
|
9493
10012
|
const responseText = await response.text();
|
|
9494
10013
|
if (!response.ok) {
|
|
9495
10014
|
if (isRetryableRelayStatus(response.status) && attempt < maxRootRetries) {
|
|
@@ -9512,7 +10031,7 @@ async function swapUtxo(params, options) {
|
|
|
9512
10031
|
forceChainIndexing = !relayUrl;
|
|
9513
10032
|
continue;
|
|
9514
10033
|
}
|
|
9515
|
-
throw new Error(relayFailureMessage("Relay error", responseText));
|
|
10034
|
+
throw new Error(relayFailureMessage("Relay error", responseText, requestBody));
|
|
9516
10035
|
}
|
|
9517
10036
|
const apiResponse = JSON.parse(responseText);
|
|
9518
10037
|
if (!apiResponse.success || !apiResponse.data) {
|
|
@@ -9648,7 +10167,6 @@ async function swapUtxo(params, options) {
|
|
|
9648
10167
|
// V3-04: the refund-fallback secret (hex, 32-byte field elements). Persist to claim a timed-out
|
|
9649
10168
|
// swap; see the UtxoSwapResult.refund docs. amountAfterFee is read from on-chain SwapState.
|
|
9650
10169
|
refund: {
|
|
9651
|
-
privateKey: Buffer.from(bigintToBytes322(refundKeypair.privateKey)).toString("hex"),
|
|
9652
10170
|
publicKey: Buffer.from(bigintToBytes322(refundKeypair.publicKey)).toString("hex"),
|
|
9653
10171
|
blinding: Buffer.from(bigintToBytes322(refundBlinding)).toString("hex"),
|
|
9654
10172
|
derivedFromNk: refundDerivedFromNk
|
|
@@ -9656,6 +10174,7 @@ async function swapUtxo(params, options) {
|
|
|
9656
10174
|
};
|
|
9657
10175
|
}
|
|
9658
10176
|
async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta, minOutputAmount, options, recipientWallet) {
|
|
10177
|
+
const owner = await requireOwnerUtxoKeypair(options, "swapWithChange");
|
|
9659
10178
|
const totalInput = sumUtxoAmounts(inputUtxos);
|
|
9660
10179
|
const change = totalInput - swapAmount;
|
|
9661
10180
|
if (change < BigInt(0)) {
|
|
@@ -9664,16 +10183,11 @@ async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta,
|
|
|
9664
10183
|
let changeUtxo;
|
|
9665
10184
|
let changeNoteSalt;
|
|
9666
10185
|
if (change > BigInt(0)) {
|
|
9667
|
-
const myKeypair = inputUtxos[0].keypair;
|
|
9668
10186
|
const mint = inputUtxos[0].mintAddress;
|
|
9669
|
-
const changeNk = await
|
|
9670
|
-
|
|
9671
|
-
|
|
9672
|
-
|
|
9673
|
-
changeNoteSalt = salt;
|
|
9674
|
-
} else {
|
|
9675
|
-
changeUtxo = await createUtxo(change, myKeypair, mint);
|
|
9676
|
-
}
|
|
10187
|
+
const changeNk = await requireWalletNk(options, "swapWithChange");
|
|
10188
|
+
const salt = randomChangeNoteSalt();
|
|
10189
|
+
changeUtxo = (await createRecoverableChangeUtxo(change, owner, changeNk, mint, salt, 0)).utxo;
|
|
10190
|
+
changeNoteSalt = salt;
|
|
9677
10191
|
}
|
|
9678
10192
|
return swapUtxo(
|
|
9679
10193
|
{
|
|
@@ -9996,7 +10510,7 @@ var RelayBatchAuthCoordinator = class {
|
|
|
9996
10510
|
throw new Error("Every item of a batch must target the same program id.");
|
|
9997
10511
|
}
|
|
9998
10512
|
}
|
|
9999
|
-
const nowSeconds =
|
|
10513
|
+
const nowSeconds = relayNowSeconds();
|
|
10000
10514
|
const preimages = waiting.map(
|
|
10001
10515
|
(w) => buildRelayAuthPreimage(w.endpoint, programId, w.body, this.sender, nowSeconds, w.fields)
|
|
10002
10516
|
);
|
|
@@ -10434,7 +10948,7 @@ async function deriveDepositCandidate(viewingKeyNk, noteSalt) {
|
|
|
10434
10948
|
const cached = depositSecretsCache.get(key);
|
|
10435
10949
|
if (cached) return cached;
|
|
10436
10950
|
try {
|
|
10437
|
-
const secrets = await
|
|
10951
|
+
const secrets = await deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt);
|
|
10438
10952
|
if (depositSecretsCache.size >= 4096) {
|
|
10439
10953
|
const oldest = depositSecretsCache.keys().next();
|
|
10440
10954
|
if (!oldest.done) depositSecretsCache.delete(oldest.value);
|
|
@@ -11017,6 +11531,7 @@ async function scanTransactions(opts) {
|
|
|
11017
11531
|
} else {
|
|
11018
11532
|
const derived = await deriveDepositCandidate(viewingKeyNk, compactNote.noteSalt);
|
|
11019
11533
|
const candidateKeys = [
|
|
11534
|
+
opts.ownerUtxoPublicKey,
|
|
11020
11535
|
derived?.keypair.publicKey,
|
|
11021
11536
|
opts.ownUtxoPublicKey,
|
|
11022
11537
|
BigInt(0)
|
|
@@ -11070,6 +11585,7 @@ async function scanTransactions(opts) {
|
|
|
11070
11585
|
try {
|
|
11071
11586
|
const recoveredDeposit = await matchDepositNote({
|
|
11072
11587
|
viewingKeyNk,
|
|
11588
|
+
ownerUtxoKeypair: opts.ownerUtxoPublicKey !== void 0 ? { privateKey: 0n, publicKey: opts.ownerUtxoPublicKey } : void 0,
|
|
11073
11589
|
noteSalt: compactNote.noteSalt,
|
|
11074
11590
|
// Output 0's amount. For a shield with no inputs — the shape `transact` builds for a
|
|
11075
11591
|
// deposit — that is the public deposit amount. A deposit that also merged inputs
|
|
@@ -11104,7 +11620,8 @@ async function scanTransactions(opts) {
|
|
|
11104
11620
|
mintAddress: address(asset.mint),
|
|
11105
11621
|
outputIndex: 0,
|
|
11106
11622
|
// v4 describes output 0, which is where change lands
|
|
11107
|
-
outputCommitments: ixCtx.outputCommitments ?? []
|
|
11623
|
+
outputCommitments: ixCtx.outputCommitments ?? [],
|
|
11624
|
+
ownerUtxoPublicKey: opts.ownerUtxoPublicKey
|
|
11108
11625
|
});
|
|
11109
11626
|
if (recoveredChange) {
|
|
11110
11627
|
recoveredChangeNotes.push({
|
|
@@ -11214,6 +11731,17 @@ async function scanTransactions(opts) {
|
|
|
11214
11731
|
runningByAsset.set(key, running);
|
|
11215
11732
|
tx.runningBalance = running;
|
|
11216
11733
|
}
|
|
11734
|
+
const legacyKeys = /* @__PURE__ */ new Map();
|
|
11735
|
+
for (const note of recoveredDepositNotes) {
|
|
11736
|
+
if (note.legacyExposed) legacyKeys.set(note.keypair.publicKey, note.keypair.privateKey);
|
|
11737
|
+
}
|
|
11738
|
+
for (const change of recoveredChangeNotes) {
|
|
11739
|
+
const legacyPrivateKey = legacyKeys.get(change.keypair.publicKey);
|
|
11740
|
+
if (legacyPrivateKey !== void 0) {
|
|
11741
|
+
change.keypair = { privateKey: legacyPrivateKey, publicKey: change.keypair.publicKey };
|
|
11742
|
+
change.legacyExposed = true;
|
|
11743
|
+
}
|
|
11744
|
+
}
|
|
11217
11745
|
return {
|
|
11218
11746
|
transactions: txs,
|
|
11219
11747
|
summary: {
|
|
@@ -11293,19 +11821,1645 @@ function formatComplianceCsv(report) {
|
|
|
11293
11821
|
return header + rows;
|
|
11294
11822
|
}
|
|
11295
11823
|
|
|
11296
|
-
// src/
|
|
11297
|
-
|
|
11298
|
-
|
|
11299
|
-
|
|
11300
|
-
|
|
11824
|
+
// src/relay/note-index-format.ts
|
|
11825
|
+
import { sha256 as sha2565 } from "@noble/hashes/sha2";
|
|
11826
|
+
var NOTE_INDEX_MAGIC = new Uint8Array([67, 78, 73, 49]);
|
|
11827
|
+
var NOTE_INDEX_FORMAT_VERSION = 1;
|
|
11828
|
+
var NOTE_INDEX_PAGE_SIZE = 1024;
|
|
11829
|
+
var NOTE_INDEX_NO_LEAF = 0xffffffffffffffffn;
|
|
11830
|
+
var NOTE_INDEX_MAX_PAGE_BYTES = 2 * 1024 * 1024;
|
|
11831
|
+
var NOTE_INDEX_HEADER_LEN = 68;
|
|
11832
|
+
var NOTE_INDEX_KIND_TX = 1;
|
|
11833
|
+
var NOTE_INDEX_KIND_DELIVERY = 2;
|
|
11834
|
+
var NOTE_INDEX_KIND_SWAP_REFUND = 3;
|
|
11835
|
+
var NOTE_SOURCE_NONE = 0;
|
|
11836
|
+
var NOTE_SOURCE_CARRIER = 2;
|
|
11837
|
+
var ITEM_HEADER_LEN = 3;
|
|
11838
|
+
var TX_FIXED_LEN = 263;
|
|
11839
|
+
var DELIVERY_BODY_LEN = 256;
|
|
11840
|
+
var SWAP_REFUND_BODY_LEN = 184;
|
|
11841
|
+
var MAX_UNKNOWN_BODY_LEN = 1024;
|
|
11842
|
+
var DELIVERY_ENVELOPE_LEN = 112;
|
|
11843
|
+
var SIGNATURE_LEN = 64;
|
|
11844
|
+
var NOTE_VERSION_BY_LEN = /* @__PURE__ */ new Map([
|
|
11845
|
+
[25, 2],
|
|
11846
|
+
[57, 3],
|
|
11847
|
+
[98, 4]
|
|
11848
|
+
]);
|
|
11849
|
+
var COMPLETE_FLAG = 1;
|
|
11850
|
+
var U64_MAX2 = (1n << 64n) - 1n;
|
|
11851
|
+
var U32_MAX = 4294967295;
|
|
11852
|
+
var MAX_LEAF_INDEX = (1n << 32n) - 1n;
|
|
11853
|
+
var WSOL_BYTES = addressBytes(NATIVE_SOL_MINT);
|
|
11854
|
+
var NoteIndexFormatError = class extends Error {
|
|
11855
|
+
constructor(message) {
|
|
11856
|
+
super(`Note index format error: ${message}`);
|
|
11857
|
+
this.name = "NoteIndexFormatError";
|
|
11301
11858
|
}
|
|
11302
|
-
|
|
11303
|
-
|
|
11304
|
-
|
|
11305
|
-
|
|
11306
|
-
|
|
11307
|
-
|
|
11308
|
-
|
|
11859
|
+
};
|
|
11860
|
+
function isAllZero2(bytes) {
|
|
11861
|
+
for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
|
|
11862
|
+
return true;
|
|
11863
|
+
}
|
|
11864
|
+
function bytesEqual(a, b) {
|
|
11865
|
+
if (a.length !== b.length) return false;
|
|
11866
|
+
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
|
|
11867
|
+
return true;
|
|
11868
|
+
}
|
|
11869
|
+
function checkLeafPair(commitment, leaf, label) {
|
|
11870
|
+
if (isAllZero2(commitment)) {
|
|
11871
|
+
if (leaf !== NOTE_INDEX_NO_LEAF) throw new NoteIndexFormatError(`${label}: zero commitment must carry NO_LEAF`);
|
|
11872
|
+
return;
|
|
11873
|
+
}
|
|
11874
|
+
if (leaf > MAX_LEAF_INDEX) throw new NoteIndexFormatError(`${label}: leaf ${leaf} is not a leaf of the tree`);
|
|
11875
|
+
}
|
|
11876
|
+
var Reader = class {
|
|
11877
|
+
constructor(bytes, start, end) {
|
|
11878
|
+
this.bytes = bytes;
|
|
11879
|
+
this.end = end;
|
|
11880
|
+
this.offset = start;
|
|
11881
|
+
this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
11882
|
+
}
|
|
11883
|
+
take(len) {
|
|
11884
|
+
if (this.offset + len > this.end) throw new NoteIndexFormatError("truncated item body");
|
|
11885
|
+
const at = this.offset;
|
|
11886
|
+
this.offset += len;
|
|
11887
|
+
return at;
|
|
11888
|
+
}
|
|
11889
|
+
u8() {
|
|
11890
|
+
return this.bytes[this.take(1)];
|
|
11891
|
+
}
|
|
11892
|
+
u32() {
|
|
11893
|
+
return this.view.getUint32(this.take(4), true);
|
|
11894
|
+
}
|
|
11895
|
+
u64() {
|
|
11896
|
+
return this.view.getBigUint64(this.take(8), true);
|
|
11897
|
+
}
|
|
11898
|
+
i64() {
|
|
11899
|
+
return this.view.getBigInt64(this.take(8), true);
|
|
11900
|
+
}
|
|
11901
|
+
raw(len) {
|
|
11902
|
+
const at = this.take(len);
|
|
11903
|
+
return this.bytes.slice(at, at + len);
|
|
11904
|
+
}
|
|
11905
|
+
get position() {
|
|
11906
|
+
return this.offset;
|
|
11907
|
+
}
|
|
11908
|
+
};
|
|
11909
|
+
function parseTx(r, bodyLen) {
|
|
11910
|
+
const mint = r.raw(32);
|
|
11911
|
+
const slot = r.u64();
|
|
11912
|
+
const blockPos = r.u32();
|
|
11913
|
+
const ixTag = r.u8();
|
|
11914
|
+
if (ixTag !== 0 && ixTag !== 1) throw new NoteIndexFormatError(`TX: ix_tag ${ixTag}`);
|
|
11915
|
+
const publicAmount = r.i64();
|
|
11916
|
+
const nullifier0 = r.raw(32);
|
|
11917
|
+
const nullifier1 = r.raw(32);
|
|
11918
|
+
const comm0 = r.raw(32);
|
|
11919
|
+
const leaf0 = r.u64();
|
|
11920
|
+
const comm1 = r.raw(32);
|
|
11921
|
+
const leaf1 = r.u64();
|
|
11922
|
+
const noteSource = r.u8();
|
|
11923
|
+
if (noteSource > NOTE_SOURCE_CARRIER) throw new NoteIndexFormatError(`TX: note_source ${noteSource}`);
|
|
11924
|
+
const noteLen = r.u8();
|
|
11925
|
+
if (noteSource === NOTE_SOURCE_NONE) {
|
|
11926
|
+
if (noteLen !== 0) throw new NoteIndexFormatError(`TX: note_len ${noteLen} without a note source`);
|
|
11927
|
+
} else if (!NOTE_VERSION_BY_LEN.has(noteLen)) {
|
|
11928
|
+
throw new NoteIndexFormatError(`TX: note_len ${noteLen}`);
|
|
11929
|
+
}
|
|
11930
|
+
if (bodyLen !== TX_FIXED_LEN + noteLen) {
|
|
11931
|
+
throw new NoteIndexFormatError(`TX: body_len ${bodyLen} != ${TX_FIXED_LEN + noteLen} for note_len ${noteLen}`);
|
|
11932
|
+
}
|
|
11933
|
+
const note = r.raw(noteLen);
|
|
11934
|
+
if (noteLen > 0 && note[0] !== NOTE_VERSION_BY_LEN.get(noteLen)) {
|
|
11935
|
+
throw new NoteIndexFormatError(`TX: note version ${note[0]} does not match note_len ${noteLen}`);
|
|
11936
|
+
}
|
|
11937
|
+
const signature = r.raw(SIGNATURE_LEN);
|
|
11938
|
+
checkLeafPair(comm0, leaf0, "TX comm0");
|
|
11939
|
+
checkLeafPair(comm1, leaf1, "TX comm1");
|
|
11940
|
+
return {
|
|
11941
|
+
kind: 1,
|
|
11942
|
+
mint,
|
|
11943
|
+
slot,
|
|
11944
|
+
blockPos,
|
|
11945
|
+
ixTag,
|
|
11946
|
+
publicAmount,
|
|
11947
|
+
nullifier0,
|
|
11948
|
+
nullifier1,
|
|
11949
|
+
comm0,
|
|
11950
|
+
leaf0,
|
|
11951
|
+
comm1,
|
|
11952
|
+
leaf1,
|
|
11953
|
+
noteSource,
|
|
11954
|
+
note,
|
|
11955
|
+
signature
|
|
11956
|
+
};
|
|
11957
|
+
}
|
|
11958
|
+
function parseDelivery(r) {
|
|
11959
|
+
const mint = r.raw(32);
|
|
11960
|
+
const slot = r.u64();
|
|
11961
|
+
const commitment = r.raw(32);
|
|
11962
|
+
const leaf = r.u64();
|
|
11963
|
+
const envelope = r.raw(DELIVERY_ENVELOPE_LEN);
|
|
11964
|
+
const signature = r.raw(SIGNATURE_LEN);
|
|
11965
|
+
if (isAllZero2(commitment)) throw new NoteIndexFormatError("DELIVERY: zero commitment");
|
|
11966
|
+
checkLeafPair(commitment, leaf, "DELIVERY");
|
|
11967
|
+
return { kind: 2, mint, slot, commitment, leaf, envelope, signature };
|
|
11968
|
+
}
|
|
11969
|
+
function parseSwapRefund(r) {
|
|
11970
|
+
const mint = r.raw(32);
|
|
11971
|
+
if (!bytesEqual(mint, WSOL_BYTES)) throw new NoteIndexFormatError("SWAP_REFUND: mint is not WSOL");
|
|
11972
|
+
const slot = r.u64();
|
|
11973
|
+
const commitment = r.raw(32);
|
|
11974
|
+
const leaf = r.u64();
|
|
11975
|
+
const amountAfterFee = r.u64();
|
|
11976
|
+
const nullifier0 = r.raw(32);
|
|
11977
|
+
const signature = r.raw(SIGNATURE_LEN);
|
|
11978
|
+
if (isAllZero2(commitment)) throw new NoteIndexFormatError("SWAP_REFUND: zero commitment");
|
|
11979
|
+
checkLeafPair(commitment, leaf, "SWAP_REFUND");
|
|
11980
|
+
return { kind: 3, mint, slot, commitment, leaf, amountAfterFee, nullifier0, signature };
|
|
11981
|
+
}
|
|
11982
|
+
function parseNoteIndexPage(bytes, expect, options = {}) {
|
|
11983
|
+
if (!(bytes instanceof Uint8Array)) throw new NoteIndexFormatError("page must be a Uint8Array");
|
|
11984
|
+
if (bytes.length > NOTE_INDEX_MAX_PAGE_BYTES) {
|
|
11985
|
+
throw new NoteIndexFormatError(`page is ${bytes.length} bytes, over the ${NOTE_INDEX_MAX_PAGE_BYTES}-byte bound`);
|
|
11986
|
+
}
|
|
11987
|
+
if (bytes.length < NOTE_INDEX_HEADER_LEN) throw new NoteIndexFormatError("truncated page header");
|
|
11988
|
+
for (let i = 0; i < NOTE_INDEX_MAGIC.length; i++) {
|
|
11989
|
+
if (bytes[i] !== NOTE_INDEX_MAGIC[i]) throw new NoteIndexFormatError("bad magic");
|
|
11990
|
+
}
|
|
11991
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
11992
|
+
const version = bytes[4];
|
|
11993
|
+
if (version !== NOTE_INDEX_FORMAT_VERSION) throw new NoteIndexFormatError(`unsupported version ${version}`);
|
|
11994
|
+
const flags = bytes[5];
|
|
11995
|
+
if ((flags & ~COMPLETE_FLAG) !== 0) throw new NoteIndexFormatError(`unknown flag bits 0x${flags.toString(16)}`);
|
|
11996
|
+
if (view.getUint16(6, true) !== 0) throw new NoteIndexFormatError("reserved bytes are not zero");
|
|
11997
|
+
const epoch = view.getBigUint64(8, true);
|
|
11998
|
+
const page = view.getBigUint64(16, true);
|
|
11999
|
+
const firstSeq = view.getBigUint64(24, true);
|
|
12000
|
+
const count = view.getUint32(32, true);
|
|
12001
|
+
const prevChain = bytes.slice(36, 68);
|
|
12002
|
+
const complete = (flags & COMPLETE_FLAG) !== 0;
|
|
12003
|
+
if (expect) {
|
|
12004
|
+
if (epoch !== expect.epoch) throw new NoteIndexFormatError(`epoch ${epoch} is not the requested ${expect.epoch}`);
|
|
12005
|
+
if (page !== BigInt(expect.page)) throw new NoteIndexFormatError(`page ${page} is not the requested ${expect.page}`);
|
|
12006
|
+
}
|
|
12007
|
+
if (count > NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`count ${count} exceeds ${NOTE_INDEX_PAGE_SIZE}`);
|
|
12008
|
+
if (complete && count !== NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`complete page with count ${count}`);
|
|
12009
|
+
if (firstSeq !== page * BigInt(NOTE_INDEX_PAGE_SIZE)) {
|
|
12010
|
+
throw new NoteIndexFormatError(`first_seq ${firstSeq} is not page ${page} * ${NOTE_INDEX_PAGE_SIZE}`);
|
|
12011
|
+
}
|
|
12012
|
+
const items = [];
|
|
12013
|
+
const rawItems = [];
|
|
12014
|
+
const itemPositions = [];
|
|
12015
|
+
let skippedUnknown = 0;
|
|
12016
|
+
let skippedMalformed = 0;
|
|
12017
|
+
let offset = NOTE_INDEX_HEADER_LEN;
|
|
12018
|
+
for (let i = 0; i < count; i++) {
|
|
12019
|
+
if (offset + ITEM_HEADER_LEN > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} header`);
|
|
12020
|
+
const kind = bytes[offset];
|
|
12021
|
+
const bodyLen = view.getUint16(offset + 1, true);
|
|
12022
|
+
const bodyStart = offset + ITEM_HEADER_LEN;
|
|
12023
|
+
const bodyEnd = bodyStart + bodyLen;
|
|
12024
|
+
if (bodyEnd > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} body`);
|
|
12025
|
+
if (kind !== NOTE_INDEX_KIND_TX && kind !== NOTE_INDEX_KIND_DELIVERY && kind !== NOTE_INDEX_KIND_SWAP_REFUND) {
|
|
12026
|
+
if (bodyLen > MAX_UNKNOWN_BODY_LEN) throw new NoteIndexFormatError(`unknown kind ${kind} with body_len ${bodyLen}`);
|
|
12027
|
+
skippedUnknown++;
|
|
12028
|
+
offset = bodyEnd;
|
|
12029
|
+
continue;
|
|
12030
|
+
}
|
|
12031
|
+
let item;
|
|
12032
|
+
try {
|
|
12033
|
+
item = parseKnownBody(bytes, kind, bodyStart, bodyEnd, i);
|
|
12034
|
+
} catch (error) {
|
|
12035
|
+
if (!options.skipMalformedItems || !(error instanceof NoteIndexFormatError)) throw error;
|
|
12036
|
+
skippedMalformed++;
|
|
12037
|
+
offset = bodyEnd;
|
|
12038
|
+
continue;
|
|
12039
|
+
}
|
|
12040
|
+
items.push(item);
|
|
12041
|
+
rawItems.push(bytes.slice(offset, bodyEnd));
|
|
12042
|
+
itemPositions.push(i);
|
|
12043
|
+
offset = bodyEnd;
|
|
12044
|
+
}
|
|
12045
|
+
if (offset !== bytes.length) throw new NoteIndexFormatError(`${bytes.length - offset} trailing bytes after ${count} items`);
|
|
12046
|
+
return { epoch, page, firstSeq, complete, count, prevChain, items, rawItems, skippedUnknown, itemPositions, skippedMalformed };
|
|
12047
|
+
}
|
|
12048
|
+
function parseKnownBody(bytes, kind, bodyStart, bodyEnd, i) {
|
|
12049
|
+
const bodyLen = bodyEnd - bodyStart;
|
|
12050
|
+
const r = new Reader(bytes, bodyStart, bodyEnd);
|
|
12051
|
+
let item;
|
|
12052
|
+
if (kind === NOTE_INDEX_KIND_TX) {
|
|
12053
|
+
if (bodyLen < TX_FIXED_LEN) throw new NoteIndexFormatError(`TX: body_len ${bodyLen}`);
|
|
12054
|
+
item = parseTx(r, bodyLen);
|
|
12055
|
+
} else if (kind === NOTE_INDEX_KIND_DELIVERY) {
|
|
12056
|
+
if (bodyLen !== DELIVERY_BODY_LEN) throw new NoteIndexFormatError(`DELIVERY: body_len ${bodyLen}`);
|
|
12057
|
+
item = parseDelivery(r);
|
|
12058
|
+
} else {
|
|
12059
|
+
if (bodyLen !== SWAP_REFUND_BODY_LEN) throw new NoteIndexFormatError(`SWAP_REFUND: body_len ${bodyLen}`);
|
|
12060
|
+
item = parseSwapRefund(r);
|
|
12061
|
+
}
|
|
12062
|
+
if (r.position !== bodyEnd) throw new NoteIndexFormatError(`item ${i} body has unread bytes`);
|
|
12063
|
+
return item;
|
|
12064
|
+
}
|
|
12065
|
+
function parseNoteIndexItem(raw) {
|
|
12066
|
+
if (!(raw instanceof Uint8Array) || raw.length < ITEM_HEADER_LEN) throw new NoteIndexFormatError("truncated item");
|
|
12067
|
+
const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
|
|
12068
|
+
const kind = raw[0];
|
|
12069
|
+
const bodyLen = view.getUint16(1, true);
|
|
12070
|
+
if (ITEM_HEADER_LEN + bodyLen !== raw.length) throw new NoteIndexFormatError("item length mismatch");
|
|
12071
|
+
const r = new Reader(raw, ITEM_HEADER_LEN, raw.length);
|
|
12072
|
+
let item;
|
|
12073
|
+
if (kind === NOTE_INDEX_KIND_TX && bodyLen >= TX_FIXED_LEN) item = parseTx(r, bodyLen);
|
|
12074
|
+
else if (kind === NOTE_INDEX_KIND_DELIVERY && bodyLen === DELIVERY_BODY_LEN) item = parseDelivery(r);
|
|
12075
|
+
else if (kind === NOTE_INDEX_KIND_SWAP_REFUND && bodyLen === SWAP_REFUND_BODY_LEN) item = parseSwapRefund(r);
|
|
12076
|
+
else throw new NoteIndexFormatError(`item kind ${kind} with body_len ${bodyLen}`);
|
|
12077
|
+
if (r.position !== raw.length) throw new NoteIndexFormatError("item body has unread bytes");
|
|
12078
|
+
return item;
|
|
12079
|
+
}
|
|
12080
|
+
function computeNoteIndexChain(prevChain, pageBytes) {
|
|
12081
|
+
if (!(prevChain instanceof Uint8Array) || prevChain.length !== 32) throw new NoteIndexFormatError("prevChain must be 32 bytes");
|
|
12082
|
+
if (pageBytes.length < NOTE_INDEX_HEADER_LEN) throw new NoteIndexFormatError("truncated page header");
|
|
12083
|
+
const items = pageBytes.subarray(NOTE_INDEX_HEADER_LEN);
|
|
12084
|
+
const input = new Uint8Array(32 + items.length);
|
|
12085
|
+
input.set(prevChain);
|
|
12086
|
+
input.set(items, 32);
|
|
12087
|
+
return sha2565(input);
|
|
12088
|
+
}
|
|
12089
|
+
var Writer = class {
|
|
12090
|
+
constructor() {
|
|
12091
|
+
this.chunks = [];
|
|
12092
|
+
this.length = 0;
|
|
12093
|
+
}
|
|
12094
|
+
push(bytes) {
|
|
12095
|
+
this.chunks.push(bytes);
|
|
12096
|
+
this.length += bytes.length;
|
|
12097
|
+
}
|
|
12098
|
+
u8(v) {
|
|
12099
|
+
if (!Number.isInteger(v) || v < 0 || v > 255) throw new NoteIndexFormatError(`u8 out of range: ${v}`);
|
|
12100
|
+
this.push(Uint8Array.of(v));
|
|
12101
|
+
}
|
|
12102
|
+
u16(v) {
|
|
12103
|
+
if (!Number.isInteger(v) || v < 0 || v > 65535) throw new NoteIndexFormatError(`u16 out of range: ${v}`);
|
|
12104
|
+
const b = new Uint8Array(2);
|
|
12105
|
+
new DataView(b.buffer).setUint16(0, v, true);
|
|
12106
|
+
this.push(b);
|
|
12107
|
+
}
|
|
12108
|
+
u32(v) {
|
|
12109
|
+
if (!Number.isInteger(v) || v < 0 || v > U32_MAX) throw new NoteIndexFormatError(`u32 out of range: ${v}`);
|
|
12110
|
+
const b = new Uint8Array(4);
|
|
12111
|
+
new DataView(b.buffer).setUint32(0, v, true);
|
|
12112
|
+
this.push(b);
|
|
12113
|
+
}
|
|
12114
|
+
u64(v) {
|
|
12115
|
+
if (v < 0n || v > U64_MAX2) throw new NoteIndexFormatError(`u64 out of range: ${v}`);
|
|
12116
|
+
const b = new Uint8Array(8);
|
|
12117
|
+
new DataView(b.buffer).setBigUint64(0, v, true);
|
|
12118
|
+
this.push(b);
|
|
12119
|
+
}
|
|
12120
|
+
i64(v) {
|
|
12121
|
+
if (v < -(1n << 63n) || v >= 1n << 63n) throw new NoteIndexFormatError(`i64 out of range: ${v}`);
|
|
12122
|
+
const b = new Uint8Array(8);
|
|
12123
|
+
new DataView(b.buffer).setBigInt64(0, v, true);
|
|
12124
|
+
this.push(b);
|
|
12125
|
+
}
|
|
12126
|
+
fixed(bytes, len, label) {
|
|
12127
|
+
if (!(bytes instanceof Uint8Array) || bytes.length !== len) throw new NoteIndexFormatError(`${label} must be ${len} bytes`);
|
|
12128
|
+
this.push(bytes);
|
|
12129
|
+
}
|
|
12130
|
+
finish() {
|
|
12131
|
+
const out = new Uint8Array(this.length);
|
|
12132
|
+
let off = 0;
|
|
12133
|
+
for (const c of this.chunks) {
|
|
12134
|
+
out.set(c, off);
|
|
12135
|
+
off += c.length;
|
|
12136
|
+
}
|
|
12137
|
+
return out;
|
|
12138
|
+
}
|
|
12139
|
+
};
|
|
12140
|
+
function encodeItemBody(item) {
|
|
12141
|
+
const w = new Writer();
|
|
12142
|
+
switch (item.kind) {
|
|
12143
|
+
case NOTE_INDEX_KIND_TX: {
|
|
12144
|
+
w.fixed(item.mint, 32, "mint");
|
|
12145
|
+
w.u64(item.slot);
|
|
12146
|
+
w.u32(item.blockPos);
|
|
12147
|
+
w.u8(item.ixTag);
|
|
12148
|
+
w.i64(item.publicAmount);
|
|
12149
|
+
w.fixed(item.nullifier0, 32, "nullifier0");
|
|
12150
|
+
w.fixed(item.nullifier1, 32, "nullifier1");
|
|
12151
|
+
w.fixed(item.comm0, 32, "comm0");
|
|
12152
|
+
w.u64(item.leaf0);
|
|
12153
|
+
w.fixed(item.comm1, 32, "comm1");
|
|
12154
|
+
w.u64(item.leaf1);
|
|
12155
|
+
w.u8(item.noteSource);
|
|
12156
|
+
const noteLen = item.note.length;
|
|
12157
|
+
if (item.noteSource === NOTE_SOURCE_NONE ? noteLen !== 0 : !NOTE_VERSION_BY_LEN.has(noteLen)) {
|
|
12158
|
+
throw new NoteIndexFormatError(`note_len ${noteLen} invalid for note_source ${item.noteSource}`);
|
|
12159
|
+
}
|
|
12160
|
+
w.u8(noteLen);
|
|
12161
|
+
w.push(item.note);
|
|
12162
|
+
w.fixed(item.signature, SIGNATURE_LEN, "signature");
|
|
12163
|
+
break;
|
|
12164
|
+
}
|
|
12165
|
+
case NOTE_INDEX_KIND_DELIVERY:
|
|
12166
|
+
w.fixed(item.mint, 32, "mint");
|
|
12167
|
+
w.u64(item.slot);
|
|
12168
|
+
w.fixed(item.commitment, 32, "commitment");
|
|
12169
|
+
w.u64(item.leaf);
|
|
12170
|
+
w.fixed(item.envelope, DELIVERY_ENVELOPE_LEN, "envelope");
|
|
12171
|
+
w.fixed(item.signature, SIGNATURE_LEN, "signature");
|
|
12172
|
+
break;
|
|
12173
|
+
case NOTE_INDEX_KIND_SWAP_REFUND:
|
|
12174
|
+
w.fixed(item.mint, 32, "mint");
|
|
12175
|
+
w.u64(item.slot);
|
|
12176
|
+
w.fixed(item.commitment, 32, "commitment");
|
|
12177
|
+
w.u64(item.leaf);
|
|
12178
|
+
w.u64(item.amountAfterFee);
|
|
12179
|
+
w.fixed(item.nullifier0, 32, "nullifier0");
|
|
12180
|
+
w.fixed(item.signature, SIGNATURE_LEN, "signature");
|
|
12181
|
+
break;
|
|
12182
|
+
default:
|
|
12183
|
+
throw new NoteIndexFormatError(`cannot encode kind ${item.kind}`);
|
|
12184
|
+
}
|
|
12185
|
+
return w.finish();
|
|
12186
|
+
}
|
|
12187
|
+
function encodeNoteIndexItem(item) {
|
|
12188
|
+
const body = encodeItemBody(item);
|
|
12189
|
+
const w = new Writer();
|
|
12190
|
+
w.u8(item.kind);
|
|
12191
|
+
w.u16(body.length);
|
|
12192
|
+
w.push(body);
|
|
12193
|
+
return w.finish();
|
|
12194
|
+
}
|
|
12195
|
+
function encodeNoteIndexPage(params) {
|
|
12196
|
+
const items = params.items ?? [];
|
|
12197
|
+
if (items.length > NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`count ${items.length} exceeds ${NOTE_INDEX_PAGE_SIZE}`);
|
|
12198
|
+
const w = new Writer();
|
|
12199
|
+
w.push(NOTE_INDEX_MAGIC);
|
|
12200
|
+
w.u8(NOTE_INDEX_FORMAT_VERSION);
|
|
12201
|
+
w.u8(params.complete ? COMPLETE_FLAG : 0);
|
|
12202
|
+
w.u16(0);
|
|
12203
|
+
w.u64(BigInt(params.epoch));
|
|
12204
|
+
w.u64(BigInt(params.page));
|
|
12205
|
+
w.u64(BigInt(params.firstSeq));
|
|
12206
|
+
w.u32(items.length);
|
|
12207
|
+
w.fixed(params.prevChain, 32, "prevChain");
|
|
12208
|
+
for (const item of items) w.push(encodeNoteIndexItem(item));
|
|
12209
|
+
return w.finish();
|
|
12210
|
+
}
|
|
12211
|
+
|
|
12212
|
+
// src/relay/note-index-client.ts
|
|
12213
|
+
var DEFAULT_TIMEOUT_MS2 = 3e4;
|
|
12214
|
+
var DEFAULT_MAX_RETRIES2 = 3;
|
|
12215
|
+
var RETRY_BASE_DELAY_MS = 500;
|
|
12216
|
+
var U64_MAX3 = (1n << 64n) - 1n;
|
|
12217
|
+
function joinPath(relayUrl, path) {
|
|
12218
|
+
const url = new URL(relayUrl);
|
|
12219
|
+
url.pathname = url.pathname.replace(/\/$/, "") + path;
|
|
12220
|
+
return url;
|
|
12221
|
+
}
|
|
12222
|
+
function abortError() {
|
|
12223
|
+
const error = new Error("Note index request aborted");
|
|
12224
|
+
error.name = "AbortError";
|
|
12225
|
+
return error;
|
|
12226
|
+
}
|
|
12227
|
+
function sleep4(ms, signal) {
|
|
12228
|
+
return new Promise((resolve, reject) => {
|
|
12229
|
+
if (signal?.aborted) return reject(abortError());
|
|
12230
|
+
const timer = setTimeout(() => {
|
|
12231
|
+
signal?.removeEventListener("abort", onAbort);
|
|
12232
|
+
resolve();
|
|
12233
|
+
}, ms);
|
|
12234
|
+
const onAbort = () => {
|
|
12235
|
+
clearTimeout(timer);
|
|
12236
|
+
reject(abortError());
|
|
12237
|
+
};
|
|
12238
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
12239
|
+
});
|
|
12240
|
+
}
|
|
12241
|
+
var RetryableStatusError = class extends Error {
|
|
12242
|
+
};
|
|
12243
|
+
var HttpStatusError = class extends Error {
|
|
12244
|
+
constructor(status, message) {
|
|
12245
|
+
super(message);
|
|
12246
|
+
this.status = status;
|
|
12247
|
+
this.name = "HttpStatusError";
|
|
12248
|
+
}
|
|
12249
|
+
};
|
|
12250
|
+
async function requestWithRetry(url, options, read) {
|
|
12251
|
+
assertAllowedRelayOrigin(url);
|
|
12252
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
|
|
12253
|
+
const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES2;
|
|
12254
|
+
let lastError;
|
|
12255
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
12256
|
+
if (options.signal?.aborted) throw abortError();
|
|
12257
|
+
const controller = new AbortController();
|
|
12258
|
+
const onAbort = () => controller.abort();
|
|
12259
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
12260
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
12261
|
+
try {
|
|
12262
|
+
const response = await relayFetch(url, { signal: controller.signal }, { observeClock: false });
|
|
12263
|
+
if (response.status === 429 || response.status >= 500) {
|
|
12264
|
+
throw new RetryableStatusError(`HTTP ${response.status} from ${new URL(url).pathname}`);
|
|
12265
|
+
}
|
|
12266
|
+
return await read(response, controller.signal);
|
|
12267
|
+
} catch (error) {
|
|
12268
|
+
if (options.signal?.aborted) throw abortError();
|
|
12269
|
+
const retryable = error instanceof RetryableStatusError || error instanceof Error && !(error instanceof NoteIndexFormatError) && !(error instanceof HttpStatusError);
|
|
12270
|
+
if (!retryable || attempt >= maxRetries) throw error;
|
|
12271
|
+
lastError = error;
|
|
12272
|
+
await sleep4(RETRY_BASE_DELAY_MS * 2 ** attempt + Math.random() * 250, options.signal);
|
|
12273
|
+
} finally {
|
|
12274
|
+
clearTimeout(timer);
|
|
12275
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
12276
|
+
}
|
|
12277
|
+
}
|
|
12278
|
+
throw lastError instanceof Error ? lastError : new Error(String(lastError));
|
|
12279
|
+
}
|
|
12280
|
+
async function readBoundedBody(response, maxBytes) {
|
|
12281
|
+
const declaredHeader = response.headers?.get?.("content-length") ?? null;
|
|
12282
|
+
const declared = declaredHeader === null ? NaN : Number(declaredHeader);
|
|
12283
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
12284
|
+
throw new NoteIndexFormatError(`response declares ${declared} bytes, over the ${maxBytes}-byte bound`);
|
|
12285
|
+
}
|
|
12286
|
+
const reader = response.body?.getReader?.();
|
|
12287
|
+
if (!reader) {
|
|
12288
|
+
const encoding = (response.headers?.get?.("content-encoding") ?? "").trim().toLowerCase();
|
|
12289
|
+
if (!Number.isSafeInteger(declared) || declared < 0) {
|
|
12290
|
+
throw new NoteIndexFormatError("response has no stream reader and no Content-Length: its size cannot be bounded");
|
|
12291
|
+
}
|
|
12292
|
+
if (encoding !== "" && encoding !== "identity") {
|
|
12293
|
+
throw new NoteIndexFormatError("response has no stream reader and a Content-Encoding: its decoded size cannot be bounded");
|
|
12294
|
+
}
|
|
12295
|
+
const buffer = new Uint8Array(await response.arrayBuffer());
|
|
12296
|
+
if (buffer.length > maxBytes || buffer.length !== declared) {
|
|
12297
|
+
throw new NoteIndexFormatError(`response is ${buffer.length} bytes, not the declared ${declared} within the ${maxBytes}-byte bound`);
|
|
12298
|
+
}
|
|
12299
|
+
return buffer;
|
|
12300
|
+
}
|
|
12301
|
+
const chunks = [];
|
|
12302
|
+
let total = 0;
|
|
12303
|
+
for (; ; ) {
|
|
12304
|
+
const { done, value } = await reader.read();
|
|
12305
|
+
if (done) break;
|
|
12306
|
+
total += value.length;
|
|
12307
|
+
if (total > maxBytes) {
|
|
12308
|
+
await reader.cancel().catch(() => void 0);
|
|
12309
|
+
throw new NoteIndexFormatError(`response exceeds the ${maxBytes}-byte bound`);
|
|
12310
|
+
}
|
|
12311
|
+
chunks.push(value);
|
|
12312
|
+
}
|
|
12313
|
+
const out = new Uint8Array(total);
|
|
12314
|
+
let off = 0;
|
|
12315
|
+
for (const c of chunks) {
|
|
12316
|
+
out.set(c, off);
|
|
12317
|
+
off += c.length;
|
|
12318
|
+
}
|
|
12319
|
+
return out;
|
|
12320
|
+
}
|
|
12321
|
+
function isNonNegativeSafeInteger(value) {
|
|
12322
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
12323
|
+
}
|
|
12324
|
+
async function fetchNoteIndexHead(relayUrl, options = {}) {
|
|
12325
|
+
const url = joinPath(relayUrl, "/note-index/v1/head").toString();
|
|
12326
|
+
const raw = await requestWithRetry(url, options, async (response) => {
|
|
12327
|
+
if (!response.ok) {
|
|
12328
|
+
throw new HttpStatusError(response.status, `note index head: HTTP ${response.status}`);
|
|
12329
|
+
}
|
|
12330
|
+
const text = new TextDecoder().decode(await readBoundedBody(response, 64 * 1024));
|
|
12331
|
+
try {
|
|
12332
|
+
return JSON.parse(text);
|
|
12333
|
+
} catch {
|
|
12334
|
+
throw new NoteIndexFormatError("head is not JSON");
|
|
12335
|
+
}
|
|
12336
|
+
});
|
|
12337
|
+
if (!raw || typeof raw !== "object") throw new NoteIndexFormatError("head is not an object");
|
|
12338
|
+
if (raw.format !== NOTE_INDEX_FORMAT_VERSION) {
|
|
12339
|
+
throw new NoteIndexFormatError(`unsupported head format ${String(raw.format)}`);
|
|
12340
|
+
}
|
|
12341
|
+
if (raw.page_size !== NOTE_INDEX_PAGE_SIZE) {
|
|
12342
|
+
throw new NoteIndexFormatError(`unsupported page_size ${String(raw.page_size)}`);
|
|
12343
|
+
}
|
|
12344
|
+
if (!isNonNegativeSafeInteger(raw.watermark) || !isNonNegativeSafeInteger(raw.complete_pages)) {
|
|
12345
|
+
throw new NoteIndexFormatError("head watermark/complete_pages are not non-negative integers");
|
|
12346
|
+
}
|
|
12347
|
+
if (raw.complete_pages !== Math.floor(raw.watermark / NOTE_INDEX_PAGE_SIZE)) {
|
|
12348
|
+
throw new NoteIndexFormatError(
|
|
12349
|
+
`complete_pages ${raw.complete_pages} disagrees with watermark ${raw.watermark}`
|
|
12350
|
+
);
|
|
12351
|
+
}
|
|
12352
|
+
if (typeof raw.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(raw.epoch) || BigInt(raw.epoch) > U64_MAX3) {
|
|
12353
|
+
throw new NoteIndexFormatError("head epoch is not a u64 decimal string");
|
|
12354
|
+
}
|
|
12355
|
+
if (typeof raw.chain_tip !== "string" || !/^[0-9a-fA-F]{64}$/.test(raw.chain_tip)) {
|
|
12356
|
+
throw new NoteIndexFormatError("head chain_tip is not 32-byte hex");
|
|
12357
|
+
}
|
|
12358
|
+
return {
|
|
12359
|
+
format: 1,
|
|
12360
|
+
epoch: BigInt(raw.epoch),
|
|
12361
|
+
pageSize: NOTE_INDEX_PAGE_SIZE,
|
|
12362
|
+
watermark: raw.watermark,
|
|
12363
|
+
completePages: raw.complete_pages,
|
|
12364
|
+
chainTip: raw.chain_tip.toLowerCase()
|
|
12365
|
+
};
|
|
12366
|
+
}
|
|
12367
|
+
async function fetchNoteIndexPage(relayUrl, epoch, page, options = {}) {
|
|
12368
|
+
if (typeof epoch !== "bigint" || epoch < 0n || epoch > U64_MAX3) throw new Error("epoch must be a u64 bigint");
|
|
12369
|
+
if (!isNonNegativeSafeInteger(page)) throw new Error(`page must be a non-negative integer, got ${page}`);
|
|
12370
|
+
const url = joinPath(relayUrl, `/note-index/v1/e/${epoch.toString(10)}/pages/${page}`).toString();
|
|
12371
|
+
return requestWithRetry(url, options, async (response) => {
|
|
12372
|
+
if (!response.ok) {
|
|
12373
|
+
throw new HttpStatusError(response.status, `note index page ${page}: HTTP ${response.status}`);
|
|
12374
|
+
}
|
|
12375
|
+
return readBoundedBody(response, NOTE_INDEX_MAX_PAGE_BYTES);
|
|
12376
|
+
});
|
|
12377
|
+
}
|
|
12378
|
+
|
|
12379
|
+
// src/scanning/note-index.ts
|
|
12380
|
+
import _bs584 from "bs58";
|
|
12381
|
+
import { sha256 as sha2566 } from "@noble/hashes/sha2";
|
|
12382
|
+
var bs584 = _bs584.default || _bs584;
|
|
12383
|
+
var CURSOR_VERSION = 2;
|
|
12384
|
+
var DEFAULT_CONCURRENCY = 6;
|
|
12385
|
+
var MAX_CONCURRENCY = 32;
|
|
12386
|
+
var ITEM_BATCH = 64;
|
|
12387
|
+
var CURSOR_PAGE_ALIGN = 8;
|
|
12388
|
+
var MAX_PERSISTED_PENDING_LEAVES = 4096;
|
|
12389
|
+
var MAX_CARRIED_PENDING = 256;
|
|
12390
|
+
var MAX_REJECTED_IDS = 1024;
|
|
12391
|
+
var LEAF_WINDOW = 512;
|
|
12392
|
+
var MAX_OVERRIDES = 256;
|
|
12393
|
+
var MAX_CURSOR_OWN_ITEMS = 65536;
|
|
12394
|
+
var MAX_LEGACY_VIEWING_KEYS = 8;
|
|
12395
|
+
var MAX_CURSOR_KEYS = 131072;
|
|
12396
|
+
var MAX_CURSOR_POOLS = 256;
|
|
12397
|
+
var MAX_CURSOR_PAGE = 2 ** 32;
|
|
12398
|
+
var TREE_CAPACITY = 2 ** MERKLE_TREE_HEIGHT2;
|
|
12399
|
+
var ZERO_CHAIN = "00".repeat(32);
|
|
12400
|
+
var U64_MAX4 = (1n << 64n) - 1n;
|
|
12401
|
+
var NoteIndexHeadBehindError = class extends Error {
|
|
12402
|
+
constructor(cursorWatermark, headWatermark) {
|
|
12403
|
+
super(
|
|
12404
|
+
`note index head is behind this cursor (watermark ${headWatermark} < ${cursorWatermark} seen before in this epoch): a stale cache or a rollback; retry later with the same cursor`
|
|
12405
|
+
);
|
|
12406
|
+
this.cursorWatermark = cursorWatermark;
|
|
12407
|
+
this.headWatermark = headWatermark;
|
|
12408
|
+
this.retryable = true;
|
|
12409
|
+
this.name = "NoteIndexHeadBehindError";
|
|
12410
|
+
}
|
|
12411
|
+
};
|
|
12412
|
+
var FullPassSignal = class {
|
|
12413
|
+
constructor(reason) {
|
|
12414
|
+
this.reason = reason;
|
|
12415
|
+
}
|
|
12416
|
+
};
|
|
12417
|
+
function abortError2() {
|
|
12418
|
+
const error = new Error("recoverNotesFromIndex aborted");
|
|
12419
|
+
error.name = "AbortError";
|
|
12420
|
+
return error;
|
|
12421
|
+
}
|
|
12422
|
+
function bytesToBigint2(bytes) {
|
|
12423
|
+
let v = 0n;
|
|
12424
|
+
for (let i = 0; i < bytes.length; i++) v = v << 8n | BigInt(bytes[i]);
|
|
12425
|
+
return v;
|
|
12426
|
+
}
|
|
12427
|
+
function toHex2(bytes) {
|
|
12428
|
+
let s = "";
|
|
12429
|
+
for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, "0");
|
|
12430
|
+
return s;
|
|
12431
|
+
}
|
|
12432
|
+
function fromHex(hex) {
|
|
12433
|
+
return Uint8Array.from(Buffer.from(hex, "hex"));
|
|
12434
|
+
}
|
|
12435
|
+
function hex32(v) {
|
|
12436
|
+
return v.toString(16).padStart(64, "0");
|
|
12437
|
+
}
|
|
12438
|
+
function isAllZero3(bytes) {
|
|
12439
|
+
for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
|
|
12440
|
+
return true;
|
|
12441
|
+
}
|
|
12442
|
+
function floorAlign(page) {
|
|
12443
|
+
return page - page % CURSOR_PAGE_ALIGN;
|
|
12444
|
+
}
|
|
12445
|
+
function verifiedKey(mint, leaf, commitment) {
|
|
12446
|
+
return `${mint}:${leaf}:${hex32(commitment)}`;
|
|
12447
|
+
}
|
|
12448
|
+
function itemIdentity(raw) {
|
|
12449
|
+
return toHex2(sha2566(raw).subarray(0, 16));
|
|
12450
|
+
}
|
|
12451
|
+
var LeafBuffer = class {
|
|
12452
|
+
constructor() {
|
|
12453
|
+
this.bytes = new Uint8Array(32 * 1024);
|
|
12454
|
+
this.view = new DataView(this.bytes.buffer);
|
|
12455
|
+
this.count = 0;
|
|
12456
|
+
}
|
|
12457
|
+
get length() {
|
|
12458
|
+
return this.count;
|
|
12459
|
+
}
|
|
12460
|
+
push(values) {
|
|
12461
|
+
const need = (this.count + values.length) * 32;
|
|
12462
|
+
if (need > this.bytes.length) {
|
|
12463
|
+
let size = this.bytes.length;
|
|
12464
|
+
while (size < need) size *= 2;
|
|
12465
|
+
const next = new Uint8Array(size);
|
|
12466
|
+
next.set(this.bytes.subarray(0, this.count * 32));
|
|
12467
|
+
this.bytes = next;
|
|
12468
|
+
this.view = new DataView(next.buffer);
|
|
12469
|
+
}
|
|
12470
|
+
for (const v of values) {
|
|
12471
|
+
const o = this.count * 32;
|
|
12472
|
+
this.view.setBigUint64(o, v >> 192n & 0xffffffffffffffffn);
|
|
12473
|
+
this.view.setBigUint64(o + 8, v >> 128n & 0xffffffffffffffffn);
|
|
12474
|
+
this.view.setBigUint64(o + 16, v >> 64n & 0xffffffffffffffffn);
|
|
12475
|
+
this.view.setBigUint64(o + 24, v & 0xffffffffffffffffn);
|
|
12476
|
+
this.count++;
|
|
12477
|
+
}
|
|
12478
|
+
}
|
|
12479
|
+
get(i) {
|
|
12480
|
+
if (i < 0 || i >= this.count) return void 0;
|
|
12481
|
+
const o = i * 32;
|
|
12482
|
+
return this.view.getBigUint64(o) << 192n | this.view.getBigUint64(o + 8) << 128n | this.view.getBigUint64(o + 16) << 64n | this.view.getBigUint64(o + 24);
|
|
12483
|
+
}
|
|
12484
|
+
};
|
|
12485
|
+
async function trialItem(item, trials) {
|
|
12486
|
+
for (const trial of trials) {
|
|
12487
|
+
if (trial.legacy && item.kind === 2) continue;
|
|
12488
|
+
const opened = await trialItemWith(item, trial);
|
|
12489
|
+
if (opened) return { ...opened, trial };
|
|
12490
|
+
}
|
|
12491
|
+
return null;
|
|
12492
|
+
}
|
|
12493
|
+
async function trialItemIsolated(item, trials, stats) {
|
|
12494
|
+
try {
|
|
12495
|
+
return await trialItem(item, trials);
|
|
12496
|
+
} catch {
|
|
12497
|
+
stats.skipped++;
|
|
12498
|
+
return null;
|
|
12499
|
+
}
|
|
12500
|
+
}
|
|
12501
|
+
async function trialItemWith(item, trial) {
|
|
12502
|
+
if (item.kind === 1) {
|
|
12503
|
+
if (item.note.length === 0) return null;
|
|
12504
|
+
let note = isAllZero3(item.comm0) ? null : await trial.decrypt(item.note, item.comm0);
|
|
12505
|
+
if (!note && item.note[0] === 2 && !isAllZero3(item.comm1)) note = await trial.decrypt(item.note, item.comm1);
|
|
12506
|
+
return note ? { note } : null;
|
|
12507
|
+
}
|
|
12508
|
+
if (item.kind === 2) {
|
|
12509
|
+
const delivery = await trial.open(item.envelope);
|
|
12510
|
+
return delivery ? { delivery } : null;
|
|
12511
|
+
}
|
|
12512
|
+
if (item.amountAfterFee === 0n) return null;
|
|
12513
|
+
const refund = await matchSwapRefundLeaf({
|
|
12514
|
+
viewingKeyNk: trial.nk,
|
|
12515
|
+
inputNullifier: item.nullifier0,
|
|
12516
|
+
amountAfterFee: item.amountAfterFee,
|
|
12517
|
+
commitment: item.commitment,
|
|
12518
|
+
ownerUtxoKeypair: trial.owner
|
|
12519
|
+
});
|
|
12520
|
+
return refund ? { refund } : null;
|
|
12521
|
+
}
|
|
12522
|
+
function txOutputs(item) {
|
|
12523
|
+
const out = [toHex2(item.comm0)];
|
|
12524
|
+
if (!isAllZero3(item.comm1)) out.push(toHex2(item.comm1));
|
|
12525
|
+
return out;
|
|
12526
|
+
}
|
|
12527
|
+
function leafOfTxOutput(item, commitment) {
|
|
12528
|
+
if (!isAllZero3(item.comm0) && commitment === bytesToBigint2(item.comm0)) return Number(item.leaf0);
|
|
12529
|
+
if (!isAllZero3(item.comm1) && commitment === bytesToBigint2(item.comm1)) return Number(item.leaf1);
|
|
12530
|
+
return null;
|
|
12531
|
+
}
|
|
12532
|
+
function changeBlindingOrNull(nk, noteSalt, outputIndex) {
|
|
12533
|
+
try {
|
|
12534
|
+
return deriveChangeNoteBlinding(nk, noteSalt, outputIndex);
|
|
12535
|
+
} catch {
|
|
12536
|
+
return null;
|
|
12537
|
+
}
|
|
12538
|
+
}
|
|
12539
|
+
async function matchOwnItems(own, owner, onReject, onSkip) {
|
|
12540
|
+
const candidates = [];
|
|
12541
|
+
const claimed = /* @__PURE__ */ new Set();
|
|
12542
|
+
const byNullifier = /* @__PURE__ */ new Map();
|
|
12543
|
+
const legacyKeys = /* @__PURE__ */ new Map();
|
|
12544
|
+
const ownTxs = own.filter((o) => o.item.kind === 1 && o.note?.noteSalt !== void 0);
|
|
12545
|
+
const spendsOf = /* @__PURE__ */ new Map();
|
|
12546
|
+
const byOutKey = /* @__PURE__ */ new Map();
|
|
12547
|
+
const index = (map, key, o) => {
|
|
12548
|
+
const list = map.get(key);
|
|
12549
|
+
if (list) list.push(o);
|
|
12550
|
+
else map.set(key, [o]);
|
|
12551
|
+
};
|
|
12552
|
+
for (const o of ownTxs) {
|
|
12553
|
+
for (const n of [o.item.nullifier0, o.item.nullifier1]) if (!isAllZero3(n)) index(spendsOf, toHex2(n), o);
|
|
12554
|
+
if (o.note.outPubkey0 !== void 0) index(byOutKey, o.note.outPubkey0, o);
|
|
12555
|
+
}
|
|
12556
|
+
const queue = [];
|
|
12557
|
+
const queued = /* @__PURE__ */ new Set();
|
|
12558
|
+
const enqueue = (o) => {
|
|
12559
|
+
if (queued.has(o)) return;
|
|
12560
|
+
queued.add(o);
|
|
12561
|
+
queue.push(o);
|
|
12562
|
+
};
|
|
12563
|
+
const add = async (o, c) => {
|
|
12564
|
+
const nullifier = hex32(
|
|
12565
|
+
await computeNullifier({ amount: c.amount, keypair: c.keypair, blinding: c.blinding, mintAddress: c.mint, index: c.leaf, commitment: c.commitment })
|
|
12566
|
+
);
|
|
12567
|
+
const full = { ...c, atRisk: c.atRisk || o.trial.legacy, signature: o.item.signature, page: o.page, seq: o.seq, nullifier };
|
|
12568
|
+
candidates.push(full);
|
|
12569
|
+
if (!byNullifier.has(nullifier)) {
|
|
12570
|
+
byNullifier.set(nullifier, full);
|
|
12571
|
+
for (const s of spendsOf.get(nullifier) ?? []) enqueue(s);
|
|
12572
|
+
}
|
|
12573
|
+
if (c.atRisk && c.keypair.publicKey !== owner.publicKey && !legacyKeys.has(c.keypair.publicKey)) {
|
|
12574
|
+
legacyKeys.set(c.keypair.publicKey, c.keypair);
|
|
12575
|
+
for (const s of byOutKey.get(c.keypair.publicKey) ?? []) enqueue(s);
|
|
12576
|
+
}
|
|
12577
|
+
};
|
|
12578
|
+
const tryDeposit = async (o, item, amount) => {
|
|
12579
|
+
const note = o.note;
|
|
12580
|
+
const mint = addressFromBytes(item.mint);
|
|
12581
|
+
const deposit = await matchDepositNote({
|
|
12582
|
+
viewingKeyNk: o.trial.nk,
|
|
12583
|
+
noteSalt: note.noteSalt,
|
|
12584
|
+
amount,
|
|
12585
|
+
mintAddress: mint,
|
|
12586
|
+
outputCommitments: txOutputs(item),
|
|
12587
|
+
ownerUtxoKeypair: owner
|
|
12588
|
+
});
|
|
12589
|
+
const leaf = deposit ? leafOfTxOutput(item, deposit.commitment) : null;
|
|
12590
|
+
if (!deposit || leaf === null) return false;
|
|
12591
|
+
await add(o, {
|
|
12592
|
+
kind: "deposit",
|
|
12593
|
+
atRisk: deposit.legacyExposed,
|
|
12594
|
+
amount: deposit.amount,
|
|
12595
|
+
blinding: deposit.blinding,
|
|
12596
|
+
keypair: deposit.legacyExposed ? deposit.keypair : owner,
|
|
12597
|
+
mint,
|
|
12598
|
+
commitment: deposit.commitment,
|
|
12599
|
+
leaf
|
|
12600
|
+
});
|
|
12601
|
+
return true;
|
|
12602
|
+
};
|
|
12603
|
+
const tryChange0 = async (o, item, keypair, atRisk) => {
|
|
12604
|
+
const note = o.note;
|
|
12605
|
+
const mint = addressFromBytes(item.mint);
|
|
12606
|
+
const change = await matchChangeNote({
|
|
12607
|
+
viewingKeyNk: o.trial.nk,
|
|
12608
|
+
noteSalt: note.noteSalt,
|
|
12609
|
+
amount: note.outAmount0,
|
|
12610
|
+
keypair,
|
|
12611
|
+
mintAddress: mint,
|
|
12612
|
+
outputIndex: 0,
|
|
12613
|
+
outputCommitments: [toHex2(item.comm0)],
|
|
12614
|
+
ownerUtxoPublicKey: owner.publicKey
|
|
12615
|
+
});
|
|
12616
|
+
if (!change) return false;
|
|
12617
|
+
await add(o, {
|
|
12618
|
+
kind: "change",
|
|
12619
|
+
atRisk,
|
|
12620
|
+
amount: change.amount,
|
|
12621
|
+
blinding: change.blinding,
|
|
12622
|
+
keypair,
|
|
12623
|
+
mint,
|
|
12624
|
+
commitment: change.commitment,
|
|
12625
|
+
leaf: Number(item.leaf0)
|
|
12626
|
+
});
|
|
12627
|
+
return true;
|
|
12628
|
+
};
|
|
12629
|
+
const direct = async (o) => {
|
|
12630
|
+
const item = o.item;
|
|
12631
|
+
if (item.kind === 1 && o.note?.noteSalt !== void 0) {
|
|
12632
|
+
const note = o.note;
|
|
12633
|
+
if (note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
|
|
12634
|
+
if (await tryDeposit(o, item, item.publicAmount)) claimed.add(`${o.seq}:0`);
|
|
12635
|
+
}
|
|
12636
|
+
if (note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 === owner.publicKey) {
|
|
12637
|
+
if (await tryChange0(o, item, owner, false)) claimed.add(`${o.seq}:0`);
|
|
12638
|
+
}
|
|
12639
|
+
} else if (item.kind === 2 && o.delivery) {
|
|
12640
|
+
const mint = addressFromBytes(item.mint);
|
|
12641
|
+
if (o.delivery.amount <= 0n || o.delivery.blinding === 0n) {
|
|
12642
|
+
onReject(o);
|
|
12643
|
+
return;
|
|
12644
|
+
}
|
|
12645
|
+
const commitment = await computeCommitment({
|
|
12646
|
+
amount: o.delivery.amount,
|
|
12647
|
+
keypair: { privateKey: 0n, publicKey: owner.publicKey },
|
|
12648
|
+
blinding: o.delivery.blinding,
|
|
12649
|
+
mintAddress: mint
|
|
12650
|
+
});
|
|
12651
|
+
if (commitment !== bytesToBigint2(item.commitment)) {
|
|
12652
|
+
onReject(o);
|
|
12653
|
+
return;
|
|
12654
|
+
}
|
|
12655
|
+
await add(o, {
|
|
12656
|
+
kind: "received",
|
|
12657
|
+
atRisk: false,
|
|
12658
|
+
amount: o.delivery.amount,
|
|
12659
|
+
blinding: o.delivery.blinding,
|
|
12660
|
+
keypair: owner,
|
|
12661
|
+
mint,
|
|
12662
|
+
commitment,
|
|
12663
|
+
leaf: Number(item.leaf)
|
|
12664
|
+
});
|
|
12665
|
+
} else if (item.kind === 3 && o.refund) {
|
|
12666
|
+
await add(o, {
|
|
12667
|
+
kind: "swap_refund",
|
|
12668
|
+
atRisk: o.refund.legacyExposed,
|
|
12669
|
+
amount: o.refund.amount,
|
|
12670
|
+
blinding: o.refund.blinding,
|
|
12671
|
+
keypair: o.refund.legacyExposed ? o.refund.keypair : owner,
|
|
12672
|
+
mint: NATIVE_SOL_MINT,
|
|
12673
|
+
commitment: o.refund.commitment,
|
|
12674
|
+
leaf: Number(item.leaf)
|
|
12675
|
+
});
|
|
12676
|
+
}
|
|
12677
|
+
};
|
|
12678
|
+
for (const o of own) {
|
|
12679
|
+
try {
|
|
12680
|
+
await direct(o);
|
|
12681
|
+
} catch {
|
|
12682
|
+
onSkip(o);
|
|
12683
|
+
}
|
|
12684
|
+
}
|
|
12685
|
+
const processTx = async (o) => {
|
|
12686
|
+
const item = o.item;
|
|
12687
|
+
const note = o.note;
|
|
12688
|
+
if (!claimed.has(`${o.seq}:0`) && note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 !== void 0) {
|
|
12689
|
+
const legacy = legacyKeys.get(note.outPubkey0);
|
|
12690
|
+
if (legacy && await tryChange0(o, item, legacy, true)) claimed.add(`${o.seq}:0`);
|
|
12691
|
+
}
|
|
12692
|
+
const mint = addressFromBytes(item.mint);
|
|
12693
|
+
const inputs = [item.nullifier0, item.nullifier1].filter((n) => !isAllZero3(n)).map((n) => byNullifier.get(toHex2(n))).filter((c) => c !== void 0 && c.mint === mint);
|
|
12694
|
+
if (inputs.length === 0) return;
|
|
12695
|
+
const sumIn = inputs.reduce((acc, c) => acc + c.amount, 0n);
|
|
12696
|
+
if (!claimed.has(`${o.seq}:1`) && note.outAmount0 !== void 0 && !isAllZero3(item.comm1)) {
|
|
12697
|
+
const out1 = sumIn + item.publicAmount - note.outAmount0;
|
|
12698
|
+
const blinding = out1 > 0n ? changeBlindingOrNull(o.trial.nk, note.noteSalt, 1) : null;
|
|
12699
|
+
if (out1 > 0n && blinding === null) onSkip(o);
|
|
12700
|
+
else if (blinding !== null) {
|
|
12701
|
+
const owners = [{ keypair: owner, atRisk: false }];
|
|
12702
|
+
const legacyInput = legacyKeys.get(inputs[0].keypair.publicKey);
|
|
12703
|
+
if (legacyInput && legacyInput.publicKey !== owner.publicKey) owners.push({ keypair: legacyInput, atRisk: true });
|
|
12704
|
+
for (const { keypair, atRisk } of owners) {
|
|
12705
|
+
const commitment = await computeCommitment({ amount: out1, keypair, blinding, mintAddress: mint });
|
|
12706
|
+
if (commitment !== bytesToBigint2(item.comm1)) continue;
|
|
12707
|
+
claimed.add(`${o.seq}:1`);
|
|
12708
|
+
await add(o, { kind: "change", atRisk, amount: out1, blinding, keypair, mint, commitment, leaf: Number(item.leaf1) });
|
|
12709
|
+
break;
|
|
12710
|
+
}
|
|
12711
|
+
}
|
|
12712
|
+
}
|
|
12713
|
+
if (!claimed.has(`${o.seq}:0`) && note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
|
|
12714
|
+
if (await tryDeposit(o, item, item.publicAmount + sumIn)) claimed.add(`${o.seq}:0`);
|
|
12715
|
+
}
|
|
12716
|
+
};
|
|
12717
|
+
for (const o of ownTxs) enqueue(o);
|
|
12718
|
+
for (let i = 0; i < queue.length; i++) {
|
|
12719
|
+
const o = queue[i];
|
|
12720
|
+
queued.delete(o);
|
|
12721
|
+
try {
|
|
12722
|
+
await processTx(o);
|
|
12723
|
+
} catch {
|
|
12724
|
+
onSkip(o);
|
|
12725
|
+
}
|
|
12726
|
+
}
|
|
12727
|
+
return candidates;
|
|
12728
|
+
}
|
|
12729
|
+
async function replayStream(start, pages, overrides, chain, targetPage) {
|
|
12730
|
+
const frontier = await MerkleFrontier.create(start.frontier ?? void 0, MERKLE_TREE_HEIGHT2);
|
|
12731
|
+
const startN = frontier.nextIndex;
|
|
12732
|
+
const pending = new Map(start.pending);
|
|
12733
|
+
const flushed = new LeafBuffer();
|
|
12734
|
+
const corrections = /* @__PURE__ */ new Map();
|
|
12735
|
+
let conflicts = 0;
|
|
12736
|
+
let verifiedPrefix = 0;
|
|
12737
|
+
let mismatch = false;
|
|
12738
|
+
const checks = [];
|
|
12739
|
+
const setBits = [];
|
|
12740
|
+
if (chain && chain.nextIndex > 0) {
|
|
12741
|
+
const last = chain.nextIndex - 1;
|
|
12742
|
+
for (let l = 0; l < MERKLE_TREE_HEIGHT2; l++) if (Math.floor(last / 2 ** l) % 2 === 1) setBits.push(l);
|
|
12743
|
+
for (const l of setBits) {
|
|
12744
|
+
const at = Math.floor(last / 2 ** l) * 2 ** l;
|
|
12745
|
+
if (at >= startN) checks.push({ at, level: l });
|
|
12746
|
+
}
|
|
12747
|
+
if (chain.nextIndex >= startN) checks.push({ at: chain.nextIndex, level: -1 });
|
|
12748
|
+
checks.sort((a, b) => a.at - b.at);
|
|
12749
|
+
}
|
|
12750
|
+
let nextCheck = 0;
|
|
12751
|
+
const runChecks = () => {
|
|
12752
|
+
while (nextCheck < checks.length && checks[nextCheck].at === frontier.nextIndex) {
|
|
12753
|
+
const { at, level } = checks[nextCheck++];
|
|
12754
|
+
const ok = level < 0 ? frontier.root() === chain.root : setBits.every((j) => j < level || frontier.leftAt(j) === chain.subtrees[j]);
|
|
12755
|
+
if (ok) verifiedPrefix = Math.max(verifiedPrefix, at);
|
|
12756
|
+
else mismatch = true;
|
|
12757
|
+
}
|
|
12758
|
+
};
|
|
12759
|
+
const append = (values) => {
|
|
12760
|
+
let i = 0;
|
|
12761
|
+
while (i < values.length) {
|
|
12762
|
+
const room = nextCheck < checks.length ? checks[nextCheck].at - frontier.nextIndex : values.length - i;
|
|
12763
|
+
const take = Math.min(values.length - i, room);
|
|
12764
|
+
if (take > 0) {
|
|
12765
|
+
const part = values.slice(i, i + take);
|
|
12766
|
+
frontier.append(part);
|
|
12767
|
+
flushed.push(part);
|
|
12768
|
+
i += take;
|
|
12769
|
+
}
|
|
12770
|
+
runChecks();
|
|
12771
|
+
}
|
|
12772
|
+
};
|
|
12773
|
+
const valueAt = (leaf) => leaf >= startN && leaf < startN + flushed.length ? flushed.get(leaf - startN) : pending.get(leaf);
|
|
12774
|
+
const flush = () => {
|
|
12775
|
+
const batch = [];
|
|
12776
|
+
let next = frontier.nextIndex;
|
|
12777
|
+
while (pending.has(next)) {
|
|
12778
|
+
batch.push(pending.get(next));
|
|
12779
|
+
pending.delete(next);
|
|
12780
|
+
next++;
|
|
12781
|
+
}
|
|
12782
|
+
if (batch.length > 0) append(batch);
|
|
12783
|
+
};
|
|
12784
|
+
let snapshot = null;
|
|
12785
|
+
let taken = false;
|
|
12786
|
+
const takeSnapshot = () => {
|
|
12787
|
+
taken = true;
|
|
12788
|
+
if (pending.size > MAX_PERSISTED_PENDING_LEAVES) return;
|
|
12789
|
+
snapshot = { frontier: frontier.toState(), pending: new Map(pending), nextIndex: frontier.nextIndex };
|
|
12790
|
+
};
|
|
12791
|
+
runChecks();
|
|
12792
|
+
flush();
|
|
12793
|
+
for (const { page, entries } of pages) {
|
|
12794
|
+
if (!taken && page >= targetPage) takeSnapshot();
|
|
12795
|
+
for (const e of entries) {
|
|
12796
|
+
if (e.leaf < startN) continue;
|
|
12797
|
+
const prior = valueAt(e.leaf);
|
|
12798
|
+
if (prior !== void 0) {
|
|
12799
|
+
if (prior !== e.commitment) {
|
|
12800
|
+
conflicts++;
|
|
12801
|
+
corrections.set(e.leaf, e.commitment);
|
|
12802
|
+
}
|
|
12803
|
+
continue;
|
|
12804
|
+
}
|
|
12805
|
+
pending.set(e.leaf, overrides.get(e.leaf) ?? e.commitment);
|
|
12806
|
+
}
|
|
12807
|
+
flush();
|
|
12808
|
+
}
|
|
12809
|
+
if (!taken) takeSnapshot();
|
|
12810
|
+
if (chain && treeAccountAcceptsRoot(chain.data, hex32(frontier.root()))) {
|
|
12811
|
+
verifiedPrefix = Math.max(verifiedPrefix, Math.min(frontier.nextIndex, chain.nextIndex));
|
|
12812
|
+
}
|
|
12813
|
+
return { endCount: frontier.nextIndex, valueAt, snapshot, conflicts, corrections, verifiedPrefix, mismatch };
|
|
12814
|
+
}
|
|
12815
|
+
var HEX64 = /^[0-9a-f]{64}$/;
|
|
12816
|
+
var HEX32 = /^[0-9a-f]{32}$/;
|
|
12817
|
+
var ADDRESS = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
|
|
12818
|
+
var VERIFIED_KEY = /^[1-9A-HJ-NP-Za-km-z]{32,44}:(0|[1-9][0-9]{0,9}):[0-9a-f]{64}$/;
|
|
12819
|
+
function isRecord(v) {
|
|
12820
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
12821
|
+
}
|
|
12822
|
+
function isIntIn(v, min, max) {
|
|
12823
|
+
return typeof v === "number" && Number.isSafeInteger(v) && v >= min && v <= max;
|
|
12824
|
+
}
|
|
12825
|
+
function isBoundedArray(v, max) {
|
|
12826
|
+
return Array.isArray(v) && v.length <= max;
|
|
12827
|
+
}
|
|
12828
|
+
function emptyStartTree() {
|
|
12829
|
+
return {
|
|
12830
|
+
frontier: null,
|
|
12831
|
+
nextIndex: 0,
|
|
12832
|
+
pending: /* @__PURE__ */ new Map(),
|
|
12833
|
+
window: [],
|
|
12834
|
+
windowStart: 0,
|
|
12835
|
+
verified: 0,
|
|
12836
|
+
overrides: /* @__PURE__ */ new Map(),
|
|
12837
|
+
mismatch: false,
|
|
12838
|
+
hiBefore: -1
|
|
12839
|
+
};
|
|
12840
|
+
}
|
|
12841
|
+
async function parseCursor(cursor, poolMints) {
|
|
12842
|
+
try {
|
|
12843
|
+
if (!isRecord(cursor)) return "not an object";
|
|
12844
|
+
if (cursor.v !== CURSOR_VERSION) return "unsupported cursor version";
|
|
12845
|
+
const c = cursor;
|
|
12846
|
+
if (typeof c.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(c.epoch) || BigInt(c.epoch) > U64_MAX4) return "bad epoch";
|
|
12847
|
+
if (!isIntIn(c.page, 0, MAX_CURSOR_PAGE) || c.page % CURSOR_PAGE_ALIGN !== 0) return "bad page";
|
|
12848
|
+
if (typeof c.chain !== "string" || !HEX64.test(c.chain)) return "bad chain";
|
|
12849
|
+
if (!isIntIn(c.watermark, 0, Number.MAX_SAFE_INTEGER) || c.page * NOTE_INDEX_PAGE_SIZE > c.watermark) return "bad watermark";
|
|
12850
|
+
if (!isIntIn(c.fullPassSeq, 0, c.watermark)) return "bad full-pass mark";
|
|
12851
|
+
if (!isRecord(c.trees) || Object.keys(c.trees).length > MAX_CURSOR_POOLS) return "bad trees";
|
|
12852
|
+
const trees = /* @__PURE__ */ new Map();
|
|
12853
|
+
for (const mint of poolMints) {
|
|
12854
|
+
const t = c.trees[mint];
|
|
12855
|
+
if (!isRecord(t)) return "a listed pool is missing from the cursor";
|
|
12856
|
+
const tree = t;
|
|
12857
|
+
if (!isRecord(tree.frontier)) return "bad frontier";
|
|
12858
|
+
let frontier;
|
|
12859
|
+
try {
|
|
12860
|
+
frontier = await MerkleFrontier.create(tree.frontier, MERKLE_TREE_HEIGHT2);
|
|
12861
|
+
} catch {
|
|
12862
|
+
return "bad frontier";
|
|
12863
|
+
}
|
|
12864
|
+
const nextIndex = frontier.nextIndex;
|
|
12865
|
+
if (!isBoundedArray(tree.pending, MAX_PERSISTED_PENDING_LEAVES)) return "bad pending leaves";
|
|
12866
|
+
const pending = /* @__PURE__ */ new Map();
|
|
12867
|
+
let hiBefore = nextIndex - 1;
|
|
12868
|
+
for (const entry of tree.pending) {
|
|
12869
|
+
if (!Array.isArray(entry) || entry.length !== 2) return "bad pending leaves";
|
|
12870
|
+
const [leaf, value] = entry;
|
|
12871
|
+
if (!isIntIn(leaf, nextIndex + 1, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value) || pending.has(leaf)) {
|
|
12872
|
+
return "bad pending leaves";
|
|
12873
|
+
}
|
|
12874
|
+
pending.set(leaf, BigInt("0x" + value));
|
|
12875
|
+
hiBefore = Math.max(hiBefore, leaf);
|
|
12876
|
+
}
|
|
12877
|
+
if (typeof tree.window !== "string" || tree.window.length % 64 !== 0 || !/^[0-9a-f]*$/.test(tree.window)) return "bad window";
|
|
12878
|
+
const windowLen = tree.window.length / 64;
|
|
12879
|
+
if (windowLen > LEAF_WINDOW || windowLen > nextIndex) return "bad window";
|
|
12880
|
+
const window2 = [];
|
|
12881
|
+
for (let i = 0; i < windowLen; i++) window2.push(BigInt("0x" + tree.window.slice(i * 64, (i + 1) * 64)));
|
|
12882
|
+
if (!isIntIn(tree.verified, 0, nextIndex)) return "bad verified prefix";
|
|
12883
|
+
if (!isBoundedArray(tree.overrides, MAX_OVERRIDES)) return "bad overrides";
|
|
12884
|
+
const overrides = /* @__PURE__ */ new Map();
|
|
12885
|
+
for (const entry of tree.overrides) {
|
|
12886
|
+
if (!Array.isArray(entry) || entry.length !== 2) return "bad overrides";
|
|
12887
|
+
const [leaf, value] = entry;
|
|
12888
|
+
if (!isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) return "bad overrides";
|
|
12889
|
+
overrides.set(leaf, BigInt("0x" + value));
|
|
12890
|
+
}
|
|
12891
|
+
if (typeof tree.mismatch !== "boolean") return "bad mismatch flag";
|
|
12892
|
+
trees.set(mint, {
|
|
12893
|
+
frontier: frontier.toState(),
|
|
12894
|
+
nextIndex,
|
|
12895
|
+
pending,
|
|
12896
|
+
window: window2,
|
|
12897
|
+
windowStart: nextIndex - windowLen,
|
|
12898
|
+
verified: tree.verified,
|
|
12899
|
+
overrides,
|
|
12900
|
+
mismatch: tree.mismatch,
|
|
12901
|
+
hiBefore
|
|
12902
|
+
});
|
|
12903
|
+
}
|
|
12904
|
+
const own = c.own;
|
|
12905
|
+
if (!isRecord(own)) return "bad own state";
|
|
12906
|
+
if (!isBoundedArray(own.items, MAX_CURSOR_OWN_ITEMS)) return "bad own items";
|
|
12907
|
+
const items = [];
|
|
12908
|
+
const seqs = /* @__PURE__ */ new Set();
|
|
12909
|
+
for (const entry of own.items) {
|
|
12910
|
+
if (!isRecord(entry)) return "bad own items";
|
|
12911
|
+
const { seq, item } = entry;
|
|
12912
|
+
if (!isIntIn(seq, 0, c.page * NOTE_INDEX_PAGE_SIZE - 1) || seqs.has(seq)) return "bad own items";
|
|
12913
|
+
if (typeof item !== "string" || item.length % 2 !== 0 || item.length > 2 * 4096 || !/^[0-9a-f]+$/.test(item)) return "bad own items";
|
|
12914
|
+
seqs.add(seq);
|
|
12915
|
+
const raw = fromHex(item);
|
|
12916
|
+
items.push({ seq, raw, item: parseNoteIndexItem(raw) });
|
|
12917
|
+
}
|
|
12918
|
+
if (!isBoundedArray(own.verified, MAX_CURSOR_KEYS) || !own.verified.every((k) => typeof k === "string" && VERIFIED_KEY.test(k))) {
|
|
12919
|
+
return "bad verified notes";
|
|
12920
|
+
}
|
|
12921
|
+
if (!isBoundedArray(own.spent, MAX_CURSOR_KEYS) || !own.spent.every((k) => typeof k === "string" && HEX64.test(k))) return "bad spent set";
|
|
12922
|
+
if (!isBoundedArray(own.pendingLeaves, MAX_CARRIED_PENDING)) return "bad pending notes";
|
|
12923
|
+
const pendingLeaves = /* @__PURE__ */ new Map();
|
|
12924
|
+
for (const entry of own.pendingLeaves) {
|
|
12925
|
+
if (!Array.isArray(entry) || entry.length !== 3) return "bad pending notes";
|
|
12926
|
+
const [mint, leaf, value] = entry;
|
|
12927
|
+
if (typeof mint !== "string" || !ADDRESS.test(mint) || !isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) {
|
|
12928
|
+
return "bad pending notes";
|
|
12929
|
+
}
|
|
12930
|
+
pendingLeaves.set(`${mint}:${leaf}`, BigInt("0x" + value));
|
|
12931
|
+
}
|
|
12932
|
+
if (!isBoundedArray(own.rejected, MAX_REJECTED_IDS) || !own.rejected.every((k) => typeof k === "string" && HEX32.test(k))) {
|
|
12933
|
+
return "bad rejected set";
|
|
12934
|
+
}
|
|
12935
|
+
return {
|
|
12936
|
+
raw: c,
|
|
12937
|
+
trees,
|
|
12938
|
+
items,
|
|
12939
|
+
verified: new Set(own.verified),
|
|
12940
|
+
spent: new Set(own.spent),
|
|
12941
|
+
pendingLeaves,
|
|
12942
|
+
rejected: own.rejected
|
|
12943
|
+
};
|
|
12944
|
+
} catch {
|
|
12945
|
+
return "unreadable state";
|
|
12946
|
+
}
|
|
12947
|
+
}
|
|
12948
|
+
async function recoverNotesFromIndex(params) {
|
|
12949
|
+
const startedAt = Date.now();
|
|
12950
|
+
const { relayUrl, connection, viewingKeyNk, programId } = params;
|
|
12951
|
+
assertAllowedRelayOrigin(relayUrl);
|
|
12952
|
+
assertAllowedRpcConnection(connection);
|
|
12953
|
+
if (!(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) throw new Error("viewingKeyNk must be 32 bytes");
|
|
12954
|
+
const owner = await assertOwnerUtxoKeypair(params.ownerUtxoKeypair);
|
|
12955
|
+
if (!Array.isArray(params.poolMints)) throw new Error("poolMints must list every active pool mint");
|
|
12956
|
+
const concurrency = params.concurrency ?? DEFAULT_CONCURRENCY;
|
|
12957
|
+
if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > MAX_CONCURRENCY) {
|
|
12958
|
+
throw new Error(`concurrency must be an integer in 1..${MAX_CONCURRENCY}`);
|
|
12959
|
+
}
|
|
12960
|
+
if (params.signal?.aborted) throw abortError2();
|
|
12961
|
+
const stats = {
|
|
12962
|
+
pages: 0,
|
|
12963
|
+
items: 0,
|
|
12964
|
+
bytes: 0,
|
|
12965
|
+
rpcCalls: 0,
|
|
12966
|
+
ms: 0,
|
|
12967
|
+
dropped: 0,
|
|
12968
|
+
decrypted: 0,
|
|
12969
|
+
candidates: 0,
|
|
12970
|
+
spent: 0,
|
|
12971
|
+
conflicts: 0,
|
|
12972
|
+
pendingDropped: 0,
|
|
12973
|
+
skipped: 0
|
|
12974
|
+
};
|
|
12975
|
+
const rpc = new Proxy(connection, {
|
|
12976
|
+
get(target, prop, receiver) {
|
|
12977
|
+
const value = Reflect.get(target, prop, receiver);
|
|
12978
|
+
if (typeof value !== "function") return value;
|
|
12979
|
+
return (...args) => {
|
|
12980
|
+
const pending = value.apply(target, args);
|
|
12981
|
+
if (pending && typeof pending.send === "function") {
|
|
12982
|
+
const send = pending.send.bind(pending);
|
|
12983
|
+
return {
|
|
12984
|
+
...pending,
|
|
12985
|
+
send: (...sendArgs) => {
|
|
12986
|
+
stats.rpcCalls++;
|
|
12987
|
+
return send(...sendArgs);
|
|
12988
|
+
}
|
|
12989
|
+
};
|
|
12990
|
+
}
|
|
12991
|
+
return pending;
|
|
12992
|
+
};
|
|
12993
|
+
}
|
|
12994
|
+
});
|
|
12995
|
+
const makeTrial = async (nk, legacy) => ({
|
|
12996
|
+
nk,
|
|
12997
|
+
legacy,
|
|
12998
|
+
owner,
|
|
12999
|
+
decrypt: await createCompactChainNoteDecryptor(nk),
|
|
13000
|
+
open: await createRecipientDeliveryOpener(deriveViewingKeyFromNk(nk).privateKey)
|
|
13001
|
+
});
|
|
13002
|
+
const trials = [await makeTrial(viewingKeyNk, false)];
|
|
13003
|
+
const legacyNks = params.legacyViewingKeyNks ?? [];
|
|
13004
|
+
if (!Array.isArray(legacyNks)) throw new Error("legacyViewingKeyNks must be an array of 32-byte keys");
|
|
13005
|
+
if (legacyNks.length > MAX_LEGACY_VIEWING_KEYS) throw new Error(`legacyViewingKeyNks takes at most ${MAX_LEGACY_VIEWING_KEYS} keys`);
|
|
13006
|
+
const seenNks = /* @__PURE__ */ new Set([toHex2(viewingKeyNk)]);
|
|
13007
|
+
for (const nk of legacyNks) {
|
|
13008
|
+
if (!(nk instanceof Uint8Array) || nk.length !== 32) throw new Error("legacyViewingKeyNks entries must be 32 bytes");
|
|
13009
|
+
const key = toHex2(nk);
|
|
13010
|
+
if (seenNks.has(key)) continue;
|
|
13011
|
+
seenNks.add(key);
|
|
13012
|
+
trials.push(await makeTrial(Uint8Array.from(nk), true));
|
|
13013
|
+
}
|
|
13014
|
+
const poolMints = Array.from(new Set(params.poolMints));
|
|
13015
|
+
const warnings = [];
|
|
13016
|
+
const head = await fetchNoteIndexHead(relayUrl, { signal: params.signal });
|
|
13017
|
+
let cursor;
|
|
13018
|
+
if (params.cursor !== void 0) {
|
|
13019
|
+
const checked = await parseCursor(params.cursor, poolMints);
|
|
13020
|
+
if (typeof checked === "string") warnings.push(`note index cursor is unusable (${checked}); re-syncing from page 0`);
|
|
13021
|
+
else if (BigInt(checked.raw.epoch) !== head.epoch) warnings.push("note index epoch changed; re-syncing from page 0");
|
|
13022
|
+
else if (head.watermark < checked.raw.watermark || head.completePages < checked.raw.page) {
|
|
13023
|
+
throw new NoteIndexHeadBehindError(checked.raw.watermark, head.watermark);
|
|
13024
|
+
} else cursor = checked;
|
|
13025
|
+
}
|
|
13026
|
+
const treePdas = await Promise.all(poolMints.map(async (mint) => (await getShieldPoolPDAs(programId, mint)).merkleTree));
|
|
13027
|
+
let treeRead;
|
|
13028
|
+
const readTrees = () => treeRead ?? (treeRead = (async () => {
|
|
13029
|
+
const accounts = poolMints.length > 0 ? await fetchMultipleAccountBytes(rpc, treePdas, "confirmed") : [];
|
|
13030
|
+
return poolMints.map((_, i) => {
|
|
13031
|
+
const account = accounts[i];
|
|
13032
|
+
const parsed = account ? readTreeAccountFrontier(account.data) : null;
|
|
13033
|
+
return account && parsed ? { ...parsed, data: account.data } : null;
|
|
13034
|
+
});
|
|
13035
|
+
})());
|
|
13036
|
+
const ctx = { params, head, trials, owner, stats, poolMints, warnings, readTrees };
|
|
13037
|
+
let outcome = await runOnce(ctx, cursor);
|
|
13038
|
+
if (outcome instanceof FullPassSignal) {
|
|
13039
|
+
warnings.push(`${outcome.reason}; re-syncing from page 0`);
|
|
13040
|
+
Object.assign(stats, { dropped: 0, decrypted: 0, candidates: 0, spent: 0, conflicts: 0, pendingDropped: 0, skipped: 0 });
|
|
13041
|
+
outcome = await runOnce(ctx, void 0);
|
|
13042
|
+
if (outcome instanceof FullPassSignal) throw new Error(`note index recovery failed: ${outcome.reason}`);
|
|
13043
|
+
}
|
|
13044
|
+
if (stats.skipped > 0) warnings.push(`${stats.skipped} note index entries could not be processed and were skipped`);
|
|
13045
|
+
stats.ms = Date.now() - startedAt;
|
|
13046
|
+
return { ...outcome, stats, warnings };
|
|
13047
|
+
}
|
|
13048
|
+
async function runOnce(ctx, cursor) {
|
|
13049
|
+
const { params, head, trials, owner, stats, poolMints } = ctx;
|
|
13050
|
+
const { relayUrl, onProgress } = params;
|
|
13051
|
+
const poolSet = new Set(poolMints);
|
|
13052
|
+
const startPage = cursor?.raw.page ?? 0;
|
|
13053
|
+
const startChain = cursor?.raw.chain ?? ZERO_CHAIN;
|
|
13054
|
+
const fullPassSeq = cursor?.raw.fullPassSeq ?? 0;
|
|
13055
|
+
const pagesTotal = Math.ceil(head.watermark / NOTE_INDEX_PAGE_SIZE);
|
|
13056
|
+
const targetPage = Math.max(startPage, floorAlign(head.completePages));
|
|
13057
|
+
const startTrees = new Map(poolMints.map((m) => [m, cursor?.trees.get(m) ?? emptyStartTree()]));
|
|
13058
|
+
const rejectedIds = new Set(cursor?.rejected ?? []);
|
|
13059
|
+
const controller = new AbortController();
|
|
13060
|
+
const onCallerAbort = () => controller.abort();
|
|
13061
|
+
params.signal?.addEventListener("abort", onCallerAbort, { once: true });
|
|
13062
|
+
const signal = controller.signal;
|
|
13063
|
+
try {
|
|
13064
|
+
const pageData = /* @__PURE__ */ new Map();
|
|
13065
|
+
const ownItems = [];
|
|
13066
|
+
const nullifiers = /* @__PURE__ */ new Set();
|
|
13067
|
+
let fullPassReason = null;
|
|
13068
|
+
const lateReference = (mint, leaf, value, seq) => {
|
|
13069
|
+
if (!cursor || seq < fullPassSeq) return null;
|
|
13070
|
+
const t = startTrees.get(mint);
|
|
13071
|
+
if (leaf < t.nextIndex) {
|
|
13072
|
+
if (leaf < t.windowStart) return "a later item refers to the tree before the cursor";
|
|
13073
|
+
if (value !== void 0 && value !== t.window[leaf - t.windowStart]) return "a later item rewrites the tree before the cursor";
|
|
13074
|
+
return null;
|
|
13075
|
+
}
|
|
13076
|
+
const held = t.pending.get(leaf);
|
|
13077
|
+
if (held !== void 0) return value !== void 0 && value !== held ? "a later item rewrites the tree before the cursor" : null;
|
|
13078
|
+
if (value !== void 0 && leaf < t.hiBefore) return "a later item fills the tree before the cursor";
|
|
13079
|
+
return null;
|
|
13080
|
+
};
|
|
13081
|
+
const chainAt = /* @__PURE__ */ new Map([[startPage, startChain]]);
|
|
13082
|
+
const waiting = /* @__PURE__ */ new Map();
|
|
13083
|
+
let chainNext = startPage;
|
|
13084
|
+
let chainError = null;
|
|
13085
|
+
let wakers = [];
|
|
13086
|
+
const wakeAll = () => {
|
|
13087
|
+
const w = wakers;
|
|
13088
|
+
wakers = [];
|
|
13089
|
+
for (const f of w) f();
|
|
13090
|
+
};
|
|
13091
|
+
signal.addEventListener("abort", wakeAll);
|
|
13092
|
+
const advanceChain = () => {
|
|
13093
|
+
while (!chainError && waiting.has(chainNext)) {
|
|
13094
|
+
const w = waiting.get(chainNext);
|
|
13095
|
+
waiting.delete(chainNext);
|
|
13096
|
+
const expected = chainAt.get(chainNext);
|
|
13097
|
+
if (w.prevChain !== expected) {
|
|
13098
|
+
chainError = cursor && chainNext === startPage ? new FullPassSignal("note index hash chain does not continue from the cursor") : new NoteIndexFormatError(`hash chain broken at page ${chainNext}`);
|
|
13099
|
+
controller.abort();
|
|
13100
|
+
return;
|
|
13101
|
+
}
|
|
13102
|
+
if (!w.complete) break;
|
|
13103
|
+
chainAt.set(chainNext + 1, toHex2(computeNoteIndexChain(fromHex(expected), w.bytes)));
|
|
13104
|
+
chainNext++;
|
|
13105
|
+
}
|
|
13106
|
+
wakeAll();
|
|
13107
|
+
};
|
|
13108
|
+
const workerCount = Math.max(1, Math.min(params.concurrency ?? DEFAULT_CONCURRENCY, pagesTotal - startPage));
|
|
13109
|
+
const lookahead = 2 * workerCount + 2;
|
|
13110
|
+
let nextToFetch = startPage;
|
|
13111
|
+
let pagesDone = 0;
|
|
13112
|
+
const worker = async () => {
|
|
13113
|
+
for (; ; ) {
|
|
13114
|
+
if (signal.aborted) throw abortError2();
|
|
13115
|
+
const pageNo = nextToFetch++;
|
|
13116
|
+
if (pageNo >= pagesTotal) return;
|
|
13117
|
+
while (pageNo - chainNext >= lookahead && !signal.aborted) await new Promise((resolve) => wakers.push(resolve));
|
|
13118
|
+
if (signal.aborted) throw abortError2();
|
|
13119
|
+
const bytes = await fetchNoteIndexPage(relayUrl, head.epoch, pageNo, { signal });
|
|
13120
|
+
stats.bytes += bytes.length;
|
|
13121
|
+
const page2 = parseNoteIndexPage(bytes, { epoch: head.epoch, page: pageNo }, { skipMalformedItems: true });
|
|
13122
|
+
if (pageNo < head.completePages && !page2.complete) {
|
|
13123
|
+
throw new NoteIndexFormatError(`page ${pageNo} is below complete_pages but not complete`);
|
|
13124
|
+
}
|
|
13125
|
+
stats.pages++;
|
|
13126
|
+
stats.skipped += page2.skippedMalformed;
|
|
13127
|
+
const seqOf = (i) => pageNo * NOTE_INDEX_PAGE_SIZE + page2.itemPositions[i];
|
|
13128
|
+
waiting.set(pageNo, { bytes: page2.complete ? bytes : new Uint8Array(0), prevChain: toHex2(page2.prevChain), complete: page2.complete });
|
|
13129
|
+
advanceChain();
|
|
13130
|
+
const data = { complete: page2.complete, leaves: /* @__PURE__ */ new Map() };
|
|
13131
|
+
const late = (reason) => {
|
|
13132
|
+
if (reason && !fullPassReason) {
|
|
13133
|
+
fullPassReason = reason;
|
|
13134
|
+
controller.abort();
|
|
13135
|
+
}
|
|
13136
|
+
};
|
|
13137
|
+
const addLeaf = (mintBytes, commitment, leaf, seq) => {
|
|
13138
|
+
if (isAllZero3(commitment)) return;
|
|
13139
|
+
const mint = addressFromBytes(mintBytes);
|
|
13140
|
+
if (!poolSet.has(mint)) return;
|
|
13141
|
+
const entry = { leaf: Number(leaf), commitment: bytesToBigint2(commitment) };
|
|
13142
|
+
late(lateReference(mint, entry.leaf, entry.commitment, seq));
|
|
13143
|
+
const list = data.leaves.get(mint);
|
|
13144
|
+
if (list) list.push(entry);
|
|
13145
|
+
else data.leaves.set(mint, [entry]);
|
|
13146
|
+
};
|
|
13147
|
+
page2.items.forEach((item, i) => {
|
|
13148
|
+
const seq = seqOf(i);
|
|
13149
|
+
if (item.kind === 1) {
|
|
13150
|
+
addLeaf(item.mint, item.comm0, item.leaf0, seq);
|
|
13151
|
+
addLeaf(item.mint, item.comm1, item.leaf1, seq);
|
|
13152
|
+
if (!isAllZero3(item.nullifier0)) nullifiers.add(toHex2(item.nullifier0));
|
|
13153
|
+
if (!isAllZero3(item.nullifier1)) nullifiers.add(toHex2(item.nullifier1));
|
|
13154
|
+
} else if (item.kind === 3) {
|
|
13155
|
+
addLeaf(item.mint, item.commitment, item.leaf, seq);
|
|
13156
|
+
} else {
|
|
13157
|
+
const mint = addressFromBytes(item.mint);
|
|
13158
|
+
if (poolSet.has(mint)) late(lateReference(mint, Number(item.leaf), void 0, seq));
|
|
13159
|
+
}
|
|
13160
|
+
});
|
|
13161
|
+
if (signal.aborted) throw abortError2();
|
|
13162
|
+
for (let i = 0; i < page2.items.length; i += ITEM_BATCH) {
|
|
13163
|
+
if (signal.aborted) throw abortError2();
|
|
13164
|
+
const batch = page2.items.slice(i, i + ITEM_BATCH);
|
|
13165
|
+
const opened = await Promise.all(batch.map((item) => trialItemIsolated(item, trials, stats)));
|
|
13166
|
+
opened.forEach((o, k) => {
|
|
13167
|
+
if (!o) return;
|
|
13168
|
+
stats.decrypted++;
|
|
13169
|
+
const raw = page2.rawItems[i + k];
|
|
13170
|
+
const id = itemIdentity(raw);
|
|
13171
|
+
if (rejectedIds.has(id)) {
|
|
13172
|
+
stats.dropped++;
|
|
13173
|
+
return;
|
|
13174
|
+
}
|
|
13175
|
+
ownItems.push({ page: pageNo, seq: seqOf(i + k), raw, id, item: batch[k], fromCursor: false, ...o, trial: o.trial });
|
|
13176
|
+
});
|
|
13177
|
+
stats.items += batch.length;
|
|
13178
|
+
}
|
|
13179
|
+
pageData.set(pageNo, data);
|
|
13180
|
+
pagesDone++;
|
|
13181
|
+
onProgress?.({ pagesDone, pagesTotal: pagesTotal - startPage, itemsChecked: stats.items, notesFound: ownItems.length });
|
|
13182
|
+
}
|
|
13183
|
+
};
|
|
13184
|
+
const workers = Array.from(
|
|
13185
|
+
{ length: workerCount },
|
|
13186
|
+
() => worker().catch((error) => {
|
|
13187
|
+
controller.abort();
|
|
13188
|
+
throw error;
|
|
13189
|
+
})
|
|
13190
|
+
);
|
|
13191
|
+
const settled = await Promise.allSettled(workers);
|
|
13192
|
+
signal.removeEventListener("abort", wakeAll);
|
|
13193
|
+
if (params.signal?.aborted) throw abortError2();
|
|
13194
|
+
const lateReason = fullPassReason;
|
|
13195
|
+
if (lateReason) return new FullPassSignal(lateReason);
|
|
13196
|
+
const chainFailure = chainError;
|
|
13197
|
+
if (chainFailure) {
|
|
13198
|
+
if (chainFailure instanceof FullPassSignal) return chainFailure;
|
|
13199
|
+
throw chainFailure;
|
|
13200
|
+
}
|
|
13201
|
+
const failure = settled.find((s) => s.status === "rejected" && s.reason?.name !== "AbortError") ?? settled.find((s) => s.status === "rejected");
|
|
13202
|
+
if (failure) throw failure.reason;
|
|
13203
|
+
if (head.completePages >= startPage && chainAt.get(head.completePages) !== head.chainTip) {
|
|
13204
|
+
if (cursor) return new FullPassSignal("note index hash chain does not reach the head's chain_tip");
|
|
13205
|
+
throw new NoteIndexFormatError("hash chain does not reach the head's chain_tip");
|
|
13206
|
+
}
|
|
13207
|
+
for (const entry of cursor?.items ?? []) {
|
|
13208
|
+
const o = await trialItemIsolated(entry.item, trials, stats);
|
|
13209
|
+
if (!o) continue;
|
|
13210
|
+
const page2 = Math.floor(entry.seq / NOTE_INDEX_PAGE_SIZE);
|
|
13211
|
+
ownItems.push({ page: page2, seq: entry.seq, raw: entry.raw, id: itemIdentity(entry.raw), item: entry.item, fromCursor: true, ...o, trial: o.trial });
|
|
13212
|
+
if (entry.item.kind === 1) {
|
|
13213
|
+
if (!isAllZero3(entry.item.nullifier0)) nullifiers.add(toHex2(entry.item.nullifier0));
|
|
13214
|
+
if (!isAllZero3(entry.item.nullifier1)) nullifiers.add(toHex2(entry.item.nullifier1));
|
|
13215
|
+
}
|
|
13216
|
+
}
|
|
13217
|
+
const knownSpent = cursor?.spent ?? /* @__PURE__ */ new Set();
|
|
13218
|
+
ownItems.sort((a, b) => a.seq - b.seq);
|
|
13219
|
+
const rejectedNow = /* @__PURE__ */ new Set();
|
|
13220
|
+
const skippedNow = /* @__PURE__ */ new Set();
|
|
13221
|
+
const allCandidates = await matchOwnItems(
|
|
13222
|
+
ownItems,
|
|
13223
|
+
owner,
|
|
13224
|
+
(o) => {
|
|
13225
|
+
stats.dropped++;
|
|
13226
|
+
rejectedNow.add(o.id);
|
|
13227
|
+
},
|
|
13228
|
+
(o) => {
|
|
13229
|
+
if (skippedNow.has(o)) return;
|
|
13230
|
+
skippedNow.add(o);
|
|
13231
|
+
stats.skipped++;
|
|
13232
|
+
}
|
|
13233
|
+
);
|
|
13234
|
+
stats.candidates = allCandidates.length;
|
|
13235
|
+
const cutoff = params.legacyCutoffLeaf ?? {};
|
|
13236
|
+
const candidates = allCandidates.filter((c) => {
|
|
13237
|
+
const limit = cutoff[c.mint];
|
|
13238
|
+
if (c.atRisk && limit !== void 0 && BigInt(c.leaf) >= limit) {
|
|
13239
|
+
stats.dropped++;
|
|
13240
|
+
return false;
|
|
13241
|
+
}
|
|
13242
|
+
return true;
|
|
13243
|
+
});
|
|
13244
|
+
const chainTrees = await ctx.readTrees();
|
|
13245
|
+
const orderedPages = Array.from(pageData.keys()).sort((a, b) => a - b);
|
|
13246
|
+
const replays = /* @__PURE__ */ new Map();
|
|
13247
|
+
for (let i = 0; i < poolMints.length; i++) {
|
|
13248
|
+
const mint = poolMints[i];
|
|
13249
|
+
const start = startTrees.get(mint);
|
|
13250
|
+
const chainTree = chainTrees[i] ?? null;
|
|
13251
|
+
const pages = orderedPages.map((page2) => ({ page: page2, entries: pageData.get(page2).leaves.get(mint) ?? [] }));
|
|
13252
|
+
let r = await replayStream(start, pages, start.overrides, chainTree, targetPage);
|
|
13253
|
+
let overrides = start.overrides;
|
|
13254
|
+
stats.conflicts += r.conflicts;
|
|
13255
|
+
if (r.corrections.size > 0 && (r.mismatch || r.verifiedPrefix < r.endCount)) {
|
|
13256
|
+
const merged = new Map([...start.overrides, ...r.corrections]);
|
|
13257
|
+
const alternative = await replayStream(start, pages, merged, chainTree, targetPage);
|
|
13258
|
+
if (alternative.verifiedPrefix > r.verifiedPrefix || r.mismatch && !alternative.mismatch) {
|
|
13259
|
+
r = alternative;
|
|
13260
|
+
overrides = merged;
|
|
13261
|
+
}
|
|
13262
|
+
}
|
|
13263
|
+
if (r.mismatch && cursor && !start.mismatch) return new FullPassSignal("a rebuilt tree disagrees with the chain");
|
|
13264
|
+
replays.set(mint, { r, overrides });
|
|
13265
|
+
}
|
|
13266
|
+
const verifiedUpTo = (mint) => Math.max(startTrees.get(mint).verified, replays.get(mint).r.verifiedPrefix);
|
|
13267
|
+
const streamValue = (mint, leaf) => {
|
|
13268
|
+
const v = replays.get(mint)?.r.valueAt(leaf);
|
|
13269
|
+
if (v !== void 0) return v;
|
|
13270
|
+
const carried = cursor?.pendingLeaves.get(`${mint}:${leaf}`);
|
|
13271
|
+
if (carried !== void 0) return carried;
|
|
13272
|
+
const t = startTrees.get(mint);
|
|
13273
|
+
if (t && leaf >= t.windowStart && leaf < t.nextIndex) return t.window[leaf - t.windowStart];
|
|
13274
|
+
return void 0;
|
|
13275
|
+
};
|
|
13276
|
+
const knownVerified = cursor?.verified ?? /* @__PURE__ */ new Set();
|
|
13277
|
+
const verified = [];
|
|
13278
|
+
const pendingByKey = /* @__PURE__ */ new Map();
|
|
13279
|
+
const rejectedCandidates = /* @__PURE__ */ new Set();
|
|
13280
|
+
const outcomeOf = /* @__PURE__ */ new Map();
|
|
13281
|
+
const tally = (c, what) => {
|
|
13282
|
+
const t = outcomeOf.get(c.seq) ?? { kept: false, rejected: 0, total: 0 };
|
|
13283
|
+
t.total++;
|
|
13284
|
+
if (what === "kept") t.kept = true;
|
|
13285
|
+
if (what === "rejected") t.rejected++;
|
|
13286
|
+
outcomeOf.set(c.seq, t);
|
|
13287
|
+
};
|
|
13288
|
+
const pend = (c, rank) => {
|
|
13289
|
+
const key = verifiedKey(c.mint, c.leaf, c.commitment);
|
|
13290
|
+
const prior = pendingByKey.get(key);
|
|
13291
|
+
if (!prior || prior.c.seq > c.seq) pendingByKey.set(key, { c, rank });
|
|
13292
|
+
};
|
|
13293
|
+
for (const c of candidates) {
|
|
13294
|
+
if (knownVerified.has(verifiedKey(c.mint, c.leaf, c.commitment))) {
|
|
13295
|
+
verified.push(c);
|
|
13296
|
+
continue;
|
|
13297
|
+
}
|
|
13298
|
+
if (!poolSet.has(c.mint)) {
|
|
13299
|
+
pend(c, 3);
|
|
13300
|
+
continue;
|
|
13301
|
+
}
|
|
13302
|
+
const value = streamValue(c.mint, c.leaf);
|
|
13303
|
+
if (value === void 0) {
|
|
13304
|
+
if (c.leaf < startTrees.get(c.mint).nextIndex) {
|
|
13305
|
+
stats.dropped++;
|
|
13306
|
+
tally(c, "other");
|
|
13307
|
+
} else pend(c, 1);
|
|
13308
|
+
} else if (c.leaf >= verifiedUpTo(c.mint)) {
|
|
13309
|
+
pend(c, value === c.commitment ? 0 : 2);
|
|
13310
|
+
} else if (value === c.commitment) {
|
|
13311
|
+
verified.push(c);
|
|
13312
|
+
} else {
|
|
13313
|
+
stats.dropped++;
|
|
13314
|
+
rejectedCandidates.add(c);
|
|
13315
|
+
tally(c, "rejected");
|
|
13316
|
+
}
|
|
13317
|
+
}
|
|
13318
|
+
verified.sort((a, b) => a.seq - b.seq);
|
|
13319
|
+
const byLeaf = /* @__PURE__ */ new Map();
|
|
13320
|
+
for (const c of verified) {
|
|
13321
|
+
const key = `${c.mint}:${c.leaf}`;
|
|
13322
|
+
if (byLeaf.has(key)) {
|
|
13323
|
+
stats.dropped++;
|
|
13324
|
+
tally(c, "other");
|
|
13325
|
+
continue;
|
|
13326
|
+
}
|
|
13327
|
+
byLeaf.set(key, c);
|
|
13328
|
+
}
|
|
13329
|
+
const notes = [];
|
|
13330
|
+
const atRisk = [];
|
|
13331
|
+
const spentOut = new Set(knownSpent);
|
|
13332
|
+
const verifiedOut = new Set(knownVerified);
|
|
13333
|
+
const keyChecked = /* @__PURE__ */ new Map();
|
|
13334
|
+
for (const c of byLeaf.values()) {
|
|
13335
|
+
const pubOk = keyChecked.get(c.keypair.privateKey) ?? (c.keypair.privateKey !== 0n && await derivePublicKey(c.keypair.privateKey) === c.keypair.publicKey);
|
|
13336
|
+
keyChecked.set(c.keypair.privateKey, pubOk);
|
|
13337
|
+
if (!pubOk || !c.atRisk && c.keypair.publicKey !== owner.publicKey) {
|
|
13338
|
+
stats.dropped++;
|
|
13339
|
+
tally(c, "rejected");
|
|
13340
|
+
continue;
|
|
13341
|
+
}
|
|
13342
|
+
tally(c, "kept");
|
|
13343
|
+
verifiedOut.add(verifiedKey(c.mint, c.leaf, c.commitment));
|
|
13344
|
+
const utxo = {
|
|
13345
|
+
amount: c.amount,
|
|
13346
|
+
keypair: c.atRisk ? { ...c.keypair } : owner,
|
|
13347
|
+
blinding: c.blinding,
|
|
13348
|
+
mintAddress: c.mint,
|
|
13349
|
+
index: c.leaf,
|
|
13350
|
+
commitment: c.commitment
|
|
13351
|
+
};
|
|
13352
|
+
if (nullifiers.has(c.nullifier) || knownSpent.has(c.nullifier)) {
|
|
13353
|
+
stats.spent++;
|
|
13354
|
+
spentOut.add(c.nullifier);
|
|
13355
|
+
continue;
|
|
13356
|
+
}
|
|
13357
|
+
const note = {
|
|
13358
|
+
kind: c.kind,
|
|
13359
|
+
utxo,
|
|
13360
|
+
signature: bs584.encode(c.signature),
|
|
13361
|
+
legacyExposed: c.atRisk
|
|
13362
|
+
};
|
|
13363
|
+
(c.atRisk ? atRisk : notes).push(note);
|
|
13364
|
+
}
|
|
13365
|
+
const sortNotes = (list) => list.sort((a, b) => a.utxo.mintAddress === b.utxo.mintAddress ? a.utxo.index - b.utxo.index : a.utxo.mintAddress < b.utxo.mintAddress ? -1 : 1);
|
|
13366
|
+
sortNotes(notes);
|
|
13367
|
+
sortNotes(atRisk);
|
|
13368
|
+
const pendingList = Array.from(pendingByKey.values()).sort((a, b) => a.rank - b.rank || a.c.seq - b.c.seq);
|
|
13369
|
+
const carriedPending = pendingList.slice(0, MAX_CARRIED_PENDING).map((p) => p.c);
|
|
13370
|
+
const overflow = pendingList.length - carriedPending.length;
|
|
13371
|
+
if (overflow > 0) {
|
|
13372
|
+
stats.pendingDropped += overflow;
|
|
13373
|
+
ctx.warnings.push(`${overflow} unverified candidates over the carry limit were not carried to the next run`);
|
|
13374
|
+
}
|
|
13375
|
+
for (const { c } of pendingList) if (nullifiers.has(c.nullifier)) spentOut.add(c.nullifier);
|
|
13376
|
+
for (const c of carriedPending) tally(c, "kept");
|
|
13377
|
+
for (const { c } of pendingList.slice(MAX_CARRIED_PENDING)) tally(c, "other");
|
|
13378
|
+
let page = targetPage;
|
|
13379
|
+
for (const { r } of replays.values()) if (r.snapshot === null) page = startPage;
|
|
13380
|
+
const trees = {};
|
|
13381
|
+
const treeEnd = /* @__PURE__ */ new Map();
|
|
13382
|
+
for (const mint of poolMints) {
|
|
13383
|
+
const start = startTrees.get(mint);
|
|
13384
|
+
const { r, overrides } = replays.get(mint);
|
|
13385
|
+
const snap = page === startPage ? { frontier: start.frontier ?? (await MerkleFrontier.create()).toState(), pending: start.pending, nextIndex: start.nextIndex } : r.snapshot;
|
|
13386
|
+
const n = snap.nextIndex;
|
|
13387
|
+
const window2 = [];
|
|
13388
|
+
for (let leaf = n - 1; leaf >= Math.max(0, n - LEAF_WINDOW); leaf--) {
|
|
13389
|
+
const v = leaf >= start.nextIndex ? r.valueAt(leaf) : leaf >= start.windowStart ? start.window[leaf - start.windowStart] : void 0;
|
|
13390
|
+
if (v === void 0) break;
|
|
13391
|
+
window2.push(hex32(v));
|
|
13392
|
+
}
|
|
13393
|
+
window2.reverse();
|
|
13394
|
+
trees[mint] = {
|
|
13395
|
+
frontier: snap.frontier,
|
|
13396
|
+
pending: Array.from(snap.pending.entries(), ([leaf, v]) => [leaf, hex32(v)]).sort((a, b) => a[0] - b[0]),
|
|
13397
|
+
window: window2.join(""),
|
|
13398
|
+
verified: Math.min(verifiedUpTo(mint), n),
|
|
13399
|
+
overrides: Array.from(overrides.entries()).filter(([leaf]) => leaf >= n && !snap.pending.has(leaf)).sort((a, b) => a[0] - b[0]).slice(0, MAX_OVERRIDES).map(([leaf, v]) => [leaf, hex32(v)]),
|
|
13400
|
+
mismatch: r.mismatch
|
|
13401
|
+
};
|
|
13402
|
+
treeEnd.set(mint, { nextIndex: n, pending: snap.pending });
|
|
13403
|
+
}
|
|
13404
|
+
const pendingLeaves = [];
|
|
13405
|
+
const pendingLeafSeen = /* @__PURE__ */ new Set();
|
|
13406
|
+
for (const c of carriedPending) {
|
|
13407
|
+
const end = treeEnd.get(c.mint);
|
|
13408
|
+
if (!end || c.leaf >= end.nextIndex) continue;
|
|
13409
|
+
const value = streamValue(c.mint, c.leaf);
|
|
13410
|
+
const key = `${c.mint}:${c.leaf}`;
|
|
13411
|
+
if (value === void 0 || pendingLeafSeen.has(key)) continue;
|
|
13412
|
+
pendingLeafSeen.add(key);
|
|
13413
|
+
pendingLeaves.push([c.mint, c.leaf, hex32(value)]);
|
|
13414
|
+
}
|
|
13415
|
+
const keptItems = [];
|
|
13416
|
+
const keptIds = /* @__PURE__ */ new Set();
|
|
13417
|
+
for (const o of ownItems) {
|
|
13418
|
+
const t = outcomeOf.get(o.seq);
|
|
13419
|
+
if (rejectedNow.has(o.id) || t && t.total > 0 && t.rejected === t.total) {
|
|
13420
|
+
rejectedNow.add(o.id);
|
|
13421
|
+
continue;
|
|
13422
|
+
}
|
|
13423
|
+
if (o.page >= page || !t?.kept || keptIds.has(o.id)) continue;
|
|
13424
|
+
keptIds.add(o.id);
|
|
13425
|
+
keptItems.push({ seq: o.seq, item: toHex2(o.raw) });
|
|
13426
|
+
}
|
|
13427
|
+
const rejected = Array.from(/* @__PURE__ */ new Set([...cursor?.rejected ?? [], ...rejectedNow]));
|
|
13428
|
+
const nextCursor = {
|
|
13429
|
+
v: CURSOR_VERSION,
|
|
13430
|
+
epoch: head.epoch.toString(10),
|
|
13431
|
+
page,
|
|
13432
|
+
chain: chainAt.get(page) ?? startChain,
|
|
13433
|
+
watermark: Math.max(cursor?.raw.watermark ?? 0, head.watermark),
|
|
13434
|
+
fullPassSeq: cursor ? fullPassSeq : head.watermark,
|
|
13435
|
+
trees,
|
|
13436
|
+
own: {
|
|
13437
|
+
items: keptItems,
|
|
13438
|
+
verified: Array.from(verifiedOut),
|
|
13439
|
+
spent: Array.from(spentOut),
|
|
13440
|
+
pendingLeaves,
|
|
13441
|
+
rejected: rejected.slice(Math.max(0, rejected.length - MAX_REJECTED_IDS))
|
|
13442
|
+
}
|
|
13443
|
+
};
|
|
13444
|
+
return { notes, atRisk, pending: pendingByKey.size, cursor: nextCursor };
|
|
13445
|
+
} finally {
|
|
13446
|
+
params.signal?.removeEventListener("abort", onCallerAbort);
|
|
13447
|
+
}
|
|
13448
|
+
}
|
|
13449
|
+
|
|
13450
|
+
// src/wallet/utxo-wallet.ts
|
|
13451
|
+
var UtxoWallet = class _UtxoWallet {
|
|
13452
|
+
constructor(viewingKey) {
|
|
13453
|
+
this.wallets = /* @__PURE__ */ new Map();
|
|
13454
|
+
this.viewingKey = viewingKey;
|
|
13455
|
+
}
|
|
13456
|
+
/**
|
|
13457
|
+
* Add a UTXO to the wallet (discovered from chain or created)
|
|
13458
|
+
*/
|
|
13459
|
+
addUtxo(utxo, mint = NATIVE_SOL_MINT) {
|
|
13460
|
+
const mintKey = mint;
|
|
13461
|
+
if (!this.wallets.has(mintKey)) {
|
|
13462
|
+
this.wallets.set(mintKey, {
|
|
11309
13463
|
mint,
|
|
11310
13464
|
utxos: []
|
|
11311
13465
|
});
|
|
@@ -11647,7 +13801,7 @@ async function loadWeb3() {
|
|
|
11647
13801
|
|
|
11648
13802
|
// src/bridge/rail-verify.ts
|
|
11649
13803
|
import nacl6 from "tweetnacl";
|
|
11650
|
-
import { sha256 as
|
|
13804
|
+
import { sha256 as sha2567 } from "@noble/hashes/sha256";
|
|
11651
13805
|
var ONECLICK_PUBKEY_B58 = "reYaWhvwu8Jzo3WUM3zhn6VrhuMEF4eADL17qtRVifc";
|
|
11652
13806
|
var b58 = /* @__PURE__ */ (() => {
|
|
11653
13807
|
const A = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
@@ -11753,7 +13907,7 @@ function canonicalPayloadString(resp) {
|
|
|
11753
13907
|
function verifyQuoteSignature(resp) {
|
|
11754
13908
|
if (!resp?.signature) return { valid: false, reason: "no signature on the response" };
|
|
11755
13909
|
const payload = { ...signedRequest(resp), ...signedQuote(resp), timestamp: resp.timestamp };
|
|
11756
|
-
const digest =
|
|
13910
|
+
const digest = sha2567(new TextEncoder().encode(stable(payload)));
|
|
11757
13911
|
const message = new TextEncoder().encode(b58.encode(new Uint8Array(digest)));
|
|
11758
13912
|
const sig = resp.signature.replace(/^ed25519:/, "");
|
|
11759
13913
|
try {
|
|
@@ -11948,7 +14102,7 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
|
|
|
11948
14102
|
})
|
|
11949
14103
|
});
|
|
11950
14104
|
const prepared = await parseBridgeResponse2(prepareRes, "paymaster prepare");
|
|
11951
|
-
if (
|
|
14105
|
+
if (relayNowSeconds() >= prepared.expires_at_unix) {
|
|
11952
14106
|
throw new Error(
|
|
11953
14107
|
"paymaster prepare returned a voucher that is already expired \u2014 refusing to sign a stale top-up rather than fail confusingly at cosign"
|
|
11954
14108
|
);
|
|
@@ -11985,9 +14139,12 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
|
|
|
11985
14139
|
// src/bridge/derive.ts
|
|
11986
14140
|
import { hmac } from "@noble/hashes/hmac";
|
|
11987
14141
|
import { sha512 } from "@noble/hashes/sha512";
|
|
14142
|
+
import { blake3 as blake36 } from "@noble/hashes/blake3";
|
|
11988
14143
|
var BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
|
|
14144
|
+
var BRIDGE_ESCROW_LABEL_V2 = "cloak_bridge_escrow_v2";
|
|
14145
|
+
var BRIDGE_RECEIVER_KEY_DOMAIN = new TextEncoder().encode("cloak_bridge_receiver_key_v2");
|
|
11989
14146
|
var MAX_RECEIVER_INDEX = 1e4;
|
|
11990
|
-
|
|
14147
|
+
function assertReceiverIndex(index) {
|
|
11991
14148
|
if (!Number.isInteger(index) || index < 0) {
|
|
11992
14149
|
throw new Error(`index must be a non-negative integer, got ${index}`);
|
|
11993
14150
|
}
|
|
@@ -11996,6 +14153,26 @@ async function deriveBridgeReceiver(nk, index) {
|
|
|
11996
14153
|
`index ${index} exceeds MAX_RECEIVER_INDEX (${MAX_RECEIVER_INDEX}). Indices must be a small sequential counter \u2014 discovery derives 0\u2026N and reads each on chain, so a timestamp index is unreachable by any scan and the deposit would be invisible to every device but this one.`
|
|
11997
14154
|
);
|
|
11998
14155
|
}
|
|
14156
|
+
}
|
|
14157
|
+
async function deriveBridgeReceiver(ownerUtxoKeypair, index) {
|
|
14158
|
+
if (ownerUtxoKeypair instanceof Uint8Array) {
|
|
14159
|
+
throw new Error(
|
|
14160
|
+
"deriveBridgeReceiver takes the wallet's UTXO keypair, not a byte key. Receivers are no longer derived from nk; use deriveLegacyBridgeReceiver(nk, index) only to find old deposits."
|
|
14161
|
+
);
|
|
14162
|
+
}
|
|
14163
|
+
assertReceiverIndex(index);
|
|
14164
|
+
const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
|
|
14165
|
+
const priv = bigintToBytes322(owner.privateKey);
|
|
14166
|
+
const preimage = new Uint8Array(BRIDGE_RECEIVER_KEY_DOMAIN.length + priv.length);
|
|
14167
|
+
preimage.set(BRIDGE_RECEIVER_KEY_DOMAIN, 0);
|
|
14168
|
+
preimage.set(priv, BRIDGE_RECEIVER_KEY_DOMAIN.length);
|
|
14169
|
+
const key = blake36(preimage);
|
|
14170
|
+
const h = hmac(sha512, key, new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL_V2}:${index}`));
|
|
14171
|
+
return signerFromSecretKey(h.slice(0, 32));
|
|
14172
|
+
}
|
|
14173
|
+
async function deriveLegacyBridgeReceiver(nk, index) {
|
|
14174
|
+
assertReceiverIndex(index);
|
|
14175
|
+
if (!nk || nk.length !== 32) throw new Error("nk must be 32 bytes");
|
|
11999
14176
|
const h = hmac(sha512, new Uint8Array(nk), new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL}:${index}`));
|
|
12000
14177
|
return signerFromSecretKey(h.slice(0, 32));
|
|
12001
14178
|
}
|
|
@@ -12006,13 +14183,44 @@ import { TOKEN_PROGRAM_ADDRESS as TOKEN_PROGRAM_ADDRESS4, findAssociatedTokenPda
|
|
|
12006
14183
|
function describeError(err) {
|
|
12007
14184
|
return err instanceof Error ? err.message : String(err);
|
|
12008
14185
|
}
|
|
12009
|
-
async function listBridgeDeposits(rpc,
|
|
14186
|
+
async function listBridgeDeposits(rpc, ownerUtxoKeypair, opts) {
|
|
14187
|
+
if (ownerUtxoKeypair instanceof Uint8Array) {
|
|
14188
|
+
throw new Error(
|
|
14189
|
+
"listBridgeDeposits takes the wallet's UTXO keypair, not nk. Receivers are no longer derived from nk; legacy nk receivers are scanned automatically (see DiscoverOptions.includeLegacy)."
|
|
14190
|
+
);
|
|
14191
|
+
}
|
|
14192
|
+
const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
|
|
14193
|
+
const out = await scanReceivers(rpc, opts, (index) => deriveBridgeReceiver(owner, index), {
|
|
14194
|
+
legacyExposed: false
|
|
14195
|
+
});
|
|
14196
|
+
if (opts.includeLegacy === false) return out;
|
|
14197
|
+
const nks = [];
|
|
14198
|
+
const seen = /* @__PURE__ */ new Set();
|
|
14199
|
+
for (const nk of [getNkFromUtxoPrivateKey(owner.privateKey), ...opts.legacyViewingKeyNks ?? []]) {
|
|
14200
|
+
if (!(nk instanceof Uint8Array) || nk.length !== 32) {
|
|
14201
|
+
throw new Error("legacyViewingKeyNks entries must be 32 bytes");
|
|
14202
|
+
}
|
|
14203
|
+
const key = Array.from(nk, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
14204
|
+
if (seen.has(key)) continue;
|
|
14205
|
+
seen.add(key);
|
|
14206
|
+
nks.push(nk);
|
|
14207
|
+
}
|
|
14208
|
+
for (const nk of nks) {
|
|
14209
|
+
const legacy = await scanReceivers(rpc, opts, (index) => deriveLegacyBridgeReceiver(nk, index), {
|
|
14210
|
+
legacyExposed: true,
|
|
14211
|
+
legacyViewingKeyNk: nk
|
|
14212
|
+
});
|
|
14213
|
+
out.push(...legacy);
|
|
14214
|
+
}
|
|
14215
|
+
return out;
|
|
14216
|
+
}
|
|
14217
|
+
async function scanReceivers(rpc, opts, receiverAt, provenance) {
|
|
12010
14218
|
const scanDepth = Math.min(opts.scanDepth ?? 20, MAX_RECEIVER_INDEX + 1);
|
|
12011
14219
|
const stopAfterUnused = opts.stopAfterUnused ?? 5;
|
|
12012
14220
|
const out = [];
|
|
12013
14221
|
let consecutiveUnused = 0;
|
|
12014
14222
|
for (let index = 0; index < scanDepth; index++) {
|
|
12015
|
-
const kp = await
|
|
14223
|
+
const kp = await receiverAt(index);
|
|
12016
14224
|
const receiver = kp.address;
|
|
12017
14225
|
const [tokenAccount] = await findAssociatedTokenPda4({
|
|
12018
14226
|
mint: opts.mint,
|
|
@@ -12064,7 +14272,8 @@ async function listBridgeDeposits(rpc, nk, opts) {
|
|
|
12064
14272
|
tokenBalance,
|
|
12065
14273
|
lamports,
|
|
12066
14274
|
shieldSignature,
|
|
12067
|
-
...indexReused ? { indexReused, shieldSignatures } : {}
|
|
14275
|
+
...indexReused ? { indexReused, shieldSignatures } : {},
|
|
14276
|
+
...provenance
|
|
12068
14277
|
});
|
|
12069
14278
|
} catch (err) {
|
|
12070
14279
|
out.push({
|
|
@@ -12074,7 +14283,8 @@ async function listBridgeDeposits(rpc, nk, opts) {
|
|
|
12074
14283
|
state: "unknown",
|
|
12075
14284
|
tokenBalance: 0n,
|
|
12076
14285
|
lamports: 0n,
|
|
12077
|
-
error: describeError(err)
|
|
14286
|
+
error: describeError(err),
|
|
14287
|
+
...provenance
|
|
12078
14288
|
});
|
|
12079
14289
|
}
|
|
12080
14290
|
}
|
|
@@ -12229,7 +14439,12 @@ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log,
|
|
|
12229
14439
|
const signMessage = (m) => signMessageBytes(R, m);
|
|
12230
14440
|
const utxoKeypair = await deriveUtxoKeypairFromSpendKey(opts.noteSpendKey);
|
|
12231
14441
|
const nk = getNkFromUtxoPrivateKey(utxoKeypair.privateKey);
|
|
12232
|
-
const { utxo, noteSalt } = await createRecoverableDepositUtxo(
|
|
14442
|
+
const { utxo, noteSalt } = await createRecoverableDepositUtxo({
|
|
14443
|
+
amount,
|
|
14444
|
+
viewingKeyNk: nk,
|
|
14445
|
+
ownerUtxoKeypair: utxoKeypair,
|
|
14446
|
+
mintAddress: mint
|
|
14447
|
+
});
|
|
12233
14448
|
const zeroInput = await createZeroUtxo(mint);
|
|
12234
14449
|
const rBefore = (await rpc.getBalance(R.address).send()).value;
|
|
12235
14450
|
let result;
|
|
@@ -12248,6 +14463,7 @@ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log,
|
|
|
12248
14463
|
signMessage,
|
|
12249
14464
|
chainNoteViewingKeyNk: nk,
|
|
12250
14465
|
chainNoteSalt: noteSalt,
|
|
14466
|
+
ownerUtxoKeypair: utxoKeypair,
|
|
12251
14467
|
relaySupplementalAlt: true,
|
|
12252
14468
|
onProgress: (s) => log(` \xB7 ${s}`)
|
|
12253
14469
|
}
|
|
@@ -12441,13 +14657,13 @@ var DoNotRetry = class extends Error {
|
|
|
12441
14657
|
};
|
|
12442
14658
|
async function withShieldRetries(attempt, hooks = {}) {
|
|
12443
14659
|
const attempts = hooks.attempts ?? 3;
|
|
12444
|
-
const
|
|
14660
|
+
const sleep5 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
12445
14661
|
let last = "";
|
|
12446
14662
|
for (let n = 1; n <= attempts; n++) {
|
|
12447
14663
|
if (n > 1) {
|
|
12448
14664
|
const delay = retryDelayMs(n);
|
|
12449
14665
|
hooks.onRetry?.(n, delay, last);
|
|
12450
|
-
await
|
|
14666
|
+
await sleep5(delay);
|
|
12451
14667
|
}
|
|
12452
14668
|
try {
|
|
12453
14669
|
return await attempt(n);
|
|
@@ -12461,11 +14677,12 @@ async function withShieldRetries(attempt, hooks = {}) {
|
|
|
12461
14677
|
}
|
|
12462
14678
|
|
|
12463
14679
|
// src/index.ts
|
|
12464
|
-
var VERSION = "0.2.
|
|
14680
|
+
var VERSION = "0.2.6";
|
|
12465
14681
|
var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
12466
14682
|
export {
|
|
12467
14683
|
AccountRole,
|
|
12468
14684
|
BRIDGE_ESCROW_LABEL,
|
|
14685
|
+
BRIDGE_ESCROW_LABEL_V2,
|
|
12469
14686
|
BUILD_ALLOWS_LOCAL_ENDPOINTS,
|
|
12470
14687
|
CHAIN_NOTE_SALT_BITS,
|
|
12471
14688
|
CLEANUP_FEE_BUDGET,
|
|
@@ -12494,6 +14711,10 @@ export {
|
|
|
12494
14711
|
MemoryStorageAdapter,
|
|
12495
14712
|
MerkleTree,
|
|
12496
14713
|
NATIVE_SOL_MINT,
|
|
14714
|
+
NOTE_INDEX_NO_LEAF,
|
|
14715
|
+
NOTE_INDEX_PAGE_SIZE,
|
|
14716
|
+
NoteIndexFormatError,
|
|
14717
|
+
NoteIndexHeadBehindError,
|
|
12497
14718
|
ONECLICK_PUBKEY_B58,
|
|
12498
14719
|
RECIPIENT_DELIVERY_CIPHERTEXT_LEN,
|
|
12499
14720
|
RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
|
|
@@ -12570,6 +14791,7 @@ export {
|
|
|
12570
14791
|
computeChainNoteHash,
|
|
12571
14792
|
computeExtDataHash,
|
|
12572
14793
|
computeMerkleRoot,
|
|
14794
|
+
computeNoteIndexChain,
|
|
12573
14795
|
computeProofForLatestDeposit,
|
|
12574
14796
|
computeProofFromChain,
|
|
12575
14797
|
computeSignature,
|
|
@@ -12594,14 +14816,18 @@ export {
|
|
|
12594
14816
|
depositFromDerivedKey,
|
|
12595
14817
|
deriveBridgeReceiver,
|
|
12596
14818
|
deriveChangeNoteBlinding,
|
|
12597
|
-
|
|
14819
|
+
deriveDepositNoteBlinding,
|
|
12598
14820
|
deriveDiversifiedViewingKey,
|
|
12599
14821
|
deriveDiversifier,
|
|
12600
14822
|
deriveFundingTargets,
|
|
12601
14823
|
deriveInputNullifierPdas,
|
|
14824
|
+
deriveLegacyBridgeReceiver,
|
|
14825
|
+
deriveLegacyDepositNoteSecrets,
|
|
14826
|
+
deriveLegacySwapRefundAuthorization,
|
|
12602
14827
|
derivePublicKey,
|
|
12603
14828
|
deriveSpendKey,
|
|
12604
14829
|
deriveSwapRefundAuthorization,
|
|
14830
|
+
deriveSwapRefundBlinding,
|
|
12605
14831
|
deriveUserCompliancePublicKey,
|
|
12606
14832
|
deriveUserComplianceScalar,
|
|
12607
14833
|
deriveUtxoKeypairFromSpendKey,
|
|
@@ -12614,6 +14840,8 @@ export {
|
|
|
12614
14840
|
discoverSwapRefunds,
|
|
12615
14841
|
downloadNote,
|
|
12616
14842
|
encodeDeliveryCarrierMemo,
|
|
14843
|
+
encodeNoteIndexItem,
|
|
14844
|
+
encodeNoteIndexPage,
|
|
12617
14845
|
encodeNoteSimple,
|
|
12618
14846
|
encodeRecipientDeliveryNote,
|
|
12619
14847
|
encryptCompactChainNote,
|
|
@@ -12629,6 +14857,8 @@ export {
|
|
|
12629
14857
|
fetchCommitments,
|
|
12630
14858
|
fetchLatestBlockhash,
|
|
12631
14859
|
fetchLookupTables,
|
|
14860
|
+
fetchNoteIndexHead,
|
|
14861
|
+
fetchNoteIndexPage,
|
|
12632
14862
|
fetchRiskQuoteInstruction,
|
|
12633
14863
|
fetchRiskQuoteIx,
|
|
12634
14864
|
fetchSignaturesForAddress,
|
|
@@ -12701,6 +14931,8 @@ export {
|
|
|
12701
14931
|
parseDeliveryCarrierMemo,
|
|
12702
14932
|
parseError,
|
|
12703
14933
|
parseNote2 as parseNote,
|
|
14934
|
+
parseNoteIndexItem,
|
|
14935
|
+
parseNoteIndexPage,
|
|
12704
14936
|
parseRelayErrorResponse,
|
|
12705
14937
|
parseRelayErrorSignature,
|
|
12706
14938
|
parseTransactionError,
|
|
@@ -12722,6 +14954,7 @@ export {
|
|
|
12722
14954
|
readMerkleTreeState,
|
|
12723
14955
|
readRent,
|
|
12724
14956
|
recipientDeliveryNoteToBase64,
|
|
14957
|
+
recoverNotesFromIndex,
|
|
12725
14958
|
registerViewingKey,
|
|
12726
14959
|
relayRequestDigestHex,
|
|
12727
14960
|
removePendingDeposit,
|