@cloak.dev/sdk 0.2.6-staging.af2dfc0 → 0.2.6-staging.d42dbe0
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 +70 -0
- package/README.md +102 -4
- package/dist/index.cjs +2155 -79
- package/dist/index.d.cts +547 -29
- package/dist/index.d.ts +547 -29
- package/dist/index.js +2139 -81
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -606,6 +606,10 @@ __export(index_exports, {
|
|
|
606
606
|
MemoryStorageAdapter: () => MemoryStorageAdapter,
|
|
607
607
|
MerkleTree: () => MerkleTree,
|
|
608
608
|
NATIVE_SOL_MINT: () => NATIVE_SOL_MINT,
|
|
609
|
+
NOTE_INDEX_NO_LEAF: () => NOTE_INDEX_NO_LEAF,
|
|
610
|
+
NOTE_INDEX_PAGE_SIZE: () => NOTE_INDEX_PAGE_SIZE,
|
|
611
|
+
NoteIndexFormatError: () => NoteIndexFormatError,
|
|
612
|
+
NoteIndexHeadBehindError: () => NoteIndexHeadBehindError,
|
|
609
613
|
ONECLICK_PUBKEY_B58: () => ONECLICK_PUBKEY_B58,
|
|
610
614
|
RECIPIENT_DELIVERY_CIPHERTEXT_LEN: () => RECIPIENT_DELIVERY_CIPHERTEXT_LEN,
|
|
611
615
|
RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN: () => RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
|
|
@@ -682,6 +686,7 @@ __export(index_exports, {
|
|
|
682
686
|
computeChainNoteHash: () => computeChainNoteHash,
|
|
683
687
|
computeExtDataHash: () => computeExtDataHash,
|
|
684
688
|
computeMerkleRoot: () => computeMerkleRoot,
|
|
689
|
+
computeNoteIndexChain: () => computeNoteIndexChain,
|
|
685
690
|
computeProofForLatestDeposit: () => computeProofForLatestDeposit,
|
|
686
691
|
computeProofFromChain: () => computeProofFromChain,
|
|
687
692
|
computeSignature: () => computeSignature,
|
|
@@ -718,6 +723,7 @@ __export(index_exports, {
|
|
|
718
723
|
deriveSpendKey: () => deriveSpendKey,
|
|
719
724
|
deriveSwapRefundAuthorization: () => deriveSwapRefundAuthorization,
|
|
720
725
|
deriveSwapRefundBlinding: () => deriveSwapRefundBlinding,
|
|
726
|
+
deriveSwapRefundKeypair: () => deriveSwapRefundKeypair,
|
|
721
727
|
deriveUserCompliancePublicKey: () => deriveUserCompliancePublicKey,
|
|
722
728
|
deriveUserComplianceScalar: () => deriveUserComplianceScalar,
|
|
723
729
|
deriveUtxoKeypairFromSpendKey: () => deriveUtxoKeypairFromSpendKey,
|
|
@@ -730,6 +736,8 @@ __export(index_exports, {
|
|
|
730
736
|
discoverSwapRefunds: () => discoverSwapRefunds,
|
|
731
737
|
downloadNote: () => downloadNote,
|
|
732
738
|
encodeDeliveryCarrierMemo: () => encodeDeliveryCarrierMemo,
|
|
739
|
+
encodeNoteIndexItem: () => encodeNoteIndexItem,
|
|
740
|
+
encodeNoteIndexPage: () => encodeNoteIndexPage,
|
|
733
741
|
encodeNoteSimple: () => encodeNoteSimple,
|
|
734
742
|
encodeRecipientDeliveryNote: () => encodeRecipientDeliveryNote,
|
|
735
743
|
encryptCompactChainNote: () => encryptCompactChainNote,
|
|
@@ -745,6 +753,8 @@ __export(index_exports, {
|
|
|
745
753
|
fetchCommitments: () => fetchCommitments,
|
|
746
754
|
fetchLatestBlockhash: () => fetchLatestBlockhash,
|
|
747
755
|
fetchLookupTables: () => fetchLookupTables,
|
|
756
|
+
fetchNoteIndexHead: () => fetchNoteIndexHead,
|
|
757
|
+
fetchNoteIndexPage: () => fetchNoteIndexPage,
|
|
748
758
|
fetchRiskQuoteInstruction: () => fetchRiskQuoteInstruction,
|
|
749
759
|
fetchRiskQuoteIx: () => fetchRiskQuoteIx,
|
|
750
760
|
fetchSignaturesForAddress: () => fetchSignaturesForAddress,
|
|
@@ -817,6 +827,8 @@ __export(index_exports, {
|
|
|
817
827
|
parseDeliveryCarrierMemo: () => parseDeliveryCarrierMemo,
|
|
818
828
|
parseError: () => parseError,
|
|
819
829
|
parseNote: () => parseNote2,
|
|
830
|
+
parseNoteIndexItem: () => parseNoteIndexItem,
|
|
831
|
+
parseNoteIndexPage: () => parseNoteIndexPage,
|
|
820
832
|
parseRelayErrorResponse: () => parseRelayErrorResponse,
|
|
821
833
|
parseRelayErrorSignature: () => parseRelayErrorSignature,
|
|
822
834
|
parseTransactionError: () => parseTransactionError,
|
|
@@ -838,6 +850,7 @@ __export(index_exports, {
|
|
|
838
850
|
readMerkleTreeState: () => readMerkleTreeState,
|
|
839
851
|
readRent: () => readRent,
|
|
840
852
|
recipientDeliveryNoteToBase64: () => recipientDeliveryNoteToBase64,
|
|
853
|
+
recoverNotesFromIndex: () => recoverNotesFromIndex,
|
|
841
854
|
registerViewingKey: () => registerViewingKey,
|
|
842
855
|
relayRequestDigestHex: () => relayRequestDigestHex,
|
|
843
856
|
removePendingDeposit: () => removePendingDeposit,
|
|
@@ -866,6 +879,7 @@ __export(index_exports, {
|
|
|
866
879
|
signTransaction: () => signTransaction,
|
|
867
880
|
signerFromKeypair: () => signerFromKeypair,
|
|
868
881
|
signerFromSecretKey: () => signerFromSecretKey,
|
|
882
|
+
signerFromTransactionBytes: () => signerFromTransactionBytes,
|
|
869
883
|
signerFromWalletAdapter: () => signerFromWalletAdapter,
|
|
870
884
|
splitTo2Limbs: () => splitTo2Limbs,
|
|
871
885
|
submitTransactToRelay: () => submitTransactToRelay,
|
|
@@ -1512,13 +1526,16 @@ init_inputs();
|
|
|
1512
1526
|
|
|
1513
1527
|
// src/relay/viewing-key.ts
|
|
1514
1528
|
var VIEWING_KEY_CHALLENGE_PREFIX = "CLOAK_VIEWING_KEY_REGISTER";
|
|
1529
|
+
var VIEWING_KEY_CHALLENGE_READABLE_HEADER = "Cloak: Enable private transactions\n\nShares your viewing key with Cloak so you can transact privately. Signing this does not move any funds.\n\n";
|
|
1530
|
+
var VIEWING_KEY_CHALLENGE_REQUEST_FORMAT = "readable";
|
|
1515
1531
|
var UUID_V4_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
1516
1532
|
var MAX_VIEWING_KEY_CHALLENGE_TTL_SECONDS = 300;
|
|
1517
1533
|
function normalizeViewingKeyHex(viewingKeyHex) {
|
|
1518
1534
|
return viewingKeyHex.replace(/^0x/i, "").toLowerCase();
|
|
1519
1535
|
}
|
|
1520
|
-
function buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex) {
|
|
1521
|
-
|
|
1536
|
+
function buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex, format = "legacy") {
|
|
1537
|
+
const header = format === "readable" ? VIEWING_KEY_CHALLENGE_READABLE_HEADER : "";
|
|
1538
|
+
return header + [
|
|
1522
1539
|
VIEWING_KEY_CHALLENGE_PREFIX,
|
|
1523
1540
|
userPubkey,
|
|
1524
1541
|
nonce,
|
|
@@ -1533,17 +1550,16 @@ function parseStrictViewingKeyChallenge(response, userPubkey, viewingKeyHex) {
|
|
|
1533
1550
|
const challenge = data;
|
|
1534
1551
|
const nonce = typeof challenge.nonce === "string" ? challenge.nonce : "";
|
|
1535
1552
|
const expiresInSeconds = challenge.expires_in_seconds;
|
|
1536
|
-
const
|
|
1537
|
-
userPubkey,
|
|
1538
|
-
nonce,
|
|
1539
|
-
viewingKeyHex
|
|
1553
|
+
const messageFormat = ["readable", "legacy"].find(
|
|
1554
|
+
(format) => challenge.message === buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex, format)
|
|
1540
1555
|
);
|
|
1541
|
-
if (!UUID_V4_PATTERN.test(nonce) || !Number.isInteger(expiresInSeconds) || expiresInSeconds < 1 || expiresInSeconds > MAX_VIEWING_KEY_CHALLENGE_TTL_SECONDS ||
|
|
1556
|
+
if (!UUID_V4_PATTERN.test(nonce) || !Number.isInteger(expiresInSeconds) || expiresInSeconds < 1 || expiresInSeconds > MAX_VIEWING_KEY_CHALLENGE_TTL_SECONDS || messageFormat === void 0) {
|
|
1542
1557
|
throw new Error("Relay returned an unsafe viewing-key challenge");
|
|
1543
1558
|
}
|
|
1544
1559
|
return {
|
|
1545
1560
|
nonce,
|
|
1546
|
-
message:
|
|
1561
|
+
message: buildViewingKeyChallengeMessage(userPubkey, nonce, viewingKeyHex, messageFormat),
|
|
1562
|
+
messageFormat,
|
|
1547
1563
|
expiresInSeconds
|
|
1548
1564
|
};
|
|
1549
1565
|
}
|
|
@@ -1630,7 +1646,7 @@ var BUILD_ALLOWS_LOCAL_ENDPOINTS = RELAY_ORIGIN_ALLOWLIST.some(isLoopbackHost);
|
|
|
1630
1646
|
// src/relay/clock.ts
|
|
1631
1647
|
var RELAY_SERVER_TIME_HEADER = "x-cloak-server-time";
|
|
1632
1648
|
var MAX_CLOCK_DIVERGENCE_MS = 2e3;
|
|
1633
|
-
var MAX_PLAUSIBLE_OFFSET_MS =
|
|
1649
|
+
var MAX_PLAUSIBLE_OFFSET_MS = 24 * 60 * 60 * 1e3;
|
|
1634
1650
|
var sample = null;
|
|
1635
1651
|
function monotonicNowMs() {
|
|
1636
1652
|
const perf = globalThis.performance;
|
|
@@ -1717,7 +1733,7 @@ async function relayFetch(url, init, options) {
|
|
|
1717
1733
|
assertAllowedRelayOrigin(url);
|
|
1718
1734
|
const extra = sanitizeExtraHeaders(options?.extraHeaders);
|
|
1719
1735
|
const response = extra ? await fetch(url, { ...init, headers: mergeRelayHeaders(init?.headers, extra) }) : await fetch(url, init);
|
|
1720
|
-
observeRelayClock(response);
|
|
1736
|
+
if (options?.observeClock !== false) observeRelayClock(response);
|
|
1721
1737
|
return response;
|
|
1722
1738
|
}
|
|
1723
1739
|
var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
@@ -2485,7 +2501,8 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
|
|
|
2485
2501
|
headers: { "Content-Type": "application/json" },
|
|
2486
2502
|
body: JSON.stringify({
|
|
2487
2503
|
user_pubkey: userPubkey,
|
|
2488
|
-
viewing_key: nkHex
|
|
2504
|
+
viewing_key: nkHex,
|
|
2505
|
+
message_format: VIEWING_KEY_CHALLENGE_REQUEST_FORMAT
|
|
2489
2506
|
})
|
|
2490
2507
|
});
|
|
2491
2508
|
if (!challengeResponse.ok) {
|
|
@@ -2513,7 +2530,8 @@ async function registerViewingKey(relayUrl, userPubkey, nk, signMessage) {
|
|
|
2513
2530
|
nonce: challenge.nonce,
|
|
2514
2531
|
identifier: keyId,
|
|
2515
2532
|
signature,
|
|
2516
|
-
...signed.mode === "transaction" ? { auth_mode: signed.mode } : {}
|
|
2533
|
+
...signed.mode === "transaction" ? { auth_mode: signed.mode } : {},
|
|
2534
|
+
...challenge.messageFormat === "readable" ? { message_format: challenge.messageFormat } : {}
|
|
2517
2535
|
})
|
|
2518
2536
|
});
|
|
2519
2537
|
if (!response.ok) {
|
|
@@ -2801,6 +2819,14 @@ function isSubmissionOutcomeUnknownResponse(responseText) {
|
|
|
2801
2819
|
return false;
|
|
2802
2820
|
}
|
|
2803
2821
|
}
|
|
2822
|
+
function isRelayRequestInFlightResponse(responseText) {
|
|
2823
|
+
try {
|
|
2824
|
+
const parsed = JSON.parse(responseText);
|
|
2825
|
+
return parsed?.code === "transient_upstream" && typeof parsed.message === "string" && parsed.message.includes("is already processing");
|
|
2826
|
+
} catch {
|
|
2827
|
+
return false;
|
|
2828
|
+
}
|
|
2829
|
+
}
|
|
2804
2830
|
function classifyRelayError(responseText, httpStatus) {
|
|
2805
2831
|
let inner = "";
|
|
2806
2832
|
try {
|
|
@@ -4348,7 +4374,11 @@ var RelayService = class {
|
|
|
4348
4374
|
const challengeRes = await relayFetch(`${this.baseUrl}/viewing-key/challenge`, {
|
|
4349
4375
|
method: "POST",
|
|
4350
4376
|
headers: { "Content-Type": "application/json" },
|
|
4351
|
-
body: JSON.stringify({
|
|
4377
|
+
body: JSON.stringify({
|
|
4378
|
+
user_pubkey: userPubkey,
|
|
4379
|
+
viewing_key: viewingKey,
|
|
4380
|
+
message_format: VIEWING_KEY_CHALLENGE_REQUEST_FORMAT
|
|
4381
|
+
})
|
|
4352
4382
|
});
|
|
4353
4383
|
if (!challengeRes.ok) {
|
|
4354
4384
|
const error = await challengeRes.text();
|
|
@@ -4373,7 +4403,8 @@ var RelayService = class {
|
|
|
4373
4403
|
nonce: challenge.nonce,
|
|
4374
4404
|
identifier,
|
|
4375
4405
|
signature,
|
|
4376
|
-
...signed.mode === "transaction" ? { auth_mode: signed.mode } : {}
|
|
4406
|
+
...signed.mode === "transaction" ? { auth_mode: signed.mode } : {},
|
|
4407
|
+
...challenge.messageFormat === "readable" ? { message_format: challenge.messageFormat } : {}
|
|
4377
4408
|
})
|
|
4378
4409
|
});
|
|
4379
4410
|
if (!response.ok) {
|
|
@@ -4843,6 +4874,27 @@ function isRootAccepted(data, rootHex) {
|
|
|
4843
4874
|
const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
|
|
4844
4875
|
return readRootHistory(data).some((r) => r === want);
|
|
4845
4876
|
}
|
|
4877
|
+
function treeAccountAcceptsRoot(data, rootHex) {
|
|
4878
|
+
const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
|
|
4879
|
+
if (data.length >= ROOT_OFFSET + 32) {
|
|
4880
|
+
const current = Buffer.from(data.subarray(ROOT_OFFSET, ROOT_OFFSET + 32)).toString("hex");
|
|
4881
|
+
if (current === want) return true;
|
|
4882
|
+
}
|
|
4883
|
+
return isRootAccepted(data, want);
|
|
4884
|
+
}
|
|
4885
|
+
function readTreeAccountFrontier(data) {
|
|
4886
|
+
if (!data || data.length < ROOT_INDEX_OFFSET + 8) return null;
|
|
4887
|
+
const buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
|
|
4888
|
+
const next = readBigUInt64LE(buf, 32);
|
|
4889
|
+
if (next > 2n ** BigInt(MERKLE_TREE_HEIGHT)) return null;
|
|
4890
|
+
const subtrees = [];
|
|
4891
|
+
for (let level = 0; level < MERKLE_TREE_HEIGHT; level++) {
|
|
4892
|
+
const offset = SUBTREES_OFFSET + level * 32;
|
|
4893
|
+
subtrees.push(BigInt("0x" + buf.subarray(offset, offset + 32).toString("hex")));
|
|
4894
|
+
}
|
|
4895
|
+
const root = BigInt("0x" + buf.subarray(ROOT_OFFSET, ROOT_OFFSET + 32).toString("hex"));
|
|
4896
|
+
return { nextIndex: Number(next), subtrees, root };
|
|
4897
|
+
}
|
|
4846
4898
|
|
|
4847
4899
|
// src/proving/merkle.ts
|
|
4848
4900
|
var import_circomlibjs3 = require("circomlibjs");
|
|
@@ -5002,6 +5054,89 @@ var MerkleTree = class _MerkleTree {
|
|
|
5002
5054
|
async function buildMerkleTree(commitments, height = MERKLE_TREE_HEIGHT2) {
|
|
5003
5055
|
return MerkleTree.create(height, commitments);
|
|
5004
5056
|
}
|
|
5057
|
+
var MerkleFrontier = class _MerkleFrontier {
|
|
5058
|
+
constructor(levels, zeros, poseidon3, count, left) {
|
|
5059
|
+
this.levels = levels;
|
|
5060
|
+
this.zeros = zeros;
|
|
5061
|
+
this.poseidon = poseidon3;
|
|
5062
|
+
this.count = count;
|
|
5063
|
+
this.left = left;
|
|
5064
|
+
}
|
|
5065
|
+
static async create(state, levels = MERKLE_TREE_HEIGHT2) {
|
|
5066
|
+
const zeros = await getZeroValues();
|
|
5067
|
+
const poseidon3 = await getPoseidon3();
|
|
5068
|
+
const left = new Array(levels).fill(null);
|
|
5069
|
+
let count = 0;
|
|
5070
|
+
if (state) {
|
|
5071
|
+
if (!Number.isSafeInteger(state.nextIndex) || state.nextIndex < 0 || state.nextIndex > 2 ** levels) {
|
|
5072
|
+
throw new Error("MerkleFrontierState.nextIndex out of range");
|
|
5073
|
+
}
|
|
5074
|
+
if (!Array.isArray(state.left) || state.left.length !== levels) {
|
|
5075
|
+
throw new Error(`MerkleFrontierState.left must have ${levels} entries`);
|
|
5076
|
+
}
|
|
5077
|
+
count = state.nextIndex;
|
|
5078
|
+
for (let l = 0; l < levels; l++) {
|
|
5079
|
+
const odd = Math.floor(count / 2 ** l) % 2 === 1;
|
|
5080
|
+
const entry = state.left[l];
|
|
5081
|
+
if (odd !== (entry !== "")) throw new Error(`MerkleFrontierState.left[${l}] disagrees with nextIndex`);
|
|
5082
|
+
if (odd) {
|
|
5083
|
+
if (!/^[0-9a-f]{64}$/.test(entry)) throw new Error(`MerkleFrontierState.left[${l}] is not 32-byte hex`);
|
|
5084
|
+
left[l] = BigInt("0x" + entry);
|
|
5085
|
+
}
|
|
5086
|
+
}
|
|
5087
|
+
}
|
|
5088
|
+
return new _MerkleFrontier(levels, zeros, poseidon3, count, left);
|
|
5089
|
+
}
|
|
5090
|
+
get nextIndex() {
|
|
5091
|
+
return this.count;
|
|
5092
|
+
}
|
|
5093
|
+
/**
|
|
5094
|
+
* The complete LEFT node held at `level`: the node at index `floor(nextIndex / 2^level) - 1`,
|
|
5095
|
+
* present only while that index is even (bit `level` of `nextIndex` is set), else `null`.
|
|
5096
|
+
* With every set bit of `nextIndex`, these nodes cover leaves `[0, nextIndex)` exactly.
|
|
5097
|
+
*/
|
|
5098
|
+
leftAt(level) {
|
|
5099
|
+
if (!Number.isInteger(level) || level < 0 || level >= this.levels) return null;
|
|
5100
|
+
return this.left[level];
|
|
5101
|
+
}
|
|
5102
|
+
hash(a, b) {
|
|
5103
|
+
return this.poseidon.F.toObject(this.poseidon([a, b]));
|
|
5104
|
+
}
|
|
5105
|
+
/** Append leaves at indices `nextIndex .. nextIndex + leaves.length - 1`. */
|
|
5106
|
+
append(leaves) {
|
|
5107
|
+
if (leaves.length === 0) return;
|
|
5108
|
+
if (this.count + leaves.length > 2 ** this.levels) throw new Error("Tree is full");
|
|
5109
|
+
let nodes = leaves;
|
|
5110
|
+
for (let l = 0; l < this.levels && nodes.length > 0; l++) {
|
|
5111
|
+
const before = Math.floor(this.count / 2 ** l);
|
|
5112
|
+
const seq = before % 2 === 1 ? [this.left[l], ...nodes] : nodes;
|
|
5113
|
+
const parents = [];
|
|
5114
|
+
for (let i = 0; i + 1 < seq.length; i += 2) parents.push(this.hash(seq[i], seq[i + 1]));
|
|
5115
|
+
this.left[l] = (before + nodes.length) % 2 === 1 ? seq[seq.length - 1] : null;
|
|
5116
|
+
nodes = parents;
|
|
5117
|
+
}
|
|
5118
|
+
this.count += leaves.length;
|
|
5119
|
+
}
|
|
5120
|
+
/** The root of the first `nextIndex` leaves, zero-padded to the right. */
|
|
5121
|
+
root() {
|
|
5122
|
+
let partial = this.zeros[0];
|
|
5123
|
+
for (let l = 0; l < this.levels; l++) {
|
|
5124
|
+
const odd = Math.floor(this.count / 2 ** l) % 2 === 1;
|
|
5125
|
+
if (odd) partial = this.hash(this.left[l], partial);
|
|
5126
|
+
else partial = partial === this.zeros[l] ? this.zeros[l + 1] : this.hash(partial, this.zeros[l]);
|
|
5127
|
+
}
|
|
5128
|
+
return partial;
|
|
5129
|
+
}
|
|
5130
|
+
toState() {
|
|
5131
|
+
return {
|
|
5132
|
+
nextIndex: this.count,
|
|
5133
|
+
left: this.left.map((v) => v === null ? "" : v.toString(16).padStart(64, "0"))
|
|
5134
|
+
};
|
|
5135
|
+
}
|
|
5136
|
+
clone() {
|
|
5137
|
+
return new _MerkleFrontier(this.levels, this.zeros, this.poseidon, this.count, [...this.left]);
|
|
5138
|
+
}
|
|
5139
|
+
};
|
|
5005
5140
|
|
|
5006
5141
|
// src/relay/client.ts
|
|
5007
5142
|
init_address();
|
|
@@ -5506,38 +5641,77 @@ async function aesGcmDecrypt2(ciphertext, keyBytes, nonce) {
|
|
|
5506
5641
|
const plaintext = await subtle.decrypt({ name: "AES-GCM", iv: toArrayBuffer2(nonce) }, key, toArrayBuffer2(ciphertext));
|
|
5507
5642
|
return new Uint8Array(plaintext);
|
|
5508
5643
|
}
|
|
5509
|
-
async function
|
|
5644
|
+
async function importNkHkdfKey(nk) {
|
|
5510
5645
|
if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
|
|
5511
5646
|
throw new Error("nk must be 32 bytes");
|
|
5512
5647
|
}
|
|
5648
|
+
return getSubtleCrypto2().importKey("raw", toArrayBuffer2(nk), "HKDF", false, ["deriveBits"]);
|
|
5649
|
+
}
|
|
5650
|
+
async function deriveAesKeyAndNonceFromIkm(ikm, salt) {
|
|
5513
5651
|
const subtle = getSubtleCrypto2();
|
|
5514
|
-
const
|
|
5515
|
-
|
|
5516
|
-
|
|
5517
|
-
|
|
5518
|
-
|
|
5519
|
-
|
|
5520
|
-
|
|
5521
|
-
|
|
5522
|
-
|
|
5523
|
-
|
|
5524
|
-
|
|
5525
|
-
|
|
5526
|
-
|
|
5527
|
-
|
|
5528
|
-
|
|
5529
|
-
|
|
5530
|
-
|
|
5531
|
-
|
|
5532
|
-
|
|
5533
|
-
|
|
5534
|
-
|
|
5535
|
-
);
|
|
5652
|
+
const [keyBits, nonceBits] = await Promise.all([
|
|
5653
|
+
subtle.deriveBits(
|
|
5654
|
+
{
|
|
5655
|
+
name: "HKDF",
|
|
5656
|
+
hash: "SHA-256",
|
|
5657
|
+
salt: toArrayBuffer2(salt),
|
|
5658
|
+
info: toArrayBuffer2(CHAIN_NOTE_KEY_INFO)
|
|
5659
|
+
},
|
|
5660
|
+
ikm,
|
|
5661
|
+
256
|
|
5662
|
+
),
|
|
5663
|
+
subtle.deriveBits(
|
|
5664
|
+
{
|
|
5665
|
+
name: "HKDF",
|
|
5666
|
+
hash: "SHA-256",
|
|
5667
|
+
salt: toArrayBuffer2(salt),
|
|
5668
|
+
info: toArrayBuffer2(CHAIN_NOTE_NONCE_INFO)
|
|
5669
|
+
},
|
|
5670
|
+
ikm,
|
|
5671
|
+
96
|
|
5672
|
+
)
|
|
5673
|
+
]);
|
|
5536
5674
|
return {
|
|
5537
5675
|
key: new Uint8Array(keyBits),
|
|
5538
5676
|
nonce: new Uint8Array(nonceBits)
|
|
5539
5677
|
};
|
|
5540
5678
|
}
|
|
5679
|
+
async function deriveAesKeyAndNonce(nk, commitmentHex) {
|
|
5680
|
+
const ikm = await importNkHkdfKey(nk);
|
|
5681
|
+
return deriveAesKeyAndNonceFromIkm(ikm, hexToBytes32(commitmentHex));
|
|
5682
|
+
}
|
|
5683
|
+
function decodeChainNotePlaintext(version, plaintext, commitmentHex) {
|
|
5684
|
+
if (version === NOTE_VERSION_V4) {
|
|
5685
|
+
if (plaintext.length !== PLAINTEXT_LEN_V4) {
|
|
5686
|
+
throw new Error(`Invalid v4 chain note plaintext length: ${plaintext.length}`);
|
|
5687
|
+
}
|
|
5688
|
+
return {
|
|
5689
|
+
timestamp: readU64LE(plaintext, 0),
|
|
5690
|
+
commitment: commitmentHex.toLowerCase(),
|
|
5691
|
+
noteSalt: readU256BE(plaintext, TIMESTAMP_LEN),
|
|
5692
|
+
outAmount0: readU64LE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN),
|
|
5693
|
+
outPubkey0: readU256BE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN + OUT_AMOUNT_LEN),
|
|
5694
|
+
isSendToSelfKey0: BigInt(plaintext[PLAINTEXT_LEN_V4 - 1])
|
|
5695
|
+
};
|
|
5696
|
+
}
|
|
5697
|
+
if (version === NOTE_VERSION_V3) {
|
|
5698
|
+
if (plaintext.length !== PLAINTEXT_LEN_V3) {
|
|
5699
|
+
throw new Error(`Invalid v3 chain note plaintext length: ${plaintext.length}`);
|
|
5700
|
+
}
|
|
5701
|
+
return {
|
|
5702
|
+
timestamp: readU64LE(plaintext, 0),
|
|
5703
|
+
commitment: commitmentHex.toLowerCase(),
|
|
5704
|
+
noteSalt: readU256BE(plaintext, TIMESTAMP_LEN)
|
|
5705
|
+
};
|
|
5706
|
+
}
|
|
5707
|
+
if (plaintext.length !== PLAINTEXT_LEN_V2) {
|
|
5708
|
+
throw new Error(`Invalid v2 chain note plaintext length: ${plaintext.length}`);
|
|
5709
|
+
}
|
|
5710
|
+
return {
|
|
5711
|
+
timestamp: readU64LE(plaintext, 0),
|
|
5712
|
+
commitment: commitmentHex.toLowerCase()
|
|
5713
|
+
};
|
|
5714
|
+
}
|
|
5541
5715
|
async function encryptCompactChainNote(timestamp, nk, commitmentHex, noteSalt, semantics) {
|
|
5542
5716
|
if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
|
|
5543
5717
|
throw new Error("nk must be 32 bytes");
|
|
@@ -5601,36 +5775,7 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
|
|
|
5601
5775
|
try {
|
|
5602
5776
|
const { key, nonce } = await deriveAesKeyAndNonce(nk, commitment);
|
|
5603
5777
|
const plaintext = await aesGcmDecrypt2(ciphertext, key, nonce);
|
|
5604
|
-
|
|
5605
|
-
if (plaintext.length !== PLAINTEXT_LEN_V4) {
|
|
5606
|
-
throw new Error(`Invalid v4 chain note plaintext length: ${plaintext.length}`);
|
|
5607
|
-
}
|
|
5608
|
-
return {
|
|
5609
|
-
timestamp: readU64LE(plaintext, 0),
|
|
5610
|
-
commitment: commitment.toLowerCase(),
|
|
5611
|
-
noteSalt: readU256BE(plaintext, TIMESTAMP_LEN),
|
|
5612
|
-
outAmount0: readU64LE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN),
|
|
5613
|
-
outPubkey0: readU256BE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN + OUT_AMOUNT_LEN),
|
|
5614
|
-
isSendToSelfKey0: BigInt(plaintext[PLAINTEXT_LEN_V4 - 1])
|
|
5615
|
-
};
|
|
5616
|
-
}
|
|
5617
|
-
if (version === NOTE_VERSION_V3) {
|
|
5618
|
-
if (plaintext.length !== PLAINTEXT_LEN_V3) {
|
|
5619
|
-
throw new Error(`Invalid v3 chain note plaintext length: ${plaintext.length}`);
|
|
5620
|
-
}
|
|
5621
|
-
return {
|
|
5622
|
-
timestamp: readU64LE(plaintext, 0),
|
|
5623
|
-
commitment: commitment.toLowerCase(),
|
|
5624
|
-
noteSalt: readU256BE(plaintext, TIMESTAMP_LEN)
|
|
5625
|
-
};
|
|
5626
|
-
}
|
|
5627
|
-
if (plaintext.length !== PLAINTEXT_LEN_V2) {
|
|
5628
|
-
throw new Error(`Invalid v2 chain note plaintext length: ${plaintext.length}`);
|
|
5629
|
-
}
|
|
5630
|
-
return {
|
|
5631
|
-
timestamp: readU64LE(plaintext, 0),
|
|
5632
|
-
commitment: commitment.toLowerCase()
|
|
5633
|
-
};
|
|
5778
|
+
return decodeChainNotePlaintext(version, plaintext, commitment);
|
|
5634
5779
|
} catch (error) {
|
|
5635
5780
|
lastError = error;
|
|
5636
5781
|
}
|
|
@@ -5639,6 +5784,26 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
|
|
|
5639
5784
|
`Failed to decrypt compact chain note with provided commitments: ${lastError instanceof Error ? lastError.message : String(lastError)}`
|
|
5640
5785
|
);
|
|
5641
5786
|
}
|
|
5787
|
+
async function createCompactChainNoteDecryptor(nk) {
|
|
5788
|
+
const ikm = await importNkHkdfKey(nk);
|
|
5789
|
+
return async (noteBytes, commitment) => {
|
|
5790
|
+
if (!(noteBytes instanceof Uint8Array) || noteBytes.length <= 1) return null;
|
|
5791
|
+
if (!(commitment instanceof Uint8Array) || commitment.length !== 32) return null;
|
|
5792
|
+
const version = noteBytes[0];
|
|
5793
|
+
if (version !== NOTE_VERSION_V4 && version !== NOTE_VERSION_V3 && version !== NOTE_VERSION_V2) {
|
|
5794
|
+
return null;
|
|
5795
|
+
}
|
|
5796
|
+
try {
|
|
5797
|
+
const { key, nonce } = await deriveAesKeyAndNonceFromIkm(ikm, commitment);
|
|
5798
|
+
const plaintext = await aesGcmDecrypt2(noteBytes.subarray(1), key, nonce);
|
|
5799
|
+
let hex = "";
|
|
5800
|
+
for (let i = 0; i < 32; i++) hex += commitment[i].toString(16).padStart(2, "0");
|
|
5801
|
+
return decodeChainNotePlaintext(version, plaintext, hex);
|
|
5802
|
+
} catch {
|
|
5803
|
+
return null;
|
|
5804
|
+
}
|
|
5805
|
+
};
|
|
5806
|
+
}
|
|
5642
5807
|
function chainNoteToBase64(noteBytes) {
|
|
5643
5808
|
return Buffer.from(noteBytes).toString("base64");
|
|
5644
5809
|
}
|
|
@@ -5735,6 +5900,80 @@ function openRecipientDeliveryNote(envelope, viewingSecretKey) {
|
|
|
5735
5900
|
return null;
|
|
5736
5901
|
}
|
|
5737
5902
|
}
|
|
5903
|
+
var X25519_PKCS8_PREFIX = Uint8Array.from([
|
|
5904
|
+
48,
|
|
5905
|
+
46,
|
|
5906
|
+
2,
|
|
5907
|
+
1,
|
|
5908
|
+
0,
|
|
5909
|
+
48,
|
|
5910
|
+
5,
|
|
5911
|
+
6,
|
|
5912
|
+
3,
|
|
5913
|
+
43,
|
|
5914
|
+
101,
|
|
5915
|
+
110,
|
|
5916
|
+
4,
|
|
5917
|
+
34,
|
|
5918
|
+
4,
|
|
5919
|
+
32
|
|
5920
|
+
]);
|
|
5921
|
+
var HSALSA_SIGMA = new TextEncoder().encode("expand 32-byte k");
|
|
5922
|
+
function decodeOpened(plaintext) {
|
|
5923
|
+
if (!plaintext || plaintext.length !== RECIPIENT_DELIVERY_PLAINTEXT_LEN) return null;
|
|
5924
|
+
return { amount: readU64LE2(plaintext, 0), blinding: readU256BE2(plaintext, 8) };
|
|
5925
|
+
}
|
|
5926
|
+
async function createRecipientDeliveryOpener(viewingSecretKey) {
|
|
5927
|
+
if (!(viewingSecretKey instanceof Uint8Array) || viewingSecretKey.length !== 32) {
|
|
5928
|
+
throw new Error("viewingSecretKey must be 32 bytes");
|
|
5929
|
+
}
|
|
5930
|
+
const slow = async (envelope) => openRecipientDeliveryNote(envelope, viewingSecretKey);
|
|
5931
|
+
const subtle = globalThis.crypto?.subtle;
|
|
5932
|
+
const hsalsa = import_tweetnacl4.default.lowlevel?.crypto_core_hsalsa20;
|
|
5933
|
+
if (!subtle || typeof hsalsa !== "function") return slow;
|
|
5934
|
+
let privateKey;
|
|
5935
|
+
const sharedKey = async (ephemeralPk) => {
|
|
5936
|
+
const publicKey = await subtle.importKey("raw", new Uint8Array(ephemeralPk), { name: "X25519" }, false, []);
|
|
5937
|
+
const shared = new Uint8Array(
|
|
5938
|
+
await subtle.deriveBits({ name: "X25519", public: publicKey }, privateKey, 256)
|
|
5939
|
+
);
|
|
5940
|
+
const key = new Uint8Array(32);
|
|
5941
|
+
hsalsa(key, new Uint8Array(16), shared, HSALSA_SIGMA);
|
|
5942
|
+
return key;
|
|
5943
|
+
};
|
|
5944
|
+
try {
|
|
5945
|
+
const pkcs8 = new Uint8Array(X25519_PKCS8_PREFIX.length + 32);
|
|
5946
|
+
pkcs8.set(X25519_PKCS8_PREFIX);
|
|
5947
|
+
pkcs8.set(viewingSecretKey, X25519_PKCS8_PREFIX.length);
|
|
5948
|
+
privateKey = await subtle.importKey("pkcs8", pkcs8, { name: "X25519" }, false, ["deriveBits"]);
|
|
5949
|
+
const probe = import_tweetnacl4.default.box.keyPair().publicKey;
|
|
5950
|
+
const fast = await sharedKey(probe);
|
|
5951
|
+
const reference = import_tweetnacl4.default.box.before(probe, viewingSecretKey);
|
|
5952
|
+
if (fast.length !== reference.length || fast.some((b, i) => b !== reference[i])) return slow;
|
|
5953
|
+
} catch {
|
|
5954
|
+
return slow;
|
|
5955
|
+
}
|
|
5956
|
+
return async (envelope) => {
|
|
5957
|
+
if (!(envelope instanceof Uint8Array) || envelope.length !== RECIPIENT_DELIVERY_NOTE_BYTES) return null;
|
|
5958
|
+
const ephemeralPk = envelope.subarray(0, RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN);
|
|
5959
|
+
const nonce = envelope.subarray(
|
|
5960
|
+
RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
|
|
5961
|
+
RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN
|
|
5962
|
+
);
|
|
5963
|
+
const ciphertext = envelope.subarray(RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN);
|
|
5964
|
+
let key;
|
|
5965
|
+
try {
|
|
5966
|
+
key = await sharedKey(ephemeralPk);
|
|
5967
|
+
} catch {
|
|
5968
|
+
return openRecipientDeliveryNote(envelope, viewingSecretKey);
|
|
5969
|
+
}
|
|
5970
|
+
try {
|
|
5971
|
+
return decodeOpened(import_tweetnacl4.default.secretbox.open(ciphertext, nonce, key));
|
|
5972
|
+
} catch {
|
|
5973
|
+
return null;
|
|
5974
|
+
}
|
|
5975
|
+
};
|
|
5976
|
+
}
|
|
5738
5977
|
function recipientDeliveryNoteToBase64(envelope) {
|
|
5739
5978
|
return Buffer.from(envelope).toString("base64");
|
|
5740
5979
|
}
|
|
@@ -5825,6 +6064,8 @@ function normalizeOwnerPublicKey(publicKey, label) {
|
|
|
5825
6064
|
init_inputs();
|
|
5826
6065
|
var bs582 = import_bs582.default.default || import_bs582.default;
|
|
5827
6066
|
var REFUND_SEED_DOMAIN = new TextEncoder().encode("cloak_swap_refund_v1");
|
|
6067
|
+
var REFUND_KEY_DOMAIN_V2 = new TextEncoder().encode("cloak_swap_refund_v2");
|
|
6068
|
+
var REFUND_PRIVATE_KEY_INFO_V2 = new TextEncoder().encode("sk_v2");
|
|
5828
6069
|
var LEGACY_REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
|
|
5829
6070
|
var REFUND_BLINDING_INFO = new TextEncoder().encode("blinding");
|
|
5830
6071
|
function normalizeNullifier(inputNullifier) {
|
|
@@ -5869,13 +6110,35 @@ function deriveSwapRefundBlinding(viewingKeyNk, inputNullifier) {
|
|
|
5869
6110
|
const nk = assertNk(viewingKeyNk);
|
|
5870
6111
|
return toFieldSecret(derive(nk, normalizeNullifier(inputNullifier), REFUND_BLINDING_INFO));
|
|
5871
6112
|
}
|
|
5872
|
-
|
|
6113
|
+
function privateKeyBytes(privateKey) {
|
|
6114
|
+
return Uint8Array.from(Buffer.from(privateKey.toString(16).padStart(64, "0"), "hex"));
|
|
6115
|
+
}
|
|
6116
|
+
async function deriveSwapRefundKeypair(ownerUtxoKeypair, inputNullifier) {
|
|
5873
6117
|
const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
|
|
6118
|
+
const nullifier = normalizeNullifier(inputNullifier);
|
|
6119
|
+
const preimage = new Uint8Array(
|
|
6120
|
+
REFUND_KEY_DOMAIN_V2.length + 32 + nullifier.length + REFUND_PRIVATE_KEY_INFO_V2.length
|
|
6121
|
+
);
|
|
6122
|
+
let off = 0;
|
|
6123
|
+
preimage.set(REFUND_KEY_DOMAIN_V2, off);
|
|
6124
|
+
off += REFUND_KEY_DOMAIN_V2.length;
|
|
6125
|
+
preimage.set(privateKeyBytes(owner.privateKey), off);
|
|
6126
|
+
off += 32;
|
|
6127
|
+
preimage.set(nullifier, off);
|
|
6128
|
+
off += nullifier.length;
|
|
6129
|
+
preimage.set(REFUND_PRIVATE_KEY_INFO_V2, off);
|
|
6130
|
+
const privateKey = toFieldSecret((0, import_blake34.blake3)(preimage));
|
|
6131
|
+
const publicKey = await derivePublicKey(privateKey);
|
|
6132
|
+
if (publicKey === 0n) throw new Error("refund authorization is degenerate");
|
|
6133
|
+
return { privateKey, publicKey };
|
|
6134
|
+
}
|
|
6135
|
+
async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier, ownerUtxoKeypair) {
|
|
5874
6136
|
const blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
|
|
5875
|
-
|
|
6137
|
+
const keypair = await deriveSwapRefundKeypair(ownerUtxoKeypair, inputNullifier);
|
|
6138
|
+
if (keypair.publicKey === 0n || blinding === 0n) {
|
|
5876
6139
|
throw new Error("refund authorization is degenerate");
|
|
5877
6140
|
}
|
|
5878
|
-
return { privateKey:
|
|
6141
|
+
return { privateKey: keypair.privateKey, publicKey: keypair.publicKey, blinding };
|
|
5879
6142
|
}
|
|
5880
6143
|
async function deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier) {
|
|
5881
6144
|
const nk = assertNk(viewingKeyNk);
|
|
@@ -5896,9 +6159,12 @@ async function computeSwapRefundCommitment(amountAfterFee, refundPublicKey, refu
|
|
|
5896
6159
|
mintAddress: NATIVE_SOL_MINT
|
|
5897
6160
|
});
|
|
5898
6161
|
}
|
|
6162
|
+
function toField(value) {
|
|
6163
|
+
return value instanceof Uint8Array ? BigInt("0x" + Buffer.from(value).toString("hex")) : value;
|
|
6164
|
+
}
|
|
5899
6165
|
async function matchSwapRefundLeaf(params) {
|
|
5900
6166
|
const { viewingKeyNk, inputNullifier, amountAfterFee } = params;
|
|
5901
|
-
const expected =
|
|
6167
|
+
const expected = toField(params.commitment);
|
|
5902
6168
|
let blinding;
|
|
5903
6169
|
try {
|
|
5904
6170
|
blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
|
|
@@ -5906,11 +6172,55 @@ async function matchSwapRefundLeaf(params) {
|
|
|
5906
6172
|
return null;
|
|
5907
6173
|
}
|
|
5908
6174
|
const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
|
|
6175
|
+
const ownerPriv = params.ownerUtxoKeypair?.privateKey ?? 0n;
|
|
6176
|
+
let perSwapPub;
|
|
6177
|
+
let perSwapPriv = 0n;
|
|
6178
|
+
if (ownerPriv > 0n && ownerPub !== void 0) {
|
|
6179
|
+
try {
|
|
6180
|
+
const kp = await deriveSwapRefundKeypair({ privateKey: ownerPriv, publicKey: ownerPub }, inputNullifier);
|
|
6181
|
+
perSwapPub = kp.publicKey;
|
|
6182
|
+
perSwapPriv = kp.privateKey;
|
|
6183
|
+
} catch {
|
|
6184
|
+
return null;
|
|
6185
|
+
}
|
|
6186
|
+
}
|
|
6187
|
+
if (params.publishedRefundPubkey !== void 0 && params.publishedRefundBlinding !== void 0) {
|
|
6188
|
+
const published = toField(params.publishedRefundPubkey);
|
|
6189
|
+
const publishedBlinding = toField(params.publishedRefundBlinding);
|
|
6190
|
+
if (published !== 0n && publishedBlinding === blinding) {
|
|
6191
|
+
if (perSwapPub === void 0 || perSwapPub === published) {
|
|
6192
|
+
const candidate = await computeSwapRefundCommitment(amountAfterFee, published, blinding);
|
|
6193
|
+
if (candidate === expected && published !== ownerPub) {
|
|
6194
|
+
return {
|
|
6195
|
+
keypair: { privateKey: perSwapPub === published ? perSwapPriv : 0n, publicKey: published },
|
|
6196
|
+
shape: "per-swap",
|
|
6197
|
+
blinding,
|
|
6198
|
+
amount: amountAfterFee,
|
|
6199
|
+
commitment: candidate,
|
|
6200
|
+
legacyExposed: false
|
|
6201
|
+
};
|
|
6202
|
+
}
|
|
6203
|
+
}
|
|
6204
|
+
}
|
|
6205
|
+
} else if (perSwapPub !== void 0) {
|
|
6206
|
+
const candidate = await computeSwapRefundCommitment(amountAfterFee, perSwapPub, blinding);
|
|
6207
|
+
if (candidate === expected) {
|
|
6208
|
+
return {
|
|
6209
|
+
keypair: { privateKey: perSwapPriv, publicKey: perSwapPub },
|
|
6210
|
+
shape: "per-swap",
|
|
6211
|
+
blinding,
|
|
6212
|
+
amount: amountAfterFee,
|
|
6213
|
+
commitment: candidate,
|
|
6214
|
+
legacyExposed: false
|
|
6215
|
+
};
|
|
6216
|
+
}
|
|
6217
|
+
}
|
|
5909
6218
|
if (ownerPub !== void 0) {
|
|
5910
6219
|
const candidate = await computeSwapRefundCommitment(amountAfterFee, ownerPub, blinding);
|
|
5911
6220
|
if (candidate === expected) {
|
|
5912
6221
|
return {
|
|
5913
|
-
keypair: { privateKey:
|
|
6222
|
+
keypair: { privateKey: ownerPriv, publicKey: ownerPub },
|
|
6223
|
+
shape: "owner",
|
|
5914
6224
|
blinding,
|
|
5915
6225
|
amount: amountAfterFee,
|
|
5916
6226
|
commitment: candidate,
|
|
@@ -5928,6 +6238,7 @@ async function matchSwapRefundLeaf(params) {
|
|
|
5928
6238
|
if (legacyCandidate !== expected) return null;
|
|
5929
6239
|
return {
|
|
5930
6240
|
keypair: { privateKey: legacy.privateKey, publicKey: legacy.publicKey },
|
|
6241
|
+
shape: "legacy-nk",
|
|
5931
6242
|
blinding: legacy.blinding,
|
|
5932
6243
|
amount: amountAfterFee,
|
|
5933
6244
|
commitment: legacyCandidate,
|
|
@@ -5939,6 +6250,9 @@ var PROOF_LEN2 = 256;
|
|
|
5939
6250
|
var NULLIFIER_0_OFFSET = 1 + PROOF_LEN2 + 104;
|
|
5940
6251
|
var PUBLIC_INPUTS_LEN2 = 264;
|
|
5941
6252
|
var MIN_TRANSACT_SWAP_LEN = 1 + PROOF_LEN2 + PUBLIC_INPUTS_LEN2;
|
|
6253
|
+
var REFUND_PUBKEY_OFFSET = 1 + PROOF_LEN2 + PUBLIC_INPUTS_LEN2 + 72;
|
|
6254
|
+
var REFUND_BLINDING_OFFSET = REFUND_PUBKEY_OFFSET + 32;
|
|
6255
|
+
var MIN_TRANSACT_SWAP_WITH_PARAMS_LEN = REFUND_BLINDING_OFFSET + 32;
|
|
5942
6256
|
function toBase58(key) {
|
|
5943
6257
|
if (!key) return void 0;
|
|
5944
6258
|
if (typeof key === "string") return key;
|
|
@@ -6001,7 +6315,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options)
|
|
|
6001
6315
|
}
|
|
6002
6316
|
if (!options || normalizeOwnerPublicKey(options.ownerUtxoKeypair?.publicKey, "options.ownerUtxoKeypair.publicKey") === void 0) {
|
|
6003
6317
|
throw new Error(
|
|
6004
|
-
"discoverSwapRefunds requires options.ownerUtxoKeypair (the wallet's long-lived UTXO keypair): refund leaves are
|
|
6318
|
+
"discoverSwapRefunds requires options.ownerUtxoKeypair (the wallet's long-lived UTXO keypair): per-swap and owner-key refund leaves are matched against it, and nk alone can only find legacy refunds."
|
|
6005
6319
|
);
|
|
6006
6320
|
}
|
|
6007
6321
|
const ownerUtxoKeypair = options.ownerUtxoKeypair;
|
|
@@ -6061,7 +6375,15 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options)
|
|
|
6061
6375
|
programId
|
|
6062
6376
|
);
|
|
6063
6377
|
const key = swapState;
|
|
6064
|
-
|
|
6378
|
+
const hasParams = data.length >= MIN_TRANSACT_SWAP_WITH_PARAMS_LEN;
|
|
6379
|
+
if (!nullifierBySwapState.has(key)) {
|
|
6380
|
+
nullifierBySwapState.set(key, {
|
|
6381
|
+
nullifier,
|
|
6382
|
+
signature,
|
|
6383
|
+
refundPubkey: hasParams ? data.slice(REFUND_PUBKEY_OFFSET, REFUND_PUBKEY_OFFSET + 32) : void 0,
|
|
6384
|
+
refundBlinding: hasParams ? data.slice(REFUND_BLINDING_OFFSET, REFUND_BLINDING_OFFSET + 32) : void 0
|
|
6385
|
+
});
|
|
6386
|
+
}
|
|
6065
6387
|
}
|
|
6066
6388
|
const logs = tx.meta?.logMessages;
|
|
6067
6389
|
const scan = scanRefundLeafEvents(logs, programIdBase58);
|
|
@@ -6080,7 +6402,9 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options)
|
|
|
6080
6402
|
inputNullifier: candidate.nullifier,
|
|
6081
6403
|
amountAfterFee: event.amountAfterFee,
|
|
6082
6404
|
commitment: event.commitmentField,
|
|
6083
|
-
ownerUtxoKeypair
|
|
6405
|
+
ownerUtxoKeypair,
|
|
6406
|
+
publishedRefundPubkey: candidate.refundPubkey,
|
|
6407
|
+
publishedRefundBlinding: candidate.refundBlinding
|
|
6084
6408
|
});
|
|
6085
6409
|
if (!recovered) continue;
|
|
6086
6410
|
const dedupe = `${close.signature}:${event.leafIndex}`;
|
|
@@ -6634,6 +6958,12 @@ var NEAR_TIP_ONCHAIN_FALLBACK_MAX_DISTANCE_LOCAL_RPC = 8;
|
|
|
6634
6958
|
var DEFAULT_RELAY_REQUEST_TIMEOUT_MS = 45e3;
|
|
6635
6959
|
var DEFAULT_RELAY_NETWORK_RETRIES = 6;
|
|
6636
6960
|
var RETRYABLE_RELAY_STATUSES = /* @__PURE__ */ new Set([408, 409, 425, 429, 500, 502, 503, 504, 522, 524]);
|
|
6961
|
+
var RELAY_SOURCE_LEASE_MS = 18e4;
|
|
6962
|
+
var RELAY_SOURCE_LEASE_MARGIN_MS = 5e3;
|
|
6963
|
+
var MAX_LEASE_EXPIRY_REPLAYS = 2;
|
|
6964
|
+
var RELAY_IN_FLIGHT_POLL_MS = 5e3;
|
|
6965
|
+
var RELAY_LANDED_POLL_MS = 1e3;
|
|
6966
|
+
var MAX_LANDED_POLLS = 5;
|
|
6637
6967
|
function parseMissingRelayIndexError(message) {
|
|
6638
6968
|
const match = message.match(
|
|
6639
6969
|
/Relay tree missing required commitment index\s+(\d+)\s+\(tree length:\s*(\d+)\)/i
|
|
@@ -7078,7 +7408,8 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
|
|
|
7078
7408
|
headers: { "Content-Type": "application/json" },
|
|
7079
7409
|
body: JSON.stringify({
|
|
7080
7410
|
user_pubkey: userPubkey,
|
|
7081
|
-
viewing_key: viewingKeyHex
|
|
7411
|
+
viewing_key: viewingKeyHex,
|
|
7412
|
+
message_format: VIEWING_KEY_CHALLENGE_REQUEST_FORMAT
|
|
7082
7413
|
})
|
|
7083
7414
|
});
|
|
7084
7415
|
if (!challengeResponse.ok) {
|
|
@@ -7125,7 +7456,8 @@ async function registerViewingKeyOnce(relayUrl, userPubkey, viewingKeyHex, cache
|
|
|
7125
7456
|
viewing_key: viewingKeyHex,
|
|
7126
7457
|
nonce: challenge.nonce,
|
|
7127
7458
|
signature: signatureBase64,
|
|
7128
|
-
...authMode === "transaction" ? { auth_mode: authMode } : {}
|
|
7459
|
+
...authMode === "transaction" ? { auth_mode: authMode } : {},
|
|
7460
|
+
...challenge.messageFormat === "readable" ? { message_format: challenge.messageFormat } : {}
|
|
7129
7461
|
})
|
|
7130
7462
|
});
|
|
7131
7463
|
if (!response.ok) {
|
|
@@ -8218,6 +8550,20 @@ async function reconcileCommitmentIndicesWithRelay(relayUrl, mint, suggestedIndi
|
|
|
8218
8550
|
function sleep2(ms) {
|
|
8219
8551
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
8220
8552
|
}
|
|
8553
|
+
function sleepUnlessAborted(ms, signal) {
|
|
8554
|
+
if (signal?.aborted) return Promise.resolve(false);
|
|
8555
|
+
return new Promise((resolve) => {
|
|
8556
|
+
const onAbort = () => {
|
|
8557
|
+
clearTimeout(timer);
|
|
8558
|
+
resolve(false);
|
|
8559
|
+
};
|
|
8560
|
+
const timer = setTimeout(() => {
|
|
8561
|
+
signal?.removeEventListener("abort", onAbort);
|
|
8562
|
+
resolve(true);
|
|
8563
|
+
}, ms);
|
|
8564
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
8565
|
+
});
|
|
8566
|
+
}
|
|
8221
8567
|
function hexToBytes2(hex) {
|
|
8222
8568
|
const bytes = new Uint8Array(hex.length / 2);
|
|
8223
8569
|
for (let i = 0; i < hex.length; i += 2) {
|
|
@@ -8452,6 +8798,9 @@ async function submitTransactToRelay(args) {
|
|
|
8452
8798
|
let unknownOutcomeSignature = null;
|
|
8453
8799
|
let possiblySubmitted = false;
|
|
8454
8800
|
let networkRetry = 0;
|
|
8801
|
+
let leaseReplays = 0;
|
|
8802
|
+
let landedPolls = 0;
|
|
8803
|
+
let leaseBaseMs = null;
|
|
8455
8804
|
const verifySettlement = (signature, timeoutMs) => confirmTransactSettlement({
|
|
8456
8805
|
connection: settlement.connection,
|
|
8457
8806
|
programId: settlement.programId,
|
|
@@ -8507,6 +8856,7 @@ async function submitTransactToRelay(args) {
|
|
|
8507
8856
|
const controller = new AbortController();
|
|
8508
8857
|
const timeoutId = setTimeout(() => controller.abort(), requestTimeoutMs);
|
|
8509
8858
|
let response;
|
|
8859
|
+
leaseBaseMs ?? (leaseBaseMs = Date.now());
|
|
8510
8860
|
try {
|
|
8511
8861
|
response = await doFetch(`${relayUrl}/transact`, {
|
|
8512
8862
|
method: "POST",
|
|
@@ -8525,6 +8875,49 @@ async function submitTransactToRelay(args) {
|
|
|
8525
8875
|
if (isSubmissionOutcomeUnknownResponse(responseText) || isRetryableRelayStatus(response.status)) {
|
|
8526
8876
|
possiblySubmitted = true;
|
|
8527
8877
|
}
|
|
8878
|
+
if ((isRelayRequestInFlightResponse(responseText) || isSubmissionOutcomeUnknownResponse(responseText)) && leaseReplays < MAX_LEASE_EXPIRY_REPLAYS) {
|
|
8879
|
+
networkRetry = 0;
|
|
8880
|
+
const leaseEndsMs = (leaseBaseMs ?? Date.now()) + RELAY_SOURCE_LEASE_MS + RELAY_SOURCE_LEASE_MARGIN_MS;
|
|
8881
|
+
const polling = Date.now() < leaseEndsMs;
|
|
8882
|
+
const probe = await verifySettlement(
|
|
8883
|
+
unknownOutcomeSignature,
|
|
8884
|
+
polling ? 0 : args.failureProbeTimeoutMs ?? Math.min(settlementTimeoutMs(), 1e4)
|
|
8885
|
+
);
|
|
8886
|
+
if (probe.status === "landed") {
|
|
8887
|
+
landedPolls++;
|
|
8888
|
+
if (!polling || landedPolls > MAX_LANDED_POLLS) {
|
|
8889
|
+
return await resolveFailure(
|
|
8890
|
+
new Error(relayFailureMessage("Relay error", responseText, requestBody))
|
|
8891
|
+
);
|
|
8892
|
+
}
|
|
8893
|
+
if (!await sleepUnlessAborted(RELAY_LANDED_POLL_MS, args.signal)) {
|
|
8894
|
+
return await resolveFailure(new Error("Relay lease-expiry replay aborted by caller"));
|
|
8895
|
+
}
|
|
8896
|
+
continue;
|
|
8897
|
+
}
|
|
8898
|
+
if (polling) {
|
|
8899
|
+
onProgress?.("Relay is still processing this request; checking again shortly...");
|
|
8900
|
+
const pollMs = Math.min(RELAY_IN_FLIGHT_POLL_MS, leaseEndsMs - Date.now());
|
|
8901
|
+
if (!await sleepUnlessAborted(pollMs, args.signal)) {
|
|
8902
|
+
return await resolveFailure(new Error("Relay lease-expiry replay aborted by caller"));
|
|
8903
|
+
}
|
|
8904
|
+
continue;
|
|
8905
|
+
}
|
|
8906
|
+
leaseReplays++;
|
|
8907
|
+
const waitMs = Math.max(
|
|
8908
|
+
0,
|
|
8909
|
+
(leaseBaseMs ?? Date.now()) + RELAY_SOURCE_LEASE_MS + RELAY_SOURCE_LEASE_MARGIN_MS - Date.now()
|
|
8910
|
+
);
|
|
8911
|
+
onProgress?.(
|
|
8912
|
+
`Relay has not confirmed the outcome. Waiting ${Math.ceil(waitMs / 1e3)}s for its request lease to expire, then replaying the identical signed request (${leaseReplays}/${MAX_LEASE_EXPIRY_REPLAYS})...`
|
|
8913
|
+
);
|
|
8914
|
+
if (!await sleepUnlessAborted(waitMs, args.signal)) {
|
|
8915
|
+
return await resolveFailure(new Error("Relay lease-expiry replay aborted by caller"));
|
|
8916
|
+
}
|
|
8917
|
+
networkRetry = 0;
|
|
8918
|
+
leaseBaseMs = null;
|
|
8919
|
+
continue;
|
|
8920
|
+
}
|
|
8528
8921
|
if (isRetryableRelayStatus(response.status) && networkRetry < maxNetworkRetries) {
|
|
8529
8922
|
networkRetry++;
|
|
8530
8923
|
const delay = relayBackoffMs(networkRetry);
|
|
@@ -12495,6 +12888,1638 @@ function formatComplianceCsv(report) {
|
|
|
12495
12888
|
return header + rows;
|
|
12496
12889
|
}
|
|
12497
12890
|
|
|
12891
|
+
// src/relay/note-index-format.ts
|
|
12892
|
+
var import_sha25 = require("@noble/hashes/sha2");
|
|
12893
|
+
init_address();
|
|
12894
|
+
init_utxo();
|
|
12895
|
+
var NOTE_INDEX_MAGIC = new Uint8Array([67, 78, 73, 49]);
|
|
12896
|
+
var NOTE_INDEX_FORMAT_VERSION = 1;
|
|
12897
|
+
var NOTE_INDEX_PAGE_SIZE = 1024;
|
|
12898
|
+
var NOTE_INDEX_NO_LEAF = 0xffffffffffffffffn;
|
|
12899
|
+
var NOTE_INDEX_MAX_PAGE_BYTES = 2 * 1024 * 1024;
|
|
12900
|
+
var NOTE_INDEX_HEADER_LEN = 68;
|
|
12901
|
+
var NOTE_INDEX_KIND_TX = 1;
|
|
12902
|
+
var NOTE_INDEX_KIND_DELIVERY = 2;
|
|
12903
|
+
var NOTE_INDEX_KIND_SWAP_REFUND = 3;
|
|
12904
|
+
var NOTE_SOURCE_NONE = 0;
|
|
12905
|
+
var NOTE_SOURCE_CARRIER = 2;
|
|
12906
|
+
var ITEM_HEADER_LEN = 3;
|
|
12907
|
+
var TX_FIXED_LEN = 263;
|
|
12908
|
+
var DELIVERY_BODY_LEN = 256;
|
|
12909
|
+
var SWAP_REFUND_BODY_LEN = 184;
|
|
12910
|
+
var MAX_UNKNOWN_BODY_LEN = 1024;
|
|
12911
|
+
var DELIVERY_ENVELOPE_LEN = 112;
|
|
12912
|
+
var SIGNATURE_LEN = 64;
|
|
12913
|
+
var NOTE_VERSION_BY_LEN = /* @__PURE__ */ new Map([
|
|
12914
|
+
[25, 2],
|
|
12915
|
+
[57, 3],
|
|
12916
|
+
[98, 4]
|
|
12917
|
+
]);
|
|
12918
|
+
var COMPLETE_FLAG = 1;
|
|
12919
|
+
var U64_MAX2 = (1n << 64n) - 1n;
|
|
12920
|
+
var U32_MAX = 4294967295;
|
|
12921
|
+
var MAX_LEAF_INDEX = (1n << 32n) - 1n;
|
|
12922
|
+
var WSOL_BYTES = addressBytes(NATIVE_SOL_MINT);
|
|
12923
|
+
var NoteIndexFormatError = class extends Error {
|
|
12924
|
+
constructor(message) {
|
|
12925
|
+
super(`Note index format error: ${message}`);
|
|
12926
|
+
this.name = "NoteIndexFormatError";
|
|
12927
|
+
}
|
|
12928
|
+
};
|
|
12929
|
+
function isAllZero2(bytes) {
|
|
12930
|
+
for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
|
|
12931
|
+
return true;
|
|
12932
|
+
}
|
|
12933
|
+
function bytesEqual(a, b) {
|
|
12934
|
+
if (a.length !== b.length) return false;
|
|
12935
|
+
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
|
|
12936
|
+
return true;
|
|
12937
|
+
}
|
|
12938
|
+
function checkLeafPair(commitment, leaf, label) {
|
|
12939
|
+
if (isAllZero2(commitment)) {
|
|
12940
|
+
if (leaf !== NOTE_INDEX_NO_LEAF) throw new NoteIndexFormatError(`${label}: zero commitment must carry NO_LEAF`);
|
|
12941
|
+
return;
|
|
12942
|
+
}
|
|
12943
|
+
if (leaf > MAX_LEAF_INDEX) throw new NoteIndexFormatError(`${label}: leaf ${leaf} is not a leaf of the tree`);
|
|
12944
|
+
}
|
|
12945
|
+
var Reader = class {
|
|
12946
|
+
constructor(bytes, start, end) {
|
|
12947
|
+
this.bytes = bytes;
|
|
12948
|
+
this.end = end;
|
|
12949
|
+
this.offset = start;
|
|
12950
|
+
this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
12951
|
+
}
|
|
12952
|
+
take(len) {
|
|
12953
|
+
if (this.offset + len > this.end) throw new NoteIndexFormatError("truncated item body");
|
|
12954
|
+
const at = this.offset;
|
|
12955
|
+
this.offset += len;
|
|
12956
|
+
return at;
|
|
12957
|
+
}
|
|
12958
|
+
u8() {
|
|
12959
|
+
return this.bytes[this.take(1)];
|
|
12960
|
+
}
|
|
12961
|
+
u32() {
|
|
12962
|
+
return this.view.getUint32(this.take(4), true);
|
|
12963
|
+
}
|
|
12964
|
+
u64() {
|
|
12965
|
+
return this.view.getBigUint64(this.take(8), true);
|
|
12966
|
+
}
|
|
12967
|
+
i64() {
|
|
12968
|
+
return this.view.getBigInt64(this.take(8), true);
|
|
12969
|
+
}
|
|
12970
|
+
raw(len) {
|
|
12971
|
+
const at = this.take(len);
|
|
12972
|
+
return this.bytes.slice(at, at + len);
|
|
12973
|
+
}
|
|
12974
|
+
get position() {
|
|
12975
|
+
return this.offset;
|
|
12976
|
+
}
|
|
12977
|
+
};
|
|
12978
|
+
function parseTx(r, bodyLen) {
|
|
12979
|
+
const mint = r.raw(32);
|
|
12980
|
+
const slot = r.u64();
|
|
12981
|
+
const blockPos = r.u32();
|
|
12982
|
+
const ixTag = r.u8();
|
|
12983
|
+
if (ixTag !== 0 && ixTag !== 1) throw new NoteIndexFormatError(`TX: ix_tag ${ixTag}`);
|
|
12984
|
+
const publicAmount = r.i64();
|
|
12985
|
+
const nullifier0 = r.raw(32);
|
|
12986
|
+
const nullifier1 = r.raw(32);
|
|
12987
|
+
const comm0 = r.raw(32);
|
|
12988
|
+
const leaf0 = r.u64();
|
|
12989
|
+
const comm1 = r.raw(32);
|
|
12990
|
+
const leaf1 = r.u64();
|
|
12991
|
+
const noteSource = r.u8();
|
|
12992
|
+
if (noteSource > NOTE_SOURCE_CARRIER) throw new NoteIndexFormatError(`TX: note_source ${noteSource}`);
|
|
12993
|
+
const noteLen = r.u8();
|
|
12994
|
+
if (noteSource === NOTE_SOURCE_NONE) {
|
|
12995
|
+
if (noteLen !== 0) throw new NoteIndexFormatError(`TX: note_len ${noteLen} without a note source`);
|
|
12996
|
+
} else if (!NOTE_VERSION_BY_LEN.has(noteLen)) {
|
|
12997
|
+
throw new NoteIndexFormatError(`TX: note_len ${noteLen}`);
|
|
12998
|
+
}
|
|
12999
|
+
if (bodyLen !== TX_FIXED_LEN + noteLen) {
|
|
13000
|
+
throw new NoteIndexFormatError(`TX: body_len ${bodyLen} != ${TX_FIXED_LEN + noteLen} for note_len ${noteLen}`);
|
|
13001
|
+
}
|
|
13002
|
+
const note = r.raw(noteLen);
|
|
13003
|
+
if (noteLen > 0 && note[0] !== NOTE_VERSION_BY_LEN.get(noteLen)) {
|
|
13004
|
+
throw new NoteIndexFormatError(`TX: note version ${note[0]} does not match note_len ${noteLen}`);
|
|
13005
|
+
}
|
|
13006
|
+
const signature = r.raw(SIGNATURE_LEN);
|
|
13007
|
+
checkLeafPair(comm0, leaf0, "TX comm0");
|
|
13008
|
+
checkLeafPair(comm1, leaf1, "TX comm1");
|
|
13009
|
+
return {
|
|
13010
|
+
kind: 1,
|
|
13011
|
+
mint,
|
|
13012
|
+
slot,
|
|
13013
|
+
blockPos,
|
|
13014
|
+
ixTag,
|
|
13015
|
+
publicAmount,
|
|
13016
|
+
nullifier0,
|
|
13017
|
+
nullifier1,
|
|
13018
|
+
comm0,
|
|
13019
|
+
leaf0,
|
|
13020
|
+
comm1,
|
|
13021
|
+
leaf1,
|
|
13022
|
+
noteSource,
|
|
13023
|
+
note,
|
|
13024
|
+
signature
|
|
13025
|
+
};
|
|
13026
|
+
}
|
|
13027
|
+
function parseDelivery(r) {
|
|
13028
|
+
const mint = r.raw(32);
|
|
13029
|
+
const slot = r.u64();
|
|
13030
|
+
const commitment = r.raw(32);
|
|
13031
|
+
const leaf = r.u64();
|
|
13032
|
+
const envelope = r.raw(DELIVERY_ENVELOPE_LEN);
|
|
13033
|
+
const signature = r.raw(SIGNATURE_LEN);
|
|
13034
|
+
if (isAllZero2(commitment)) throw new NoteIndexFormatError("DELIVERY: zero commitment");
|
|
13035
|
+
checkLeafPair(commitment, leaf, "DELIVERY");
|
|
13036
|
+
return { kind: 2, mint, slot, commitment, leaf, envelope, signature };
|
|
13037
|
+
}
|
|
13038
|
+
function parseSwapRefund(r) {
|
|
13039
|
+
const mint = r.raw(32);
|
|
13040
|
+
if (!bytesEqual(mint, WSOL_BYTES)) throw new NoteIndexFormatError("SWAP_REFUND: mint is not WSOL");
|
|
13041
|
+
const slot = r.u64();
|
|
13042
|
+
const commitment = r.raw(32);
|
|
13043
|
+
const leaf = r.u64();
|
|
13044
|
+
const amountAfterFee = r.u64();
|
|
13045
|
+
const nullifier0 = r.raw(32);
|
|
13046
|
+
const signature = r.raw(SIGNATURE_LEN);
|
|
13047
|
+
if (isAllZero2(commitment)) throw new NoteIndexFormatError("SWAP_REFUND: zero commitment");
|
|
13048
|
+
checkLeafPair(commitment, leaf, "SWAP_REFUND");
|
|
13049
|
+
return { kind: 3, mint, slot, commitment, leaf, amountAfterFee, nullifier0, signature };
|
|
13050
|
+
}
|
|
13051
|
+
function parseNoteIndexPage(bytes, expect, options = {}) {
|
|
13052
|
+
if (!(bytes instanceof Uint8Array)) throw new NoteIndexFormatError("page must be a Uint8Array");
|
|
13053
|
+
if (bytes.length > NOTE_INDEX_MAX_PAGE_BYTES) {
|
|
13054
|
+
throw new NoteIndexFormatError(`page is ${bytes.length} bytes, over the ${NOTE_INDEX_MAX_PAGE_BYTES}-byte bound`);
|
|
13055
|
+
}
|
|
13056
|
+
if (bytes.length < NOTE_INDEX_HEADER_LEN) throw new NoteIndexFormatError("truncated page header");
|
|
13057
|
+
for (let i = 0; i < NOTE_INDEX_MAGIC.length; i++) {
|
|
13058
|
+
if (bytes[i] !== NOTE_INDEX_MAGIC[i]) throw new NoteIndexFormatError("bad magic");
|
|
13059
|
+
}
|
|
13060
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
13061
|
+
const version = bytes[4];
|
|
13062
|
+
if (version !== NOTE_INDEX_FORMAT_VERSION) throw new NoteIndexFormatError(`unsupported version ${version}`);
|
|
13063
|
+
const flags = bytes[5];
|
|
13064
|
+
if ((flags & ~COMPLETE_FLAG) !== 0) throw new NoteIndexFormatError(`unknown flag bits 0x${flags.toString(16)}`);
|
|
13065
|
+
if (view.getUint16(6, true) !== 0) throw new NoteIndexFormatError("reserved bytes are not zero");
|
|
13066
|
+
const epoch = view.getBigUint64(8, true);
|
|
13067
|
+
const page = view.getBigUint64(16, true);
|
|
13068
|
+
const firstSeq = view.getBigUint64(24, true);
|
|
13069
|
+
const count = view.getUint32(32, true);
|
|
13070
|
+
const prevChain = bytes.slice(36, 68);
|
|
13071
|
+
const complete = (flags & COMPLETE_FLAG) !== 0;
|
|
13072
|
+
if (expect) {
|
|
13073
|
+
if (epoch !== expect.epoch) throw new NoteIndexFormatError(`epoch ${epoch} is not the requested ${expect.epoch}`);
|
|
13074
|
+
if (page !== BigInt(expect.page)) throw new NoteIndexFormatError(`page ${page} is not the requested ${expect.page}`);
|
|
13075
|
+
}
|
|
13076
|
+
if (count > NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`count ${count} exceeds ${NOTE_INDEX_PAGE_SIZE}`);
|
|
13077
|
+
if (complete && count !== NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`complete page with count ${count}`);
|
|
13078
|
+
if (firstSeq !== page * BigInt(NOTE_INDEX_PAGE_SIZE)) {
|
|
13079
|
+
throw new NoteIndexFormatError(`first_seq ${firstSeq} is not page ${page} * ${NOTE_INDEX_PAGE_SIZE}`);
|
|
13080
|
+
}
|
|
13081
|
+
const items = [];
|
|
13082
|
+
const rawItems = [];
|
|
13083
|
+
const itemPositions = [];
|
|
13084
|
+
let skippedUnknown = 0;
|
|
13085
|
+
let skippedMalformed = 0;
|
|
13086
|
+
let offset = NOTE_INDEX_HEADER_LEN;
|
|
13087
|
+
for (let i = 0; i < count; i++) {
|
|
13088
|
+
if (offset + ITEM_HEADER_LEN > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} header`);
|
|
13089
|
+
const kind = bytes[offset];
|
|
13090
|
+
const bodyLen = view.getUint16(offset + 1, true);
|
|
13091
|
+
const bodyStart = offset + ITEM_HEADER_LEN;
|
|
13092
|
+
const bodyEnd = bodyStart + bodyLen;
|
|
13093
|
+
if (bodyEnd > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} body`);
|
|
13094
|
+
if (kind !== NOTE_INDEX_KIND_TX && kind !== NOTE_INDEX_KIND_DELIVERY && kind !== NOTE_INDEX_KIND_SWAP_REFUND) {
|
|
13095
|
+
if (bodyLen > MAX_UNKNOWN_BODY_LEN) throw new NoteIndexFormatError(`unknown kind ${kind} with body_len ${bodyLen}`);
|
|
13096
|
+
skippedUnknown++;
|
|
13097
|
+
offset = bodyEnd;
|
|
13098
|
+
continue;
|
|
13099
|
+
}
|
|
13100
|
+
let item;
|
|
13101
|
+
try {
|
|
13102
|
+
item = parseKnownBody(bytes, kind, bodyStart, bodyEnd, i);
|
|
13103
|
+
} catch (error) {
|
|
13104
|
+
if (!options.skipMalformedItems || !(error instanceof NoteIndexFormatError)) throw error;
|
|
13105
|
+
skippedMalformed++;
|
|
13106
|
+
offset = bodyEnd;
|
|
13107
|
+
continue;
|
|
13108
|
+
}
|
|
13109
|
+
items.push(item);
|
|
13110
|
+
rawItems.push(bytes.slice(offset, bodyEnd));
|
|
13111
|
+
itemPositions.push(i);
|
|
13112
|
+
offset = bodyEnd;
|
|
13113
|
+
}
|
|
13114
|
+
if (offset !== bytes.length) throw new NoteIndexFormatError(`${bytes.length - offset} trailing bytes after ${count} items`);
|
|
13115
|
+
return { epoch, page, firstSeq, complete, count, prevChain, items, rawItems, skippedUnknown, itemPositions, skippedMalformed };
|
|
13116
|
+
}
|
|
13117
|
+
function parseKnownBody(bytes, kind, bodyStart, bodyEnd, i) {
|
|
13118
|
+
const bodyLen = bodyEnd - bodyStart;
|
|
13119
|
+
const r = new Reader(bytes, bodyStart, bodyEnd);
|
|
13120
|
+
let item;
|
|
13121
|
+
if (kind === NOTE_INDEX_KIND_TX) {
|
|
13122
|
+
if (bodyLen < TX_FIXED_LEN) throw new NoteIndexFormatError(`TX: body_len ${bodyLen}`);
|
|
13123
|
+
item = parseTx(r, bodyLen);
|
|
13124
|
+
} else if (kind === NOTE_INDEX_KIND_DELIVERY) {
|
|
13125
|
+
if (bodyLen !== DELIVERY_BODY_LEN) throw new NoteIndexFormatError(`DELIVERY: body_len ${bodyLen}`);
|
|
13126
|
+
item = parseDelivery(r);
|
|
13127
|
+
} else {
|
|
13128
|
+
if (bodyLen !== SWAP_REFUND_BODY_LEN) throw new NoteIndexFormatError(`SWAP_REFUND: body_len ${bodyLen}`);
|
|
13129
|
+
item = parseSwapRefund(r);
|
|
13130
|
+
}
|
|
13131
|
+
if (r.position !== bodyEnd) throw new NoteIndexFormatError(`item ${i} body has unread bytes`);
|
|
13132
|
+
return item;
|
|
13133
|
+
}
|
|
13134
|
+
function parseNoteIndexItem(raw) {
|
|
13135
|
+
if (!(raw instanceof Uint8Array) || raw.length < ITEM_HEADER_LEN) throw new NoteIndexFormatError("truncated item");
|
|
13136
|
+
const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
|
|
13137
|
+
const kind = raw[0];
|
|
13138
|
+
const bodyLen = view.getUint16(1, true);
|
|
13139
|
+
if (ITEM_HEADER_LEN + bodyLen !== raw.length) throw new NoteIndexFormatError("item length mismatch");
|
|
13140
|
+
const r = new Reader(raw, ITEM_HEADER_LEN, raw.length);
|
|
13141
|
+
let item;
|
|
13142
|
+
if (kind === NOTE_INDEX_KIND_TX && bodyLen >= TX_FIXED_LEN) item = parseTx(r, bodyLen);
|
|
13143
|
+
else if (kind === NOTE_INDEX_KIND_DELIVERY && bodyLen === DELIVERY_BODY_LEN) item = parseDelivery(r);
|
|
13144
|
+
else if (kind === NOTE_INDEX_KIND_SWAP_REFUND && bodyLen === SWAP_REFUND_BODY_LEN) item = parseSwapRefund(r);
|
|
13145
|
+
else throw new NoteIndexFormatError(`item kind ${kind} with body_len ${bodyLen}`);
|
|
13146
|
+
if (r.position !== raw.length) throw new NoteIndexFormatError("item body has unread bytes");
|
|
13147
|
+
return item;
|
|
13148
|
+
}
|
|
13149
|
+
function computeNoteIndexChain(prevChain, pageBytes) {
|
|
13150
|
+
if (!(prevChain instanceof Uint8Array) || prevChain.length !== 32) throw new NoteIndexFormatError("prevChain must be 32 bytes");
|
|
13151
|
+
if (pageBytes.length < NOTE_INDEX_HEADER_LEN) throw new NoteIndexFormatError("truncated page header");
|
|
13152
|
+
const items = pageBytes.subarray(NOTE_INDEX_HEADER_LEN);
|
|
13153
|
+
const input = new Uint8Array(32 + items.length);
|
|
13154
|
+
input.set(prevChain);
|
|
13155
|
+
input.set(items, 32);
|
|
13156
|
+
return (0, import_sha25.sha256)(input);
|
|
13157
|
+
}
|
|
13158
|
+
var Writer = class {
|
|
13159
|
+
constructor() {
|
|
13160
|
+
this.chunks = [];
|
|
13161
|
+
this.length = 0;
|
|
13162
|
+
}
|
|
13163
|
+
push(bytes) {
|
|
13164
|
+
this.chunks.push(bytes);
|
|
13165
|
+
this.length += bytes.length;
|
|
13166
|
+
}
|
|
13167
|
+
u8(v) {
|
|
13168
|
+
if (!Number.isInteger(v) || v < 0 || v > 255) throw new NoteIndexFormatError(`u8 out of range: ${v}`);
|
|
13169
|
+
this.push(Uint8Array.of(v));
|
|
13170
|
+
}
|
|
13171
|
+
u16(v) {
|
|
13172
|
+
if (!Number.isInteger(v) || v < 0 || v > 65535) throw new NoteIndexFormatError(`u16 out of range: ${v}`);
|
|
13173
|
+
const b = new Uint8Array(2);
|
|
13174
|
+
new DataView(b.buffer).setUint16(0, v, true);
|
|
13175
|
+
this.push(b);
|
|
13176
|
+
}
|
|
13177
|
+
u32(v) {
|
|
13178
|
+
if (!Number.isInteger(v) || v < 0 || v > U32_MAX) throw new NoteIndexFormatError(`u32 out of range: ${v}`);
|
|
13179
|
+
const b = new Uint8Array(4);
|
|
13180
|
+
new DataView(b.buffer).setUint32(0, v, true);
|
|
13181
|
+
this.push(b);
|
|
13182
|
+
}
|
|
13183
|
+
u64(v) {
|
|
13184
|
+
if (v < 0n || v > U64_MAX2) throw new NoteIndexFormatError(`u64 out of range: ${v}`);
|
|
13185
|
+
const b = new Uint8Array(8);
|
|
13186
|
+
new DataView(b.buffer).setBigUint64(0, v, true);
|
|
13187
|
+
this.push(b);
|
|
13188
|
+
}
|
|
13189
|
+
i64(v) {
|
|
13190
|
+
if (v < -(1n << 63n) || v >= 1n << 63n) throw new NoteIndexFormatError(`i64 out of range: ${v}`);
|
|
13191
|
+
const b = new Uint8Array(8);
|
|
13192
|
+
new DataView(b.buffer).setBigInt64(0, v, true);
|
|
13193
|
+
this.push(b);
|
|
13194
|
+
}
|
|
13195
|
+
fixed(bytes, len, label) {
|
|
13196
|
+
if (!(bytes instanceof Uint8Array) || bytes.length !== len) throw new NoteIndexFormatError(`${label} must be ${len} bytes`);
|
|
13197
|
+
this.push(bytes);
|
|
13198
|
+
}
|
|
13199
|
+
finish() {
|
|
13200
|
+
const out = new Uint8Array(this.length);
|
|
13201
|
+
let off = 0;
|
|
13202
|
+
for (const c of this.chunks) {
|
|
13203
|
+
out.set(c, off);
|
|
13204
|
+
off += c.length;
|
|
13205
|
+
}
|
|
13206
|
+
return out;
|
|
13207
|
+
}
|
|
13208
|
+
};
|
|
13209
|
+
function encodeItemBody(item) {
|
|
13210
|
+
const w = new Writer();
|
|
13211
|
+
switch (item.kind) {
|
|
13212
|
+
case NOTE_INDEX_KIND_TX: {
|
|
13213
|
+
w.fixed(item.mint, 32, "mint");
|
|
13214
|
+
w.u64(item.slot);
|
|
13215
|
+
w.u32(item.blockPos);
|
|
13216
|
+
w.u8(item.ixTag);
|
|
13217
|
+
w.i64(item.publicAmount);
|
|
13218
|
+
w.fixed(item.nullifier0, 32, "nullifier0");
|
|
13219
|
+
w.fixed(item.nullifier1, 32, "nullifier1");
|
|
13220
|
+
w.fixed(item.comm0, 32, "comm0");
|
|
13221
|
+
w.u64(item.leaf0);
|
|
13222
|
+
w.fixed(item.comm1, 32, "comm1");
|
|
13223
|
+
w.u64(item.leaf1);
|
|
13224
|
+
w.u8(item.noteSource);
|
|
13225
|
+
const noteLen = item.note.length;
|
|
13226
|
+
if (item.noteSource === NOTE_SOURCE_NONE ? noteLen !== 0 : !NOTE_VERSION_BY_LEN.has(noteLen)) {
|
|
13227
|
+
throw new NoteIndexFormatError(`note_len ${noteLen} invalid for note_source ${item.noteSource}`);
|
|
13228
|
+
}
|
|
13229
|
+
w.u8(noteLen);
|
|
13230
|
+
w.push(item.note);
|
|
13231
|
+
w.fixed(item.signature, SIGNATURE_LEN, "signature");
|
|
13232
|
+
break;
|
|
13233
|
+
}
|
|
13234
|
+
case NOTE_INDEX_KIND_DELIVERY:
|
|
13235
|
+
w.fixed(item.mint, 32, "mint");
|
|
13236
|
+
w.u64(item.slot);
|
|
13237
|
+
w.fixed(item.commitment, 32, "commitment");
|
|
13238
|
+
w.u64(item.leaf);
|
|
13239
|
+
w.fixed(item.envelope, DELIVERY_ENVELOPE_LEN, "envelope");
|
|
13240
|
+
w.fixed(item.signature, SIGNATURE_LEN, "signature");
|
|
13241
|
+
break;
|
|
13242
|
+
case NOTE_INDEX_KIND_SWAP_REFUND:
|
|
13243
|
+
w.fixed(item.mint, 32, "mint");
|
|
13244
|
+
w.u64(item.slot);
|
|
13245
|
+
w.fixed(item.commitment, 32, "commitment");
|
|
13246
|
+
w.u64(item.leaf);
|
|
13247
|
+
w.u64(item.amountAfterFee);
|
|
13248
|
+
w.fixed(item.nullifier0, 32, "nullifier0");
|
|
13249
|
+
w.fixed(item.signature, SIGNATURE_LEN, "signature");
|
|
13250
|
+
break;
|
|
13251
|
+
default:
|
|
13252
|
+
throw new NoteIndexFormatError(`cannot encode kind ${item.kind}`);
|
|
13253
|
+
}
|
|
13254
|
+
return w.finish();
|
|
13255
|
+
}
|
|
13256
|
+
function encodeNoteIndexItem(item) {
|
|
13257
|
+
const body = encodeItemBody(item);
|
|
13258
|
+
const w = new Writer();
|
|
13259
|
+
w.u8(item.kind);
|
|
13260
|
+
w.u16(body.length);
|
|
13261
|
+
w.push(body);
|
|
13262
|
+
return w.finish();
|
|
13263
|
+
}
|
|
13264
|
+
function encodeNoteIndexPage(params) {
|
|
13265
|
+
const items = params.items ?? [];
|
|
13266
|
+
if (items.length > NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`count ${items.length} exceeds ${NOTE_INDEX_PAGE_SIZE}`);
|
|
13267
|
+
const w = new Writer();
|
|
13268
|
+
w.push(NOTE_INDEX_MAGIC);
|
|
13269
|
+
w.u8(NOTE_INDEX_FORMAT_VERSION);
|
|
13270
|
+
w.u8(params.complete ? COMPLETE_FLAG : 0);
|
|
13271
|
+
w.u16(0);
|
|
13272
|
+
w.u64(BigInt(params.epoch));
|
|
13273
|
+
w.u64(BigInt(params.page));
|
|
13274
|
+
w.u64(BigInt(params.firstSeq));
|
|
13275
|
+
w.u32(items.length);
|
|
13276
|
+
w.fixed(params.prevChain, 32, "prevChain");
|
|
13277
|
+
for (const item of items) w.push(encodeNoteIndexItem(item));
|
|
13278
|
+
return w.finish();
|
|
13279
|
+
}
|
|
13280
|
+
|
|
13281
|
+
// src/relay/note-index-client.ts
|
|
13282
|
+
var DEFAULT_TIMEOUT_MS2 = 3e4;
|
|
13283
|
+
var DEFAULT_MAX_RETRIES2 = 3;
|
|
13284
|
+
var RETRY_BASE_DELAY_MS = 500;
|
|
13285
|
+
var U64_MAX3 = (1n << 64n) - 1n;
|
|
13286
|
+
function joinPath(relayUrl, path) {
|
|
13287
|
+
const url = new URL(relayUrl);
|
|
13288
|
+
url.pathname = url.pathname.replace(/\/$/, "") + path;
|
|
13289
|
+
return url;
|
|
13290
|
+
}
|
|
13291
|
+
function abortError() {
|
|
13292
|
+
const error = new Error("Note index request aborted");
|
|
13293
|
+
error.name = "AbortError";
|
|
13294
|
+
return error;
|
|
13295
|
+
}
|
|
13296
|
+
function sleep4(ms, signal) {
|
|
13297
|
+
return new Promise((resolve, reject) => {
|
|
13298
|
+
if (signal?.aborted) return reject(abortError());
|
|
13299
|
+
const timer = setTimeout(() => {
|
|
13300
|
+
signal?.removeEventListener("abort", onAbort);
|
|
13301
|
+
resolve();
|
|
13302
|
+
}, ms);
|
|
13303
|
+
const onAbort = () => {
|
|
13304
|
+
clearTimeout(timer);
|
|
13305
|
+
reject(abortError());
|
|
13306
|
+
};
|
|
13307
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
13308
|
+
});
|
|
13309
|
+
}
|
|
13310
|
+
var RetryableStatusError = class extends Error {
|
|
13311
|
+
};
|
|
13312
|
+
var HttpStatusError = class extends Error {
|
|
13313
|
+
constructor(status, message) {
|
|
13314
|
+
super(message);
|
|
13315
|
+
this.status = status;
|
|
13316
|
+
this.name = "HttpStatusError";
|
|
13317
|
+
}
|
|
13318
|
+
};
|
|
13319
|
+
async function requestWithRetry(url, options, read) {
|
|
13320
|
+
assertAllowedRelayOrigin(url);
|
|
13321
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
|
|
13322
|
+
const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES2;
|
|
13323
|
+
let lastError;
|
|
13324
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
13325
|
+
if (options.signal?.aborted) throw abortError();
|
|
13326
|
+
const controller = new AbortController();
|
|
13327
|
+
const onAbort = () => controller.abort();
|
|
13328
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
13329
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
13330
|
+
try {
|
|
13331
|
+
const response = await relayFetch(url, { signal: controller.signal }, { observeClock: false });
|
|
13332
|
+
if (response.status === 429 || response.status >= 500) {
|
|
13333
|
+
throw new RetryableStatusError(`HTTP ${response.status} from ${new URL(url).pathname}`);
|
|
13334
|
+
}
|
|
13335
|
+
return await read(response, controller.signal);
|
|
13336
|
+
} catch (error) {
|
|
13337
|
+
if (options.signal?.aborted) throw abortError();
|
|
13338
|
+
const retryable = error instanceof RetryableStatusError || error instanceof Error && !(error instanceof NoteIndexFormatError) && !(error instanceof HttpStatusError);
|
|
13339
|
+
if (!retryable || attempt >= maxRetries) throw error;
|
|
13340
|
+
lastError = error;
|
|
13341
|
+
await sleep4(RETRY_BASE_DELAY_MS * 2 ** attempt + Math.random() * 250, options.signal);
|
|
13342
|
+
} finally {
|
|
13343
|
+
clearTimeout(timer);
|
|
13344
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
13345
|
+
}
|
|
13346
|
+
}
|
|
13347
|
+
throw lastError instanceof Error ? lastError : new Error(String(lastError));
|
|
13348
|
+
}
|
|
13349
|
+
async function readBoundedBody(response, maxBytes) {
|
|
13350
|
+
const declaredHeader = response.headers?.get?.("content-length") ?? null;
|
|
13351
|
+
const declared = declaredHeader === null ? NaN : Number(declaredHeader);
|
|
13352
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
13353
|
+
throw new NoteIndexFormatError(`response declares ${declared} bytes, over the ${maxBytes}-byte bound`);
|
|
13354
|
+
}
|
|
13355
|
+
const reader = response.body?.getReader?.();
|
|
13356
|
+
if (!reader) {
|
|
13357
|
+
const encoding = (response.headers?.get?.("content-encoding") ?? "").trim().toLowerCase();
|
|
13358
|
+
if (!Number.isSafeInteger(declared) || declared < 0) {
|
|
13359
|
+
throw new NoteIndexFormatError("response has no stream reader and no Content-Length: its size cannot be bounded");
|
|
13360
|
+
}
|
|
13361
|
+
if (encoding !== "" && encoding !== "identity") {
|
|
13362
|
+
throw new NoteIndexFormatError("response has no stream reader and a Content-Encoding: its decoded size cannot be bounded");
|
|
13363
|
+
}
|
|
13364
|
+
const buffer = new Uint8Array(await response.arrayBuffer());
|
|
13365
|
+
if (buffer.length > maxBytes || buffer.length !== declared) {
|
|
13366
|
+
throw new NoteIndexFormatError(`response is ${buffer.length} bytes, not the declared ${declared} within the ${maxBytes}-byte bound`);
|
|
13367
|
+
}
|
|
13368
|
+
return buffer;
|
|
13369
|
+
}
|
|
13370
|
+
const chunks = [];
|
|
13371
|
+
let total = 0;
|
|
13372
|
+
for (; ; ) {
|
|
13373
|
+
const { done, value } = await reader.read();
|
|
13374
|
+
if (done) break;
|
|
13375
|
+
total += value.length;
|
|
13376
|
+
if (total > maxBytes) {
|
|
13377
|
+
await reader.cancel().catch(() => void 0);
|
|
13378
|
+
throw new NoteIndexFormatError(`response exceeds the ${maxBytes}-byte bound`);
|
|
13379
|
+
}
|
|
13380
|
+
chunks.push(value);
|
|
13381
|
+
}
|
|
13382
|
+
const out = new Uint8Array(total);
|
|
13383
|
+
let off = 0;
|
|
13384
|
+
for (const c of chunks) {
|
|
13385
|
+
out.set(c, off);
|
|
13386
|
+
off += c.length;
|
|
13387
|
+
}
|
|
13388
|
+
return out;
|
|
13389
|
+
}
|
|
13390
|
+
function isNonNegativeSafeInteger(value) {
|
|
13391
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
13392
|
+
}
|
|
13393
|
+
async function fetchNoteIndexHead(relayUrl, options = {}) {
|
|
13394
|
+
const url = joinPath(relayUrl, "/note-index/v1/head").toString();
|
|
13395
|
+
const raw = await requestWithRetry(url, options, async (response) => {
|
|
13396
|
+
if (!response.ok) {
|
|
13397
|
+
throw new HttpStatusError(response.status, `note index head: HTTP ${response.status}`);
|
|
13398
|
+
}
|
|
13399
|
+
const text = new TextDecoder().decode(await readBoundedBody(response, 64 * 1024));
|
|
13400
|
+
try {
|
|
13401
|
+
return JSON.parse(text);
|
|
13402
|
+
} catch {
|
|
13403
|
+
throw new NoteIndexFormatError("head is not JSON");
|
|
13404
|
+
}
|
|
13405
|
+
});
|
|
13406
|
+
if (!raw || typeof raw !== "object") throw new NoteIndexFormatError("head is not an object");
|
|
13407
|
+
if (raw.format !== NOTE_INDEX_FORMAT_VERSION) {
|
|
13408
|
+
throw new NoteIndexFormatError(`unsupported head format ${String(raw.format)}`);
|
|
13409
|
+
}
|
|
13410
|
+
if (raw.page_size !== NOTE_INDEX_PAGE_SIZE) {
|
|
13411
|
+
throw new NoteIndexFormatError(`unsupported page_size ${String(raw.page_size)}`);
|
|
13412
|
+
}
|
|
13413
|
+
if (!isNonNegativeSafeInteger(raw.watermark) || !isNonNegativeSafeInteger(raw.complete_pages)) {
|
|
13414
|
+
throw new NoteIndexFormatError("head watermark/complete_pages are not non-negative integers");
|
|
13415
|
+
}
|
|
13416
|
+
if (raw.complete_pages !== Math.floor(raw.watermark / NOTE_INDEX_PAGE_SIZE)) {
|
|
13417
|
+
throw new NoteIndexFormatError(
|
|
13418
|
+
`complete_pages ${raw.complete_pages} disagrees with watermark ${raw.watermark}`
|
|
13419
|
+
);
|
|
13420
|
+
}
|
|
13421
|
+
if (typeof raw.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(raw.epoch) || BigInt(raw.epoch) > U64_MAX3) {
|
|
13422
|
+
throw new NoteIndexFormatError("head epoch is not a u64 decimal string");
|
|
13423
|
+
}
|
|
13424
|
+
if (typeof raw.chain_tip !== "string" || !/^[0-9a-fA-F]{64}$/.test(raw.chain_tip)) {
|
|
13425
|
+
throw new NoteIndexFormatError("head chain_tip is not 32-byte hex");
|
|
13426
|
+
}
|
|
13427
|
+
return {
|
|
13428
|
+
format: 1,
|
|
13429
|
+
epoch: BigInt(raw.epoch),
|
|
13430
|
+
pageSize: NOTE_INDEX_PAGE_SIZE,
|
|
13431
|
+
watermark: raw.watermark,
|
|
13432
|
+
completePages: raw.complete_pages,
|
|
13433
|
+
chainTip: raw.chain_tip.toLowerCase()
|
|
13434
|
+
};
|
|
13435
|
+
}
|
|
13436
|
+
async function fetchNoteIndexPage(relayUrl, epoch, page, options = {}) {
|
|
13437
|
+
if (typeof epoch !== "bigint" || epoch < 0n || epoch > U64_MAX3) throw new Error("epoch must be a u64 bigint");
|
|
13438
|
+
if (!isNonNegativeSafeInteger(page)) throw new Error(`page must be a non-negative integer, got ${page}`);
|
|
13439
|
+
const url = joinPath(relayUrl, `/note-index/v1/e/${epoch.toString(10)}/pages/${page}`).toString();
|
|
13440
|
+
return requestWithRetry(url, options, async (response) => {
|
|
13441
|
+
if (!response.ok) {
|
|
13442
|
+
throw new HttpStatusError(response.status, `note index page ${page}: HTTP ${response.status}`);
|
|
13443
|
+
}
|
|
13444
|
+
return readBoundedBody(response, NOTE_INDEX_MAX_PAGE_BYTES);
|
|
13445
|
+
});
|
|
13446
|
+
}
|
|
13447
|
+
|
|
13448
|
+
// src/scanning/note-index.ts
|
|
13449
|
+
var import_bs584 = __toESM(require("bs58"), 1);
|
|
13450
|
+
var import_sha26 = require("@noble/hashes/sha2");
|
|
13451
|
+
init_address();
|
|
13452
|
+
init_utxo();
|
|
13453
|
+
var bs584 = import_bs584.default.default || import_bs584.default;
|
|
13454
|
+
var CURSOR_VERSION = 2;
|
|
13455
|
+
var DEFAULT_CONCURRENCY = 6;
|
|
13456
|
+
var MAX_CONCURRENCY = 32;
|
|
13457
|
+
var ITEM_BATCH = 64;
|
|
13458
|
+
var CURSOR_PAGE_ALIGN = 8;
|
|
13459
|
+
var MAX_PERSISTED_PENDING_LEAVES = 4096;
|
|
13460
|
+
var MAX_CARRIED_PENDING = 256;
|
|
13461
|
+
var MAX_REJECTED_IDS = 1024;
|
|
13462
|
+
var LEAF_WINDOW = 512;
|
|
13463
|
+
var MAX_OVERRIDES = 256;
|
|
13464
|
+
var MAX_CURSOR_OWN_ITEMS = 65536;
|
|
13465
|
+
var MAX_LEGACY_VIEWING_KEYS = 8;
|
|
13466
|
+
var MAX_CURSOR_KEYS = 131072;
|
|
13467
|
+
var MAX_CURSOR_POOLS = 256;
|
|
13468
|
+
var MAX_CURSOR_PAGE = 2 ** 32;
|
|
13469
|
+
var TREE_CAPACITY = 2 ** MERKLE_TREE_HEIGHT2;
|
|
13470
|
+
var ZERO_CHAIN = "00".repeat(32);
|
|
13471
|
+
var U64_MAX4 = (1n << 64n) - 1n;
|
|
13472
|
+
var NoteIndexHeadBehindError = class extends Error {
|
|
13473
|
+
constructor(cursorWatermark, headWatermark) {
|
|
13474
|
+
super(
|
|
13475
|
+
`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`
|
|
13476
|
+
);
|
|
13477
|
+
this.cursorWatermark = cursorWatermark;
|
|
13478
|
+
this.headWatermark = headWatermark;
|
|
13479
|
+
this.retryable = true;
|
|
13480
|
+
this.name = "NoteIndexHeadBehindError";
|
|
13481
|
+
}
|
|
13482
|
+
};
|
|
13483
|
+
var FullPassSignal = class {
|
|
13484
|
+
constructor(reason) {
|
|
13485
|
+
this.reason = reason;
|
|
13486
|
+
}
|
|
13487
|
+
};
|
|
13488
|
+
function abortError2() {
|
|
13489
|
+
const error = new Error("recoverNotesFromIndex aborted");
|
|
13490
|
+
error.name = "AbortError";
|
|
13491
|
+
return error;
|
|
13492
|
+
}
|
|
13493
|
+
function bytesToBigint3(bytes) {
|
|
13494
|
+
let v = 0n;
|
|
13495
|
+
for (let i = 0; i < bytes.length; i++) v = v << 8n | BigInt(bytes[i]);
|
|
13496
|
+
return v;
|
|
13497
|
+
}
|
|
13498
|
+
function toHex2(bytes) {
|
|
13499
|
+
let s = "";
|
|
13500
|
+
for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, "0");
|
|
13501
|
+
return s;
|
|
13502
|
+
}
|
|
13503
|
+
function fromHex(hex) {
|
|
13504
|
+
return Uint8Array.from(Buffer.from(hex, "hex"));
|
|
13505
|
+
}
|
|
13506
|
+
function hex32(v) {
|
|
13507
|
+
return v.toString(16).padStart(64, "0");
|
|
13508
|
+
}
|
|
13509
|
+
function isAllZero3(bytes) {
|
|
13510
|
+
for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
|
|
13511
|
+
return true;
|
|
13512
|
+
}
|
|
13513
|
+
function floorAlign(page) {
|
|
13514
|
+
return page - page % CURSOR_PAGE_ALIGN;
|
|
13515
|
+
}
|
|
13516
|
+
function verifiedKey(mint, leaf, commitment) {
|
|
13517
|
+
return `${mint}:${leaf}:${hex32(commitment)}`;
|
|
13518
|
+
}
|
|
13519
|
+
function itemIdentity(raw) {
|
|
13520
|
+
return toHex2((0, import_sha26.sha256)(raw).subarray(0, 16));
|
|
13521
|
+
}
|
|
13522
|
+
var LeafBuffer = class {
|
|
13523
|
+
constructor() {
|
|
13524
|
+
this.bytes = new Uint8Array(32 * 1024);
|
|
13525
|
+
this.view = new DataView(this.bytes.buffer);
|
|
13526
|
+
this.count = 0;
|
|
13527
|
+
}
|
|
13528
|
+
get length() {
|
|
13529
|
+
return this.count;
|
|
13530
|
+
}
|
|
13531
|
+
push(values) {
|
|
13532
|
+
const need = (this.count + values.length) * 32;
|
|
13533
|
+
if (need > this.bytes.length) {
|
|
13534
|
+
let size = this.bytes.length;
|
|
13535
|
+
while (size < need) size *= 2;
|
|
13536
|
+
const next = new Uint8Array(size);
|
|
13537
|
+
next.set(this.bytes.subarray(0, this.count * 32));
|
|
13538
|
+
this.bytes = next;
|
|
13539
|
+
this.view = new DataView(next.buffer);
|
|
13540
|
+
}
|
|
13541
|
+
for (const v of values) {
|
|
13542
|
+
const o = this.count * 32;
|
|
13543
|
+
this.view.setBigUint64(o, v >> 192n & 0xffffffffffffffffn);
|
|
13544
|
+
this.view.setBigUint64(o + 8, v >> 128n & 0xffffffffffffffffn);
|
|
13545
|
+
this.view.setBigUint64(o + 16, v >> 64n & 0xffffffffffffffffn);
|
|
13546
|
+
this.view.setBigUint64(o + 24, v & 0xffffffffffffffffn);
|
|
13547
|
+
this.count++;
|
|
13548
|
+
}
|
|
13549
|
+
}
|
|
13550
|
+
get(i) {
|
|
13551
|
+
if (i < 0 || i >= this.count) return void 0;
|
|
13552
|
+
const o = i * 32;
|
|
13553
|
+
return this.view.getBigUint64(o) << 192n | this.view.getBigUint64(o + 8) << 128n | this.view.getBigUint64(o + 16) << 64n | this.view.getBigUint64(o + 24);
|
|
13554
|
+
}
|
|
13555
|
+
};
|
|
13556
|
+
async function trialItem(item, trials) {
|
|
13557
|
+
for (const trial of trials) {
|
|
13558
|
+
if (trial.legacy && item.kind === 2) continue;
|
|
13559
|
+
const opened = await trialItemWith(item, trial);
|
|
13560
|
+
if (opened) return { ...opened, trial };
|
|
13561
|
+
}
|
|
13562
|
+
return null;
|
|
13563
|
+
}
|
|
13564
|
+
async function trialItemIsolated(item, trials, stats) {
|
|
13565
|
+
try {
|
|
13566
|
+
return await trialItem(item, trials);
|
|
13567
|
+
} catch {
|
|
13568
|
+
stats.skipped++;
|
|
13569
|
+
return null;
|
|
13570
|
+
}
|
|
13571
|
+
}
|
|
13572
|
+
async function trialItemWith(item, trial) {
|
|
13573
|
+
if (item.kind === 1) {
|
|
13574
|
+
if (item.note.length === 0) return null;
|
|
13575
|
+
let note = isAllZero3(item.comm0) ? null : await trial.decrypt(item.note, item.comm0);
|
|
13576
|
+
if (!note && item.note[0] === 2 && !isAllZero3(item.comm1)) note = await trial.decrypt(item.note, item.comm1);
|
|
13577
|
+
return note ? { note } : null;
|
|
13578
|
+
}
|
|
13579
|
+
if (item.kind === 2) {
|
|
13580
|
+
const delivery = await trial.open(item.envelope);
|
|
13581
|
+
return delivery ? { delivery } : null;
|
|
13582
|
+
}
|
|
13583
|
+
if (item.amountAfterFee === 0n) return null;
|
|
13584
|
+
const refund = await matchSwapRefundLeaf({
|
|
13585
|
+
viewingKeyNk: trial.nk,
|
|
13586
|
+
inputNullifier: item.nullifier0,
|
|
13587
|
+
amountAfterFee: item.amountAfterFee,
|
|
13588
|
+
commitment: item.commitment,
|
|
13589
|
+
ownerUtxoKeypair: trial.owner
|
|
13590
|
+
});
|
|
13591
|
+
return refund ? { refund } : null;
|
|
13592
|
+
}
|
|
13593
|
+
function txOutputs(item) {
|
|
13594
|
+
const out = [toHex2(item.comm0)];
|
|
13595
|
+
if (!isAllZero3(item.comm1)) out.push(toHex2(item.comm1));
|
|
13596
|
+
return out;
|
|
13597
|
+
}
|
|
13598
|
+
function leafOfTxOutput(item, commitment) {
|
|
13599
|
+
if (!isAllZero3(item.comm0) && commitment === bytesToBigint3(item.comm0)) return Number(item.leaf0);
|
|
13600
|
+
if (!isAllZero3(item.comm1) && commitment === bytesToBigint3(item.comm1)) return Number(item.leaf1);
|
|
13601
|
+
return null;
|
|
13602
|
+
}
|
|
13603
|
+
function changeBlindingOrNull(nk, noteSalt, outputIndex) {
|
|
13604
|
+
try {
|
|
13605
|
+
return deriveChangeNoteBlinding(nk, noteSalt, outputIndex);
|
|
13606
|
+
} catch {
|
|
13607
|
+
return null;
|
|
13608
|
+
}
|
|
13609
|
+
}
|
|
13610
|
+
async function matchOwnItems(own, owner, onReject, onSkip) {
|
|
13611
|
+
const candidates = [];
|
|
13612
|
+
const claimed = /* @__PURE__ */ new Set();
|
|
13613
|
+
const byNullifier = /* @__PURE__ */ new Map();
|
|
13614
|
+
const legacyKeys = /* @__PURE__ */ new Map();
|
|
13615
|
+
const ownTxs = own.filter((o) => o.item.kind === 1 && o.note?.noteSalt !== void 0);
|
|
13616
|
+
const spendsOf = /* @__PURE__ */ new Map();
|
|
13617
|
+
const byOutKey = /* @__PURE__ */ new Map();
|
|
13618
|
+
const index = (map, key, o) => {
|
|
13619
|
+
const list = map.get(key);
|
|
13620
|
+
if (list) list.push(o);
|
|
13621
|
+
else map.set(key, [o]);
|
|
13622
|
+
};
|
|
13623
|
+
for (const o of ownTxs) {
|
|
13624
|
+
for (const n of [o.item.nullifier0, o.item.nullifier1]) if (!isAllZero3(n)) index(spendsOf, toHex2(n), o);
|
|
13625
|
+
if (o.note.outPubkey0 !== void 0) index(byOutKey, o.note.outPubkey0, o);
|
|
13626
|
+
}
|
|
13627
|
+
const queue = [];
|
|
13628
|
+
const queued = /* @__PURE__ */ new Set();
|
|
13629
|
+
const enqueue = (o) => {
|
|
13630
|
+
if (queued.has(o)) return;
|
|
13631
|
+
queued.add(o);
|
|
13632
|
+
queue.push(o);
|
|
13633
|
+
};
|
|
13634
|
+
const add = async (o, c) => {
|
|
13635
|
+
const nullifier = hex32(
|
|
13636
|
+
await computeNullifier({ amount: c.amount, keypair: c.keypair, blinding: c.blinding, mintAddress: c.mint, index: c.leaf, commitment: c.commitment })
|
|
13637
|
+
);
|
|
13638
|
+
const full = { ...c, atRisk: c.atRisk || o.trial.legacy, signature: o.item.signature, page: o.page, seq: o.seq, nullifier };
|
|
13639
|
+
candidates.push(full);
|
|
13640
|
+
if (!byNullifier.has(nullifier)) {
|
|
13641
|
+
byNullifier.set(nullifier, full);
|
|
13642
|
+
for (const s of spendsOf.get(nullifier) ?? []) enqueue(s);
|
|
13643
|
+
}
|
|
13644
|
+
if (c.atRisk && c.keypair.publicKey !== owner.publicKey && !legacyKeys.has(c.keypair.publicKey)) {
|
|
13645
|
+
legacyKeys.set(c.keypair.publicKey, c.keypair);
|
|
13646
|
+
for (const s of byOutKey.get(c.keypair.publicKey) ?? []) enqueue(s);
|
|
13647
|
+
}
|
|
13648
|
+
};
|
|
13649
|
+
const tryDeposit = async (o, item, amount) => {
|
|
13650
|
+
const note = o.note;
|
|
13651
|
+
const mint = addressFromBytes(item.mint);
|
|
13652
|
+
const deposit = await matchDepositNote({
|
|
13653
|
+
viewingKeyNk: o.trial.nk,
|
|
13654
|
+
noteSalt: note.noteSalt,
|
|
13655
|
+
amount,
|
|
13656
|
+
mintAddress: mint,
|
|
13657
|
+
outputCommitments: txOutputs(item),
|
|
13658
|
+
ownerUtxoKeypair: owner
|
|
13659
|
+
});
|
|
13660
|
+
const leaf = deposit ? leafOfTxOutput(item, deposit.commitment) : null;
|
|
13661
|
+
if (!deposit || leaf === null) return false;
|
|
13662
|
+
await add(o, {
|
|
13663
|
+
kind: "deposit",
|
|
13664
|
+
atRisk: deposit.legacyExposed,
|
|
13665
|
+
amount: deposit.amount,
|
|
13666
|
+
blinding: deposit.blinding,
|
|
13667
|
+
keypair: deposit.legacyExposed ? deposit.keypair : owner,
|
|
13668
|
+
mint,
|
|
13669
|
+
commitment: deposit.commitment,
|
|
13670
|
+
leaf
|
|
13671
|
+
});
|
|
13672
|
+
return true;
|
|
13673
|
+
};
|
|
13674
|
+
const tryChange0 = async (o, item, keypair, atRisk) => {
|
|
13675
|
+
const note = o.note;
|
|
13676
|
+
const mint = addressFromBytes(item.mint);
|
|
13677
|
+
const change = await matchChangeNote({
|
|
13678
|
+
viewingKeyNk: o.trial.nk,
|
|
13679
|
+
noteSalt: note.noteSalt,
|
|
13680
|
+
amount: note.outAmount0,
|
|
13681
|
+
keypair,
|
|
13682
|
+
mintAddress: mint,
|
|
13683
|
+
outputIndex: 0,
|
|
13684
|
+
outputCommitments: [toHex2(item.comm0)],
|
|
13685
|
+
ownerUtxoPublicKey: owner.publicKey
|
|
13686
|
+
});
|
|
13687
|
+
if (!change) return false;
|
|
13688
|
+
await add(o, {
|
|
13689
|
+
kind: "change",
|
|
13690
|
+
atRisk,
|
|
13691
|
+
amount: change.amount,
|
|
13692
|
+
blinding: change.blinding,
|
|
13693
|
+
keypair,
|
|
13694
|
+
mint,
|
|
13695
|
+
commitment: change.commitment,
|
|
13696
|
+
leaf: Number(item.leaf0)
|
|
13697
|
+
});
|
|
13698
|
+
return true;
|
|
13699
|
+
};
|
|
13700
|
+
const direct = async (o) => {
|
|
13701
|
+
const item = o.item;
|
|
13702
|
+
if (item.kind === 1 && o.note?.noteSalt !== void 0) {
|
|
13703
|
+
const note = o.note;
|
|
13704
|
+
if (note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
|
|
13705
|
+
if (await tryDeposit(o, item, item.publicAmount)) claimed.add(`${o.seq}:0`);
|
|
13706
|
+
}
|
|
13707
|
+
if (note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 === owner.publicKey) {
|
|
13708
|
+
if (await tryChange0(o, item, owner, false)) claimed.add(`${o.seq}:0`);
|
|
13709
|
+
}
|
|
13710
|
+
} else if (item.kind === 2 && o.delivery) {
|
|
13711
|
+
const mint = addressFromBytes(item.mint);
|
|
13712
|
+
if (o.delivery.amount <= 0n || o.delivery.blinding === 0n) {
|
|
13713
|
+
onReject(o);
|
|
13714
|
+
return;
|
|
13715
|
+
}
|
|
13716
|
+
const commitment = await computeCommitment2({
|
|
13717
|
+
amount: o.delivery.amount,
|
|
13718
|
+
keypair: { privateKey: 0n, publicKey: owner.publicKey },
|
|
13719
|
+
blinding: o.delivery.blinding,
|
|
13720
|
+
mintAddress: mint
|
|
13721
|
+
});
|
|
13722
|
+
if (commitment !== bytesToBigint3(item.commitment)) {
|
|
13723
|
+
onReject(o);
|
|
13724
|
+
return;
|
|
13725
|
+
}
|
|
13726
|
+
await add(o, {
|
|
13727
|
+
kind: "received",
|
|
13728
|
+
atRisk: false,
|
|
13729
|
+
amount: o.delivery.amount,
|
|
13730
|
+
blinding: o.delivery.blinding,
|
|
13731
|
+
keypair: owner,
|
|
13732
|
+
mint,
|
|
13733
|
+
commitment,
|
|
13734
|
+
leaf: Number(item.leaf)
|
|
13735
|
+
});
|
|
13736
|
+
} else if (item.kind === 3 && o.refund) {
|
|
13737
|
+
await add(o, {
|
|
13738
|
+
kind: "swap_refund",
|
|
13739
|
+
atRisk: o.refund.legacyExposed,
|
|
13740
|
+
amount: o.refund.amount,
|
|
13741
|
+
blinding: o.refund.blinding,
|
|
13742
|
+
// per-swap refunds carry their derived keypair; owner-shape ones carry the owner
|
|
13743
|
+
keypair: o.refund.keypair,
|
|
13744
|
+
mint: NATIVE_SOL_MINT,
|
|
13745
|
+
commitment: o.refund.commitment,
|
|
13746
|
+
leaf: Number(item.leaf)
|
|
13747
|
+
});
|
|
13748
|
+
}
|
|
13749
|
+
};
|
|
13750
|
+
for (const o of own) {
|
|
13751
|
+
try {
|
|
13752
|
+
await direct(o);
|
|
13753
|
+
} catch {
|
|
13754
|
+
onSkip(o);
|
|
13755
|
+
}
|
|
13756
|
+
}
|
|
13757
|
+
const processTx = async (o) => {
|
|
13758
|
+
const item = o.item;
|
|
13759
|
+
const note = o.note;
|
|
13760
|
+
if (!claimed.has(`${o.seq}:0`) && note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 !== void 0) {
|
|
13761
|
+
const legacy = legacyKeys.get(note.outPubkey0);
|
|
13762
|
+
if (legacy && await tryChange0(o, item, legacy, true)) claimed.add(`${o.seq}:0`);
|
|
13763
|
+
}
|
|
13764
|
+
const mint = addressFromBytes(item.mint);
|
|
13765
|
+
const inputs = [item.nullifier0, item.nullifier1].filter((n) => !isAllZero3(n)).map((n) => byNullifier.get(toHex2(n))).filter((c) => c !== void 0 && c.mint === mint);
|
|
13766
|
+
if (inputs.length === 0) return;
|
|
13767
|
+
const sumIn = inputs.reduce((acc, c) => acc + c.amount, 0n);
|
|
13768
|
+
if (!claimed.has(`${o.seq}:1`) && note.outAmount0 !== void 0 && !isAllZero3(item.comm1)) {
|
|
13769
|
+
const out1 = sumIn + item.publicAmount - note.outAmount0;
|
|
13770
|
+
const blinding = out1 > 0n ? changeBlindingOrNull(o.trial.nk, note.noteSalt, 1) : null;
|
|
13771
|
+
if (out1 > 0n && blinding === null) onSkip(o);
|
|
13772
|
+
else if (blinding !== null) {
|
|
13773
|
+
const owners = [{ keypair: owner, atRisk: false }];
|
|
13774
|
+
const legacyInput = legacyKeys.get(inputs[0].keypair.publicKey);
|
|
13775
|
+
if (legacyInput && legacyInput.publicKey !== owner.publicKey) owners.push({ keypair: legacyInput, atRisk: true });
|
|
13776
|
+
for (const { keypair, atRisk } of owners) {
|
|
13777
|
+
const commitment = await computeCommitment2({ amount: out1, keypair, blinding, mintAddress: mint });
|
|
13778
|
+
if (commitment !== bytesToBigint3(item.comm1)) continue;
|
|
13779
|
+
claimed.add(`${o.seq}:1`);
|
|
13780
|
+
await add(o, { kind: "change", atRisk, amount: out1, blinding, keypair, mint, commitment, leaf: Number(item.leaf1) });
|
|
13781
|
+
break;
|
|
13782
|
+
}
|
|
13783
|
+
}
|
|
13784
|
+
}
|
|
13785
|
+
if (!claimed.has(`${o.seq}:0`) && note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
|
|
13786
|
+
if (await tryDeposit(o, item, item.publicAmount + sumIn)) claimed.add(`${o.seq}:0`);
|
|
13787
|
+
}
|
|
13788
|
+
};
|
|
13789
|
+
for (const o of ownTxs) enqueue(o);
|
|
13790
|
+
for (let i = 0; i < queue.length; i++) {
|
|
13791
|
+
const o = queue[i];
|
|
13792
|
+
queued.delete(o);
|
|
13793
|
+
try {
|
|
13794
|
+
await processTx(o);
|
|
13795
|
+
} catch {
|
|
13796
|
+
onSkip(o);
|
|
13797
|
+
}
|
|
13798
|
+
}
|
|
13799
|
+
return candidates;
|
|
13800
|
+
}
|
|
13801
|
+
async function replayStream(start, pages, overrides, chain, targetPage) {
|
|
13802
|
+
const frontier = await MerkleFrontier.create(start.frontier ?? void 0, MERKLE_TREE_HEIGHT2);
|
|
13803
|
+
const startN = frontier.nextIndex;
|
|
13804
|
+
const pending = new Map(start.pending);
|
|
13805
|
+
const flushed = new LeafBuffer();
|
|
13806
|
+
const corrections = /* @__PURE__ */ new Map();
|
|
13807
|
+
let conflicts = 0;
|
|
13808
|
+
let verifiedPrefix = 0;
|
|
13809
|
+
let mismatch = false;
|
|
13810
|
+
const checks = [];
|
|
13811
|
+
const setBits = [];
|
|
13812
|
+
if (chain && chain.nextIndex > 0) {
|
|
13813
|
+
const last = chain.nextIndex - 1;
|
|
13814
|
+
for (let l = 0; l < MERKLE_TREE_HEIGHT2; l++) if (Math.floor(last / 2 ** l) % 2 === 1) setBits.push(l);
|
|
13815
|
+
for (const l of setBits) {
|
|
13816
|
+
const at = Math.floor(last / 2 ** l) * 2 ** l;
|
|
13817
|
+
if (at >= startN) checks.push({ at, level: l });
|
|
13818
|
+
}
|
|
13819
|
+
if (chain.nextIndex >= startN) checks.push({ at: chain.nextIndex, level: -1 });
|
|
13820
|
+
checks.sort((a, b) => a.at - b.at);
|
|
13821
|
+
}
|
|
13822
|
+
let nextCheck = 0;
|
|
13823
|
+
const runChecks = () => {
|
|
13824
|
+
while (nextCheck < checks.length && checks[nextCheck].at === frontier.nextIndex) {
|
|
13825
|
+
const { at, level } = checks[nextCheck++];
|
|
13826
|
+
const ok = level < 0 ? frontier.root() === chain.root : setBits.every((j) => j < level || frontier.leftAt(j) === chain.subtrees[j]);
|
|
13827
|
+
if (ok) verifiedPrefix = Math.max(verifiedPrefix, at);
|
|
13828
|
+
else mismatch = true;
|
|
13829
|
+
}
|
|
13830
|
+
};
|
|
13831
|
+
const append = (values) => {
|
|
13832
|
+
let i = 0;
|
|
13833
|
+
while (i < values.length) {
|
|
13834
|
+
const room = nextCheck < checks.length ? checks[nextCheck].at - frontier.nextIndex : values.length - i;
|
|
13835
|
+
const take = Math.min(values.length - i, room);
|
|
13836
|
+
if (take > 0) {
|
|
13837
|
+
const part = values.slice(i, i + take);
|
|
13838
|
+
frontier.append(part);
|
|
13839
|
+
flushed.push(part);
|
|
13840
|
+
i += take;
|
|
13841
|
+
}
|
|
13842
|
+
runChecks();
|
|
13843
|
+
}
|
|
13844
|
+
};
|
|
13845
|
+
const valueAt = (leaf) => leaf >= startN && leaf < startN + flushed.length ? flushed.get(leaf - startN) : pending.get(leaf);
|
|
13846
|
+
const flush = () => {
|
|
13847
|
+
const batch = [];
|
|
13848
|
+
let next = frontier.nextIndex;
|
|
13849
|
+
while (pending.has(next)) {
|
|
13850
|
+
batch.push(pending.get(next));
|
|
13851
|
+
pending.delete(next);
|
|
13852
|
+
next++;
|
|
13853
|
+
}
|
|
13854
|
+
if (batch.length > 0) append(batch);
|
|
13855
|
+
};
|
|
13856
|
+
let snapshot = null;
|
|
13857
|
+
let taken = false;
|
|
13858
|
+
const takeSnapshot = () => {
|
|
13859
|
+
taken = true;
|
|
13860
|
+
if (pending.size > MAX_PERSISTED_PENDING_LEAVES) return;
|
|
13861
|
+
snapshot = { frontier: frontier.toState(), pending: new Map(pending), nextIndex: frontier.nextIndex };
|
|
13862
|
+
};
|
|
13863
|
+
runChecks();
|
|
13864
|
+
flush();
|
|
13865
|
+
for (const { page, entries } of pages) {
|
|
13866
|
+
if (!taken && page >= targetPage) takeSnapshot();
|
|
13867
|
+
for (const e of entries) {
|
|
13868
|
+
if (e.leaf < startN) continue;
|
|
13869
|
+
const prior = valueAt(e.leaf);
|
|
13870
|
+
if (prior !== void 0) {
|
|
13871
|
+
if (prior !== e.commitment) {
|
|
13872
|
+
conflicts++;
|
|
13873
|
+
corrections.set(e.leaf, e.commitment);
|
|
13874
|
+
}
|
|
13875
|
+
continue;
|
|
13876
|
+
}
|
|
13877
|
+
pending.set(e.leaf, overrides.get(e.leaf) ?? e.commitment);
|
|
13878
|
+
}
|
|
13879
|
+
flush();
|
|
13880
|
+
}
|
|
13881
|
+
if (!taken) takeSnapshot();
|
|
13882
|
+
if (chain && treeAccountAcceptsRoot(chain.data, hex32(frontier.root()))) {
|
|
13883
|
+
verifiedPrefix = Math.max(verifiedPrefix, Math.min(frontier.nextIndex, chain.nextIndex));
|
|
13884
|
+
}
|
|
13885
|
+
return { endCount: frontier.nextIndex, valueAt, snapshot, conflicts, corrections, verifiedPrefix, mismatch };
|
|
13886
|
+
}
|
|
13887
|
+
var HEX64 = /^[0-9a-f]{64}$/;
|
|
13888
|
+
var HEX32 = /^[0-9a-f]{32}$/;
|
|
13889
|
+
var ADDRESS = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
|
|
13890
|
+
var VERIFIED_KEY = /^[1-9A-HJ-NP-Za-km-z]{32,44}:(0|[1-9][0-9]{0,9}):[0-9a-f]{64}$/;
|
|
13891
|
+
function isRecord(v) {
|
|
13892
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
13893
|
+
}
|
|
13894
|
+
function isIntIn(v, min, max) {
|
|
13895
|
+
return typeof v === "number" && Number.isSafeInteger(v) && v >= min && v <= max;
|
|
13896
|
+
}
|
|
13897
|
+
function isBoundedArray(v, max) {
|
|
13898
|
+
return Array.isArray(v) && v.length <= max;
|
|
13899
|
+
}
|
|
13900
|
+
function emptyStartTree() {
|
|
13901
|
+
return {
|
|
13902
|
+
frontier: null,
|
|
13903
|
+
nextIndex: 0,
|
|
13904
|
+
pending: /* @__PURE__ */ new Map(),
|
|
13905
|
+
window: [],
|
|
13906
|
+
windowStart: 0,
|
|
13907
|
+
verified: 0,
|
|
13908
|
+
overrides: /* @__PURE__ */ new Map(),
|
|
13909
|
+
mismatch: false,
|
|
13910
|
+
hiBefore: -1
|
|
13911
|
+
};
|
|
13912
|
+
}
|
|
13913
|
+
async function parseCursor(cursor, poolMints) {
|
|
13914
|
+
try {
|
|
13915
|
+
if (!isRecord(cursor)) return "not an object";
|
|
13916
|
+
if (cursor.v !== CURSOR_VERSION) return "unsupported cursor version";
|
|
13917
|
+
const c = cursor;
|
|
13918
|
+
if (typeof c.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(c.epoch) || BigInt(c.epoch) > U64_MAX4) return "bad epoch";
|
|
13919
|
+
if (!isIntIn(c.page, 0, MAX_CURSOR_PAGE) || c.page % CURSOR_PAGE_ALIGN !== 0) return "bad page";
|
|
13920
|
+
if (typeof c.chain !== "string" || !HEX64.test(c.chain)) return "bad chain";
|
|
13921
|
+
if (!isIntIn(c.watermark, 0, Number.MAX_SAFE_INTEGER) || c.page * NOTE_INDEX_PAGE_SIZE > c.watermark) return "bad watermark";
|
|
13922
|
+
if (!isIntIn(c.fullPassSeq, 0, c.watermark)) return "bad full-pass mark";
|
|
13923
|
+
if (!isRecord(c.trees) || Object.keys(c.trees).length > MAX_CURSOR_POOLS) return "bad trees";
|
|
13924
|
+
const trees = /* @__PURE__ */ new Map();
|
|
13925
|
+
for (const mint of poolMints) {
|
|
13926
|
+
const t = c.trees[mint];
|
|
13927
|
+
if (!isRecord(t)) return "a listed pool is missing from the cursor";
|
|
13928
|
+
const tree = t;
|
|
13929
|
+
if (!isRecord(tree.frontier)) return "bad frontier";
|
|
13930
|
+
let frontier;
|
|
13931
|
+
try {
|
|
13932
|
+
frontier = await MerkleFrontier.create(tree.frontier, MERKLE_TREE_HEIGHT2);
|
|
13933
|
+
} catch {
|
|
13934
|
+
return "bad frontier";
|
|
13935
|
+
}
|
|
13936
|
+
const nextIndex = frontier.nextIndex;
|
|
13937
|
+
if (!isBoundedArray(tree.pending, MAX_PERSISTED_PENDING_LEAVES)) return "bad pending leaves";
|
|
13938
|
+
const pending = /* @__PURE__ */ new Map();
|
|
13939
|
+
let hiBefore = nextIndex - 1;
|
|
13940
|
+
for (const entry of tree.pending) {
|
|
13941
|
+
if (!Array.isArray(entry) || entry.length !== 2) return "bad pending leaves";
|
|
13942
|
+
const [leaf, value] = entry;
|
|
13943
|
+
if (!isIntIn(leaf, nextIndex + 1, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value) || pending.has(leaf)) {
|
|
13944
|
+
return "bad pending leaves";
|
|
13945
|
+
}
|
|
13946
|
+
pending.set(leaf, BigInt("0x" + value));
|
|
13947
|
+
hiBefore = Math.max(hiBefore, leaf);
|
|
13948
|
+
}
|
|
13949
|
+
if (typeof tree.window !== "string" || tree.window.length % 64 !== 0 || !/^[0-9a-f]*$/.test(tree.window)) return "bad window";
|
|
13950
|
+
const windowLen = tree.window.length / 64;
|
|
13951
|
+
if (windowLen > LEAF_WINDOW || windowLen > nextIndex) return "bad window";
|
|
13952
|
+
const window2 = [];
|
|
13953
|
+
for (let i = 0; i < windowLen; i++) window2.push(BigInt("0x" + tree.window.slice(i * 64, (i + 1) * 64)));
|
|
13954
|
+
if (!isIntIn(tree.verified, 0, nextIndex)) return "bad verified prefix";
|
|
13955
|
+
if (!isBoundedArray(tree.overrides, MAX_OVERRIDES)) return "bad overrides";
|
|
13956
|
+
const overrides = /* @__PURE__ */ new Map();
|
|
13957
|
+
for (const entry of tree.overrides) {
|
|
13958
|
+
if (!Array.isArray(entry) || entry.length !== 2) return "bad overrides";
|
|
13959
|
+
const [leaf, value] = entry;
|
|
13960
|
+
if (!isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) return "bad overrides";
|
|
13961
|
+
overrides.set(leaf, BigInt("0x" + value));
|
|
13962
|
+
}
|
|
13963
|
+
if (typeof tree.mismatch !== "boolean") return "bad mismatch flag";
|
|
13964
|
+
trees.set(mint, {
|
|
13965
|
+
frontier: frontier.toState(),
|
|
13966
|
+
nextIndex,
|
|
13967
|
+
pending,
|
|
13968
|
+
window: window2,
|
|
13969
|
+
windowStart: nextIndex - windowLen,
|
|
13970
|
+
verified: tree.verified,
|
|
13971
|
+
overrides,
|
|
13972
|
+
mismatch: tree.mismatch,
|
|
13973
|
+
hiBefore
|
|
13974
|
+
});
|
|
13975
|
+
}
|
|
13976
|
+
const own = c.own;
|
|
13977
|
+
if (!isRecord(own)) return "bad own state";
|
|
13978
|
+
if (!isBoundedArray(own.items, MAX_CURSOR_OWN_ITEMS)) return "bad own items";
|
|
13979
|
+
const items = [];
|
|
13980
|
+
const seqs = /* @__PURE__ */ new Set();
|
|
13981
|
+
for (const entry of own.items) {
|
|
13982
|
+
if (!isRecord(entry)) return "bad own items";
|
|
13983
|
+
const { seq, item } = entry;
|
|
13984
|
+
if (!isIntIn(seq, 0, c.page * NOTE_INDEX_PAGE_SIZE - 1) || seqs.has(seq)) return "bad own items";
|
|
13985
|
+
if (typeof item !== "string" || item.length % 2 !== 0 || item.length > 2 * 4096 || !/^[0-9a-f]+$/.test(item)) return "bad own items";
|
|
13986
|
+
seqs.add(seq);
|
|
13987
|
+
const raw = fromHex(item);
|
|
13988
|
+
items.push({ seq, raw, item: parseNoteIndexItem(raw) });
|
|
13989
|
+
}
|
|
13990
|
+
if (!isBoundedArray(own.verified, MAX_CURSOR_KEYS) || !own.verified.every((k) => typeof k === "string" && VERIFIED_KEY.test(k))) {
|
|
13991
|
+
return "bad verified notes";
|
|
13992
|
+
}
|
|
13993
|
+
if (!isBoundedArray(own.spent, MAX_CURSOR_KEYS) || !own.spent.every((k) => typeof k === "string" && HEX64.test(k))) return "bad spent set";
|
|
13994
|
+
if (!isBoundedArray(own.pendingLeaves, MAX_CARRIED_PENDING)) return "bad pending notes";
|
|
13995
|
+
const pendingLeaves = /* @__PURE__ */ new Map();
|
|
13996
|
+
for (const entry of own.pendingLeaves) {
|
|
13997
|
+
if (!Array.isArray(entry) || entry.length !== 3) return "bad pending notes";
|
|
13998
|
+
const [mint, leaf, value] = entry;
|
|
13999
|
+
if (typeof mint !== "string" || !ADDRESS.test(mint) || !isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) {
|
|
14000
|
+
return "bad pending notes";
|
|
14001
|
+
}
|
|
14002
|
+
pendingLeaves.set(`${mint}:${leaf}`, BigInt("0x" + value));
|
|
14003
|
+
}
|
|
14004
|
+
if (!isBoundedArray(own.rejected, MAX_REJECTED_IDS) || !own.rejected.every((k) => typeof k === "string" && HEX32.test(k))) {
|
|
14005
|
+
return "bad rejected set";
|
|
14006
|
+
}
|
|
14007
|
+
return {
|
|
14008
|
+
raw: c,
|
|
14009
|
+
trees,
|
|
14010
|
+
items,
|
|
14011
|
+
verified: new Set(own.verified),
|
|
14012
|
+
spent: new Set(own.spent),
|
|
14013
|
+
pendingLeaves,
|
|
14014
|
+
rejected: own.rejected
|
|
14015
|
+
};
|
|
14016
|
+
} catch {
|
|
14017
|
+
return "unreadable state";
|
|
14018
|
+
}
|
|
14019
|
+
}
|
|
14020
|
+
async function recoverNotesFromIndex(params) {
|
|
14021
|
+
const startedAt = Date.now();
|
|
14022
|
+
const { relayUrl, connection, viewingKeyNk, programId } = params;
|
|
14023
|
+
assertAllowedRelayOrigin(relayUrl);
|
|
14024
|
+
assertAllowedRpcConnection(connection);
|
|
14025
|
+
if (!(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) throw new Error("viewingKeyNk must be 32 bytes");
|
|
14026
|
+
const owner = await assertOwnerUtxoKeypair(params.ownerUtxoKeypair);
|
|
14027
|
+
if (!Array.isArray(params.poolMints)) throw new Error("poolMints must list every active pool mint");
|
|
14028
|
+
const concurrency = params.concurrency ?? DEFAULT_CONCURRENCY;
|
|
14029
|
+
if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > MAX_CONCURRENCY) {
|
|
14030
|
+
throw new Error(`concurrency must be an integer in 1..${MAX_CONCURRENCY}`);
|
|
14031
|
+
}
|
|
14032
|
+
if (params.signal?.aborted) throw abortError2();
|
|
14033
|
+
const stats = {
|
|
14034
|
+
pages: 0,
|
|
14035
|
+
items: 0,
|
|
14036
|
+
bytes: 0,
|
|
14037
|
+
rpcCalls: 0,
|
|
14038
|
+
ms: 0,
|
|
14039
|
+
dropped: 0,
|
|
14040
|
+
decrypted: 0,
|
|
14041
|
+
candidates: 0,
|
|
14042
|
+
spent: 0,
|
|
14043
|
+
conflicts: 0,
|
|
14044
|
+
pendingDropped: 0,
|
|
14045
|
+
skipped: 0
|
|
14046
|
+
};
|
|
14047
|
+
const rpc = new Proxy(connection, {
|
|
14048
|
+
get(target, prop, receiver) {
|
|
14049
|
+
const value = Reflect.get(target, prop, receiver);
|
|
14050
|
+
if (typeof value !== "function") return value;
|
|
14051
|
+
return (...args) => {
|
|
14052
|
+
const pending = value.apply(target, args);
|
|
14053
|
+
if (pending && typeof pending.send === "function") {
|
|
14054
|
+
const send = pending.send.bind(pending);
|
|
14055
|
+
return {
|
|
14056
|
+
...pending,
|
|
14057
|
+
send: (...sendArgs) => {
|
|
14058
|
+
stats.rpcCalls++;
|
|
14059
|
+
return send(...sendArgs);
|
|
14060
|
+
}
|
|
14061
|
+
};
|
|
14062
|
+
}
|
|
14063
|
+
return pending;
|
|
14064
|
+
};
|
|
14065
|
+
}
|
|
14066
|
+
});
|
|
14067
|
+
const makeTrial = async (nk, legacy) => ({
|
|
14068
|
+
nk,
|
|
14069
|
+
legacy,
|
|
14070
|
+
owner,
|
|
14071
|
+
decrypt: await createCompactChainNoteDecryptor(nk),
|
|
14072
|
+
open: await createRecipientDeliveryOpener(deriveViewingKeyFromNk(nk).privateKey)
|
|
14073
|
+
});
|
|
14074
|
+
const trials = [await makeTrial(viewingKeyNk, false)];
|
|
14075
|
+
const legacyNks = params.legacyViewingKeyNks ?? [];
|
|
14076
|
+
if (!Array.isArray(legacyNks)) throw new Error("legacyViewingKeyNks must be an array of 32-byte keys");
|
|
14077
|
+
if (legacyNks.length > MAX_LEGACY_VIEWING_KEYS) throw new Error(`legacyViewingKeyNks takes at most ${MAX_LEGACY_VIEWING_KEYS} keys`);
|
|
14078
|
+
const seenNks = /* @__PURE__ */ new Set([toHex2(viewingKeyNk)]);
|
|
14079
|
+
for (const nk of legacyNks) {
|
|
14080
|
+
if (!(nk instanceof Uint8Array) || nk.length !== 32) throw new Error("legacyViewingKeyNks entries must be 32 bytes");
|
|
14081
|
+
const key = toHex2(nk);
|
|
14082
|
+
if (seenNks.has(key)) continue;
|
|
14083
|
+
seenNks.add(key);
|
|
14084
|
+
trials.push(await makeTrial(Uint8Array.from(nk), true));
|
|
14085
|
+
}
|
|
14086
|
+
const poolMints = Array.from(new Set(params.poolMints));
|
|
14087
|
+
const warnings = [];
|
|
14088
|
+
const head = await fetchNoteIndexHead(relayUrl, { signal: params.signal });
|
|
14089
|
+
let cursor;
|
|
14090
|
+
if (params.cursor !== void 0) {
|
|
14091
|
+
const checked = await parseCursor(params.cursor, poolMints);
|
|
14092
|
+
if (typeof checked === "string") warnings.push(`note index cursor is unusable (${checked}); re-syncing from page 0`);
|
|
14093
|
+
else if (BigInt(checked.raw.epoch) !== head.epoch) warnings.push("note index epoch changed; re-syncing from page 0");
|
|
14094
|
+
else if (head.watermark < checked.raw.watermark || head.completePages < checked.raw.page) {
|
|
14095
|
+
throw new NoteIndexHeadBehindError(checked.raw.watermark, head.watermark);
|
|
14096
|
+
} else cursor = checked;
|
|
14097
|
+
}
|
|
14098
|
+
const treePdas = await Promise.all(poolMints.map(async (mint) => (await getShieldPoolPDAs(programId, mint)).merkleTree));
|
|
14099
|
+
let treeRead;
|
|
14100
|
+
const readTrees = () => treeRead ?? (treeRead = (async () => {
|
|
14101
|
+
const accounts = poolMints.length > 0 ? await fetchMultipleAccountBytes(rpc, treePdas, "confirmed") : [];
|
|
14102
|
+
return poolMints.map((_, i) => {
|
|
14103
|
+
const account = accounts[i];
|
|
14104
|
+
const parsed = account ? readTreeAccountFrontier(account.data) : null;
|
|
14105
|
+
return account && parsed ? { ...parsed, data: account.data } : null;
|
|
14106
|
+
});
|
|
14107
|
+
})());
|
|
14108
|
+
const ctx = { params, head, trials, owner, stats, poolMints, warnings, readTrees };
|
|
14109
|
+
let outcome = await runOnce(ctx, cursor);
|
|
14110
|
+
if (outcome instanceof FullPassSignal) {
|
|
14111
|
+
warnings.push(`${outcome.reason}; re-syncing from page 0`);
|
|
14112
|
+
Object.assign(stats, { dropped: 0, decrypted: 0, candidates: 0, spent: 0, conflicts: 0, pendingDropped: 0, skipped: 0 });
|
|
14113
|
+
outcome = await runOnce(ctx, void 0);
|
|
14114
|
+
if (outcome instanceof FullPassSignal) throw new Error(`note index recovery failed: ${outcome.reason}`);
|
|
14115
|
+
}
|
|
14116
|
+
if (stats.skipped > 0) warnings.push(`${stats.skipped} note index entries could not be processed and were skipped`);
|
|
14117
|
+
stats.ms = Date.now() - startedAt;
|
|
14118
|
+
return { ...outcome, stats, warnings };
|
|
14119
|
+
}
|
|
14120
|
+
async function runOnce(ctx, cursor) {
|
|
14121
|
+
const { params, head, trials, owner, stats, poolMints } = ctx;
|
|
14122
|
+
const { relayUrl, onProgress } = params;
|
|
14123
|
+
const poolSet = new Set(poolMints);
|
|
14124
|
+
const startPage = cursor?.raw.page ?? 0;
|
|
14125
|
+
const startChain = cursor?.raw.chain ?? ZERO_CHAIN;
|
|
14126
|
+
const fullPassSeq = cursor?.raw.fullPassSeq ?? 0;
|
|
14127
|
+
const pagesTotal = Math.ceil(head.watermark / NOTE_INDEX_PAGE_SIZE);
|
|
14128
|
+
const targetPage = Math.max(startPage, floorAlign(head.completePages));
|
|
14129
|
+
const startTrees = new Map(poolMints.map((m) => [m, cursor?.trees.get(m) ?? emptyStartTree()]));
|
|
14130
|
+
const rejectedIds = new Set(cursor?.rejected ?? []);
|
|
14131
|
+
const controller = new AbortController();
|
|
14132
|
+
const onCallerAbort = () => controller.abort();
|
|
14133
|
+
params.signal?.addEventListener("abort", onCallerAbort, { once: true });
|
|
14134
|
+
const signal = controller.signal;
|
|
14135
|
+
try {
|
|
14136
|
+
const pageData = /* @__PURE__ */ new Map();
|
|
14137
|
+
const ownItems = [];
|
|
14138
|
+
const nullifiers = /* @__PURE__ */ new Set();
|
|
14139
|
+
let fullPassReason = null;
|
|
14140
|
+
const lateReference = (mint, leaf, value, seq) => {
|
|
14141
|
+
if (!cursor || seq < fullPassSeq) return null;
|
|
14142
|
+
const t = startTrees.get(mint);
|
|
14143
|
+
if (leaf < t.nextIndex) {
|
|
14144
|
+
if (leaf < t.windowStart) return "a later item refers to the tree before the cursor";
|
|
14145
|
+
if (value !== void 0 && value !== t.window[leaf - t.windowStart]) return "a later item rewrites the tree before the cursor";
|
|
14146
|
+
return null;
|
|
14147
|
+
}
|
|
14148
|
+
const held = t.pending.get(leaf);
|
|
14149
|
+
if (held !== void 0) return value !== void 0 && value !== held ? "a later item rewrites the tree before the cursor" : null;
|
|
14150
|
+
if (value !== void 0 && leaf < t.hiBefore) return "a later item fills the tree before the cursor";
|
|
14151
|
+
return null;
|
|
14152
|
+
};
|
|
14153
|
+
const chainAt = /* @__PURE__ */ new Map([[startPage, startChain]]);
|
|
14154
|
+
const waiting = /* @__PURE__ */ new Map();
|
|
14155
|
+
let chainNext = startPage;
|
|
14156
|
+
let chainError = null;
|
|
14157
|
+
let wakers = [];
|
|
14158
|
+
const wakeAll = () => {
|
|
14159
|
+
const w = wakers;
|
|
14160
|
+
wakers = [];
|
|
14161
|
+
for (const f of w) f();
|
|
14162
|
+
};
|
|
14163
|
+
signal.addEventListener("abort", wakeAll);
|
|
14164
|
+
const advanceChain = () => {
|
|
14165
|
+
while (!chainError && waiting.has(chainNext)) {
|
|
14166
|
+
const w = waiting.get(chainNext);
|
|
14167
|
+
waiting.delete(chainNext);
|
|
14168
|
+
const expected = chainAt.get(chainNext);
|
|
14169
|
+
if (w.prevChain !== expected) {
|
|
14170
|
+
chainError = cursor && chainNext === startPage ? new FullPassSignal("note index hash chain does not continue from the cursor") : new NoteIndexFormatError(`hash chain broken at page ${chainNext}`);
|
|
14171
|
+
controller.abort();
|
|
14172
|
+
return;
|
|
14173
|
+
}
|
|
14174
|
+
if (!w.complete) break;
|
|
14175
|
+
chainAt.set(chainNext + 1, toHex2(computeNoteIndexChain(fromHex(expected), w.bytes)));
|
|
14176
|
+
chainNext++;
|
|
14177
|
+
}
|
|
14178
|
+
wakeAll();
|
|
14179
|
+
};
|
|
14180
|
+
const workerCount = Math.max(1, Math.min(params.concurrency ?? DEFAULT_CONCURRENCY, pagesTotal - startPage));
|
|
14181
|
+
const lookahead = 2 * workerCount + 2;
|
|
14182
|
+
let nextToFetch = startPage;
|
|
14183
|
+
let pagesDone = 0;
|
|
14184
|
+
const worker = async () => {
|
|
14185
|
+
for (; ; ) {
|
|
14186
|
+
if (signal.aborted) throw abortError2();
|
|
14187
|
+
const pageNo = nextToFetch++;
|
|
14188
|
+
if (pageNo >= pagesTotal) return;
|
|
14189
|
+
while (pageNo - chainNext >= lookahead && !signal.aborted) await new Promise((resolve) => wakers.push(resolve));
|
|
14190
|
+
if (signal.aborted) throw abortError2();
|
|
14191
|
+
const bytes = await fetchNoteIndexPage(relayUrl, head.epoch, pageNo, { signal });
|
|
14192
|
+
stats.bytes += bytes.length;
|
|
14193
|
+
const page2 = parseNoteIndexPage(bytes, { epoch: head.epoch, page: pageNo }, { skipMalformedItems: true });
|
|
14194
|
+
if (pageNo < head.completePages && !page2.complete) {
|
|
14195
|
+
throw new NoteIndexFormatError(`page ${pageNo} is below complete_pages but not complete`);
|
|
14196
|
+
}
|
|
14197
|
+
stats.pages++;
|
|
14198
|
+
stats.skipped += page2.skippedMalformed;
|
|
14199
|
+
const seqOf = (i) => pageNo * NOTE_INDEX_PAGE_SIZE + page2.itemPositions[i];
|
|
14200
|
+
waiting.set(pageNo, { bytes: page2.complete ? bytes : new Uint8Array(0), prevChain: toHex2(page2.prevChain), complete: page2.complete });
|
|
14201
|
+
advanceChain();
|
|
14202
|
+
const data = { complete: page2.complete, leaves: /* @__PURE__ */ new Map() };
|
|
14203
|
+
const late = (reason) => {
|
|
14204
|
+
if (reason && !fullPassReason) {
|
|
14205
|
+
fullPassReason = reason;
|
|
14206
|
+
controller.abort();
|
|
14207
|
+
}
|
|
14208
|
+
};
|
|
14209
|
+
const addLeaf = (mintBytes, commitment, leaf, seq) => {
|
|
14210
|
+
if (isAllZero3(commitment)) return;
|
|
14211
|
+
const mint = addressFromBytes(mintBytes);
|
|
14212
|
+
if (!poolSet.has(mint)) return;
|
|
14213
|
+
const entry = { leaf: Number(leaf), commitment: bytesToBigint3(commitment) };
|
|
14214
|
+
late(lateReference(mint, entry.leaf, entry.commitment, seq));
|
|
14215
|
+
const list = data.leaves.get(mint);
|
|
14216
|
+
if (list) list.push(entry);
|
|
14217
|
+
else data.leaves.set(mint, [entry]);
|
|
14218
|
+
};
|
|
14219
|
+
page2.items.forEach((item, i) => {
|
|
14220
|
+
const seq = seqOf(i);
|
|
14221
|
+
if (item.kind === 1) {
|
|
14222
|
+
addLeaf(item.mint, item.comm0, item.leaf0, seq);
|
|
14223
|
+
addLeaf(item.mint, item.comm1, item.leaf1, seq);
|
|
14224
|
+
if (!isAllZero3(item.nullifier0)) nullifiers.add(toHex2(item.nullifier0));
|
|
14225
|
+
if (!isAllZero3(item.nullifier1)) nullifiers.add(toHex2(item.nullifier1));
|
|
14226
|
+
} else if (item.kind === 3) {
|
|
14227
|
+
addLeaf(item.mint, item.commitment, item.leaf, seq);
|
|
14228
|
+
} else {
|
|
14229
|
+
const mint = addressFromBytes(item.mint);
|
|
14230
|
+
if (poolSet.has(mint)) late(lateReference(mint, Number(item.leaf), void 0, seq));
|
|
14231
|
+
}
|
|
14232
|
+
});
|
|
14233
|
+
if (signal.aborted) throw abortError2();
|
|
14234
|
+
for (let i = 0; i < page2.items.length; i += ITEM_BATCH) {
|
|
14235
|
+
if (signal.aborted) throw abortError2();
|
|
14236
|
+
const batch = page2.items.slice(i, i + ITEM_BATCH);
|
|
14237
|
+
const opened = await Promise.all(batch.map((item) => trialItemIsolated(item, trials, stats)));
|
|
14238
|
+
opened.forEach((o, k) => {
|
|
14239
|
+
if (!o) return;
|
|
14240
|
+
stats.decrypted++;
|
|
14241
|
+
const raw = page2.rawItems[i + k];
|
|
14242
|
+
const id = itemIdentity(raw);
|
|
14243
|
+
if (rejectedIds.has(id)) {
|
|
14244
|
+
stats.dropped++;
|
|
14245
|
+
return;
|
|
14246
|
+
}
|
|
14247
|
+
ownItems.push({ page: pageNo, seq: seqOf(i + k), raw, id, item: batch[k], fromCursor: false, ...o, trial: o.trial });
|
|
14248
|
+
});
|
|
14249
|
+
stats.items += batch.length;
|
|
14250
|
+
}
|
|
14251
|
+
pageData.set(pageNo, data);
|
|
14252
|
+
pagesDone++;
|
|
14253
|
+
onProgress?.({ pagesDone, pagesTotal: pagesTotal - startPage, itemsChecked: stats.items, notesFound: ownItems.length });
|
|
14254
|
+
}
|
|
14255
|
+
};
|
|
14256
|
+
const workers = Array.from(
|
|
14257
|
+
{ length: workerCount },
|
|
14258
|
+
() => worker().catch((error) => {
|
|
14259
|
+
controller.abort();
|
|
14260
|
+
throw error;
|
|
14261
|
+
})
|
|
14262
|
+
);
|
|
14263
|
+
const settled = await Promise.allSettled(workers);
|
|
14264
|
+
signal.removeEventListener("abort", wakeAll);
|
|
14265
|
+
if (params.signal?.aborted) throw abortError2();
|
|
14266
|
+
const lateReason = fullPassReason;
|
|
14267
|
+
if (lateReason) return new FullPassSignal(lateReason);
|
|
14268
|
+
const chainFailure = chainError;
|
|
14269
|
+
if (chainFailure) {
|
|
14270
|
+
if (chainFailure instanceof FullPassSignal) return chainFailure;
|
|
14271
|
+
throw chainFailure;
|
|
14272
|
+
}
|
|
14273
|
+
const failure = settled.find((s) => s.status === "rejected" && s.reason?.name !== "AbortError") ?? settled.find((s) => s.status === "rejected");
|
|
14274
|
+
if (failure) throw failure.reason;
|
|
14275
|
+
if (head.completePages >= startPage && chainAt.get(head.completePages) !== head.chainTip) {
|
|
14276
|
+
if (cursor) return new FullPassSignal("note index hash chain does not reach the head's chain_tip");
|
|
14277
|
+
throw new NoteIndexFormatError("hash chain does not reach the head's chain_tip");
|
|
14278
|
+
}
|
|
14279
|
+
for (const entry of cursor?.items ?? []) {
|
|
14280
|
+
const o = await trialItemIsolated(entry.item, trials, stats);
|
|
14281
|
+
if (!o) continue;
|
|
14282
|
+
const page2 = Math.floor(entry.seq / NOTE_INDEX_PAGE_SIZE);
|
|
14283
|
+
ownItems.push({ page: page2, seq: entry.seq, raw: entry.raw, id: itemIdentity(entry.raw), item: entry.item, fromCursor: true, ...o, trial: o.trial });
|
|
14284
|
+
if (entry.item.kind === 1) {
|
|
14285
|
+
if (!isAllZero3(entry.item.nullifier0)) nullifiers.add(toHex2(entry.item.nullifier0));
|
|
14286
|
+
if (!isAllZero3(entry.item.nullifier1)) nullifiers.add(toHex2(entry.item.nullifier1));
|
|
14287
|
+
}
|
|
14288
|
+
}
|
|
14289
|
+
const knownSpent = cursor?.spent ?? /* @__PURE__ */ new Set();
|
|
14290
|
+
ownItems.sort((a, b) => a.seq - b.seq);
|
|
14291
|
+
const rejectedNow = /* @__PURE__ */ new Set();
|
|
14292
|
+
const skippedNow = /* @__PURE__ */ new Set();
|
|
14293
|
+
const allCandidates = await matchOwnItems(
|
|
14294
|
+
ownItems,
|
|
14295
|
+
owner,
|
|
14296
|
+
(o) => {
|
|
14297
|
+
stats.dropped++;
|
|
14298
|
+
rejectedNow.add(o.id);
|
|
14299
|
+
},
|
|
14300
|
+
(o) => {
|
|
14301
|
+
if (skippedNow.has(o)) return;
|
|
14302
|
+
skippedNow.add(o);
|
|
14303
|
+
stats.skipped++;
|
|
14304
|
+
}
|
|
14305
|
+
);
|
|
14306
|
+
stats.candidates = allCandidates.length;
|
|
14307
|
+
const cutoff = params.legacyCutoffLeaf ?? {};
|
|
14308
|
+
const candidates = allCandidates.filter((c) => {
|
|
14309
|
+
const limit = cutoff[c.mint];
|
|
14310
|
+
if (c.atRisk && limit !== void 0 && BigInt(c.leaf) >= limit) {
|
|
14311
|
+
stats.dropped++;
|
|
14312
|
+
return false;
|
|
14313
|
+
}
|
|
14314
|
+
return true;
|
|
14315
|
+
});
|
|
14316
|
+
const chainTrees = await ctx.readTrees();
|
|
14317
|
+
const orderedPages = Array.from(pageData.keys()).sort((a, b) => a - b);
|
|
14318
|
+
const replays = /* @__PURE__ */ new Map();
|
|
14319
|
+
for (let i = 0; i < poolMints.length; i++) {
|
|
14320
|
+
const mint = poolMints[i];
|
|
14321
|
+
const start = startTrees.get(mint);
|
|
14322
|
+
const chainTree = chainTrees[i] ?? null;
|
|
14323
|
+
const pages = orderedPages.map((page2) => ({ page: page2, entries: pageData.get(page2).leaves.get(mint) ?? [] }));
|
|
14324
|
+
let r = await replayStream(start, pages, start.overrides, chainTree, targetPage);
|
|
14325
|
+
let overrides = start.overrides;
|
|
14326
|
+
stats.conflicts += r.conflicts;
|
|
14327
|
+
if (r.corrections.size > 0 && (r.mismatch || r.verifiedPrefix < r.endCount)) {
|
|
14328
|
+
const merged = new Map([...start.overrides, ...r.corrections]);
|
|
14329
|
+
const alternative = await replayStream(start, pages, merged, chainTree, targetPage);
|
|
14330
|
+
if (alternative.verifiedPrefix > r.verifiedPrefix || r.mismatch && !alternative.mismatch) {
|
|
14331
|
+
r = alternative;
|
|
14332
|
+
overrides = merged;
|
|
14333
|
+
}
|
|
14334
|
+
}
|
|
14335
|
+
if (r.mismatch && cursor && !start.mismatch) return new FullPassSignal("a rebuilt tree disagrees with the chain");
|
|
14336
|
+
replays.set(mint, { r, overrides });
|
|
14337
|
+
}
|
|
14338
|
+
const verifiedUpTo = (mint) => Math.max(startTrees.get(mint).verified, replays.get(mint).r.verifiedPrefix);
|
|
14339
|
+
const streamValue = (mint, leaf) => {
|
|
14340
|
+
const v = replays.get(mint)?.r.valueAt(leaf);
|
|
14341
|
+
if (v !== void 0) return v;
|
|
14342
|
+
const carried = cursor?.pendingLeaves.get(`${mint}:${leaf}`);
|
|
14343
|
+
if (carried !== void 0) return carried;
|
|
14344
|
+
const t = startTrees.get(mint);
|
|
14345
|
+
if (t && leaf >= t.windowStart && leaf < t.nextIndex) return t.window[leaf - t.windowStart];
|
|
14346
|
+
return void 0;
|
|
14347
|
+
};
|
|
14348
|
+
const knownVerified = cursor?.verified ?? /* @__PURE__ */ new Set();
|
|
14349
|
+
const verified = [];
|
|
14350
|
+
const pendingByKey = /* @__PURE__ */ new Map();
|
|
14351
|
+
const rejectedCandidates = /* @__PURE__ */ new Set();
|
|
14352
|
+
const outcomeOf = /* @__PURE__ */ new Map();
|
|
14353
|
+
const tally = (c, what) => {
|
|
14354
|
+
const t = outcomeOf.get(c.seq) ?? { kept: false, rejected: 0, total: 0 };
|
|
14355
|
+
t.total++;
|
|
14356
|
+
if (what === "kept") t.kept = true;
|
|
14357
|
+
if (what === "rejected") t.rejected++;
|
|
14358
|
+
outcomeOf.set(c.seq, t);
|
|
14359
|
+
};
|
|
14360
|
+
const pend = (c, rank) => {
|
|
14361
|
+
const key = verifiedKey(c.mint, c.leaf, c.commitment);
|
|
14362
|
+
const prior = pendingByKey.get(key);
|
|
14363
|
+
if (!prior || prior.c.seq > c.seq) pendingByKey.set(key, { c, rank });
|
|
14364
|
+
};
|
|
14365
|
+
for (const c of candidates) {
|
|
14366
|
+
if (knownVerified.has(verifiedKey(c.mint, c.leaf, c.commitment))) {
|
|
14367
|
+
verified.push(c);
|
|
14368
|
+
continue;
|
|
14369
|
+
}
|
|
14370
|
+
if (!poolSet.has(c.mint)) {
|
|
14371
|
+
pend(c, 3);
|
|
14372
|
+
continue;
|
|
14373
|
+
}
|
|
14374
|
+
const value = streamValue(c.mint, c.leaf);
|
|
14375
|
+
if (value === void 0) {
|
|
14376
|
+
if (c.leaf < startTrees.get(c.mint).nextIndex) {
|
|
14377
|
+
stats.dropped++;
|
|
14378
|
+
tally(c, "other");
|
|
14379
|
+
} else pend(c, 1);
|
|
14380
|
+
} else if (c.leaf >= verifiedUpTo(c.mint)) {
|
|
14381
|
+
pend(c, value === c.commitment ? 0 : 2);
|
|
14382
|
+
} else if (value === c.commitment) {
|
|
14383
|
+
verified.push(c);
|
|
14384
|
+
} else {
|
|
14385
|
+
stats.dropped++;
|
|
14386
|
+
rejectedCandidates.add(c);
|
|
14387
|
+
tally(c, "rejected");
|
|
14388
|
+
}
|
|
14389
|
+
}
|
|
14390
|
+
verified.sort((a, b) => a.seq - b.seq);
|
|
14391
|
+
const byLeaf = /* @__PURE__ */ new Map();
|
|
14392
|
+
for (const c of verified) {
|
|
14393
|
+
const key = `${c.mint}:${c.leaf}`;
|
|
14394
|
+
if (byLeaf.has(key)) {
|
|
14395
|
+
stats.dropped++;
|
|
14396
|
+
tally(c, "other");
|
|
14397
|
+
continue;
|
|
14398
|
+
}
|
|
14399
|
+
byLeaf.set(key, c);
|
|
14400
|
+
}
|
|
14401
|
+
const notes = [];
|
|
14402
|
+
const atRisk = [];
|
|
14403
|
+
const spentOut = new Set(knownSpent);
|
|
14404
|
+
const verifiedOut = new Set(knownVerified);
|
|
14405
|
+
const keyChecked = /* @__PURE__ */ new Map();
|
|
14406
|
+
for (const c of byLeaf.values()) {
|
|
14407
|
+
const pubOk = keyChecked.get(c.keypair.privateKey) ?? (c.keypair.privateKey !== 0n && await derivePublicKey(c.keypair.privateKey) === c.keypair.publicKey);
|
|
14408
|
+
keyChecked.set(c.keypair.privateKey, pubOk);
|
|
14409
|
+
const ownerOk = c.keypair.publicKey === owner.publicKey || c.kind === "swap_refund";
|
|
14410
|
+
if (!pubOk || !c.atRisk && !ownerOk) {
|
|
14411
|
+
stats.dropped++;
|
|
14412
|
+
tally(c, "rejected");
|
|
14413
|
+
continue;
|
|
14414
|
+
}
|
|
14415
|
+
tally(c, "kept");
|
|
14416
|
+
verifiedOut.add(verifiedKey(c.mint, c.leaf, c.commitment));
|
|
14417
|
+
const utxo = {
|
|
14418
|
+
amount: c.amount,
|
|
14419
|
+
keypair: c.atRisk || c.kind === "swap_refund" ? { ...c.keypair } : owner,
|
|
14420
|
+
blinding: c.blinding,
|
|
14421
|
+
mintAddress: c.mint,
|
|
14422
|
+
index: c.leaf,
|
|
14423
|
+
commitment: c.commitment
|
|
14424
|
+
};
|
|
14425
|
+
if (nullifiers.has(c.nullifier) || knownSpent.has(c.nullifier)) {
|
|
14426
|
+
stats.spent++;
|
|
14427
|
+
spentOut.add(c.nullifier);
|
|
14428
|
+
continue;
|
|
14429
|
+
}
|
|
14430
|
+
const note = {
|
|
14431
|
+
kind: c.kind,
|
|
14432
|
+
utxo,
|
|
14433
|
+
signature: bs584.encode(c.signature),
|
|
14434
|
+
legacyExposed: c.atRisk
|
|
14435
|
+
};
|
|
14436
|
+
(c.atRisk ? atRisk : notes).push(note);
|
|
14437
|
+
}
|
|
14438
|
+
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);
|
|
14439
|
+
sortNotes(notes);
|
|
14440
|
+
sortNotes(atRisk);
|
|
14441
|
+
const pendingList = Array.from(pendingByKey.values()).sort((a, b) => a.rank - b.rank || a.c.seq - b.c.seq);
|
|
14442
|
+
const carriedPending = pendingList.slice(0, MAX_CARRIED_PENDING).map((p) => p.c);
|
|
14443
|
+
const overflow = pendingList.length - carriedPending.length;
|
|
14444
|
+
if (overflow > 0) {
|
|
14445
|
+
stats.pendingDropped += overflow;
|
|
14446
|
+
ctx.warnings.push(`${overflow} unverified candidates over the carry limit were not carried to the next run`);
|
|
14447
|
+
}
|
|
14448
|
+
for (const { c } of pendingList) if (nullifiers.has(c.nullifier)) spentOut.add(c.nullifier);
|
|
14449
|
+
for (const c of carriedPending) tally(c, "kept");
|
|
14450
|
+
for (const { c } of pendingList.slice(MAX_CARRIED_PENDING)) tally(c, "other");
|
|
14451
|
+
let page = targetPage;
|
|
14452
|
+
for (const { r } of replays.values()) if (r.snapshot === null) page = startPage;
|
|
14453
|
+
const trees = {};
|
|
14454
|
+
const treeEnd = /* @__PURE__ */ new Map();
|
|
14455
|
+
for (const mint of poolMints) {
|
|
14456
|
+
const start = startTrees.get(mint);
|
|
14457
|
+
const { r, overrides } = replays.get(mint);
|
|
14458
|
+
const snap = page === startPage ? { frontier: start.frontier ?? (await MerkleFrontier.create()).toState(), pending: start.pending, nextIndex: start.nextIndex } : r.snapshot;
|
|
14459
|
+
const n = snap.nextIndex;
|
|
14460
|
+
const window2 = [];
|
|
14461
|
+
for (let leaf = n - 1; leaf >= Math.max(0, n - LEAF_WINDOW); leaf--) {
|
|
14462
|
+
const v = leaf >= start.nextIndex ? r.valueAt(leaf) : leaf >= start.windowStart ? start.window[leaf - start.windowStart] : void 0;
|
|
14463
|
+
if (v === void 0) break;
|
|
14464
|
+
window2.push(hex32(v));
|
|
14465
|
+
}
|
|
14466
|
+
window2.reverse();
|
|
14467
|
+
trees[mint] = {
|
|
14468
|
+
frontier: snap.frontier,
|
|
14469
|
+
pending: Array.from(snap.pending.entries(), ([leaf, v]) => [leaf, hex32(v)]).sort((a, b) => a[0] - b[0]),
|
|
14470
|
+
window: window2.join(""),
|
|
14471
|
+
verified: Math.min(verifiedUpTo(mint), n),
|
|
14472
|
+
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)]),
|
|
14473
|
+
mismatch: r.mismatch
|
|
14474
|
+
};
|
|
14475
|
+
treeEnd.set(mint, { nextIndex: n, pending: snap.pending });
|
|
14476
|
+
}
|
|
14477
|
+
const pendingLeaves = [];
|
|
14478
|
+
const pendingLeafSeen = /* @__PURE__ */ new Set();
|
|
14479
|
+
for (const c of carriedPending) {
|
|
14480
|
+
const end = treeEnd.get(c.mint);
|
|
14481
|
+
if (!end || c.leaf >= end.nextIndex) continue;
|
|
14482
|
+
const value = streamValue(c.mint, c.leaf);
|
|
14483
|
+
const key = `${c.mint}:${c.leaf}`;
|
|
14484
|
+
if (value === void 0 || pendingLeafSeen.has(key)) continue;
|
|
14485
|
+
pendingLeafSeen.add(key);
|
|
14486
|
+
pendingLeaves.push([c.mint, c.leaf, hex32(value)]);
|
|
14487
|
+
}
|
|
14488
|
+
const keptItems = [];
|
|
14489
|
+
const keptIds = /* @__PURE__ */ new Set();
|
|
14490
|
+
for (const o of ownItems) {
|
|
14491
|
+
const t = outcomeOf.get(o.seq);
|
|
14492
|
+
if (rejectedNow.has(o.id) || t && t.total > 0 && t.rejected === t.total) {
|
|
14493
|
+
rejectedNow.add(o.id);
|
|
14494
|
+
continue;
|
|
14495
|
+
}
|
|
14496
|
+
if (o.page >= page || !t?.kept || keptIds.has(o.id)) continue;
|
|
14497
|
+
keptIds.add(o.id);
|
|
14498
|
+
keptItems.push({ seq: o.seq, item: toHex2(o.raw) });
|
|
14499
|
+
}
|
|
14500
|
+
const rejected = Array.from(/* @__PURE__ */ new Set([...cursor?.rejected ?? [], ...rejectedNow]));
|
|
14501
|
+
const nextCursor = {
|
|
14502
|
+
v: CURSOR_VERSION,
|
|
14503
|
+
epoch: head.epoch.toString(10),
|
|
14504
|
+
page,
|
|
14505
|
+
chain: chainAt.get(page) ?? startChain,
|
|
14506
|
+
watermark: Math.max(cursor?.raw.watermark ?? 0, head.watermark),
|
|
14507
|
+
fullPassSeq: cursor ? fullPassSeq : head.watermark,
|
|
14508
|
+
trees,
|
|
14509
|
+
own: {
|
|
14510
|
+
items: keptItems,
|
|
14511
|
+
verified: Array.from(verifiedOut),
|
|
14512
|
+
spent: Array.from(spentOut),
|
|
14513
|
+
pendingLeaves,
|
|
14514
|
+
rejected: rejected.slice(Math.max(0, rejected.length - MAX_REJECTED_IDS))
|
|
14515
|
+
}
|
|
14516
|
+
};
|
|
14517
|
+
return { notes, atRisk, pending: pendingByKey.size, cursor: nextCursor };
|
|
14518
|
+
} finally {
|
|
14519
|
+
params.signal?.removeEventListener("abort", onCallerAbort);
|
|
14520
|
+
}
|
|
14521
|
+
}
|
|
14522
|
+
|
|
12498
14523
|
// src/wallet/utxo-wallet.ts
|
|
12499
14524
|
init_address();
|
|
12500
14525
|
init_utxo();
|
|
@@ -12836,6 +14861,43 @@ function signerFromWalletAdapter(adapter, options = {}) {
|
|
|
12836
14861
|
}
|
|
12837
14862
|
return signer;
|
|
12838
14863
|
}
|
|
14864
|
+
function signerFromTransactionBytes(wallet) {
|
|
14865
|
+
const walletAddress = wallet.address;
|
|
14866
|
+
const signer = {
|
|
14867
|
+
address: walletAddress,
|
|
14868
|
+
async modifyAndSignTransactions(transactions) {
|
|
14869
|
+
const out = [];
|
|
14870
|
+
for (const transaction of transactions) {
|
|
14871
|
+
const signedBytes = await wallet.signTransaction(transactionBytes(transaction));
|
|
14872
|
+
const decoded = transactionFromBytes(signedBytes);
|
|
14873
|
+
if (!bytesEqual2(new Uint8Array(decoded.messageBytes), new Uint8Array(transaction.messageBytes))) {
|
|
14874
|
+
throw new Error("Wallet returned a transaction whose message differs from the one it was asked to sign");
|
|
14875
|
+
}
|
|
14876
|
+
if (!decoded.signatures[walletAddress]) {
|
|
14877
|
+
throw new Error("Wallet returned a transaction without its own signature");
|
|
14878
|
+
}
|
|
14879
|
+
out.push({ ...transaction, signatures: { ...transaction.signatures, ...decoded.signatures } });
|
|
14880
|
+
}
|
|
14881
|
+
return out;
|
|
14882
|
+
}
|
|
14883
|
+
};
|
|
14884
|
+
if (wallet.signMessage) {
|
|
14885
|
+
const signMessage = wallet.signMessage;
|
|
14886
|
+
Object.assign(signer, {
|
|
14887
|
+
async signMessages(messages) {
|
|
14888
|
+
const dictionaries = [];
|
|
14889
|
+
for (const message of messages) dictionaries.push({ [walletAddress]: await signMessage(message.content) });
|
|
14890
|
+
return dictionaries;
|
|
14891
|
+
}
|
|
14892
|
+
});
|
|
14893
|
+
}
|
|
14894
|
+
return signer;
|
|
14895
|
+
}
|
|
14896
|
+
function bytesEqual2(a, b) {
|
|
14897
|
+
if (a.length !== b.length) return false;
|
|
14898
|
+
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
|
|
14899
|
+
return true;
|
|
14900
|
+
}
|
|
12839
14901
|
async function loadWeb3() {
|
|
12840
14902
|
const name = "@solana/web3.js";
|
|
12841
14903
|
try {
|
|
@@ -13703,13 +15765,13 @@ var DoNotRetry = class extends Error {
|
|
|
13703
15765
|
};
|
|
13704
15766
|
async function withShieldRetries(attempt, hooks = {}) {
|
|
13705
15767
|
const attempts = hooks.attempts ?? 3;
|
|
13706
|
-
const
|
|
15768
|
+
const sleep5 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
13707
15769
|
let last = "";
|
|
13708
15770
|
for (let n = 1; n <= attempts; n++) {
|
|
13709
15771
|
if (n > 1) {
|
|
13710
15772
|
const delay = retryDelayMs(n);
|
|
13711
15773
|
hooks.onRetry?.(n, delay, last);
|
|
13712
|
-
await
|
|
15774
|
+
await sleep5(delay);
|
|
13713
15775
|
}
|
|
13714
15776
|
try {
|
|
13715
15777
|
return await attempt(n);
|
|
@@ -13758,6 +15820,10 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
13758
15820
|
MemoryStorageAdapter,
|
|
13759
15821
|
MerkleTree,
|
|
13760
15822
|
NATIVE_SOL_MINT,
|
|
15823
|
+
NOTE_INDEX_NO_LEAF,
|
|
15824
|
+
NOTE_INDEX_PAGE_SIZE,
|
|
15825
|
+
NoteIndexFormatError,
|
|
15826
|
+
NoteIndexHeadBehindError,
|
|
13761
15827
|
ONECLICK_PUBKEY_B58,
|
|
13762
15828
|
RECIPIENT_DELIVERY_CIPHERTEXT_LEN,
|
|
13763
15829
|
RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
|
|
@@ -13834,6 +15900,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
13834
15900
|
computeChainNoteHash,
|
|
13835
15901
|
computeExtDataHash,
|
|
13836
15902
|
computeMerkleRoot,
|
|
15903
|
+
computeNoteIndexChain,
|
|
13837
15904
|
computeProofForLatestDeposit,
|
|
13838
15905
|
computeProofFromChain,
|
|
13839
15906
|
computeSignature,
|
|
@@ -13870,6 +15937,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
13870
15937
|
deriveSpendKey,
|
|
13871
15938
|
deriveSwapRefundAuthorization,
|
|
13872
15939
|
deriveSwapRefundBlinding,
|
|
15940
|
+
deriveSwapRefundKeypair,
|
|
13873
15941
|
deriveUserCompliancePublicKey,
|
|
13874
15942
|
deriveUserComplianceScalar,
|
|
13875
15943
|
deriveUtxoKeypairFromSpendKey,
|
|
@@ -13882,6 +15950,8 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
13882
15950
|
discoverSwapRefunds,
|
|
13883
15951
|
downloadNote,
|
|
13884
15952
|
encodeDeliveryCarrierMemo,
|
|
15953
|
+
encodeNoteIndexItem,
|
|
15954
|
+
encodeNoteIndexPage,
|
|
13885
15955
|
encodeNoteSimple,
|
|
13886
15956
|
encodeRecipientDeliveryNote,
|
|
13887
15957
|
encryptCompactChainNote,
|
|
@@ -13897,6 +15967,8 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
13897
15967
|
fetchCommitments,
|
|
13898
15968
|
fetchLatestBlockhash,
|
|
13899
15969
|
fetchLookupTables,
|
|
15970
|
+
fetchNoteIndexHead,
|
|
15971
|
+
fetchNoteIndexPage,
|
|
13900
15972
|
fetchRiskQuoteInstruction,
|
|
13901
15973
|
fetchRiskQuoteIx,
|
|
13902
15974
|
fetchSignaturesForAddress,
|
|
@@ -13969,6 +16041,8 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
13969
16041
|
parseDeliveryCarrierMemo,
|
|
13970
16042
|
parseError,
|
|
13971
16043
|
parseNote,
|
|
16044
|
+
parseNoteIndexItem,
|
|
16045
|
+
parseNoteIndexPage,
|
|
13972
16046
|
parseRelayErrorResponse,
|
|
13973
16047
|
parseRelayErrorSignature,
|
|
13974
16048
|
parseTransactionError,
|
|
@@ -13990,6 +16064,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
13990
16064
|
readMerkleTreeState,
|
|
13991
16065
|
readRent,
|
|
13992
16066
|
recipientDeliveryNoteToBase64,
|
|
16067
|
+
recoverNotesFromIndex,
|
|
13993
16068
|
registerViewingKey,
|
|
13994
16069
|
relayRequestDigestHex,
|
|
13995
16070
|
removePendingDeposit,
|
|
@@ -14018,6 +16093,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
14018
16093
|
signTransaction,
|
|
14019
16094
|
signerFromKeypair,
|
|
14020
16095
|
signerFromSecretKey,
|
|
16096
|
+
signerFromTransactionBytes,
|
|
14021
16097
|
signerFromWalletAdapter,
|
|
14022
16098
|
splitTo2Limbs,
|
|
14023
16099
|
submitTransactToRelay,
|