@cloak.dev/sdk 0.2.6-staging.6c85601 → 0.2.6-staging.abb3ae6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +171 -0
- package/README.md +190 -43
- package/dist/index.cjs +2477 -230
- package/dist/index.d.cts +786 -154
- package/dist/index.d.ts +786 -154
- package/dist/index.js +2457 -235
- package/package.json +2 -1
package/dist/index.cjs
CHANGED
|
@@ -577,6 +577,7 @@ var index_exports = {};
|
|
|
577
577
|
__export(index_exports, {
|
|
578
578
|
AccountRole: () => import_kit7.AccountRole,
|
|
579
579
|
BRIDGE_ESCROW_LABEL: () => BRIDGE_ESCROW_LABEL,
|
|
580
|
+
BRIDGE_ESCROW_LABEL_V2: () => BRIDGE_ESCROW_LABEL_V2,
|
|
580
581
|
BUILD_ALLOWS_LOCAL_ENDPOINTS: () => BUILD_ALLOWS_LOCAL_ENDPOINTS,
|
|
581
582
|
CHAIN_NOTE_SALT_BITS: () => CHAIN_NOTE_SALT_BITS,
|
|
582
583
|
CLEANUP_FEE_BUDGET: () => CLEANUP_FEE_BUDGET,
|
|
@@ -605,6 +606,10 @@ __export(index_exports, {
|
|
|
605
606
|
MemoryStorageAdapter: () => MemoryStorageAdapter,
|
|
606
607
|
MerkleTree: () => MerkleTree,
|
|
607
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,
|
|
608
613
|
ONECLICK_PUBKEY_B58: () => ONECLICK_PUBKEY_B58,
|
|
609
614
|
RECIPIENT_DELIVERY_CIPHERTEXT_LEN: () => RECIPIENT_DELIVERY_CIPHERTEXT_LEN,
|
|
610
615
|
RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN: () => RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
|
|
@@ -681,6 +686,7 @@ __export(index_exports, {
|
|
|
681
686
|
computeChainNoteHash: () => computeChainNoteHash,
|
|
682
687
|
computeExtDataHash: () => computeExtDataHash,
|
|
683
688
|
computeMerkleRoot: () => computeMerkleRoot,
|
|
689
|
+
computeNoteIndexChain: () => computeNoteIndexChain,
|
|
684
690
|
computeProofForLatestDeposit: () => computeProofForLatestDeposit,
|
|
685
691
|
computeProofFromChain: () => computeProofFromChain,
|
|
686
692
|
computeSignature: () => computeSignature,
|
|
@@ -705,14 +711,18 @@ __export(index_exports, {
|
|
|
705
711
|
depositFromDerivedKey: () => depositFromDerivedKey,
|
|
706
712
|
deriveBridgeReceiver: () => deriveBridgeReceiver,
|
|
707
713
|
deriveChangeNoteBlinding: () => deriveChangeNoteBlinding,
|
|
708
|
-
|
|
714
|
+
deriveDepositNoteBlinding: () => deriveDepositNoteBlinding,
|
|
709
715
|
deriveDiversifiedViewingKey: () => deriveDiversifiedViewingKey,
|
|
710
716
|
deriveDiversifier: () => deriveDiversifier,
|
|
711
717
|
deriveFundingTargets: () => deriveFundingTargets,
|
|
712
718
|
deriveInputNullifierPdas: () => deriveInputNullifierPdas,
|
|
719
|
+
deriveLegacyBridgeReceiver: () => deriveLegacyBridgeReceiver,
|
|
720
|
+
deriveLegacyDepositNoteSecrets: () => deriveLegacyDepositNoteSecrets,
|
|
721
|
+
deriveLegacySwapRefundAuthorization: () => deriveLegacySwapRefundAuthorization,
|
|
713
722
|
derivePublicKey: () => derivePublicKey,
|
|
714
723
|
deriveSpendKey: () => deriveSpendKey,
|
|
715
724
|
deriveSwapRefundAuthorization: () => deriveSwapRefundAuthorization,
|
|
725
|
+
deriveSwapRefundBlinding: () => deriveSwapRefundBlinding,
|
|
716
726
|
deriveUserCompliancePublicKey: () => deriveUserCompliancePublicKey,
|
|
717
727
|
deriveUserComplianceScalar: () => deriveUserComplianceScalar,
|
|
718
728
|
deriveUtxoKeypairFromSpendKey: () => deriveUtxoKeypairFromSpendKey,
|
|
@@ -725,6 +735,8 @@ __export(index_exports, {
|
|
|
725
735
|
discoverSwapRefunds: () => discoverSwapRefunds,
|
|
726
736
|
downloadNote: () => downloadNote,
|
|
727
737
|
encodeDeliveryCarrierMemo: () => encodeDeliveryCarrierMemo,
|
|
738
|
+
encodeNoteIndexItem: () => encodeNoteIndexItem,
|
|
739
|
+
encodeNoteIndexPage: () => encodeNoteIndexPage,
|
|
728
740
|
encodeNoteSimple: () => encodeNoteSimple,
|
|
729
741
|
encodeRecipientDeliveryNote: () => encodeRecipientDeliveryNote,
|
|
730
742
|
encryptCompactChainNote: () => encryptCompactChainNote,
|
|
@@ -740,6 +752,8 @@ __export(index_exports, {
|
|
|
740
752
|
fetchCommitments: () => fetchCommitments,
|
|
741
753
|
fetchLatestBlockhash: () => fetchLatestBlockhash,
|
|
742
754
|
fetchLookupTables: () => fetchLookupTables,
|
|
755
|
+
fetchNoteIndexHead: () => fetchNoteIndexHead,
|
|
756
|
+
fetchNoteIndexPage: () => fetchNoteIndexPage,
|
|
743
757
|
fetchRiskQuoteInstruction: () => fetchRiskQuoteInstruction,
|
|
744
758
|
fetchRiskQuoteIx: () => fetchRiskQuoteIx,
|
|
745
759
|
fetchSignaturesForAddress: () => fetchSignaturesForAddress,
|
|
@@ -812,6 +826,8 @@ __export(index_exports, {
|
|
|
812
826
|
parseDeliveryCarrierMemo: () => parseDeliveryCarrierMemo,
|
|
813
827
|
parseError: () => parseError,
|
|
814
828
|
parseNote: () => parseNote2,
|
|
829
|
+
parseNoteIndexItem: () => parseNoteIndexItem,
|
|
830
|
+
parseNoteIndexPage: () => parseNoteIndexPage,
|
|
815
831
|
parseRelayErrorResponse: () => parseRelayErrorResponse,
|
|
816
832
|
parseRelayErrorSignature: () => parseRelayErrorSignature,
|
|
817
833
|
parseTransactionError: () => parseTransactionError,
|
|
@@ -833,6 +849,7 @@ __export(index_exports, {
|
|
|
833
849
|
readMerkleTreeState: () => readMerkleTreeState,
|
|
834
850
|
readRent: () => readRent,
|
|
835
851
|
recipientDeliveryNoteToBase64: () => recipientDeliveryNoteToBase64,
|
|
852
|
+
recoverNotesFromIndex: () => recoverNotesFromIndex,
|
|
836
853
|
registerViewingKey: () => registerViewingKey,
|
|
837
854
|
relayRequestDigestHex: () => relayRequestDigestHex,
|
|
838
855
|
removePendingDeposit: () => removePendingDeposit,
|
|
@@ -1622,6 +1639,44 @@ function isLoopbackHost(value) {
|
|
|
1622
1639
|
}
|
|
1623
1640
|
var BUILD_ALLOWS_LOCAL_ENDPOINTS = RELAY_ORIGIN_ALLOWLIST.some(isLoopbackHost);
|
|
1624
1641
|
|
|
1642
|
+
// src/relay/clock.ts
|
|
1643
|
+
var RELAY_SERVER_TIME_HEADER = "x-cloak-server-time";
|
|
1644
|
+
var MAX_CLOCK_DIVERGENCE_MS = 2e3;
|
|
1645
|
+
var MAX_PLAUSIBLE_OFFSET_MS = 24 * 60 * 60 * 1e3;
|
|
1646
|
+
var sample = null;
|
|
1647
|
+
function monotonicNowMs() {
|
|
1648
|
+
const perf = globalThis.performance;
|
|
1649
|
+
return typeof perf?.now === "function" ? perf.now() : Date.now();
|
|
1650
|
+
}
|
|
1651
|
+
function observeRelayClock(response) {
|
|
1652
|
+
const raw = response?.headers?.get?.(RELAY_SERVER_TIME_HEADER);
|
|
1653
|
+
if (typeof raw !== "string" || !/^\d{1,16}$/.test(raw.trim())) return;
|
|
1654
|
+
const serverMs = Number(raw.trim());
|
|
1655
|
+
const wallMs = Date.now();
|
|
1656
|
+
const offsetMs = serverMs - wallMs;
|
|
1657
|
+
if (!Number.isSafeInteger(serverMs) || Math.abs(offsetMs) > MAX_PLAUSIBLE_OFFSET_MS) return;
|
|
1658
|
+
sample = { offsetMs, wallAtSampleMs: wallMs, monoAtSampleMs: monotonicNowMs() };
|
|
1659
|
+
}
|
|
1660
|
+
function relayNowMs() {
|
|
1661
|
+
const wallMs = Date.now();
|
|
1662
|
+
if (!sample) return wallMs;
|
|
1663
|
+
const wallElapsed = wallMs - sample.wallAtSampleMs;
|
|
1664
|
+
const monoElapsed = monotonicNowMs() - sample.monoAtSampleMs;
|
|
1665
|
+
if (Math.abs(wallElapsed - monoElapsed) > MAX_CLOCK_DIVERGENCE_MS) {
|
|
1666
|
+
sample = null;
|
|
1667
|
+
return wallMs;
|
|
1668
|
+
}
|
|
1669
|
+
return wallMs + sample.offsetMs;
|
|
1670
|
+
}
|
|
1671
|
+
function hasRelayClockSample() {
|
|
1672
|
+
if (!sample) return false;
|
|
1673
|
+
relayNowMs();
|
|
1674
|
+
return sample !== null;
|
|
1675
|
+
}
|
|
1676
|
+
function relayNowSeconds() {
|
|
1677
|
+
return Math.floor(relayNowMs() / 1e3);
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1625
1680
|
// src/relay/endpoint.ts
|
|
1626
1681
|
var ALLOWED_ORIGINS = new Set(
|
|
1627
1682
|
RELAY_ORIGIN_ALLOWLIST.map((entry) => {
|
|
@@ -1673,8 +1728,9 @@ function assertAllowedRelayOrigin(value) {
|
|
|
1673
1728
|
async function relayFetch(url, init, options) {
|
|
1674
1729
|
assertAllowedRelayOrigin(url);
|
|
1675
1730
|
const extra = sanitizeExtraHeaders(options?.extraHeaders);
|
|
1676
|
-
|
|
1677
|
-
|
|
1731
|
+
const response = extra ? await fetch(url, { ...init, headers: mergeRelayHeaders(init?.headers, extra) }) : await fetch(url, init);
|
|
1732
|
+
if (options?.observeClock !== false) observeRelayClock(response);
|
|
1733
|
+
return response;
|
|
1678
1734
|
}
|
|
1679
1735
|
var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
1680
1736
|
var FORBIDDEN_HEADER_VALUE_CHARS = /[\r\n\0]/;
|
|
@@ -2144,7 +2200,7 @@ ${digest}`
|
|
|
2144
2200
|
}
|
|
2145
2201
|
function buildRelayAuthPreimage(endpoint, programId, body, sender, nowSeconds, fields = TRANSACT_AUTH_FIELDS) {
|
|
2146
2202
|
const senderB58 = sender;
|
|
2147
|
-
const issuedAt = String(nowSeconds ??
|
|
2203
|
+
const issuedAt = String(nowSeconds ?? relayNowSeconds());
|
|
2148
2204
|
const nonce = randomNonceUuid();
|
|
2149
2205
|
const request = buildAuthRequest({ ...body, sender: senderB58 }, senderB58, fields);
|
|
2150
2206
|
const message = buildRequestAuthMessage(endpoint, programId, issuedAt, nonce, request);
|
|
@@ -2223,7 +2279,7 @@ function assertApprovalWithinFreshnessWindow(elapsedMs, maxAgeSeconds = REQUEST_
|
|
|
2223
2279
|
`The wallet approval took ${Math.round(elapsedSeconds)} seconds, and Cloak requests stay valid for ${maxAgeSeconds} seconds from the moment they are signed (${RELAY_AUTH_APPROVAL_MARGIN_SECONDS} of those are held back for the request to reach the network). The timestamp is inside the signature, so it cannot be refreshed without your approval again. NOTHING WAS SUBMITTED and no funds moved. Start the same operation again and approve the prompt when it appears.`
|
|
2224
2280
|
);
|
|
2225
2281
|
}
|
|
2226
|
-
function explainRelayAuthRejection(responseText) {
|
|
2282
|
+
function explainRelayAuthRejection(responseText, context) {
|
|
2227
2283
|
const text = String(responseText);
|
|
2228
2284
|
const has = (needle) => text.includes(needle);
|
|
2229
2285
|
if (has("issued too far in the future")) {
|
|
@@ -2233,7 +2289,9 @@ function explainRelayAuthRejection(responseText) {
|
|
|
2233
2289
|
return `The request was signed more than ${REQUEST_AUTH_MAX_AGE_SECONDS} seconds before it arrived, usually because a wallet approval was left waiting, or because this computer's clock is running behind. The signed timestamp cannot be refreshed on its own. Start the operation again. Nothing was submitted.`;
|
|
2234
2290
|
}
|
|
2235
2291
|
if (has("does not match the exact request")) {
|
|
2236
|
-
|
|
2292
|
+
const base = `The request body changed after it was signed, so the relay's digest and this one disagree. Sign the exact body that is POSTed, and re-POST a retry byte for byte rather than rebuilding it. If this is a hand-built swap call, check that every field in TRANSACT_SWAP_AUTH_FIELDS is present, including \`slippage_bps\`.`;
|
|
2293
|
+
if (!context?.carriedAffiliateCode) return base;
|
|
2294
|
+
return `${base} This request carried \`affiliate_code\`, which is signed with the rest of the body. A relay that predates the affiliate release (REL-010/REL-011) ignores that field and leaves it out of its digest, which produces exactly this mismatch. Upgrade the relay, or send the request without \`affiliateCode\`.`;
|
|
2237
2295
|
}
|
|
2238
2296
|
if (has("has no registered viewing key")) {
|
|
2239
2297
|
return `The signature was accepted, so this is not a signing problem: the wallet that signed has no viewing key registered with Cloak yet. Register one first, or let the SDK do it by leaving \`enforceViewingKeyRegistration\` on and supplying the viewing key.`;
|
|
@@ -2755,6 +2813,14 @@ function isSubmissionOutcomeUnknownResponse(responseText) {
|
|
|
2755
2813
|
return false;
|
|
2756
2814
|
}
|
|
2757
2815
|
}
|
|
2816
|
+
function isRelayRequestInFlightResponse(responseText) {
|
|
2817
|
+
try {
|
|
2818
|
+
const parsed = JSON.parse(responseText);
|
|
2819
|
+
return parsed?.code === "transient_upstream" && typeof parsed.message === "string" && parsed.message.includes("is already processing");
|
|
2820
|
+
} catch {
|
|
2821
|
+
return false;
|
|
2822
|
+
}
|
|
2823
|
+
}
|
|
2758
2824
|
function classifyRelayError(responseText, httpStatus) {
|
|
2759
2825
|
let inner = "";
|
|
2760
2826
|
try {
|
|
@@ -4797,6 +4863,27 @@ function isRootAccepted(data, rootHex) {
|
|
|
4797
4863
|
const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
|
|
4798
4864
|
return readRootHistory(data).some((r) => r === want);
|
|
4799
4865
|
}
|
|
4866
|
+
function treeAccountAcceptsRoot(data, rootHex) {
|
|
4867
|
+
const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
|
|
4868
|
+
if (data.length >= ROOT_OFFSET + 32) {
|
|
4869
|
+
const current = Buffer.from(data.subarray(ROOT_OFFSET, ROOT_OFFSET + 32)).toString("hex");
|
|
4870
|
+
if (current === want) return true;
|
|
4871
|
+
}
|
|
4872
|
+
return isRootAccepted(data, want);
|
|
4873
|
+
}
|
|
4874
|
+
function readTreeAccountFrontier(data) {
|
|
4875
|
+
if (!data || data.length < ROOT_INDEX_OFFSET + 8) return null;
|
|
4876
|
+
const buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
|
|
4877
|
+
const next = readBigUInt64LE(buf, 32);
|
|
4878
|
+
if (next > 2n ** BigInt(MERKLE_TREE_HEIGHT)) return null;
|
|
4879
|
+
const subtrees = [];
|
|
4880
|
+
for (let level = 0; level < MERKLE_TREE_HEIGHT; level++) {
|
|
4881
|
+
const offset = SUBTREES_OFFSET + level * 32;
|
|
4882
|
+
subtrees.push(BigInt("0x" + buf.subarray(offset, offset + 32).toString("hex")));
|
|
4883
|
+
}
|
|
4884
|
+
const root = BigInt("0x" + buf.subarray(ROOT_OFFSET, ROOT_OFFSET + 32).toString("hex"));
|
|
4885
|
+
return { nextIndex: Number(next), subtrees, root };
|
|
4886
|
+
}
|
|
4800
4887
|
|
|
4801
4888
|
// src/proving/merkle.ts
|
|
4802
4889
|
var import_circomlibjs3 = require("circomlibjs");
|
|
@@ -4956,6 +5043,89 @@ var MerkleTree = class _MerkleTree {
|
|
|
4956
5043
|
async function buildMerkleTree(commitments, height = MERKLE_TREE_HEIGHT2) {
|
|
4957
5044
|
return MerkleTree.create(height, commitments);
|
|
4958
5045
|
}
|
|
5046
|
+
var MerkleFrontier = class _MerkleFrontier {
|
|
5047
|
+
constructor(levels, zeros, poseidon3, count, left) {
|
|
5048
|
+
this.levels = levels;
|
|
5049
|
+
this.zeros = zeros;
|
|
5050
|
+
this.poseidon = poseidon3;
|
|
5051
|
+
this.count = count;
|
|
5052
|
+
this.left = left;
|
|
5053
|
+
}
|
|
5054
|
+
static async create(state, levels = MERKLE_TREE_HEIGHT2) {
|
|
5055
|
+
const zeros = await getZeroValues();
|
|
5056
|
+
const poseidon3 = await getPoseidon3();
|
|
5057
|
+
const left = new Array(levels).fill(null);
|
|
5058
|
+
let count = 0;
|
|
5059
|
+
if (state) {
|
|
5060
|
+
if (!Number.isSafeInteger(state.nextIndex) || state.nextIndex < 0 || state.nextIndex > 2 ** levels) {
|
|
5061
|
+
throw new Error("MerkleFrontierState.nextIndex out of range");
|
|
5062
|
+
}
|
|
5063
|
+
if (!Array.isArray(state.left) || state.left.length !== levels) {
|
|
5064
|
+
throw new Error(`MerkleFrontierState.left must have ${levels} entries`);
|
|
5065
|
+
}
|
|
5066
|
+
count = state.nextIndex;
|
|
5067
|
+
for (let l = 0; l < levels; l++) {
|
|
5068
|
+
const odd = Math.floor(count / 2 ** l) % 2 === 1;
|
|
5069
|
+
const entry = state.left[l];
|
|
5070
|
+
if (odd !== (entry !== "")) throw new Error(`MerkleFrontierState.left[${l}] disagrees with nextIndex`);
|
|
5071
|
+
if (odd) {
|
|
5072
|
+
if (!/^[0-9a-f]{64}$/.test(entry)) throw new Error(`MerkleFrontierState.left[${l}] is not 32-byte hex`);
|
|
5073
|
+
left[l] = BigInt("0x" + entry);
|
|
5074
|
+
}
|
|
5075
|
+
}
|
|
5076
|
+
}
|
|
5077
|
+
return new _MerkleFrontier(levels, zeros, poseidon3, count, left);
|
|
5078
|
+
}
|
|
5079
|
+
get nextIndex() {
|
|
5080
|
+
return this.count;
|
|
5081
|
+
}
|
|
5082
|
+
/**
|
|
5083
|
+
* The complete LEFT node held at `level`: the node at index `floor(nextIndex / 2^level) - 1`,
|
|
5084
|
+
* present only while that index is even (bit `level` of `nextIndex` is set), else `null`.
|
|
5085
|
+
* With every set bit of `nextIndex`, these nodes cover leaves `[0, nextIndex)` exactly.
|
|
5086
|
+
*/
|
|
5087
|
+
leftAt(level) {
|
|
5088
|
+
if (!Number.isInteger(level) || level < 0 || level >= this.levels) return null;
|
|
5089
|
+
return this.left[level];
|
|
5090
|
+
}
|
|
5091
|
+
hash(a, b) {
|
|
5092
|
+
return this.poseidon.F.toObject(this.poseidon([a, b]));
|
|
5093
|
+
}
|
|
5094
|
+
/** Append leaves at indices `nextIndex .. nextIndex + leaves.length - 1`. */
|
|
5095
|
+
append(leaves) {
|
|
5096
|
+
if (leaves.length === 0) return;
|
|
5097
|
+
if (this.count + leaves.length > 2 ** this.levels) throw new Error("Tree is full");
|
|
5098
|
+
let nodes = leaves;
|
|
5099
|
+
for (let l = 0; l < this.levels && nodes.length > 0; l++) {
|
|
5100
|
+
const before = Math.floor(this.count / 2 ** l);
|
|
5101
|
+
const seq = before % 2 === 1 ? [this.left[l], ...nodes] : nodes;
|
|
5102
|
+
const parents = [];
|
|
5103
|
+
for (let i = 0; i + 1 < seq.length; i += 2) parents.push(this.hash(seq[i], seq[i + 1]));
|
|
5104
|
+
this.left[l] = (before + nodes.length) % 2 === 1 ? seq[seq.length - 1] : null;
|
|
5105
|
+
nodes = parents;
|
|
5106
|
+
}
|
|
5107
|
+
this.count += leaves.length;
|
|
5108
|
+
}
|
|
5109
|
+
/** The root of the first `nextIndex` leaves, zero-padded to the right. */
|
|
5110
|
+
root() {
|
|
5111
|
+
let partial = this.zeros[0];
|
|
5112
|
+
for (let l = 0; l < this.levels; l++) {
|
|
5113
|
+
const odd = Math.floor(this.count / 2 ** l) % 2 === 1;
|
|
5114
|
+
if (odd) partial = this.hash(this.left[l], partial);
|
|
5115
|
+
else partial = partial === this.zeros[l] ? this.zeros[l + 1] : this.hash(partial, this.zeros[l]);
|
|
5116
|
+
}
|
|
5117
|
+
return partial;
|
|
5118
|
+
}
|
|
5119
|
+
toState() {
|
|
5120
|
+
return {
|
|
5121
|
+
nextIndex: this.count,
|
|
5122
|
+
left: this.left.map((v) => v === null ? "" : v.toString(16).padStart(64, "0"))
|
|
5123
|
+
};
|
|
5124
|
+
}
|
|
5125
|
+
clone() {
|
|
5126
|
+
return new _MerkleFrontier(this.levels, this.zeros, this.poseidon, this.count, [...this.left]);
|
|
5127
|
+
}
|
|
5128
|
+
};
|
|
4959
5129
|
|
|
4960
5130
|
// src/relay/client.ts
|
|
4961
5131
|
init_address();
|
|
@@ -5107,6 +5277,7 @@ async function fetchWithRetry(url, options = {}) {
|
|
|
5107
5277
|
try {
|
|
5108
5278
|
const response = await fetch(url, { signal: controller.signal });
|
|
5109
5279
|
clearTimeout(timeoutId);
|
|
5280
|
+
observeRelayClock(response);
|
|
5110
5281
|
return response;
|
|
5111
5282
|
} finally {
|
|
5112
5283
|
clearTimeout(timeoutId);
|
|
@@ -5459,38 +5630,77 @@ async function aesGcmDecrypt2(ciphertext, keyBytes, nonce) {
|
|
|
5459
5630
|
const plaintext = await subtle.decrypt({ name: "AES-GCM", iv: toArrayBuffer2(nonce) }, key, toArrayBuffer2(ciphertext));
|
|
5460
5631
|
return new Uint8Array(plaintext);
|
|
5461
5632
|
}
|
|
5462
|
-
async function
|
|
5633
|
+
async function importNkHkdfKey(nk) {
|
|
5463
5634
|
if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
|
|
5464
5635
|
throw new Error("nk must be 32 bytes");
|
|
5465
5636
|
}
|
|
5637
|
+
return getSubtleCrypto2().importKey("raw", toArrayBuffer2(nk), "HKDF", false, ["deriveBits"]);
|
|
5638
|
+
}
|
|
5639
|
+
async function deriveAesKeyAndNonceFromIkm(ikm, salt) {
|
|
5466
5640
|
const subtle = getSubtleCrypto2();
|
|
5467
|
-
const
|
|
5468
|
-
|
|
5469
|
-
|
|
5470
|
-
|
|
5471
|
-
|
|
5472
|
-
|
|
5473
|
-
|
|
5474
|
-
|
|
5475
|
-
|
|
5476
|
-
|
|
5477
|
-
|
|
5478
|
-
|
|
5479
|
-
|
|
5480
|
-
|
|
5481
|
-
|
|
5482
|
-
|
|
5483
|
-
|
|
5484
|
-
|
|
5485
|
-
|
|
5486
|
-
|
|
5487
|
-
|
|
5488
|
-
);
|
|
5641
|
+
const [keyBits, nonceBits] = await Promise.all([
|
|
5642
|
+
subtle.deriveBits(
|
|
5643
|
+
{
|
|
5644
|
+
name: "HKDF",
|
|
5645
|
+
hash: "SHA-256",
|
|
5646
|
+
salt: toArrayBuffer2(salt),
|
|
5647
|
+
info: toArrayBuffer2(CHAIN_NOTE_KEY_INFO)
|
|
5648
|
+
},
|
|
5649
|
+
ikm,
|
|
5650
|
+
256
|
|
5651
|
+
),
|
|
5652
|
+
subtle.deriveBits(
|
|
5653
|
+
{
|
|
5654
|
+
name: "HKDF",
|
|
5655
|
+
hash: "SHA-256",
|
|
5656
|
+
salt: toArrayBuffer2(salt),
|
|
5657
|
+
info: toArrayBuffer2(CHAIN_NOTE_NONCE_INFO)
|
|
5658
|
+
},
|
|
5659
|
+
ikm,
|
|
5660
|
+
96
|
|
5661
|
+
)
|
|
5662
|
+
]);
|
|
5489
5663
|
return {
|
|
5490
5664
|
key: new Uint8Array(keyBits),
|
|
5491
5665
|
nonce: new Uint8Array(nonceBits)
|
|
5492
5666
|
};
|
|
5493
5667
|
}
|
|
5668
|
+
async function deriveAesKeyAndNonce(nk, commitmentHex) {
|
|
5669
|
+
const ikm = await importNkHkdfKey(nk);
|
|
5670
|
+
return deriveAesKeyAndNonceFromIkm(ikm, hexToBytes32(commitmentHex));
|
|
5671
|
+
}
|
|
5672
|
+
function decodeChainNotePlaintext(version, plaintext, commitmentHex) {
|
|
5673
|
+
if (version === NOTE_VERSION_V4) {
|
|
5674
|
+
if (plaintext.length !== PLAINTEXT_LEN_V4) {
|
|
5675
|
+
throw new Error(`Invalid v4 chain note plaintext length: ${plaintext.length}`);
|
|
5676
|
+
}
|
|
5677
|
+
return {
|
|
5678
|
+
timestamp: readU64LE(plaintext, 0),
|
|
5679
|
+
commitment: commitmentHex.toLowerCase(),
|
|
5680
|
+
noteSalt: readU256BE(plaintext, TIMESTAMP_LEN),
|
|
5681
|
+
outAmount0: readU64LE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN),
|
|
5682
|
+
outPubkey0: readU256BE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN + OUT_AMOUNT_LEN),
|
|
5683
|
+
isSendToSelfKey0: BigInt(plaintext[PLAINTEXT_LEN_V4 - 1])
|
|
5684
|
+
};
|
|
5685
|
+
}
|
|
5686
|
+
if (version === NOTE_VERSION_V3) {
|
|
5687
|
+
if (plaintext.length !== PLAINTEXT_LEN_V3) {
|
|
5688
|
+
throw new Error(`Invalid v3 chain note plaintext length: ${plaintext.length}`);
|
|
5689
|
+
}
|
|
5690
|
+
return {
|
|
5691
|
+
timestamp: readU64LE(plaintext, 0),
|
|
5692
|
+
commitment: commitmentHex.toLowerCase(),
|
|
5693
|
+
noteSalt: readU256BE(plaintext, TIMESTAMP_LEN)
|
|
5694
|
+
};
|
|
5695
|
+
}
|
|
5696
|
+
if (plaintext.length !== PLAINTEXT_LEN_V2) {
|
|
5697
|
+
throw new Error(`Invalid v2 chain note plaintext length: ${plaintext.length}`);
|
|
5698
|
+
}
|
|
5699
|
+
return {
|
|
5700
|
+
timestamp: readU64LE(plaintext, 0),
|
|
5701
|
+
commitment: commitmentHex.toLowerCase()
|
|
5702
|
+
};
|
|
5703
|
+
}
|
|
5494
5704
|
async function encryptCompactChainNote(timestamp, nk, commitmentHex, noteSalt, semantics) {
|
|
5495
5705
|
if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
|
|
5496
5706
|
throw new Error("nk must be 32 bytes");
|
|
@@ -5554,36 +5764,7 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
|
|
|
5554
5764
|
try {
|
|
5555
5765
|
const { key, nonce } = await deriveAesKeyAndNonce(nk, commitment);
|
|
5556
5766
|
const plaintext = await aesGcmDecrypt2(ciphertext, key, nonce);
|
|
5557
|
-
|
|
5558
|
-
if (plaintext.length !== PLAINTEXT_LEN_V4) {
|
|
5559
|
-
throw new Error(`Invalid v4 chain note plaintext length: ${plaintext.length}`);
|
|
5560
|
-
}
|
|
5561
|
-
return {
|
|
5562
|
-
timestamp: readU64LE(plaintext, 0),
|
|
5563
|
-
commitment: commitment.toLowerCase(),
|
|
5564
|
-
noteSalt: readU256BE(plaintext, TIMESTAMP_LEN),
|
|
5565
|
-
outAmount0: readU64LE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN),
|
|
5566
|
-
outPubkey0: readU256BE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN + OUT_AMOUNT_LEN),
|
|
5567
|
-
isSendToSelfKey0: BigInt(plaintext[PLAINTEXT_LEN_V4 - 1])
|
|
5568
|
-
};
|
|
5569
|
-
}
|
|
5570
|
-
if (version === NOTE_VERSION_V3) {
|
|
5571
|
-
if (plaintext.length !== PLAINTEXT_LEN_V3) {
|
|
5572
|
-
throw new Error(`Invalid v3 chain note plaintext length: ${plaintext.length}`);
|
|
5573
|
-
}
|
|
5574
|
-
return {
|
|
5575
|
-
timestamp: readU64LE(plaintext, 0),
|
|
5576
|
-
commitment: commitment.toLowerCase(),
|
|
5577
|
-
noteSalt: readU256BE(plaintext, TIMESTAMP_LEN)
|
|
5578
|
-
};
|
|
5579
|
-
}
|
|
5580
|
-
if (plaintext.length !== PLAINTEXT_LEN_V2) {
|
|
5581
|
-
throw new Error(`Invalid v2 chain note plaintext length: ${plaintext.length}`);
|
|
5582
|
-
}
|
|
5583
|
-
return {
|
|
5584
|
-
timestamp: readU64LE(plaintext, 0),
|
|
5585
|
-
commitment: commitment.toLowerCase()
|
|
5586
|
-
};
|
|
5767
|
+
return decodeChainNotePlaintext(version, plaintext, commitment);
|
|
5587
5768
|
} catch (error) {
|
|
5588
5769
|
lastError = error;
|
|
5589
5770
|
}
|
|
@@ -5592,6 +5773,26 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
|
|
|
5592
5773
|
`Failed to decrypt compact chain note with provided commitments: ${lastError instanceof Error ? lastError.message : String(lastError)}`
|
|
5593
5774
|
);
|
|
5594
5775
|
}
|
|
5776
|
+
async function createCompactChainNoteDecryptor(nk) {
|
|
5777
|
+
const ikm = await importNkHkdfKey(nk);
|
|
5778
|
+
return async (noteBytes, commitment) => {
|
|
5779
|
+
if (!(noteBytes instanceof Uint8Array) || noteBytes.length <= 1) return null;
|
|
5780
|
+
if (!(commitment instanceof Uint8Array) || commitment.length !== 32) return null;
|
|
5781
|
+
const version = noteBytes[0];
|
|
5782
|
+
if (version !== NOTE_VERSION_V4 && version !== NOTE_VERSION_V3 && version !== NOTE_VERSION_V2) {
|
|
5783
|
+
return null;
|
|
5784
|
+
}
|
|
5785
|
+
try {
|
|
5786
|
+
const { key, nonce } = await deriveAesKeyAndNonceFromIkm(ikm, commitment);
|
|
5787
|
+
const plaintext = await aesGcmDecrypt2(noteBytes.subarray(1), key, nonce);
|
|
5788
|
+
let hex = "";
|
|
5789
|
+
for (let i = 0; i < 32; i++) hex += commitment[i].toString(16).padStart(2, "0");
|
|
5790
|
+
return decodeChainNotePlaintext(version, plaintext, hex);
|
|
5791
|
+
} catch {
|
|
5792
|
+
return null;
|
|
5793
|
+
}
|
|
5794
|
+
};
|
|
5795
|
+
}
|
|
5595
5796
|
function chainNoteToBase64(noteBytes) {
|
|
5596
5797
|
return Buffer.from(noteBytes).toString("base64");
|
|
5597
5798
|
}
|
|
@@ -5688,6 +5889,80 @@ function openRecipientDeliveryNote(envelope, viewingSecretKey) {
|
|
|
5688
5889
|
return null;
|
|
5689
5890
|
}
|
|
5690
5891
|
}
|
|
5892
|
+
var X25519_PKCS8_PREFIX = Uint8Array.from([
|
|
5893
|
+
48,
|
|
5894
|
+
46,
|
|
5895
|
+
2,
|
|
5896
|
+
1,
|
|
5897
|
+
0,
|
|
5898
|
+
48,
|
|
5899
|
+
5,
|
|
5900
|
+
6,
|
|
5901
|
+
3,
|
|
5902
|
+
43,
|
|
5903
|
+
101,
|
|
5904
|
+
110,
|
|
5905
|
+
4,
|
|
5906
|
+
34,
|
|
5907
|
+
4,
|
|
5908
|
+
32
|
|
5909
|
+
]);
|
|
5910
|
+
var HSALSA_SIGMA = new TextEncoder().encode("expand 32-byte k");
|
|
5911
|
+
function decodeOpened(plaintext) {
|
|
5912
|
+
if (!plaintext || plaintext.length !== RECIPIENT_DELIVERY_PLAINTEXT_LEN) return null;
|
|
5913
|
+
return { amount: readU64LE2(plaintext, 0), blinding: readU256BE2(plaintext, 8) };
|
|
5914
|
+
}
|
|
5915
|
+
async function createRecipientDeliveryOpener(viewingSecretKey) {
|
|
5916
|
+
if (!(viewingSecretKey instanceof Uint8Array) || viewingSecretKey.length !== 32) {
|
|
5917
|
+
throw new Error("viewingSecretKey must be 32 bytes");
|
|
5918
|
+
}
|
|
5919
|
+
const slow = async (envelope) => openRecipientDeliveryNote(envelope, viewingSecretKey);
|
|
5920
|
+
const subtle = globalThis.crypto?.subtle;
|
|
5921
|
+
const hsalsa = import_tweetnacl4.default.lowlevel?.crypto_core_hsalsa20;
|
|
5922
|
+
if (!subtle || typeof hsalsa !== "function") return slow;
|
|
5923
|
+
let privateKey;
|
|
5924
|
+
const sharedKey = async (ephemeralPk) => {
|
|
5925
|
+
const publicKey = await subtle.importKey("raw", new Uint8Array(ephemeralPk), { name: "X25519" }, false, []);
|
|
5926
|
+
const shared = new Uint8Array(
|
|
5927
|
+
await subtle.deriveBits({ name: "X25519", public: publicKey }, privateKey, 256)
|
|
5928
|
+
);
|
|
5929
|
+
const key = new Uint8Array(32);
|
|
5930
|
+
hsalsa(key, new Uint8Array(16), shared, HSALSA_SIGMA);
|
|
5931
|
+
return key;
|
|
5932
|
+
};
|
|
5933
|
+
try {
|
|
5934
|
+
const pkcs8 = new Uint8Array(X25519_PKCS8_PREFIX.length + 32);
|
|
5935
|
+
pkcs8.set(X25519_PKCS8_PREFIX);
|
|
5936
|
+
pkcs8.set(viewingSecretKey, X25519_PKCS8_PREFIX.length);
|
|
5937
|
+
privateKey = await subtle.importKey("pkcs8", pkcs8, { name: "X25519" }, false, ["deriveBits"]);
|
|
5938
|
+
const probe = import_tweetnacl4.default.box.keyPair().publicKey;
|
|
5939
|
+
const fast = await sharedKey(probe);
|
|
5940
|
+
const reference = import_tweetnacl4.default.box.before(probe, viewingSecretKey);
|
|
5941
|
+
if (fast.length !== reference.length || fast.some((b, i) => b !== reference[i])) return slow;
|
|
5942
|
+
} catch {
|
|
5943
|
+
return slow;
|
|
5944
|
+
}
|
|
5945
|
+
return async (envelope) => {
|
|
5946
|
+
if (!(envelope instanceof Uint8Array) || envelope.length !== RECIPIENT_DELIVERY_NOTE_BYTES) return null;
|
|
5947
|
+
const ephemeralPk = envelope.subarray(0, RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN);
|
|
5948
|
+
const nonce = envelope.subarray(
|
|
5949
|
+
RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
|
|
5950
|
+
RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN
|
|
5951
|
+
);
|
|
5952
|
+
const ciphertext = envelope.subarray(RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN);
|
|
5953
|
+
let key;
|
|
5954
|
+
try {
|
|
5955
|
+
key = await sharedKey(ephemeralPk);
|
|
5956
|
+
} catch {
|
|
5957
|
+
return openRecipientDeliveryNote(envelope, viewingSecretKey);
|
|
5958
|
+
}
|
|
5959
|
+
try {
|
|
5960
|
+
return decodeOpened(import_tweetnacl4.default.secretbox.open(ciphertext, nonce, key));
|
|
5961
|
+
} catch {
|
|
5962
|
+
return null;
|
|
5963
|
+
}
|
|
5964
|
+
};
|
|
5965
|
+
}
|
|
5691
5966
|
function recipientDeliveryNoteToBase64(envelope) {
|
|
5692
5967
|
return Buffer.from(envelope).toString("base64");
|
|
5693
5968
|
}
|
|
@@ -5742,10 +6017,43 @@ var import_blake34 = require("@noble/hashes/blake3");
|
|
|
5742
6017
|
init_address();
|
|
5743
6018
|
var import_bs582 = __toESM(require("bs58"), 1);
|
|
5744
6019
|
init_utxo();
|
|
6020
|
+
|
|
6021
|
+
// src/notes/owner-key.ts
|
|
6022
|
+
init_utxo();
|
|
6023
|
+
var FIELD_MODULUS2 = BigInt(
|
|
6024
|
+
"21888242871839275222246405745257275088548364400416034343698204186575808495617"
|
|
6025
|
+
);
|
|
6026
|
+
async function assertOwnerUtxoKeypair(keypair, label = "ownerUtxoKeypair") {
|
|
6027
|
+
if (!keypair || typeof keypair !== "object") {
|
|
6028
|
+
throw new Error(
|
|
6029
|
+
`${label} is required: pass the wallet's long-lived UTXO keypair (deriveUtxoKeypairFromSpendKey(skSpend)). Self-owned notes are never owned by a key derived from the viewing key nk.`
|
|
6030
|
+
);
|
|
6031
|
+
}
|
|
6032
|
+
const { privateKey, publicKey } = keypair;
|
|
6033
|
+
if (typeof privateKey !== "bigint" || privateKey <= 0n || privateKey >= FIELD_MODULUS2) {
|
|
6034
|
+
throw new Error(`${label}.privateKey must be a non-zero field element (bigint)`);
|
|
6035
|
+
}
|
|
6036
|
+
if (typeof publicKey !== "bigint" || publicKey === 0n) {
|
|
6037
|
+
throw new Error(`${label}.publicKey must be a non-zero bigint`);
|
|
6038
|
+
}
|
|
6039
|
+
if (await derivePublicKey(privateKey) !== publicKey) {
|
|
6040
|
+
throw new Error(`${label}.publicKey is not derived from ${label}.privateKey`);
|
|
6041
|
+
}
|
|
6042
|
+
return { privateKey, publicKey };
|
|
6043
|
+
}
|
|
6044
|
+
function normalizeOwnerPublicKey(publicKey, label) {
|
|
6045
|
+
if (publicKey === void 0 || publicKey === null) return void 0;
|
|
6046
|
+
if (typeof publicKey !== "bigint" || publicKey <= 0n || publicKey >= FIELD_MODULUS2) {
|
|
6047
|
+
throw new Error(`${label} must be a non-zero field element (bigint)`);
|
|
6048
|
+
}
|
|
6049
|
+
return publicKey;
|
|
6050
|
+
}
|
|
6051
|
+
|
|
6052
|
+
// src/notes/swap-refund.ts
|
|
5745
6053
|
init_inputs();
|
|
5746
6054
|
var bs582 = import_bs582.default.default || import_bs582.default;
|
|
5747
6055
|
var REFUND_SEED_DOMAIN = new TextEncoder().encode("cloak_swap_refund_v1");
|
|
5748
|
-
var
|
|
6056
|
+
var LEGACY_REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
|
|
5749
6057
|
var REFUND_BLINDING_INFO = new TextEncoder().encode("blinding");
|
|
5750
6058
|
function normalizeNullifier(inputNullifier) {
|
|
5751
6059
|
if (inputNullifier instanceof Uint8Array) {
|
|
@@ -5779,13 +6087,29 @@ function derive(nk, nullifier, info) {
|
|
|
5779
6087
|
preimage.set(info, off);
|
|
5780
6088
|
return (0, import_blake34.blake3)(preimage);
|
|
5781
6089
|
}
|
|
5782
|
-
|
|
6090
|
+
function assertNk(viewingKeyNk) {
|
|
5783
6091
|
if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
|
|
5784
6092
|
throw new Error("viewingKeyNk must be 32 bytes");
|
|
5785
6093
|
}
|
|
6094
|
+
return viewingKeyNk;
|
|
6095
|
+
}
|
|
6096
|
+
function deriveSwapRefundBlinding(viewingKeyNk, inputNullifier) {
|
|
6097
|
+
const nk = assertNk(viewingKeyNk);
|
|
6098
|
+
return toFieldSecret(derive(nk, normalizeNullifier(inputNullifier), REFUND_BLINDING_INFO));
|
|
6099
|
+
}
|
|
6100
|
+
async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier, ownerUtxoKeypair) {
|
|
6101
|
+
const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
|
|
6102
|
+
const blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
|
|
6103
|
+
if (owner.publicKey === 0n || blinding === 0n) {
|
|
6104
|
+
throw new Error("refund authorization is degenerate");
|
|
6105
|
+
}
|
|
6106
|
+
return { privateKey: owner.privateKey, publicKey: owner.publicKey, blinding };
|
|
6107
|
+
}
|
|
6108
|
+
async function deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier) {
|
|
6109
|
+
const nk = assertNk(viewingKeyNk);
|
|
5786
6110
|
const nullifier = normalizeNullifier(inputNullifier);
|
|
5787
|
-
const privateKey = toFieldSecret(derive(
|
|
5788
|
-
const blinding = toFieldSecret(derive(
|
|
6111
|
+
const privateKey = toFieldSecret(derive(nk, nullifier, LEGACY_REFUND_PRIVATE_KEY_INFO));
|
|
6112
|
+
const blinding = toFieldSecret(derive(nk, nullifier, REFUND_BLINDING_INFO));
|
|
5789
6113
|
const publicKey = await derivePublicKey(privateKey);
|
|
5790
6114
|
if (publicKey === 0n || blinding === 0n) {
|
|
5791
6115
|
throw new Error("derived refund authorization is degenerate");
|
|
@@ -5803,19 +6127,39 @@ async function computeSwapRefundCommitment(amountAfterFee, refundPublicKey, refu
|
|
|
5803
6127
|
async function matchSwapRefundLeaf(params) {
|
|
5804
6128
|
const { viewingKeyNk, inputNullifier, amountAfterFee } = params;
|
|
5805
6129
|
const expected = params.commitment instanceof Uint8Array ? BigInt("0x" + Buffer.from(params.commitment).toString("hex")) : params.commitment;
|
|
5806
|
-
let
|
|
6130
|
+
let blinding;
|
|
6131
|
+
try {
|
|
6132
|
+
blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
|
|
6133
|
+
} catch {
|
|
6134
|
+
return null;
|
|
6135
|
+
}
|
|
6136
|
+
const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
|
|
6137
|
+
if (ownerPub !== void 0) {
|
|
6138
|
+
const candidate = await computeSwapRefundCommitment(amountAfterFee, ownerPub, blinding);
|
|
6139
|
+
if (candidate === expected) {
|
|
6140
|
+
return {
|
|
6141
|
+
keypair: { privateKey: params.ownerUtxoKeypair?.privateKey ?? 0n, publicKey: ownerPub },
|
|
6142
|
+
blinding,
|
|
6143
|
+
amount: amountAfterFee,
|
|
6144
|
+
commitment: candidate,
|
|
6145
|
+
legacyExposed: false
|
|
6146
|
+
};
|
|
6147
|
+
}
|
|
6148
|
+
}
|
|
6149
|
+
let legacy;
|
|
5807
6150
|
try {
|
|
5808
|
-
|
|
6151
|
+
legacy = await deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier);
|
|
5809
6152
|
} catch {
|
|
5810
6153
|
return null;
|
|
5811
6154
|
}
|
|
5812
|
-
const
|
|
5813
|
-
if (
|
|
6155
|
+
const legacyCandidate = await computeSwapRefundCommitment(amountAfterFee, legacy.publicKey, legacy.blinding);
|
|
6156
|
+
if (legacyCandidate !== expected) return null;
|
|
5814
6157
|
return {
|
|
5815
|
-
keypair: { privateKey:
|
|
5816
|
-
blinding:
|
|
6158
|
+
keypair: { privateKey: legacy.privateKey, publicKey: legacy.publicKey },
|
|
6159
|
+
blinding: legacy.blinding,
|
|
5817
6160
|
amount: amountAfterFee,
|
|
5818
|
-
commitment:
|
|
6161
|
+
commitment: legacyCandidate,
|
|
6162
|
+
legacyExposed: true
|
|
5819
6163
|
};
|
|
5820
6164
|
}
|
|
5821
6165
|
var TRANSACT_SWAP_TAG2 = 1;
|
|
@@ -5879,10 +6223,16 @@ function instructionsForProgram(tx, accountKeys, programIdBase58) {
|
|
|
5879
6223
|
if (Array.isArray(inner)) for (const block of inner) take(block?.instructions);
|
|
5880
6224
|
return out;
|
|
5881
6225
|
}
|
|
5882
|
-
async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
|
|
6226
|
+
async function discoverSwapRefunds(connection, programId, viewingKeyNk, options) {
|
|
5883
6227
|
if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
|
|
5884
6228
|
throw new Error("viewingKeyNk must be 32 bytes");
|
|
5885
6229
|
}
|
|
6230
|
+
if (!options || normalizeOwnerPublicKey(options.ownerUtxoKeypair?.publicKey, "options.ownerUtxoKeypair.publicKey") === void 0) {
|
|
6231
|
+
throw new Error(
|
|
6232
|
+
"discoverSwapRefunds requires options.ownerUtxoKeypair (the wallet's long-lived UTXO keypair): refund leaves are owned by it, and nk alone can only find legacy refunds."
|
|
6233
|
+
);
|
|
6234
|
+
}
|
|
6235
|
+
const ownerUtxoKeypair = options.ownerUtxoKeypair;
|
|
5886
6236
|
const { limit = 0, untilSignature, batchSize = 50, onStatus } = options;
|
|
5887
6237
|
const poolMint = options.poolMint ?? NATIVE_SOL_MINT;
|
|
5888
6238
|
const programIdBase58 = programId;
|
|
@@ -5957,7 +6307,8 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options
|
|
|
5957
6307
|
viewingKeyNk,
|
|
5958
6308
|
inputNullifier: candidate.nullifier,
|
|
5959
6309
|
amountAfterFee: event.amountAfterFee,
|
|
5960
|
-
commitment: event.commitmentField
|
|
6310
|
+
commitment: event.commitmentField,
|
|
6311
|
+
ownerUtxoKeypair
|
|
5961
6312
|
});
|
|
5962
6313
|
if (!recovered) continue;
|
|
5963
6314
|
const dedupe = `${close.signature}:${event.leafIndex}`;
|
|
@@ -5983,7 +6334,7 @@ var import_blake35 = require("@noble/hashes/blake3");
|
|
|
5983
6334
|
init_utxo();
|
|
5984
6335
|
init_inputs();
|
|
5985
6336
|
var DEPOSIT_NOTE_DOMAIN = new TextEncoder().encode("cloak_deposit_note_v1");
|
|
5986
|
-
var
|
|
6337
|
+
var LEGACY_DEPOSIT_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
|
|
5987
6338
|
var DEPOSIT_BLINDING_INFO = new TextEncoder().encode("blinding");
|
|
5988
6339
|
var CHAIN_NOTE_SALT_BITS = 96;
|
|
5989
6340
|
var MAX_CHAIN_NOTE_SALT = (1n << BigInt(CHAIN_NOTE_SALT_BITS)) - 1n;
|
|
@@ -6019,30 +6370,47 @@ function derive2(nk, salt, info) {
|
|
|
6019
6370
|
preimage.set(info, off);
|
|
6020
6371
|
return (0, import_blake35.blake3)(preimage);
|
|
6021
6372
|
}
|
|
6373
|
+
function assertNk2(viewingKeyNk) {
|
|
6374
|
+
if (!viewingKeyNk || !(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) {
|
|
6375
|
+
throw new Error("viewingKeyNk must be 32 bytes");
|
|
6376
|
+
}
|
|
6377
|
+
return viewingKeyNk;
|
|
6378
|
+
}
|
|
6022
6379
|
function randomDepositNoteSalt() {
|
|
6023
6380
|
const bytes = randomBytes(12);
|
|
6024
6381
|
let v = 0n;
|
|
6025
6382
|
for (const b of bytes) v = v << 8n | BigInt(b);
|
|
6026
6383
|
return v === 0n ? 1n : v;
|
|
6027
6384
|
}
|
|
6028
|
-
|
|
6029
|
-
|
|
6030
|
-
|
|
6031
|
-
|
|
6385
|
+
function deriveDepositNoteBlinding(viewingKeyNk, noteSalt) {
|
|
6386
|
+
const nk = assertNk2(viewingKeyNk);
|
|
6387
|
+
return toFieldSecret2(derive2(nk, saltToBytes(noteSalt), DEPOSIT_BLINDING_INFO));
|
|
6388
|
+
}
|
|
6389
|
+
async function deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt) {
|
|
6390
|
+
const nk = assertNk2(viewingKeyNk);
|
|
6032
6391
|
const salt = saltToBytes(noteSalt);
|
|
6033
|
-
const privateKey = toFieldSecret2(derive2(
|
|
6034
|
-
const blinding = toFieldSecret2(derive2(
|
|
6392
|
+
const privateKey = toFieldSecret2(derive2(nk, salt, LEGACY_DEPOSIT_PRIVATE_KEY_INFO));
|
|
6393
|
+
const blinding = toFieldSecret2(derive2(nk, salt, DEPOSIT_BLINDING_INFO));
|
|
6035
6394
|
const publicKey = await derivePublicKey(privateKey);
|
|
6036
6395
|
if (publicKey === 0n || blinding === 0n) {
|
|
6037
6396
|
throw new Error("derived deposit note secrets are degenerate");
|
|
6038
6397
|
}
|
|
6039
6398
|
return { keypair: { privateKey, publicKey }, blinding };
|
|
6040
6399
|
}
|
|
6041
|
-
async function createRecoverableDepositUtxo(
|
|
6400
|
+
async function createRecoverableDepositUtxo(params) {
|
|
6401
|
+
if (!params || typeof params !== "object" || params instanceof Uint8Array) {
|
|
6402
|
+
throw new Error(
|
|
6403
|
+
"createRecoverableDepositUtxo takes one options object: { amount, viewingKeyNk, ownerUtxoKeypair, mintAddress?, noteSalt? }"
|
|
6404
|
+
);
|
|
6405
|
+
}
|
|
6406
|
+
const { amount, viewingKeyNk } = params;
|
|
6042
6407
|
if (typeof amount !== "bigint" || amount <= 0n) {
|
|
6043
6408
|
throw new Error("amount must be a positive bigint");
|
|
6044
6409
|
}
|
|
6045
|
-
const
|
|
6410
|
+
const keypair = await assertOwnerUtxoKeypair(params.ownerUtxoKeypair);
|
|
6411
|
+
const mintAddress = params.mintAddress ?? NATIVE_SOL_MINT;
|
|
6412
|
+
const noteSalt = params.noteSalt ?? randomDepositNoteSalt();
|
|
6413
|
+
const blinding = deriveDepositNoteBlinding(viewingKeyNk, noteSalt);
|
|
6046
6414
|
const utxo = { amount, keypair, blinding, mintAddress };
|
|
6047
6415
|
utxo.commitment = await computeCommitment2(utxo);
|
|
6048
6416
|
return { utxo, noteSalt };
|
|
@@ -6057,21 +6425,46 @@ function normalizeCommitment(value) {
|
|
|
6057
6425
|
async function matchDepositNote(params) {
|
|
6058
6426
|
const { viewingKeyNk, noteSalt, amount, mintAddress, outputCommitments } = params;
|
|
6059
6427
|
if (typeof amount !== "bigint" || amount <= 0n) return null;
|
|
6060
|
-
let
|
|
6428
|
+
let blinding;
|
|
6429
|
+
try {
|
|
6430
|
+
blinding = deriveDepositNoteBlinding(viewingKeyNk, noteSalt);
|
|
6431
|
+
} catch {
|
|
6432
|
+
return null;
|
|
6433
|
+
}
|
|
6434
|
+
const published = (outputCommitments ?? []).map(normalizeCommitment).filter((value) => value !== null);
|
|
6435
|
+
if (published.length === 0) return null;
|
|
6436
|
+
const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
|
|
6437
|
+
if (ownerPub !== void 0) {
|
|
6438
|
+
const keypair = {
|
|
6439
|
+
privateKey: params.ownerUtxoKeypair?.privateKey ?? 0n,
|
|
6440
|
+
publicKey: ownerPub
|
|
6441
|
+
};
|
|
6442
|
+
const candidate = await computeCommitment2({ amount, keypair, blinding, mintAddress });
|
|
6443
|
+
if (published.some((value) => value === candidate)) {
|
|
6444
|
+
return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt, legacyExposed: false };
|
|
6445
|
+
}
|
|
6446
|
+
}
|
|
6447
|
+
let legacy;
|
|
6061
6448
|
try {
|
|
6062
|
-
|
|
6449
|
+
legacy = await deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt);
|
|
6063
6450
|
} catch {
|
|
6064
6451
|
return null;
|
|
6065
6452
|
}
|
|
6066
|
-
const
|
|
6453
|
+
const legacyCandidate = await computeCommitment2({
|
|
6067
6454
|
amount,
|
|
6068
|
-
keypair:
|
|
6069
|
-
blinding:
|
|
6455
|
+
keypair: legacy.keypair,
|
|
6456
|
+
blinding: legacy.blinding,
|
|
6070
6457
|
mintAddress
|
|
6071
6458
|
});
|
|
6072
|
-
|
|
6073
|
-
|
|
6074
|
-
|
|
6459
|
+
if (!published.some((value) => value === legacyCandidate)) return null;
|
|
6460
|
+
return {
|
|
6461
|
+
...legacy,
|
|
6462
|
+
amount,
|
|
6463
|
+
mintAddress,
|
|
6464
|
+
commitment: legacyCandidate,
|
|
6465
|
+
noteSalt,
|
|
6466
|
+
legacyExposed: true
|
|
6467
|
+
};
|
|
6075
6468
|
}
|
|
6076
6469
|
|
|
6077
6470
|
// src/notes/change-note.ts
|
|
@@ -6129,10 +6522,11 @@ function deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex) {
|
|
|
6129
6522
|
preimage.set(CHANGE_BLINDING_INFO, off);
|
|
6130
6523
|
return toFieldSecret3((0, import_blake36.blake3)(preimage));
|
|
6131
6524
|
}
|
|
6132
|
-
async function createRecoverableChangeUtxo(amount,
|
|
6525
|
+
async function createRecoverableChangeUtxo(amount, ownerUtxoKeypair, viewingKeyNk, mintAddress = NATIVE_SOL_MINT, noteSalt = randomChangeNoteSalt(), outputIndex = 0) {
|
|
6133
6526
|
if (typeof amount !== "bigint" || amount <= 0n) {
|
|
6134
6527
|
throw new Error("amount must be a positive bigint");
|
|
6135
6528
|
}
|
|
6529
|
+
const keypair = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
|
|
6136
6530
|
const blinding = deriveChangeNoteBlinding(viewingKeyNk, noteSalt, outputIndex);
|
|
6137
6531
|
const utxo = { amount, keypair, blinding, mintAddress };
|
|
6138
6532
|
utxo.commitment = await computeCommitment2(utxo);
|
|
@@ -6158,12 +6552,28 @@ async function matchChangeNote(params) {
|
|
|
6158
6552
|
const candidate = await computeCommitment2({ amount, keypair, blinding, mintAddress });
|
|
6159
6553
|
const published = (outputCommitments ?? []).map(normalizeCommitment2).filter((value) => value !== null);
|
|
6160
6554
|
if (!published.some((value) => value === candidate)) return null;
|
|
6161
|
-
|
|
6555
|
+
const walletKey = normalizeOwnerPublicKey(params.ownerUtxoPublicKey, "ownerUtxoPublicKey");
|
|
6556
|
+
const legacyExposed = walletKey !== void 0 && keypair.publicKey !== walletKey;
|
|
6557
|
+
return { keypair, blinding, amount, mintAddress, commitment: candidate, noteSalt, legacyExposed };
|
|
6162
6558
|
}
|
|
6163
6559
|
|
|
6164
6560
|
// src/flows/transact.ts
|
|
6165
6561
|
var import_circomlibjs4 = require("circomlibjs");
|
|
6166
6562
|
var import_tweetnacl5 = __toESM(require("tweetnacl"), 1);
|
|
6563
|
+
|
|
6564
|
+
// src/relay/chain-note-time.ts
|
|
6565
|
+
async function relayChainNoteTimestampMs(relayUrl) {
|
|
6566
|
+
if (relayUrl && !hasRelayClockSample()) {
|
|
6567
|
+
try {
|
|
6568
|
+
const response = await relayFetch(`${relayUrl.replace(/\/$/, "")}/health`);
|
|
6569
|
+
await response.body?.cancel?.().catch(() => void 0);
|
|
6570
|
+
} catch {
|
|
6571
|
+
}
|
|
6572
|
+
}
|
|
6573
|
+
return BigInt(relayNowMs());
|
|
6574
|
+
}
|
|
6575
|
+
|
|
6576
|
+
// src/flows/transact.ts
|
|
6167
6577
|
init_inputs();
|
|
6168
6578
|
|
|
6169
6579
|
// src/proving/artifacts.ts
|
|
@@ -6452,6 +6862,12 @@ var NEAR_TIP_ONCHAIN_FALLBACK_MAX_DISTANCE_LOCAL_RPC = 8;
|
|
|
6452
6862
|
var DEFAULT_RELAY_REQUEST_TIMEOUT_MS = 45e3;
|
|
6453
6863
|
var DEFAULT_RELAY_NETWORK_RETRIES = 6;
|
|
6454
6864
|
var RETRYABLE_RELAY_STATUSES = /* @__PURE__ */ new Set([408, 409, 425, 429, 500, 502, 503, 504, 522, 524]);
|
|
6865
|
+
var RELAY_SOURCE_LEASE_MS = 18e4;
|
|
6866
|
+
var RELAY_SOURCE_LEASE_MARGIN_MS = 5e3;
|
|
6867
|
+
var MAX_LEASE_EXPIRY_REPLAYS = 2;
|
|
6868
|
+
var RELAY_IN_FLIGHT_POLL_MS = 5e3;
|
|
6869
|
+
var RELAY_LANDED_POLL_MS = 1e3;
|
|
6870
|
+
var MAX_LANDED_POLLS = 5;
|
|
6455
6871
|
function parseMissingRelayIndexError(message) {
|
|
6456
6872
|
const match = message.match(
|
|
6457
6873
|
/Relay tree missing required commitment index\s+(\d+)\s+\(tree length:\s*(\d+)\)/i
|
|
@@ -6802,6 +7218,33 @@ function parseNkInput(input) {
|
|
|
6802
7218
|
}
|
|
6803
7219
|
return Uint8Array.from(Buffer.from(clean, "hex"));
|
|
6804
7220
|
}
|
|
7221
|
+
async function resolveWalletNk(options) {
|
|
7222
|
+
const explicit = await resolveChainNoteNk(options);
|
|
7223
|
+
if (explicit) return explicit;
|
|
7224
|
+
if (options.ownerUtxoKeypair) {
|
|
7225
|
+
const owner = await assertOwnerUtxoKeypair(options.ownerUtxoKeypair);
|
|
7226
|
+
return getNkFromUtxoPrivateKey(owner.privateKey);
|
|
7227
|
+
}
|
|
7228
|
+
return null;
|
|
7229
|
+
}
|
|
7230
|
+
function missingWalletNkError(flow) {
|
|
7231
|
+
return new Error(
|
|
7232
|
+
`${flow} requires the wallet's viewing key: pass chainNoteViewingKeyNk (or getChainNoteViewingKeyNk), or ownerUtxoKeypair to use its canonical nk. The SDK no longer infers nk from a note's own key.`
|
|
7233
|
+
);
|
|
7234
|
+
}
|
|
7235
|
+
async function requireWalletNk(options, flow) {
|
|
7236
|
+
const nk = await resolveWalletNk(options);
|
|
7237
|
+
if (nk) return nk;
|
|
7238
|
+
throw missingWalletNkError(flow);
|
|
7239
|
+
}
|
|
7240
|
+
async function requireOwnerUtxoKeypair(options, flow) {
|
|
7241
|
+
if (!options.ownerUtxoKeypair) {
|
|
7242
|
+
throw new Error(
|
|
7243
|
+
`${flow} requires options.ownerUtxoKeypair, the wallet's long-lived UTXO keypair (deriveUtxoKeypairFromSpendKey(skSpend)). It owns the change and refund notes this flow creates; the SDK no longer inherits that owner from inputUtxos[0].`
|
|
7244
|
+
);
|
|
7245
|
+
}
|
|
7246
|
+
return assertOwnerUtxoKeypair(options.ownerUtxoKeypair, "options.ownerUtxoKeypair");
|
|
7247
|
+
}
|
|
6805
7248
|
async function resolveChainNoteNk(options) {
|
|
6806
7249
|
if (options.chainNoteViewingKeyNk) {
|
|
6807
7250
|
return parseNkInput(options.chainNoteViewingKeyNk);
|
|
@@ -6819,7 +7262,7 @@ function shouldDefaultUseUniqueNullifiers(_connection) {
|
|
|
6819
7262
|
function toHex(bytes) {
|
|
6820
7263
|
return Buffer.from(bytes).toString("hex");
|
|
6821
7264
|
}
|
|
6822
|
-
async function ensureViewingKeyRegistered(options, onProgress,
|
|
7265
|
+
async function ensureViewingKeyRegistered(options, onProgress, walletNk) {
|
|
6823
7266
|
if (options.enforceViewingKeyRegistration === false) {
|
|
6824
7267
|
return;
|
|
6825
7268
|
}
|
|
@@ -6833,7 +7276,7 @@ async function ensureViewingKeyRegistered(options, onProgress, fallbackNk) {
|
|
|
6833
7276
|
"Viewing key registration is mandatory: walletPublicKey or depositor public key is required."
|
|
6834
7277
|
);
|
|
6835
7278
|
}
|
|
6836
|
-
const nk =
|
|
7279
|
+
const nk = walletNk;
|
|
6837
7280
|
if (!nk || nk.length !== 32) {
|
|
6838
7281
|
throw new Error(
|
|
6839
7282
|
"Viewing key registration is mandatory: provide a chain-note viewing key (nk)."
|
|
@@ -6975,10 +7418,10 @@ function buildPublicInputsBytesFromSignals(publicSignals) {
|
|
|
6975
7418
|
result.set(bigintToBytes323(BigInt(publicSignals[0])), offset);
|
|
6976
7419
|
offset += 32;
|
|
6977
7420
|
let amount = BigInt(publicSignals[1]);
|
|
6978
|
-
const
|
|
6979
|
-
const HALF_FIELD =
|
|
7421
|
+
const FIELD_MODULUS3 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
|
|
7422
|
+
const HALF_FIELD = FIELD_MODULUS3 / BigInt(2);
|
|
6980
7423
|
if (amount > HALF_FIELD) {
|
|
6981
|
-
amount = amount -
|
|
7424
|
+
amount = amount - FIELD_MODULUS3;
|
|
6982
7425
|
}
|
|
6983
7426
|
const amountBytes = new Uint8Array(8);
|
|
6984
7427
|
let amountValue = amount;
|
|
@@ -7925,8 +8368,9 @@ function chargeWalletApproval(used, budget, lastError) {
|
|
|
7925
8368
|
}
|
|
7926
8369
|
return used + 1;
|
|
7927
8370
|
}
|
|
7928
|
-
function relayFailureMessage(prefix, responseText) {
|
|
7929
|
-
const
|
|
8371
|
+
function relayFailureMessage(prefix, responseText, requestBody) {
|
|
8372
|
+
const carriedAffiliateCode = typeof requestBody?.affiliate_code === "string";
|
|
8373
|
+
const explanation = explainRelayAuthRejection(responseText, { carriedAffiliateCode });
|
|
7930
8374
|
return explanation ? `${prefix}: ${responseText}
|
|
7931
8375
|
|
|
7932
8376
|
${explanation}` : `${prefix}: ${responseText}`;
|
|
@@ -8008,6 +8452,20 @@ async function reconcileCommitmentIndicesWithRelay(relayUrl, mint, suggestedIndi
|
|
|
8008
8452
|
function sleep2(ms) {
|
|
8009
8453
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
8010
8454
|
}
|
|
8455
|
+
function sleepUnlessAborted(ms, signal) {
|
|
8456
|
+
if (signal?.aborted) return Promise.resolve(false);
|
|
8457
|
+
return new Promise((resolve) => {
|
|
8458
|
+
const onAbort = () => {
|
|
8459
|
+
clearTimeout(timer);
|
|
8460
|
+
resolve(false);
|
|
8461
|
+
};
|
|
8462
|
+
const timer = setTimeout(() => {
|
|
8463
|
+
signal?.removeEventListener("abort", onAbort);
|
|
8464
|
+
resolve(true);
|
|
8465
|
+
}, ms);
|
|
8466
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
8467
|
+
});
|
|
8468
|
+
}
|
|
8011
8469
|
function hexToBytes2(hex) {
|
|
8012
8470
|
const bytes = new Uint8Array(hex.length / 2);
|
|
8013
8471
|
for (let i = 0; i < hex.length; i += 2) {
|
|
@@ -8242,6 +8700,9 @@ async function submitTransactToRelay(args) {
|
|
|
8242
8700
|
let unknownOutcomeSignature = null;
|
|
8243
8701
|
let possiblySubmitted = false;
|
|
8244
8702
|
let networkRetry = 0;
|
|
8703
|
+
let leaseReplays = 0;
|
|
8704
|
+
let landedPolls = 0;
|
|
8705
|
+
let leaseBaseMs = null;
|
|
8245
8706
|
const verifySettlement = (signature, timeoutMs) => confirmTransactSettlement({
|
|
8246
8707
|
connection: settlement.connection,
|
|
8247
8708
|
programId: settlement.programId,
|
|
@@ -8297,6 +8758,7 @@ async function submitTransactToRelay(args) {
|
|
|
8297
8758
|
const controller = new AbortController();
|
|
8298
8759
|
const timeoutId = setTimeout(() => controller.abort(), requestTimeoutMs);
|
|
8299
8760
|
let response;
|
|
8761
|
+
leaseBaseMs ?? (leaseBaseMs = Date.now());
|
|
8300
8762
|
try {
|
|
8301
8763
|
response = await doFetch(`${relayUrl}/transact`, {
|
|
8302
8764
|
method: "POST",
|
|
@@ -8304,6 +8766,7 @@ async function submitTransactToRelay(args) {
|
|
|
8304
8766
|
body: requestPayload,
|
|
8305
8767
|
signal: controller.signal
|
|
8306
8768
|
});
|
|
8769
|
+
observeRelayClock(response);
|
|
8307
8770
|
} finally {
|
|
8308
8771
|
clearTimeout(timeoutId);
|
|
8309
8772
|
}
|
|
@@ -8314,6 +8777,49 @@ async function submitTransactToRelay(args) {
|
|
|
8314
8777
|
if (isSubmissionOutcomeUnknownResponse(responseText) || isRetryableRelayStatus(response.status)) {
|
|
8315
8778
|
possiblySubmitted = true;
|
|
8316
8779
|
}
|
|
8780
|
+
if ((isRelayRequestInFlightResponse(responseText) || isSubmissionOutcomeUnknownResponse(responseText)) && leaseReplays < MAX_LEASE_EXPIRY_REPLAYS) {
|
|
8781
|
+
networkRetry = 0;
|
|
8782
|
+
const leaseEndsMs = (leaseBaseMs ?? Date.now()) + RELAY_SOURCE_LEASE_MS + RELAY_SOURCE_LEASE_MARGIN_MS;
|
|
8783
|
+
const polling = Date.now() < leaseEndsMs;
|
|
8784
|
+
const probe = await verifySettlement(
|
|
8785
|
+
unknownOutcomeSignature,
|
|
8786
|
+
polling ? 0 : args.failureProbeTimeoutMs ?? Math.min(settlementTimeoutMs(), 1e4)
|
|
8787
|
+
);
|
|
8788
|
+
if (probe.status === "landed") {
|
|
8789
|
+
landedPolls++;
|
|
8790
|
+
if (!polling || landedPolls > MAX_LANDED_POLLS) {
|
|
8791
|
+
return await resolveFailure(
|
|
8792
|
+
new Error(relayFailureMessage("Relay error", responseText, requestBody))
|
|
8793
|
+
);
|
|
8794
|
+
}
|
|
8795
|
+
if (!await sleepUnlessAborted(RELAY_LANDED_POLL_MS, args.signal)) {
|
|
8796
|
+
return await resolveFailure(new Error("Relay lease-expiry replay aborted by caller"));
|
|
8797
|
+
}
|
|
8798
|
+
continue;
|
|
8799
|
+
}
|
|
8800
|
+
if (polling) {
|
|
8801
|
+
onProgress?.("Relay is still processing this request; checking again shortly...");
|
|
8802
|
+
const pollMs = Math.min(RELAY_IN_FLIGHT_POLL_MS, leaseEndsMs - Date.now());
|
|
8803
|
+
if (!await sleepUnlessAborted(pollMs, args.signal)) {
|
|
8804
|
+
return await resolveFailure(new Error("Relay lease-expiry replay aborted by caller"));
|
|
8805
|
+
}
|
|
8806
|
+
continue;
|
|
8807
|
+
}
|
|
8808
|
+
leaseReplays++;
|
|
8809
|
+
const waitMs = Math.max(
|
|
8810
|
+
0,
|
|
8811
|
+
(leaseBaseMs ?? Date.now()) + RELAY_SOURCE_LEASE_MS + RELAY_SOURCE_LEASE_MARGIN_MS - Date.now()
|
|
8812
|
+
);
|
|
8813
|
+
onProgress?.(
|
|
8814
|
+
`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})...`
|
|
8815
|
+
);
|
|
8816
|
+
if (!await sleepUnlessAborted(waitMs, args.signal)) {
|
|
8817
|
+
return await resolveFailure(new Error("Relay lease-expiry replay aborted by caller"));
|
|
8818
|
+
}
|
|
8819
|
+
networkRetry = 0;
|
|
8820
|
+
leaseBaseMs = null;
|
|
8821
|
+
continue;
|
|
8822
|
+
}
|
|
8317
8823
|
if (isRetryableRelayStatus(response.status) && networkRetry < maxNetworkRetries) {
|
|
8318
8824
|
networkRetry++;
|
|
8319
8825
|
const delay = relayBackoffMs(networkRetry);
|
|
@@ -8334,7 +8840,9 @@ async function submitTransactToRelay(args) {
|
|
|
8334
8840
|
onProgress?.("Root not found (stale), will regenerate proof with fresh tree...");
|
|
8335
8841
|
return { kind: "stale-root", error: new Error(`Relay error: ${responseText}`) };
|
|
8336
8842
|
}
|
|
8337
|
-
return await resolveFailure(
|
|
8843
|
+
return await resolveFailure(
|
|
8844
|
+
new Error(relayFailureMessage("Relay error", responseText, requestBody))
|
|
8845
|
+
);
|
|
8338
8846
|
}
|
|
8339
8847
|
const apiResponse = JSON.parse(responseText);
|
|
8340
8848
|
if (!apiResponse.success || !apiResponse.data) {
|
|
@@ -8351,7 +8859,7 @@ async function submitTransactToRelay(args) {
|
|
|
8351
8859
|
return { kind: "stale-root", error: new Error(`Relay returned error: ${errorStr}`) };
|
|
8352
8860
|
}
|
|
8353
8861
|
return await resolveFailure(
|
|
8354
|
-
new Error(relayFailureMessage("Relay returned error", errorStr))
|
|
8862
|
+
new Error(relayFailureMessage("Relay returned error", errorStr, requestBody))
|
|
8355
8863
|
);
|
|
8356
8864
|
}
|
|
8357
8865
|
const result = apiResponse.data;
|
|
@@ -8459,34 +8967,37 @@ async function transact(params, options) {
|
|
|
8459
8967
|
);
|
|
8460
8968
|
}
|
|
8461
8969
|
onProgress?.("Validating transaction parameters...");
|
|
8462
|
-
const
|
|
8463
|
-
const
|
|
8464
|
-
|
|
8465
|
-
const explicitChainNoteNk = await resolveChainNoteNk(options);
|
|
8466
|
-
if (options.chainNoteSalt !== void 0 && !explicitChainNoteNk) {
|
|
8970
|
+
const walletNk = await resolveWalletNk(options);
|
|
8971
|
+
const ownerUtxoKeypair = options.ownerUtxoKeypair ? await assertOwnerUtxoKeypair(options.ownerUtxoKeypair) : void 0;
|
|
8972
|
+
if (options.chainNoteSalt !== void 0 && !walletNk) {
|
|
8467
8973
|
throw new Error(
|
|
8468
|
-
"options.chainNoteSalt requires
|
|
8974
|
+
"options.chainNoteSalt requires the wallet's viewing key: chainNoteViewingKeyNk (or getChainNoteViewingKeyNk), or ownerUtxoKeypair. The salt anchors a note derived from that nk, and the chain note has to be encrypted under the same key or the note is undiscoverable."
|
|
8469
8975
|
);
|
|
8470
8976
|
}
|
|
8471
8977
|
const chainNoteSalt = options.chainNoteSalt !== void 0 ? assertChainNoteSalt(options.chainNoteSalt) : randomChainNoteSalt();
|
|
8472
8978
|
const chainNoteWillCarrySalt = !options.disableChainNotes && !(options.encryptedNotes && options.encryptedNotes.length > 0);
|
|
8473
|
-
if (
|
|
8474
|
-
|
|
8979
|
+
if (!walletNk && (chainNoteWillCarrySalt || options.enforceViewingKeyRegistration !== false)) {
|
|
8980
|
+
throw missingWalletNkError("transact");
|
|
8981
|
+
}
|
|
8982
|
+
if (walletNk && chainNoteWillCarrySalt) {
|
|
8983
|
+
const selfOwners = new Set(inputUtxos.map((u) => u.keypair.publicKey));
|
|
8984
|
+
if (ownerUtxoKeypair) selfOwners.add(ownerUtxoKeypair.publicKey);
|
|
8985
|
+
const depositBlinding = deriveDepositNoteBlinding(walletNk, chainNoteSalt);
|
|
8475
8986
|
for (let i = 0; i < outputUtxos.length; i++) {
|
|
8476
8987
|
const out = outputUtxos[i];
|
|
8477
8988
|
if (!out || out.amount <= BigInt(0)) continue;
|
|
8478
|
-
if (!
|
|
8479
|
-
if (out.blinding !== deriveChangeNoteBlinding(
|
|
8989
|
+
if (!selfOwners.has(out.keypair.publicKey)) continue;
|
|
8990
|
+
if (out.blinding !== deriveChangeNoteBlinding(walletNk, chainNoteSalt, i) && out.blinding !== depositBlinding) {
|
|
8480
8991
|
throw new Error(
|
|
8481
|
-
`Output ${i} is change (amount ${out.amount}, owned by an input's keypair) but its blinding is not the one derivable from this wallet's viewing key. It was almost certainly built with \`createUtxo\`, whose blinding is random and is written nowhere on chain \u2014 if the caller ever drops the returned note, the funds are unspendable forever. Build change with \`createRecoverableChangeUtxo(amount, keypair, nk, mint, salt, outputIndex)\` and pass the same salt as \`options.chainNoteSalt\`, or use \`partialWithdraw\` / \`transfer\` / \`swapWithChange\`, which do it for you.`
|
|
8992
|
+
`Output ${i} is change (amount ${out.amount}, owned by an input's or the wallet's keypair) but its blinding is not the one derivable from this wallet's viewing key. It was almost certainly built with \`createUtxo\`, whose blinding is random and is written nowhere on chain \u2014 if the caller ever drops the returned note, the funds are unspendable forever. Build change with \`createRecoverableChangeUtxo(amount, keypair, nk, mint, salt, outputIndex)\` and pass the same salt as \`options.chainNoteSalt\`, or use \`partialWithdraw\` / \`transfer\` / \`swapWithChange\`, which do it for you.`
|
|
8482
8993
|
);
|
|
8483
8994
|
}
|
|
8484
8995
|
}
|
|
8485
8996
|
}
|
|
8486
8997
|
assertAllowedRpcConnection(connection);
|
|
8487
8998
|
assertInputMints(inputUtxos, options.expectedMint);
|
|
8488
|
-
await ensureViewingKeyRegistered(options, onProgress,
|
|
8489
|
-
const resolvedChainNoteNk =
|
|
8999
|
+
await ensureViewingKeyRegistered(options, onProgress, walletNk);
|
|
9000
|
+
const resolvedChainNoteNk = walletNk;
|
|
8490
9001
|
if (inputUtxos.length > 2) {
|
|
8491
9002
|
throw new Error("Maximum 2 input UTXOs allowed");
|
|
8492
9003
|
}
|
|
@@ -8860,7 +9371,7 @@ async function transact(params, options) {
|
|
|
8860
9371
|
}
|
|
8861
9372
|
const maxFee = isWithdrawal ? protocolFeeSnapshot : BigInt(0);
|
|
8862
9373
|
const extDataHash = await computeExtDataHash(recipient ?? null, relayerFee, relayer ?? null, maxFee);
|
|
8863
|
-
const chainNoteTimestamp =
|
|
9374
|
+
const chainNoteTimestamp = await relayChainNoteTimestampMs(relayUrl);
|
|
8864
9375
|
const mintField = pubkeyToFieldElement(mint);
|
|
8865
9376
|
let signature = "pending-" + Date.now().toString();
|
|
8866
9377
|
let commitmentIndices = [-1, -1];
|
|
@@ -8956,9 +9467,9 @@ async function transact(params, options) {
|
|
|
8956
9467
|
]));
|
|
8957
9468
|
const noteTailHash = poseidonHasher.F.toObject(poseidonHasher([chainNoteTimestamp, noteCommitment, chainNoteSalt, noteSemantics]));
|
|
8958
9469
|
const chainNoteHash = poseidonHasher.F.toObject(poseidonHasher([CHAIN_NOTE_DOMAIN_TAG, CHAIN_NOTE_TAG, amountDataHash, noteTailHash]));
|
|
8959
|
-
const
|
|
8960
|
-
if (chainNoteHash >=
|
|
8961
|
-
throw new Error(`chainNoteHash out of range: ${chainNoteHash.toString()} >= ${
|
|
9470
|
+
const FIELD_MODULUS3 = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
|
|
9471
|
+
if (chainNoteHash >= FIELD_MODULUS3) {
|
|
9472
|
+
throw new Error(`chainNoteHash out of range: ${chainNoteHash.toString()} >= ${FIELD_MODULUS3.toString()}`);
|
|
8962
9473
|
}
|
|
8963
9474
|
const pathElementsTotal = inPathElements.reduce((sum, arr) => sum + arr.length, 0);
|
|
8964
9475
|
const totalInputs = 1 + // root
|
|
@@ -9380,7 +9891,8 @@ async function transact(params, options) {
|
|
|
9380
9891
|
throw lastError;
|
|
9381
9892
|
}
|
|
9382
9893
|
const classified = classifyRelayError(lastError.message);
|
|
9383
|
-
const
|
|
9894
|
+
const isDepositSubmission = externalAmount > BigInt(0);
|
|
9895
|
+
const isMerkleClass = !isDepositSubmission && !(classified instanceof UtxoAlreadySpentError) && !(classified instanceof SanctionsQuoteError) && !isRootNotFoundError2(lastError);
|
|
9384
9896
|
if (canRebuildMerkleTreeFromChain() && isMerkleClass && relayUrl) {
|
|
9385
9897
|
onProgress?.(
|
|
9386
9898
|
"All relay-tree attempts failed. Rebuilding merkle tree from chain as last resort..."
|
|
@@ -9529,54 +10041,83 @@ async function transact(params, options) {
|
|
|
9529
10041
|
};
|
|
9530
10042
|
}
|
|
9531
10043
|
async function transfer(inputUtxos, recipientPubkey, amount, options) {
|
|
10044
|
+
const owner = await requireOwnerUtxoKeypair(options, "transfer");
|
|
10045
|
+
const transferNk = await requireWalletNk(options, "transfer");
|
|
9532
10046
|
const inputSum = sumUtxoAmounts(inputUtxos);
|
|
9533
10047
|
if (inputSum < amount) {
|
|
9534
10048
|
throw new Error(`Insufficient funds: have ${inputSum}, need ${amount}`);
|
|
9535
10049
|
}
|
|
9536
10050
|
const change = inputSum - amount;
|
|
9537
|
-
const myKeypair = inputUtxos[0].keypair;
|
|
9538
10051
|
const mint = inputUtxos[0].mintAddress;
|
|
9539
|
-
|
|
9540
|
-
|
|
9541
|
-
|
|
10052
|
+
let spendInputs = [
|
|
10053
|
+
...inputUtxos.filter((u) => u.keypair.publicKey === owner.publicKey),
|
|
10054
|
+
...inputUtxos.filter((u) => u.keypair.publicKey !== owner.publicKey)
|
|
10055
|
+
];
|
|
10056
|
+
let spendOptions = options;
|
|
10057
|
+
if (change > BigInt(0) && spendInputs[0].keypair.publicKey !== owner.publicKey) {
|
|
10058
|
+
if (spendInputs.length > 2) {
|
|
10059
|
+
throw new Error(
|
|
10060
|
+
`transfer: none of the ${spendInputs.length} inputs is owned by ownerUtxoKeypair (they are notes from before SDK 0.2.6), so they must first be moved under the wallet key, and one transaction moves at most 2 notes. Consolidate the older notes first (send them to yourself, ownerUtxoKeypair.publicKey, at most 2 per transfer) or withdraw them, then retry this transfer with at most 2 inputs.`
|
|
10061
|
+
);
|
|
10062
|
+
}
|
|
10063
|
+
if (options.relayAuthBatch) {
|
|
10064
|
+
throw new Error(
|
|
10065
|
+
"transfer: no input is owned by ownerUtxoKeypair, so the inputs must first be moved under the wallet key in a separate transaction, which a single batch item cannot carry. Spend them to yourself first, or run this transfer outside the batch."
|
|
10066
|
+
);
|
|
10067
|
+
}
|
|
10068
|
+
options.onProgress?.("Moving notes under the wallet key before the transfer...");
|
|
10069
|
+
const migrationSalt = randomChangeNoteSalt();
|
|
10070
|
+
const migrated = (await createRecoverableChangeUtxo(inputSum, owner, transferNk, mint, migrationSalt, 0)).utxo;
|
|
10071
|
+
const { recipientViewingPublicKey: _recipientViewingPublicKey, ...migrationOptions } = options;
|
|
10072
|
+
void _recipientViewingPublicKey;
|
|
10073
|
+
const migration = await transact(
|
|
10074
|
+
{ inputUtxos: spendInputs, outputUtxos: [migrated], externalAmount: BigInt(0) },
|
|
10075
|
+
{ ...migrationOptions, chainNoteSalt: migrationSalt }
|
|
10076
|
+
);
|
|
10077
|
+
const migratedNote = migration.outputUtxos?.[0] ?? migrated;
|
|
10078
|
+
if (migration.commitmentIndices?.[0] >= 0) {
|
|
10079
|
+
migratedNote.index = migration.commitmentIndices[0];
|
|
10080
|
+
}
|
|
10081
|
+
spendInputs = [migratedNote];
|
|
10082
|
+
spendOptions = { ...options, cachedMerkleTree: migration.merkleTree };
|
|
10083
|
+
}
|
|
10084
|
+
const changeNoteSalt = randomChangeNoteSalt();
|
|
10085
|
+
const isSendToSelf = recipientPubkey === owner.publicKey || inputUtxos.some((u) => u.keypair.publicKey === recipientPubkey);
|
|
9542
10086
|
const recipientKeypair = {
|
|
9543
10087
|
privateKey: BigInt(0),
|
|
9544
10088
|
// Recipient's private key unknown
|
|
9545
10089
|
publicKey: recipientPubkey
|
|
9546
10090
|
};
|
|
9547
|
-
const recipientUtxo =
|
|
10091
|
+
const recipientUtxo = isSendToSelf ? (await createRecoverableChangeUtxo(amount, owner, transferNk, mint, changeNoteSalt, 0)).utxo : await createUtxo(amount, recipientKeypair, mint);
|
|
9548
10092
|
const outputUtxos = [recipientUtxo];
|
|
9549
10093
|
if (change > BigInt(0)) {
|
|
9550
|
-
|
|
9551
|
-
|
|
9552
|
-
|
|
9553
|
-
|
|
9554
|
-
|
|
9555
|
-
|
|
9556
|
-
|
|
9557
|
-
|
|
9558
|
-
|
|
9559
|
-
outputUtxos.push(utxo);
|
|
9560
|
-
} else {
|
|
9561
|
-
outputUtxos.push(await createUtxo(change, myKeypair, mint));
|
|
9562
|
-
}
|
|
10094
|
+
const { utxo } = await createRecoverableChangeUtxo(
|
|
10095
|
+
change,
|
|
10096
|
+
owner,
|
|
10097
|
+
transferNk,
|
|
10098
|
+
mint,
|
|
10099
|
+
changeNoteSalt,
|
|
10100
|
+
1
|
|
10101
|
+
);
|
|
10102
|
+
outputUtxos.push(utxo);
|
|
9563
10103
|
}
|
|
9564
10104
|
return transact(
|
|
9565
10105
|
{
|
|
9566
|
-
inputUtxos,
|
|
10106
|
+
inputUtxos: spendInputs,
|
|
9567
10107
|
outputUtxos,
|
|
9568
10108
|
externalAmount: BigInt(0)
|
|
9569
10109
|
// Pure shield-to-shield
|
|
9570
10110
|
},
|
|
9571
|
-
|
|
10111
|
+
{ ...spendOptions, chainNoteSalt: changeNoteSalt }
|
|
9572
10112
|
);
|
|
9573
10113
|
}
|
|
9574
10114
|
async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
|
|
10115
|
+
const owner = await requireOwnerUtxoKeypair(options, "partialWithdraw");
|
|
10116
|
+
const walletNk = await requireWalletNk(options, "partialWithdraw");
|
|
9575
10117
|
const inputSum = sumUtxoAmounts(inputUtxos);
|
|
9576
10118
|
if (inputSum < withdrawAmount) {
|
|
9577
10119
|
throw new Error(`Insufficient funds: have ${inputSum}, need ${withdrawAmount}`);
|
|
9578
10120
|
}
|
|
9579
|
-
const myKeypair = inputUtxos[0].keypair;
|
|
9580
10121
|
const mint = inputUtxos[0].mintAddress;
|
|
9581
10122
|
let utxos = [...inputUtxos];
|
|
9582
10123
|
let cachedTree = options.cachedMerkleTree;
|
|
@@ -9585,9 +10126,8 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
|
|
|
9585
10126
|
utxos.sort((a, b) => a.amount > b.amount ? 1 : a.amount < b.amount ? -1 : 0);
|
|
9586
10127
|
const [small1, small2, ...rest] = utxos;
|
|
9587
10128
|
const mergedAmount = small1.amount + small2.amount;
|
|
9588
|
-
const
|
|
9589
|
-
const
|
|
9590
|
-
const mergedOutput = mergeNk ? (await createRecoverableChangeUtxo(mergedAmount, myKeypair, mergeNk, mint, mergeSalt, 0)).utxo : await createUtxo(mergedAmount, myKeypair, mint);
|
|
10129
|
+
const mergeSalt = randomChangeNoteSalt();
|
|
10130
|
+
const mergedOutput = (await createRecoverableChangeUtxo(mergedAmount, owner, walletNk, mint, mergeSalt, 0)).utxo;
|
|
9591
10131
|
const mergeResult = await transact(
|
|
9592
10132
|
{
|
|
9593
10133
|
inputUtxos: [small1, small2],
|
|
@@ -9598,7 +10138,7 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
|
|
|
9598
10138
|
{
|
|
9599
10139
|
...options,
|
|
9600
10140
|
cachedMerkleTree: cachedTree,
|
|
9601
|
-
|
|
10141
|
+
chainNoteSalt: mergeSalt
|
|
9602
10142
|
}
|
|
9603
10143
|
);
|
|
9604
10144
|
cachedTree = mergeResult.merkleTree;
|
|
@@ -9613,23 +10153,18 @@ async function partialWithdraw(inputUtxos, recipient, withdrawAmount, options) {
|
|
|
9613
10153
|
const outputUtxos = [];
|
|
9614
10154
|
let changeNoteSalt;
|
|
9615
10155
|
if (change > BigInt(0)) {
|
|
9616
|
-
const
|
|
9617
|
-
|
|
9618
|
-
|
|
9619
|
-
|
|
9620
|
-
|
|
9621
|
-
|
|
9622
|
-
|
|
9623
|
-
|
|
9624
|
-
|
|
9625
|
-
|
|
9626
|
-
|
|
9627
|
-
|
|
9628
|
-
outputUtxos.push(utxo);
|
|
9629
|
-
changeNoteSalt = salt;
|
|
9630
|
-
} else {
|
|
9631
|
-
outputUtxos.push(await createUtxo(change, myKeypair, mint));
|
|
9632
|
-
}
|
|
10156
|
+
const salt = randomChangeNoteSalt();
|
|
10157
|
+
const { utxo } = await createRecoverableChangeUtxo(
|
|
10158
|
+
change,
|
|
10159
|
+
owner,
|
|
10160
|
+
walletNk,
|
|
10161
|
+
mint,
|
|
10162
|
+
salt,
|
|
10163
|
+
0
|
|
10164
|
+
// partialWithdraw puts change at output 0
|
|
10165
|
+
);
|
|
10166
|
+
outputUtxos.push(utxo);
|
|
10167
|
+
changeNoteSalt = salt;
|
|
9633
10168
|
}
|
|
9634
10169
|
return transact(
|
|
9635
10170
|
{
|
|
@@ -9752,6 +10287,8 @@ async function swapUtxo(params, options) {
|
|
|
9752
10287
|
if (relayUrl) {
|
|
9753
10288
|
assertRelayAuthAvailable(relayAuthPlan, "private swap");
|
|
9754
10289
|
}
|
|
10290
|
+
const swapOwner = await requireOwnerUtxoKeypair(options, "swapUtxo");
|
|
10291
|
+
const resolvedSwapChainNoteNk = await requireWalletNk(options, "swapUtxo");
|
|
9755
10292
|
if (inputUtxos.length === 0) {
|
|
9756
10293
|
throw new Error("At least one input UTXO required");
|
|
9757
10294
|
}
|
|
@@ -9777,15 +10314,12 @@ async function swapUtxo(params, options) {
|
|
|
9777
10314
|
throw new Error(`Amount mismatch: input(${totalInputAmount}) != swap(${swapAmount}) + change(${changeAmount})`);
|
|
9778
10315
|
}
|
|
9779
10316
|
onProgress?.("Validating transaction parameters...");
|
|
9780
|
-
|
|
9781
|
-
await ensureViewingKeyRegistered(options, onProgress, swapFallbackNk);
|
|
9782
|
-
const explicitSwapChainNoteNk = await resolveChainNoteNk(options);
|
|
9783
|
-
const resolvedSwapChainNoteNk = explicitSwapChainNoteNk ?? swapFallbackNk;
|
|
10317
|
+
await ensureViewingKeyRegistered(options, onProgress, resolvedSwapChainNoteNk);
|
|
9784
10318
|
const chainNoteSalt = options.chainNoteSalt !== void 0 ? assertChainNoteSalt(options.chainNoteSalt) : randomChainNoteSalt();
|
|
9785
|
-
if (
|
|
9786
|
-
if (changeUtxo.blinding !== deriveChangeNoteBlinding(
|
|
10319
|
+
if (changeUtxo && changeUtxo.amount > BigInt(0) && (changeUtxo.keypair.publicKey === swapOwner.publicKey || inputUtxos.some((u) => u.keypair.publicKey === changeUtxo.keypair.publicKey))) {
|
|
10320
|
+
if (changeUtxo.blinding !== deriveChangeNoteBlinding(resolvedSwapChainNoteNk, chainNoteSalt, 0)) {
|
|
9787
10321
|
throw new Error(
|
|
9788
|
-
`Swap change (amount ${changeUtxo.amount}, owned by an input's keypair) has a blinding that is not derivable from this wallet's viewing key. It was almost certainly built with \`createUtxo\`, whose blinding is random and is written nowhere on chain \u2014 if the caller ever drops the returned note, the funds are unspendable forever. Build it with \`createRecoverableChangeUtxo(amount, keypair, nk, mint, salt, 0)\` and pass the same salt as \`options.chainNoteSalt\`, or use \`swapWithChange\`, which does it for you.`
|
|
10322
|
+
`Swap change (amount ${changeUtxo.amount}, owned by an input's or the wallet's keypair) has a blinding that is not derivable from this wallet's viewing key. It was almost certainly built with \`createUtxo\`, whose blinding is random and is written nowhere on chain \u2014 if the caller ever drops the returned note, the funds are unspendable forever. Build it with \`createRecoverableChangeUtxo(amount, keypair, nk, mint, salt, 0)\` and pass the same salt as \`options.chainNoteSalt\`, or use \`swapWithChange\`, which does it for you.`
|
|
9789
10323
|
);
|
|
9790
10324
|
}
|
|
9791
10325
|
}
|
|
@@ -9809,24 +10343,18 @@ async function swapUtxo(params, options) {
|
|
|
9809
10343
|
);
|
|
9810
10344
|
}
|
|
9811
10345
|
const externalAmount = -swapAmount;
|
|
9812
|
-
|
|
9813
|
-
|
|
9814
|
-
|
|
9815
|
-
|
|
9816
|
-
|
|
9817
|
-
|
|
9818
|
-
|
|
9819
|
-
|
|
9820
|
-
|
|
9821
|
-
|
|
9822
|
-
|
|
9823
|
-
|
|
9824
|
-
refundBlinding = randomFieldElement();
|
|
9825
|
-
}
|
|
9826
|
-
} else {
|
|
9827
|
-
refundKeypair = await generateUtxoKeypair();
|
|
9828
|
-
refundBlinding = randomFieldElement();
|
|
9829
|
-
}
|
|
10346
|
+
const refundNullifier = bigintToBytes323(await computeNullifier(paddedInputs[0]));
|
|
10347
|
+
const refundAuthorization = await deriveSwapRefundAuthorization(
|
|
10348
|
+
resolvedSwapChainNoteNk,
|
|
10349
|
+
refundNullifier,
|
|
10350
|
+
swapOwner
|
|
10351
|
+
);
|
|
10352
|
+
const refundKeypair = {
|
|
10353
|
+
privateKey: refundAuthorization.privateKey,
|
|
10354
|
+
publicKey: refundAuthorization.publicKey
|
|
10355
|
+
};
|
|
10356
|
+
const refundBlinding = refundAuthorization.blinding;
|
|
10357
|
+
const refundDerivedFromNk = true;
|
|
9830
10358
|
if (refundKeypair.publicKey === BigInt(0) || refundBlinding === BigInt(0)) {
|
|
9831
10359
|
throw new Error(
|
|
9832
10360
|
"Refund authorization derivation produced a zero pubkey/blinding \u2014 aborting swap to avoid an unclaimable timeout refund. Retry; a persistent failure indicates a keygen/RNG fault."
|
|
@@ -10152,7 +10680,7 @@ async function swapUtxo(params, options) {
|
|
|
10152
10680
|
for (const utxo of paddedOutputs) {
|
|
10153
10681
|
outputCommitments.push(await computeCommitment2(utxo));
|
|
10154
10682
|
}
|
|
10155
|
-
const chainNoteTimestamp =
|
|
10683
|
+
const chainNoteTimestamp = await relayChainNoteTimestampMs(relayUrl);
|
|
10156
10684
|
onProgress?.("Computing external data hash...");
|
|
10157
10685
|
const mint = swapPoolMint;
|
|
10158
10686
|
const mintField = pubkeyToFieldElement(mint);
|
|
@@ -10466,7 +10994,7 @@ async function swapUtxo(params, options) {
|
|
|
10466
10994
|
forceChainIndexing = !relayUrl;
|
|
10467
10995
|
continue;
|
|
10468
10996
|
}
|
|
10469
|
-
throw new Error(relayFailureMessage("Relay error", responseText));
|
|
10997
|
+
throw new Error(relayFailureMessage("Relay error", responseText, requestBody));
|
|
10470
10998
|
}
|
|
10471
10999
|
const apiResponse = JSON.parse(responseText);
|
|
10472
11000
|
if (!apiResponse.success || !apiResponse.data) {
|
|
@@ -10602,7 +11130,6 @@ async function swapUtxo(params, options) {
|
|
|
10602
11130
|
// V3-04: the refund-fallback secret (hex, 32-byte field elements). Persist to claim a timed-out
|
|
10603
11131
|
// swap; see the UtxoSwapResult.refund docs. amountAfterFee is read from on-chain SwapState.
|
|
10604
11132
|
refund: {
|
|
10605
|
-
privateKey: Buffer.from(bigintToBytes323(refundKeypair.privateKey)).toString("hex"),
|
|
10606
11133
|
publicKey: Buffer.from(bigintToBytes323(refundKeypair.publicKey)).toString("hex"),
|
|
10607
11134
|
blinding: Buffer.from(bigintToBytes323(refundBlinding)).toString("hex"),
|
|
10608
11135
|
derivedFromNk: refundDerivedFromNk
|
|
@@ -10610,6 +11137,7 @@ async function swapUtxo(params, options) {
|
|
|
10610
11137
|
};
|
|
10611
11138
|
}
|
|
10612
11139
|
async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta, minOutputAmount, options, recipientWallet) {
|
|
11140
|
+
const owner = await requireOwnerUtxoKeypair(options, "swapWithChange");
|
|
10613
11141
|
const totalInput = sumUtxoAmounts(inputUtxos);
|
|
10614
11142
|
const change = totalInput - swapAmount;
|
|
10615
11143
|
if (change < BigInt(0)) {
|
|
@@ -10618,16 +11146,11 @@ async function swapWithChange(inputUtxos, swapAmount, outputMint, recipientAta,
|
|
|
10618
11146
|
let changeUtxo;
|
|
10619
11147
|
let changeNoteSalt;
|
|
10620
11148
|
if (change > BigInt(0)) {
|
|
10621
|
-
const myKeypair = inputUtxos[0].keypair;
|
|
10622
11149
|
const mint = inputUtxos[0].mintAddress;
|
|
10623
|
-
const changeNk = await
|
|
10624
|
-
|
|
10625
|
-
|
|
10626
|
-
|
|
10627
|
-
changeNoteSalt = salt;
|
|
10628
|
-
} else {
|
|
10629
|
-
changeUtxo = await createUtxo(change, myKeypair, mint);
|
|
10630
|
-
}
|
|
11150
|
+
const changeNk = await requireWalletNk(options, "swapWithChange");
|
|
11151
|
+
const salt = randomChangeNoteSalt();
|
|
11152
|
+
changeUtxo = (await createRecoverableChangeUtxo(change, owner, changeNk, mint, salt, 0)).utxo;
|
|
11153
|
+
changeNoteSalt = salt;
|
|
10631
11154
|
}
|
|
10632
11155
|
return swapUtxo(
|
|
10633
11156
|
{
|
|
@@ -10953,7 +11476,7 @@ var RelayBatchAuthCoordinator = class {
|
|
|
10953
11476
|
throw new Error("Every item of a batch must target the same program id.");
|
|
10954
11477
|
}
|
|
10955
11478
|
}
|
|
10956
|
-
const nowSeconds =
|
|
11479
|
+
const nowSeconds = relayNowSeconds();
|
|
10957
11480
|
const preimages = waiting.map(
|
|
10958
11481
|
(w) => buildRelayAuthPreimage(w.endpoint, programId, w.body, this.sender, nowSeconds, w.fields)
|
|
10959
11482
|
);
|
|
@@ -11394,7 +11917,7 @@ async function deriveDepositCandidate(viewingKeyNk, noteSalt) {
|
|
|
11394
11917
|
const cached = depositSecretsCache.get(key);
|
|
11395
11918
|
if (cached) return cached;
|
|
11396
11919
|
try {
|
|
11397
|
-
const secrets = await
|
|
11920
|
+
const secrets = await deriveLegacyDepositNoteSecrets(viewingKeyNk, noteSalt);
|
|
11398
11921
|
if (depositSecretsCache.size >= 4096) {
|
|
11399
11922
|
const oldest = depositSecretsCache.keys().next();
|
|
11400
11923
|
if (!oldest.done) depositSecretsCache.delete(oldest.value);
|
|
@@ -11977,6 +12500,7 @@ async function scanTransactions(opts) {
|
|
|
11977
12500
|
} else {
|
|
11978
12501
|
const derived = await deriveDepositCandidate(viewingKeyNk, compactNote.noteSalt);
|
|
11979
12502
|
const candidateKeys = [
|
|
12503
|
+
opts.ownerUtxoPublicKey,
|
|
11980
12504
|
derived?.keypair.publicKey,
|
|
11981
12505
|
opts.ownUtxoPublicKey,
|
|
11982
12506
|
BigInt(0)
|
|
@@ -12030,6 +12554,7 @@ async function scanTransactions(opts) {
|
|
|
12030
12554
|
try {
|
|
12031
12555
|
const recoveredDeposit = await matchDepositNote({
|
|
12032
12556
|
viewingKeyNk,
|
|
12557
|
+
ownerUtxoKeypair: opts.ownerUtxoPublicKey !== void 0 ? { privateKey: 0n, publicKey: opts.ownerUtxoPublicKey } : void 0,
|
|
12033
12558
|
noteSalt: compactNote.noteSalt,
|
|
12034
12559
|
// Output 0's amount. For a shield with no inputs — the shape `transact` builds for a
|
|
12035
12560
|
// deposit — that is the public deposit amount. A deposit that also merged inputs
|
|
@@ -12064,7 +12589,8 @@ async function scanTransactions(opts) {
|
|
|
12064
12589
|
mintAddress: (0, import_kit.address)(asset.mint),
|
|
12065
12590
|
outputIndex: 0,
|
|
12066
12591
|
// v4 describes output 0, which is where change lands
|
|
12067
|
-
outputCommitments: ixCtx.outputCommitments ?? []
|
|
12592
|
+
outputCommitments: ixCtx.outputCommitments ?? [],
|
|
12593
|
+
ownerUtxoPublicKey: opts.ownerUtxoPublicKey
|
|
12068
12594
|
});
|
|
12069
12595
|
if (recoveredChange) {
|
|
12070
12596
|
recoveredChangeNotes.push({
|
|
@@ -12174,6 +12700,17 @@ async function scanTransactions(opts) {
|
|
|
12174
12700
|
runningByAsset.set(key, running);
|
|
12175
12701
|
tx.runningBalance = running;
|
|
12176
12702
|
}
|
|
12703
|
+
const legacyKeys = /* @__PURE__ */ new Map();
|
|
12704
|
+
for (const note of recoveredDepositNotes) {
|
|
12705
|
+
if (note.legacyExposed) legacyKeys.set(note.keypair.publicKey, note.keypair.privateKey);
|
|
12706
|
+
}
|
|
12707
|
+
for (const change of recoveredChangeNotes) {
|
|
12708
|
+
const legacyPrivateKey = legacyKeys.get(change.keypair.publicKey);
|
|
12709
|
+
if (legacyPrivateKey !== void 0) {
|
|
12710
|
+
change.keypair = { privateKey: legacyPrivateKey, publicKey: change.keypair.publicKey };
|
|
12711
|
+
change.legacyExposed = true;
|
|
12712
|
+
}
|
|
12713
|
+
}
|
|
12177
12714
|
return {
|
|
12178
12715
|
transactions: txs,
|
|
12179
12716
|
summary: {
|
|
@@ -12253,29 +12790,1659 @@ function formatComplianceCsv(report) {
|
|
|
12253
12790
|
return header + rows;
|
|
12254
12791
|
}
|
|
12255
12792
|
|
|
12256
|
-
// src/
|
|
12793
|
+
// src/relay/note-index-format.ts
|
|
12794
|
+
var import_sha25 = require("@noble/hashes/sha2");
|
|
12257
12795
|
init_address();
|
|
12258
12796
|
init_utxo();
|
|
12259
|
-
var
|
|
12260
|
-
|
|
12261
|
-
|
|
12262
|
-
|
|
12797
|
+
var NOTE_INDEX_MAGIC = new Uint8Array([67, 78, 73, 49]);
|
|
12798
|
+
var NOTE_INDEX_FORMAT_VERSION = 1;
|
|
12799
|
+
var NOTE_INDEX_PAGE_SIZE = 1024;
|
|
12800
|
+
var NOTE_INDEX_NO_LEAF = 0xffffffffffffffffn;
|
|
12801
|
+
var NOTE_INDEX_MAX_PAGE_BYTES = 2 * 1024 * 1024;
|
|
12802
|
+
var NOTE_INDEX_HEADER_LEN = 68;
|
|
12803
|
+
var NOTE_INDEX_KIND_TX = 1;
|
|
12804
|
+
var NOTE_INDEX_KIND_DELIVERY = 2;
|
|
12805
|
+
var NOTE_INDEX_KIND_SWAP_REFUND = 3;
|
|
12806
|
+
var NOTE_SOURCE_NONE = 0;
|
|
12807
|
+
var NOTE_SOURCE_CARRIER = 2;
|
|
12808
|
+
var ITEM_HEADER_LEN = 3;
|
|
12809
|
+
var TX_FIXED_LEN = 263;
|
|
12810
|
+
var DELIVERY_BODY_LEN = 256;
|
|
12811
|
+
var SWAP_REFUND_BODY_LEN = 184;
|
|
12812
|
+
var MAX_UNKNOWN_BODY_LEN = 1024;
|
|
12813
|
+
var DELIVERY_ENVELOPE_LEN = 112;
|
|
12814
|
+
var SIGNATURE_LEN = 64;
|
|
12815
|
+
var NOTE_VERSION_BY_LEN = /* @__PURE__ */ new Map([
|
|
12816
|
+
[25, 2],
|
|
12817
|
+
[57, 3],
|
|
12818
|
+
[98, 4]
|
|
12819
|
+
]);
|
|
12820
|
+
var COMPLETE_FLAG = 1;
|
|
12821
|
+
var U64_MAX2 = (1n << 64n) - 1n;
|
|
12822
|
+
var U32_MAX = 4294967295;
|
|
12823
|
+
var MAX_LEAF_INDEX = (1n << 32n) - 1n;
|
|
12824
|
+
var WSOL_BYTES = addressBytes(NATIVE_SOL_MINT);
|
|
12825
|
+
var NoteIndexFormatError = class extends Error {
|
|
12826
|
+
constructor(message) {
|
|
12827
|
+
super(`Note index format error: ${message}`);
|
|
12828
|
+
this.name = "NoteIndexFormatError";
|
|
12263
12829
|
}
|
|
12264
|
-
|
|
12265
|
-
|
|
12266
|
-
|
|
12267
|
-
|
|
12268
|
-
|
|
12269
|
-
|
|
12270
|
-
|
|
12271
|
-
|
|
12272
|
-
|
|
12273
|
-
|
|
12274
|
-
|
|
12275
|
-
|
|
12276
|
-
|
|
12277
|
-
|
|
12278
|
-
|
|
12830
|
+
};
|
|
12831
|
+
function isAllZero2(bytes) {
|
|
12832
|
+
for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
|
|
12833
|
+
return true;
|
|
12834
|
+
}
|
|
12835
|
+
function bytesEqual(a, b) {
|
|
12836
|
+
if (a.length !== b.length) return false;
|
|
12837
|
+
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
|
|
12838
|
+
return true;
|
|
12839
|
+
}
|
|
12840
|
+
function checkLeafPair(commitment, leaf, label) {
|
|
12841
|
+
if (isAllZero2(commitment)) {
|
|
12842
|
+
if (leaf !== NOTE_INDEX_NO_LEAF) throw new NoteIndexFormatError(`${label}: zero commitment must carry NO_LEAF`);
|
|
12843
|
+
return;
|
|
12844
|
+
}
|
|
12845
|
+
if (leaf > MAX_LEAF_INDEX) throw new NoteIndexFormatError(`${label}: leaf ${leaf} is not a leaf of the tree`);
|
|
12846
|
+
}
|
|
12847
|
+
var Reader = class {
|
|
12848
|
+
constructor(bytes, start, end) {
|
|
12849
|
+
this.bytes = bytes;
|
|
12850
|
+
this.end = end;
|
|
12851
|
+
this.offset = start;
|
|
12852
|
+
this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
12853
|
+
}
|
|
12854
|
+
take(len) {
|
|
12855
|
+
if (this.offset + len > this.end) throw new NoteIndexFormatError("truncated item body");
|
|
12856
|
+
const at = this.offset;
|
|
12857
|
+
this.offset += len;
|
|
12858
|
+
return at;
|
|
12859
|
+
}
|
|
12860
|
+
u8() {
|
|
12861
|
+
return this.bytes[this.take(1)];
|
|
12862
|
+
}
|
|
12863
|
+
u32() {
|
|
12864
|
+
return this.view.getUint32(this.take(4), true);
|
|
12865
|
+
}
|
|
12866
|
+
u64() {
|
|
12867
|
+
return this.view.getBigUint64(this.take(8), true);
|
|
12868
|
+
}
|
|
12869
|
+
i64() {
|
|
12870
|
+
return this.view.getBigInt64(this.take(8), true);
|
|
12871
|
+
}
|
|
12872
|
+
raw(len) {
|
|
12873
|
+
const at = this.take(len);
|
|
12874
|
+
return this.bytes.slice(at, at + len);
|
|
12875
|
+
}
|
|
12876
|
+
get position() {
|
|
12877
|
+
return this.offset;
|
|
12878
|
+
}
|
|
12879
|
+
};
|
|
12880
|
+
function parseTx(r, bodyLen) {
|
|
12881
|
+
const mint = r.raw(32);
|
|
12882
|
+
const slot = r.u64();
|
|
12883
|
+
const blockPos = r.u32();
|
|
12884
|
+
const ixTag = r.u8();
|
|
12885
|
+
if (ixTag !== 0 && ixTag !== 1) throw new NoteIndexFormatError(`TX: ix_tag ${ixTag}`);
|
|
12886
|
+
const publicAmount = r.i64();
|
|
12887
|
+
const nullifier0 = r.raw(32);
|
|
12888
|
+
const nullifier1 = r.raw(32);
|
|
12889
|
+
const comm0 = r.raw(32);
|
|
12890
|
+
const leaf0 = r.u64();
|
|
12891
|
+
const comm1 = r.raw(32);
|
|
12892
|
+
const leaf1 = r.u64();
|
|
12893
|
+
const noteSource = r.u8();
|
|
12894
|
+
if (noteSource > NOTE_SOURCE_CARRIER) throw new NoteIndexFormatError(`TX: note_source ${noteSource}`);
|
|
12895
|
+
const noteLen = r.u8();
|
|
12896
|
+
if (noteSource === NOTE_SOURCE_NONE) {
|
|
12897
|
+
if (noteLen !== 0) throw new NoteIndexFormatError(`TX: note_len ${noteLen} without a note source`);
|
|
12898
|
+
} else if (!NOTE_VERSION_BY_LEN.has(noteLen)) {
|
|
12899
|
+
throw new NoteIndexFormatError(`TX: note_len ${noteLen}`);
|
|
12900
|
+
}
|
|
12901
|
+
if (bodyLen !== TX_FIXED_LEN + noteLen) {
|
|
12902
|
+
throw new NoteIndexFormatError(`TX: body_len ${bodyLen} != ${TX_FIXED_LEN + noteLen} for note_len ${noteLen}`);
|
|
12903
|
+
}
|
|
12904
|
+
const note = r.raw(noteLen);
|
|
12905
|
+
if (noteLen > 0 && note[0] !== NOTE_VERSION_BY_LEN.get(noteLen)) {
|
|
12906
|
+
throw new NoteIndexFormatError(`TX: note version ${note[0]} does not match note_len ${noteLen}`);
|
|
12907
|
+
}
|
|
12908
|
+
const signature = r.raw(SIGNATURE_LEN);
|
|
12909
|
+
checkLeafPair(comm0, leaf0, "TX comm0");
|
|
12910
|
+
checkLeafPair(comm1, leaf1, "TX comm1");
|
|
12911
|
+
return {
|
|
12912
|
+
kind: 1,
|
|
12913
|
+
mint,
|
|
12914
|
+
slot,
|
|
12915
|
+
blockPos,
|
|
12916
|
+
ixTag,
|
|
12917
|
+
publicAmount,
|
|
12918
|
+
nullifier0,
|
|
12919
|
+
nullifier1,
|
|
12920
|
+
comm0,
|
|
12921
|
+
leaf0,
|
|
12922
|
+
comm1,
|
|
12923
|
+
leaf1,
|
|
12924
|
+
noteSource,
|
|
12925
|
+
note,
|
|
12926
|
+
signature
|
|
12927
|
+
};
|
|
12928
|
+
}
|
|
12929
|
+
function parseDelivery(r) {
|
|
12930
|
+
const mint = r.raw(32);
|
|
12931
|
+
const slot = r.u64();
|
|
12932
|
+
const commitment = r.raw(32);
|
|
12933
|
+
const leaf = r.u64();
|
|
12934
|
+
const envelope = r.raw(DELIVERY_ENVELOPE_LEN);
|
|
12935
|
+
const signature = r.raw(SIGNATURE_LEN);
|
|
12936
|
+
if (isAllZero2(commitment)) throw new NoteIndexFormatError("DELIVERY: zero commitment");
|
|
12937
|
+
checkLeafPair(commitment, leaf, "DELIVERY");
|
|
12938
|
+
return { kind: 2, mint, slot, commitment, leaf, envelope, signature };
|
|
12939
|
+
}
|
|
12940
|
+
function parseSwapRefund(r) {
|
|
12941
|
+
const mint = r.raw(32);
|
|
12942
|
+
if (!bytesEqual(mint, WSOL_BYTES)) throw new NoteIndexFormatError("SWAP_REFUND: mint is not WSOL");
|
|
12943
|
+
const slot = r.u64();
|
|
12944
|
+
const commitment = r.raw(32);
|
|
12945
|
+
const leaf = r.u64();
|
|
12946
|
+
const amountAfterFee = r.u64();
|
|
12947
|
+
const nullifier0 = r.raw(32);
|
|
12948
|
+
const signature = r.raw(SIGNATURE_LEN);
|
|
12949
|
+
if (isAllZero2(commitment)) throw new NoteIndexFormatError("SWAP_REFUND: zero commitment");
|
|
12950
|
+
checkLeafPair(commitment, leaf, "SWAP_REFUND");
|
|
12951
|
+
return { kind: 3, mint, slot, commitment, leaf, amountAfterFee, nullifier0, signature };
|
|
12952
|
+
}
|
|
12953
|
+
function parseNoteIndexPage(bytes, expect, options = {}) {
|
|
12954
|
+
if (!(bytes instanceof Uint8Array)) throw new NoteIndexFormatError("page must be a Uint8Array");
|
|
12955
|
+
if (bytes.length > NOTE_INDEX_MAX_PAGE_BYTES) {
|
|
12956
|
+
throw new NoteIndexFormatError(`page is ${bytes.length} bytes, over the ${NOTE_INDEX_MAX_PAGE_BYTES}-byte bound`);
|
|
12957
|
+
}
|
|
12958
|
+
if (bytes.length < NOTE_INDEX_HEADER_LEN) throw new NoteIndexFormatError("truncated page header");
|
|
12959
|
+
for (let i = 0; i < NOTE_INDEX_MAGIC.length; i++) {
|
|
12960
|
+
if (bytes[i] !== NOTE_INDEX_MAGIC[i]) throw new NoteIndexFormatError("bad magic");
|
|
12961
|
+
}
|
|
12962
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
12963
|
+
const version = bytes[4];
|
|
12964
|
+
if (version !== NOTE_INDEX_FORMAT_VERSION) throw new NoteIndexFormatError(`unsupported version ${version}`);
|
|
12965
|
+
const flags = bytes[5];
|
|
12966
|
+
if ((flags & ~COMPLETE_FLAG) !== 0) throw new NoteIndexFormatError(`unknown flag bits 0x${flags.toString(16)}`);
|
|
12967
|
+
if (view.getUint16(6, true) !== 0) throw new NoteIndexFormatError("reserved bytes are not zero");
|
|
12968
|
+
const epoch = view.getBigUint64(8, true);
|
|
12969
|
+
const page = view.getBigUint64(16, true);
|
|
12970
|
+
const firstSeq = view.getBigUint64(24, true);
|
|
12971
|
+
const count = view.getUint32(32, true);
|
|
12972
|
+
const prevChain = bytes.slice(36, 68);
|
|
12973
|
+
const complete = (flags & COMPLETE_FLAG) !== 0;
|
|
12974
|
+
if (expect) {
|
|
12975
|
+
if (epoch !== expect.epoch) throw new NoteIndexFormatError(`epoch ${epoch} is not the requested ${expect.epoch}`);
|
|
12976
|
+
if (page !== BigInt(expect.page)) throw new NoteIndexFormatError(`page ${page} is not the requested ${expect.page}`);
|
|
12977
|
+
}
|
|
12978
|
+
if (count > NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`count ${count} exceeds ${NOTE_INDEX_PAGE_SIZE}`);
|
|
12979
|
+
if (complete && count !== NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`complete page with count ${count}`);
|
|
12980
|
+
if (firstSeq !== page * BigInt(NOTE_INDEX_PAGE_SIZE)) {
|
|
12981
|
+
throw new NoteIndexFormatError(`first_seq ${firstSeq} is not page ${page} * ${NOTE_INDEX_PAGE_SIZE}`);
|
|
12982
|
+
}
|
|
12983
|
+
const items = [];
|
|
12984
|
+
const rawItems = [];
|
|
12985
|
+
const itemPositions = [];
|
|
12986
|
+
let skippedUnknown = 0;
|
|
12987
|
+
let skippedMalformed = 0;
|
|
12988
|
+
let offset = NOTE_INDEX_HEADER_LEN;
|
|
12989
|
+
for (let i = 0; i < count; i++) {
|
|
12990
|
+
if (offset + ITEM_HEADER_LEN > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} header`);
|
|
12991
|
+
const kind = bytes[offset];
|
|
12992
|
+
const bodyLen = view.getUint16(offset + 1, true);
|
|
12993
|
+
const bodyStart = offset + ITEM_HEADER_LEN;
|
|
12994
|
+
const bodyEnd = bodyStart + bodyLen;
|
|
12995
|
+
if (bodyEnd > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} body`);
|
|
12996
|
+
if (kind !== NOTE_INDEX_KIND_TX && kind !== NOTE_INDEX_KIND_DELIVERY && kind !== NOTE_INDEX_KIND_SWAP_REFUND) {
|
|
12997
|
+
if (bodyLen > MAX_UNKNOWN_BODY_LEN) throw new NoteIndexFormatError(`unknown kind ${kind} with body_len ${bodyLen}`);
|
|
12998
|
+
skippedUnknown++;
|
|
12999
|
+
offset = bodyEnd;
|
|
13000
|
+
continue;
|
|
13001
|
+
}
|
|
13002
|
+
let item;
|
|
13003
|
+
try {
|
|
13004
|
+
item = parseKnownBody(bytes, kind, bodyStart, bodyEnd, i);
|
|
13005
|
+
} catch (error) {
|
|
13006
|
+
if (!options.skipMalformedItems || !(error instanceof NoteIndexFormatError)) throw error;
|
|
13007
|
+
skippedMalformed++;
|
|
13008
|
+
offset = bodyEnd;
|
|
13009
|
+
continue;
|
|
13010
|
+
}
|
|
13011
|
+
items.push(item);
|
|
13012
|
+
rawItems.push(bytes.slice(offset, bodyEnd));
|
|
13013
|
+
itemPositions.push(i);
|
|
13014
|
+
offset = bodyEnd;
|
|
13015
|
+
}
|
|
13016
|
+
if (offset !== bytes.length) throw new NoteIndexFormatError(`${bytes.length - offset} trailing bytes after ${count} items`);
|
|
13017
|
+
return { epoch, page, firstSeq, complete, count, prevChain, items, rawItems, skippedUnknown, itemPositions, skippedMalformed };
|
|
13018
|
+
}
|
|
13019
|
+
function parseKnownBody(bytes, kind, bodyStart, bodyEnd, i) {
|
|
13020
|
+
const bodyLen = bodyEnd - bodyStart;
|
|
13021
|
+
const r = new Reader(bytes, bodyStart, bodyEnd);
|
|
13022
|
+
let item;
|
|
13023
|
+
if (kind === NOTE_INDEX_KIND_TX) {
|
|
13024
|
+
if (bodyLen < TX_FIXED_LEN) throw new NoteIndexFormatError(`TX: body_len ${bodyLen}`);
|
|
13025
|
+
item = parseTx(r, bodyLen);
|
|
13026
|
+
} else if (kind === NOTE_INDEX_KIND_DELIVERY) {
|
|
13027
|
+
if (bodyLen !== DELIVERY_BODY_LEN) throw new NoteIndexFormatError(`DELIVERY: body_len ${bodyLen}`);
|
|
13028
|
+
item = parseDelivery(r);
|
|
13029
|
+
} else {
|
|
13030
|
+
if (bodyLen !== SWAP_REFUND_BODY_LEN) throw new NoteIndexFormatError(`SWAP_REFUND: body_len ${bodyLen}`);
|
|
13031
|
+
item = parseSwapRefund(r);
|
|
13032
|
+
}
|
|
13033
|
+
if (r.position !== bodyEnd) throw new NoteIndexFormatError(`item ${i} body has unread bytes`);
|
|
13034
|
+
return item;
|
|
13035
|
+
}
|
|
13036
|
+
function parseNoteIndexItem(raw) {
|
|
13037
|
+
if (!(raw instanceof Uint8Array) || raw.length < ITEM_HEADER_LEN) throw new NoteIndexFormatError("truncated item");
|
|
13038
|
+
const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
|
|
13039
|
+
const kind = raw[0];
|
|
13040
|
+
const bodyLen = view.getUint16(1, true);
|
|
13041
|
+
if (ITEM_HEADER_LEN + bodyLen !== raw.length) throw new NoteIndexFormatError("item length mismatch");
|
|
13042
|
+
const r = new Reader(raw, ITEM_HEADER_LEN, raw.length);
|
|
13043
|
+
let item;
|
|
13044
|
+
if (kind === NOTE_INDEX_KIND_TX && bodyLen >= TX_FIXED_LEN) item = parseTx(r, bodyLen);
|
|
13045
|
+
else if (kind === NOTE_INDEX_KIND_DELIVERY && bodyLen === DELIVERY_BODY_LEN) item = parseDelivery(r);
|
|
13046
|
+
else if (kind === NOTE_INDEX_KIND_SWAP_REFUND && bodyLen === SWAP_REFUND_BODY_LEN) item = parseSwapRefund(r);
|
|
13047
|
+
else throw new NoteIndexFormatError(`item kind ${kind} with body_len ${bodyLen}`);
|
|
13048
|
+
if (r.position !== raw.length) throw new NoteIndexFormatError("item body has unread bytes");
|
|
13049
|
+
return item;
|
|
13050
|
+
}
|
|
13051
|
+
function computeNoteIndexChain(prevChain, pageBytes) {
|
|
13052
|
+
if (!(prevChain instanceof Uint8Array) || prevChain.length !== 32) throw new NoteIndexFormatError("prevChain must be 32 bytes");
|
|
13053
|
+
if (pageBytes.length < NOTE_INDEX_HEADER_LEN) throw new NoteIndexFormatError("truncated page header");
|
|
13054
|
+
const items = pageBytes.subarray(NOTE_INDEX_HEADER_LEN);
|
|
13055
|
+
const input = new Uint8Array(32 + items.length);
|
|
13056
|
+
input.set(prevChain);
|
|
13057
|
+
input.set(items, 32);
|
|
13058
|
+
return (0, import_sha25.sha256)(input);
|
|
13059
|
+
}
|
|
13060
|
+
var Writer = class {
|
|
13061
|
+
constructor() {
|
|
13062
|
+
this.chunks = [];
|
|
13063
|
+
this.length = 0;
|
|
13064
|
+
}
|
|
13065
|
+
push(bytes) {
|
|
13066
|
+
this.chunks.push(bytes);
|
|
13067
|
+
this.length += bytes.length;
|
|
13068
|
+
}
|
|
13069
|
+
u8(v) {
|
|
13070
|
+
if (!Number.isInteger(v) || v < 0 || v > 255) throw new NoteIndexFormatError(`u8 out of range: ${v}`);
|
|
13071
|
+
this.push(Uint8Array.of(v));
|
|
13072
|
+
}
|
|
13073
|
+
u16(v) {
|
|
13074
|
+
if (!Number.isInteger(v) || v < 0 || v > 65535) throw new NoteIndexFormatError(`u16 out of range: ${v}`);
|
|
13075
|
+
const b = new Uint8Array(2);
|
|
13076
|
+
new DataView(b.buffer).setUint16(0, v, true);
|
|
13077
|
+
this.push(b);
|
|
13078
|
+
}
|
|
13079
|
+
u32(v) {
|
|
13080
|
+
if (!Number.isInteger(v) || v < 0 || v > U32_MAX) throw new NoteIndexFormatError(`u32 out of range: ${v}`);
|
|
13081
|
+
const b = new Uint8Array(4);
|
|
13082
|
+
new DataView(b.buffer).setUint32(0, v, true);
|
|
13083
|
+
this.push(b);
|
|
13084
|
+
}
|
|
13085
|
+
u64(v) {
|
|
13086
|
+
if (v < 0n || v > U64_MAX2) throw new NoteIndexFormatError(`u64 out of range: ${v}`);
|
|
13087
|
+
const b = new Uint8Array(8);
|
|
13088
|
+
new DataView(b.buffer).setBigUint64(0, v, true);
|
|
13089
|
+
this.push(b);
|
|
13090
|
+
}
|
|
13091
|
+
i64(v) {
|
|
13092
|
+
if (v < -(1n << 63n) || v >= 1n << 63n) throw new NoteIndexFormatError(`i64 out of range: ${v}`);
|
|
13093
|
+
const b = new Uint8Array(8);
|
|
13094
|
+
new DataView(b.buffer).setBigInt64(0, v, true);
|
|
13095
|
+
this.push(b);
|
|
13096
|
+
}
|
|
13097
|
+
fixed(bytes, len, label) {
|
|
13098
|
+
if (!(bytes instanceof Uint8Array) || bytes.length !== len) throw new NoteIndexFormatError(`${label} must be ${len} bytes`);
|
|
13099
|
+
this.push(bytes);
|
|
13100
|
+
}
|
|
13101
|
+
finish() {
|
|
13102
|
+
const out = new Uint8Array(this.length);
|
|
13103
|
+
let off = 0;
|
|
13104
|
+
for (const c of this.chunks) {
|
|
13105
|
+
out.set(c, off);
|
|
13106
|
+
off += c.length;
|
|
13107
|
+
}
|
|
13108
|
+
return out;
|
|
13109
|
+
}
|
|
13110
|
+
};
|
|
13111
|
+
function encodeItemBody(item) {
|
|
13112
|
+
const w = new Writer();
|
|
13113
|
+
switch (item.kind) {
|
|
13114
|
+
case NOTE_INDEX_KIND_TX: {
|
|
13115
|
+
w.fixed(item.mint, 32, "mint");
|
|
13116
|
+
w.u64(item.slot);
|
|
13117
|
+
w.u32(item.blockPos);
|
|
13118
|
+
w.u8(item.ixTag);
|
|
13119
|
+
w.i64(item.publicAmount);
|
|
13120
|
+
w.fixed(item.nullifier0, 32, "nullifier0");
|
|
13121
|
+
w.fixed(item.nullifier1, 32, "nullifier1");
|
|
13122
|
+
w.fixed(item.comm0, 32, "comm0");
|
|
13123
|
+
w.u64(item.leaf0);
|
|
13124
|
+
w.fixed(item.comm1, 32, "comm1");
|
|
13125
|
+
w.u64(item.leaf1);
|
|
13126
|
+
w.u8(item.noteSource);
|
|
13127
|
+
const noteLen = item.note.length;
|
|
13128
|
+
if (item.noteSource === NOTE_SOURCE_NONE ? noteLen !== 0 : !NOTE_VERSION_BY_LEN.has(noteLen)) {
|
|
13129
|
+
throw new NoteIndexFormatError(`note_len ${noteLen} invalid for note_source ${item.noteSource}`);
|
|
13130
|
+
}
|
|
13131
|
+
w.u8(noteLen);
|
|
13132
|
+
w.push(item.note);
|
|
13133
|
+
w.fixed(item.signature, SIGNATURE_LEN, "signature");
|
|
13134
|
+
break;
|
|
13135
|
+
}
|
|
13136
|
+
case NOTE_INDEX_KIND_DELIVERY:
|
|
13137
|
+
w.fixed(item.mint, 32, "mint");
|
|
13138
|
+
w.u64(item.slot);
|
|
13139
|
+
w.fixed(item.commitment, 32, "commitment");
|
|
13140
|
+
w.u64(item.leaf);
|
|
13141
|
+
w.fixed(item.envelope, DELIVERY_ENVELOPE_LEN, "envelope");
|
|
13142
|
+
w.fixed(item.signature, SIGNATURE_LEN, "signature");
|
|
13143
|
+
break;
|
|
13144
|
+
case NOTE_INDEX_KIND_SWAP_REFUND:
|
|
13145
|
+
w.fixed(item.mint, 32, "mint");
|
|
13146
|
+
w.u64(item.slot);
|
|
13147
|
+
w.fixed(item.commitment, 32, "commitment");
|
|
13148
|
+
w.u64(item.leaf);
|
|
13149
|
+
w.u64(item.amountAfterFee);
|
|
13150
|
+
w.fixed(item.nullifier0, 32, "nullifier0");
|
|
13151
|
+
w.fixed(item.signature, SIGNATURE_LEN, "signature");
|
|
13152
|
+
break;
|
|
13153
|
+
default:
|
|
13154
|
+
throw new NoteIndexFormatError(`cannot encode kind ${item.kind}`);
|
|
13155
|
+
}
|
|
13156
|
+
return w.finish();
|
|
13157
|
+
}
|
|
13158
|
+
function encodeNoteIndexItem(item) {
|
|
13159
|
+
const body = encodeItemBody(item);
|
|
13160
|
+
const w = new Writer();
|
|
13161
|
+
w.u8(item.kind);
|
|
13162
|
+
w.u16(body.length);
|
|
13163
|
+
w.push(body);
|
|
13164
|
+
return w.finish();
|
|
13165
|
+
}
|
|
13166
|
+
function encodeNoteIndexPage(params) {
|
|
13167
|
+
const items = params.items ?? [];
|
|
13168
|
+
if (items.length > NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`count ${items.length} exceeds ${NOTE_INDEX_PAGE_SIZE}`);
|
|
13169
|
+
const w = new Writer();
|
|
13170
|
+
w.push(NOTE_INDEX_MAGIC);
|
|
13171
|
+
w.u8(NOTE_INDEX_FORMAT_VERSION);
|
|
13172
|
+
w.u8(params.complete ? COMPLETE_FLAG : 0);
|
|
13173
|
+
w.u16(0);
|
|
13174
|
+
w.u64(BigInt(params.epoch));
|
|
13175
|
+
w.u64(BigInt(params.page));
|
|
13176
|
+
w.u64(BigInt(params.firstSeq));
|
|
13177
|
+
w.u32(items.length);
|
|
13178
|
+
w.fixed(params.prevChain, 32, "prevChain");
|
|
13179
|
+
for (const item of items) w.push(encodeNoteIndexItem(item));
|
|
13180
|
+
return w.finish();
|
|
13181
|
+
}
|
|
13182
|
+
|
|
13183
|
+
// src/relay/note-index-client.ts
|
|
13184
|
+
var DEFAULT_TIMEOUT_MS2 = 3e4;
|
|
13185
|
+
var DEFAULT_MAX_RETRIES2 = 3;
|
|
13186
|
+
var RETRY_BASE_DELAY_MS = 500;
|
|
13187
|
+
var U64_MAX3 = (1n << 64n) - 1n;
|
|
13188
|
+
function joinPath(relayUrl, path) {
|
|
13189
|
+
const url = new URL(relayUrl);
|
|
13190
|
+
url.pathname = url.pathname.replace(/\/$/, "") + path;
|
|
13191
|
+
return url;
|
|
13192
|
+
}
|
|
13193
|
+
function abortError() {
|
|
13194
|
+
const error = new Error("Note index request aborted");
|
|
13195
|
+
error.name = "AbortError";
|
|
13196
|
+
return error;
|
|
13197
|
+
}
|
|
13198
|
+
function sleep4(ms, signal) {
|
|
13199
|
+
return new Promise((resolve, reject) => {
|
|
13200
|
+
if (signal?.aborted) return reject(abortError());
|
|
13201
|
+
const timer = setTimeout(() => {
|
|
13202
|
+
signal?.removeEventListener("abort", onAbort);
|
|
13203
|
+
resolve();
|
|
13204
|
+
}, ms);
|
|
13205
|
+
const onAbort = () => {
|
|
13206
|
+
clearTimeout(timer);
|
|
13207
|
+
reject(abortError());
|
|
13208
|
+
};
|
|
13209
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
13210
|
+
});
|
|
13211
|
+
}
|
|
13212
|
+
var RetryableStatusError = class extends Error {
|
|
13213
|
+
};
|
|
13214
|
+
var HttpStatusError = class extends Error {
|
|
13215
|
+
constructor(status, message) {
|
|
13216
|
+
super(message);
|
|
13217
|
+
this.status = status;
|
|
13218
|
+
this.name = "HttpStatusError";
|
|
13219
|
+
}
|
|
13220
|
+
};
|
|
13221
|
+
async function requestWithRetry(url, options, read) {
|
|
13222
|
+
assertAllowedRelayOrigin(url);
|
|
13223
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
|
|
13224
|
+
const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES2;
|
|
13225
|
+
let lastError;
|
|
13226
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
13227
|
+
if (options.signal?.aborted) throw abortError();
|
|
13228
|
+
const controller = new AbortController();
|
|
13229
|
+
const onAbort = () => controller.abort();
|
|
13230
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
13231
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
13232
|
+
try {
|
|
13233
|
+
const response = await relayFetch(url, { signal: controller.signal }, { observeClock: false });
|
|
13234
|
+
if (response.status === 429 || response.status >= 500) {
|
|
13235
|
+
throw new RetryableStatusError(`HTTP ${response.status} from ${new URL(url).pathname}`);
|
|
13236
|
+
}
|
|
13237
|
+
return await read(response, controller.signal);
|
|
13238
|
+
} catch (error) {
|
|
13239
|
+
if (options.signal?.aborted) throw abortError();
|
|
13240
|
+
const retryable = error instanceof RetryableStatusError || error instanceof Error && !(error instanceof NoteIndexFormatError) && !(error instanceof HttpStatusError);
|
|
13241
|
+
if (!retryable || attempt >= maxRetries) throw error;
|
|
13242
|
+
lastError = error;
|
|
13243
|
+
await sleep4(RETRY_BASE_DELAY_MS * 2 ** attempt + Math.random() * 250, options.signal);
|
|
13244
|
+
} finally {
|
|
13245
|
+
clearTimeout(timer);
|
|
13246
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
13247
|
+
}
|
|
13248
|
+
}
|
|
13249
|
+
throw lastError instanceof Error ? lastError : new Error(String(lastError));
|
|
13250
|
+
}
|
|
13251
|
+
async function readBoundedBody(response, maxBytes) {
|
|
13252
|
+
const declaredHeader = response.headers?.get?.("content-length") ?? null;
|
|
13253
|
+
const declared = declaredHeader === null ? NaN : Number(declaredHeader);
|
|
13254
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
13255
|
+
throw new NoteIndexFormatError(`response declares ${declared} bytes, over the ${maxBytes}-byte bound`);
|
|
13256
|
+
}
|
|
13257
|
+
const reader = response.body?.getReader?.();
|
|
13258
|
+
if (!reader) {
|
|
13259
|
+
const encoding = (response.headers?.get?.("content-encoding") ?? "").trim().toLowerCase();
|
|
13260
|
+
if (!Number.isSafeInteger(declared) || declared < 0) {
|
|
13261
|
+
throw new NoteIndexFormatError("response has no stream reader and no Content-Length: its size cannot be bounded");
|
|
13262
|
+
}
|
|
13263
|
+
if (encoding !== "" && encoding !== "identity") {
|
|
13264
|
+
throw new NoteIndexFormatError("response has no stream reader and a Content-Encoding: its decoded size cannot be bounded");
|
|
13265
|
+
}
|
|
13266
|
+
const buffer = new Uint8Array(await response.arrayBuffer());
|
|
13267
|
+
if (buffer.length > maxBytes || buffer.length !== declared) {
|
|
13268
|
+
throw new NoteIndexFormatError(`response is ${buffer.length} bytes, not the declared ${declared} within the ${maxBytes}-byte bound`);
|
|
13269
|
+
}
|
|
13270
|
+
return buffer;
|
|
13271
|
+
}
|
|
13272
|
+
const chunks = [];
|
|
13273
|
+
let total = 0;
|
|
13274
|
+
for (; ; ) {
|
|
13275
|
+
const { done, value } = await reader.read();
|
|
13276
|
+
if (done) break;
|
|
13277
|
+
total += value.length;
|
|
13278
|
+
if (total > maxBytes) {
|
|
13279
|
+
await reader.cancel().catch(() => void 0);
|
|
13280
|
+
throw new NoteIndexFormatError(`response exceeds the ${maxBytes}-byte bound`);
|
|
13281
|
+
}
|
|
13282
|
+
chunks.push(value);
|
|
13283
|
+
}
|
|
13284
|
+
const out = new Uint8Array(total);
|
|
13285
|
+
let off = 0;
|
|
13286
|
+
for (const c of chunks) {
|
|
13287
|
+
out.set(c, off);
|
|
13288
|
+
off += c.length;
|
|
13289
|
+
}
|
|
13290
|
+
return out;
|
|
13291
|
+
}
|
|
13292
|
+
function isNonNegativeSafeInteger(value) {
|
|
13293
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
13294
|
+
}
|
|
13295
|
+
async function fetchNoteIndexHead(relayUrl, options = {}) {
|
|
13296
|
+
const url = joinPath(relayUrl, "/note-index/v1/head").toString();
|
|
13297
|
+
const raw = await requestWithRetry(url, options, async (response) => {
|
|
13298
|
+
if (!response.ok) {
|
|
13299
|
+
throw new HttpStatusError(response.status, `note index head: HTTP ${response.status}`);
|
|
13300
|
+
}
|
|
13301
|
+
const text = new TextDecoder().decode(await readBoundedBody(response, 64 * 1024));
|
|
13302
|
+
try {
|
|
13303
|
+
return JSON.parse(text);
|
|
13304
|
+
} catch {
|
|
13305
|
+
throw new NoteIndexFormatError("head is not JSON");
|
|
13306
|
+
}
|
|
13307
|
+
});
|
|
13308
|
+
if (!raw || typeof raw !== "object") throw new NoteIndexFormatError("head is not an object");
|
|
13309
|
+
if (raw.format !== NOTE_INDEX_FORMAT_VERSION) {
|
|
13310
|
+
throw new NoteIndexFormatError(`unsupported head format ${String(raw.format)}`);
|
|
13311
|
+
}
|
|
13312
|
+
if (raw.page_size !== NOTE_INDEX_PAGE_SIZE) {
|
|
13313
|
+
throw new NoteIndexFormatError(`unsupported page_size ${String(raw.page_size)}`);
|
|
13314
|
+
}
|
|
13315
|
+
if (!isNonNegativeSafeInteger(raw.watermark) || !isNonNegativeSafeInteger(raw.complete_pages)) {
|
|
13316
|
+
throw new NoteIndexFormatError("head watermark/complete_pages are not non-negative integers");
|
|
13317
|
+
}
|
|
13318
|
+
if (raw.complete_pages !== Math.floor(raw.watermark / NOTE_INDEX_PAGE_SIZE)) {
|
|
13319
|
+
throw new NoteIndexFormatError(
|
|
13320
|
+
`complete_pages ${raw.complete_pages} disagrees with watermark ${raw.watermark}`
|
|
13321
|
+
);
|
|
13322
|
+
}
|
|
13323
|
+
if (typeof raw.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(raw.epoch) || BigInt(raw.epoch) > U64_MAX3) {
|
|
13324
|
+
throw new NoteIndexFormatError("head epoch is not a u64 decimal string");
|
|
13325
|
+
}
|
|
13326
|
+
if (typeof raw.chain_tip !== "string" || !/^[0-9a-fA-F]{64}$/.test(raw.chain_tip)) {
|
|
13327
|
+
throw new NoteIndexFormatError("head chain_tip is not 32-byte hex");
|
|
13328
|
+
}
|
|
13329
|
+
return {
|
|
13330
|
+
format: 1,
|
|
13331
|
+
epoch: BigInt(raw.epoch),
|
|
13332
|
+
pageSize: NOTE_INDEX_PAGE_SIZE,
|
|
13333
|
+
watermark: raw.watermark,
|
|
13334
|
+
completePages: raw.complete_pages,
|
|
13335
|
+
chainTip: raw.chain_tip.toLowerCase()
|
|
13336
|
+
};
|
|
13337
|
+
}
|
|
13338
|
+
async function fetchNoteIndexPage(relayUrl, epoch, page, options = {}) {
|
|
13339
|
+
if (typeof epoch !== "bigint" || epoch < 0n || epoch > U64_MAX3) throw new Error("epoch must be a u64 bigint");
|
|
13340
|
+
if (!isNonNegativeSafeInteger(page)) throw new Error(`page must be a non-negative integer, got ${page}`);
|
|
13341
|
+
const url = joinPath(relayUrl, `/note-index/v1/e/${epoch.toString(10)}/pages/${page}`).toString();
|
|
13342
|
+
return requestWithRetry(url, options, async (response) => {
|
|
13343
|
+
if (!response.ok) {
|
|
13344
|
+
throw new HttpStatusError(response.status, `note index page ${page}: HTTP ${response.status}`);
|
|
13345
|
+
}
|
|
13346
|
+
return readBoundedBody(response, NOTE_INDEX_MAX_PAGE_BYTES);
|
|
13347
|
+
});
|
|
13348
|
+
}
|
|
13349
|
+
|
|
13350
|
+
// src/scanning/note-index.ts
|
|
13351
|
+
var import_bs584 = __toESM(require("bs58"), 1);
|
|
13352
|
+
var import_sha26 = require("@noble/hashes/sha2");
|
|
13353
|
+
init_address();
|
|
13354
|
+
init_utxo();
|
|
13355
|
+
var bs584 = import_bs584.default.default || import_bs584.default;
|
|
13356
|
+
var CURSOR_VERSION = 2;
|
|
13357
|
+
var DEFAULT_CONCURRENCY = 6;
|
|
13358
|
+
var MAX_CONCURRENCY = 32;
|
|
13359
|
+
var ITEM_BATCH = 64;
|
|
13360
|
+
var CURSOR_PAGE_ALIGN = 8;
|
|
13361
|
+
var MAX_PERSISTED_PENDING_LEAVES = 4096;
|
|
13362
|
+
var MAX_CARRIED_PENDING = 256;
|
|
13363
|
+
var MAX_REJECTED_IDS = 1024;
|
|
13364
|
+
var LEAF_WINDOW = 512;
|
|
13365
|
+
var MAX_OVERRIDES = 256;
|
|
13366
|
+
var MAX_CURSOR_OWN_ITEMS = 65536;
|
|
13367
|
+
var MAX_LEGACY_VIEWING_KEYS = 8;
|
|
13368
|
+
var MAX_CURSOR_KEYS = 131072;
|
|
13369
|
+
var MAX_CURSOR_POOLS = 256;
|
|
13370
|
+
var MAX_CURSOR_PAGE = 2 ** 32;
|
|
13371
|
+
var TREE_CAPACITY = 2 ** MERKLE_TREE_HEIGHT2;
|
|
13372
|
+
var ZERO_CHAIN = "00".repeat(32);
|
|
13373
|
+
var U64_MAX4 = (1n << 64n) - 1n;
|
|
13374
|
+
var NoteIndexHeadBehindError = class extends Error {
|
|
13375
|
+
constructor(cursorWatermark, headWatermark) {
|
|
13376
|
+
super(
|
|
13377
|
+
`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`
|
|
13378
|
+
);
|
|
13379
|
+
this.cursorWatermark = cursorWatermark;
|
|
13380
|
+
this.headWatermark = headWatermark;
|
|
13381
|
+
this.retryable = true;
|
|
13382
|
+
this.name = "NoteIndexHeadBehindError";
|
|
13383
|
+
}
|
|
13384
|
+
};
|
|
13385
|
+
var FullPassSignal = class {
|
|
13386
|
+
constructor(reason) {
|
|
13387
|
+
this.reason = reason;
|
|
13388
|
+
}
|
|
13389
|
+
};
|
|
13390
|
+
function abortError2() {
|
|
13391
|
+
const error = new Error("recoverNotesFromIndex aborted");
|
|
13392
|
+
error.name = "AbortError";
|
|
13393
|
+
return error;
|
|
13394
|
+
}
|
|
13395
|
+
function bytesToBigint3(bytes) {
|
|
13396
|
+
let v = 0n;
|
|
13397
|
+
for (let i = 0; i < bytes.length; i++) v = v << 8n | BigInt(bytes[i]);
|
|
13398
|
+
return v;
|
|
13399
|
+
}
|
|
13400
|
+
function toHex2(bytes) {
|
|
13401
|
+
let s = "";
|
|
13402
|
+
for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, "0");
|
|
13403
|
+
return s;
|
|
13404
|
+
}
|
|
13405
|
+
function fromHex(hex) {
|
|
13406
|
+
return Uint8Array.from(Buffer.from(hex, "hex"));
|
|
13407
|
+
}
|
|
13408
|
+
function hex32(v) {
|
|
13409
|
+
return v.toString(16).padStart(64, "0");
|
|
13410
|
+
}
|
|
13411
|
+
function isAllZero3(bytes) {
|
|
13412
|
+
for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
|
|
13413
|
+
return true;
|
|
13414
|
+
}
|
|
13415
|
+
function floorAlign(page) {
|
|
13416
|
+
return page - page % CURSOR_PAGE_ALIGN;
|
|
13417
|
+
}
|
|
13418
|
+
function verifiedKey(mint, leaf, commitment) {
|
|
13419
|
+
return `${mint}:${leaf}:${hex32(commitment)}`;
|
|
13420
|
+
}
|
|
13421
|
+
function itemIdentity(raw) {
|
|
13422
|
+
return toHex2((0, import_sha26.sha256)(raw).subarray(0, 16));
|
|
13423
|
+
}
|
|
13424
|
+
var LeafBuffer = class {
|
|
13425
|
+
constructor() {
|
|
13426
|
+
this.bytes = new Uint8Array(32 * 1024);
|
|
13427
|
+
this.view = new DataView(this.bytes.buffer);
|
|
13428
|
+
this.count = 0;
|
|
13429
|
+
}
|
|
13430
|
+
get length() {
|
|
13431
|
+
return this.count;
|
|
13432
|
+
}
|
|
13433
|
+
push(values) {
|
|
13434
|
+
const need = (this.count + values.length) * 32;
|
|
13435
|
+
if (need > this.bytes.length) {
|
|
13436
|
+
let size = this.bytes.length;
|
|
13437
|
+
while (size < need) size *= 2;
|
|
13438
|
+
const next = new Uint8Array(size);
|
|
13439
|
+
next.set(this.bytes.subarray(0, this.count * 32));
|
|
13440
|
+
this.bytes = next;
|
|
13441
|
+
this.view = new DataView(next.buffer);
|
|
13442
|
+
}
|
|
13443
|
+
for (const v of values) {
|
|
13444
|
+
const o = this.count * 32;
|
|
13445
|
+
this.view.setBigUint64(o, v >> 192n & 0xffffffffffffffffn);
|
|
13446
|
+
this.view.setBigUint64(o + 8, v >> 128n & 0xffffffffffffffffn);
|
|
13447
|
+
this.view.setBigUint64(o + 16, v >> 64n & 0xffffffffffffffffn);
|
|
13448
|
+
this.view.setBigUint64(o + 24, v & 0xffffffffffffffffn);
|
|
13449
|
+
this.count++;
|
|
13450
|
+
}
|
|
13451
|
+
}
|
|
13452
|
+
get(i) {
|
|
13453
|
+
if (i < 0 || i >= this.count) return void 0;
|
|
13454
|
+
const o = i * 32;
|
|
13455
|
+
return this.view.getBigUint64(o) << 192n | this.view.getBigUint64(o + 8) << 128n | this.view.getBigUint64(o + 16) << 64n | this.view.getBigUint64(o + 24);
|
|
13456
|
+
}
|
|
13457
|
+
};
|
|
13458
|
+
async function trialItem(item, trials) {
|
|
13459
|
+
for (const trial of trials) {
|
|
13460
|
+
if (trial.legacy && item.kind === 2) continue;
|
|
13461
|
+
const opened = await trialItemWith(item, trial);
|
|
13462
|
+
if (opened) return { ...opened, trial };
|
|
13463
|
+
}
|
|
13464
|
+
return null;
|
|
13465
|
+
}
|
|
13466
|
+
async function trialItemIsolated(item, trials, stats) {
|
|
13467
|
+
try {
|
|
13468
|
+
return await trialItem(item, trials);
|
|
13469
|
+
} catch {
|
|
13470
|
+
stats.skipped++;
|
|
13471
|
+
return null;
|
|
13472
|
+
}
|
|
13473
|
+
}
|
|
13474
|
+
async function trialItemWith(item, trial) {
|
|
13475
|
+
if (item.kind === 1) {
|
|
13476
|
+
if (item.note.length === 0) return null;
|
|
13477
|
+
let note = isAllZero3(item.comm0) ? null : await trial.decrypt(item.note, item.comm0);
|
|
13478
|
+
if (!note && item.note[0] === 2 && !isAllZero3(item.comm1)) note = await trial.decrypt(item.note, item.comm1);
|
|
13479
|
+
return note ? { note } : null;
|
|
13480
|
+
}
|
|
13481
|
+
if (item.kind === 2) {
|
|
13482
|
+
const delivery = await trial.open(item.envelope);
|
|
13483
|
+
return delivery ? { delivery } : null;
|
|
13484
|
+
}
|
|
13485
|
+
if (item.amountAfterFee === 0n) return null;
|
|
13486
|
+
const refund = await matchSwapRefundLeaf({
|
|
13487
|
+
viewingKeyNk: trial.nk,
|
|
13488
|
+
inputNullifier: item.nullifier0,
|
|
13489
|
+
amountAfterFee: item.amountAfterFee,
|
|
13490
|
+
commitment: item.commitment,
|
|
13491
|
+
ownerUtxoKeypair: trial.owner
|
|
13492
|
+
});
|
|
13493
|
+
return refund ? { refund } : null;
|
|
13494
|
+
}
|
|
13495
|
+
function txOutputs(item) {
|
|
13496
|
+
const out = [toHex2(item.comm0)];
|
|
13497
|
+
if (!isAllZero3(item.comm1)) out.push(toHex2(item.comm1));
|
|
13498
|
+
return out;
|
|
13499
|
+
}
|
|
13500
|
+
function leafOfTxOutput(item, commitment) {
|
|
13501
|
+
if (!isAllZero3(item.comm0) && commitment === bytesToBigint3(item.comm0)) return Number(item.leaf0);
|
|
13502
|
+
if (!isAllZero3(item.comm1) && commitment === bytesToBigint3(item.comm1)) return Number(item.leaf1);
|
|
13503
|
+
return null;
|
|
13504
|
+
}
|
|
13505
|
+
function changeBlindingOrNull(nk, noteSalt, outputIndex) {
|
|
13506
|
+
try {
|
|
13507
|
+
return deriveChangeNoteBlinding(nk, noteSalt, outputIndex);
|
|
13508
|
+
} catch {
|
|
13509
|
+
return null;
|
|
13510
|
+
}
|
|
13511
|
+
}
|
|
13512
|
+
async function matchOwnItems(own, owner, onReject, onSkip) {
|
|
13513
|
+
const candidates = [];
|
|
13514
|
+
const claimed = /* @__PURE__ */ new Set();
|
|
13515
|
+
const byNullifier = /* @__PURE__ */ new Map();
|
|
13516
|
+
const legacyKeys = /* @__PURE__ */ new Map();
|
|
13517
|
+
const ownTxs = own.filter((o) => o.item.kind === 1 && o.note?.noteSalt !== void 0);
|
|
13518
|
+
const spendsOf = /* @__PURE__ */ new Map();
|
|
13519
|
+
const byOutKey = /* @__PURE__ */ new Map();
|
|
13520
|
+
const index = (map, key, o) => {
|
|
13521
|
+
const list = map.get(key);
|
|
13522
|
+
if (list) list.push(o);
|
|
13523
|
+
else map.set(key, [o]);
|
|
13524
|
+
};
|
|
13525
|
+
for (const o of ownTxs) {
|
|
13526
|
+
for (const n of [o.item.nullifier0, o.item.nullifier1]) if (!isAllZero3(n)) index(spendsOf, toHex2(n), o);
|
|
13527
|
+
if (o.note.outPubkey0 !== void 0) index(byOutKey, o.note.outPubkey0, o);
|
|
13528
|
+
}
|
|
13529
|
+
const queue = [];
|
|
13530
|
+
const queued = /* @__PURE__ */ new Set();
|
|
13531
|
+
const enqueue = (o) => {
|
|
13532
|
+
if (queued.has(o)) return;
|
|
13533
|
+
queued.add(o);
|
|
13534
|
+
queue.push(o);
|
|
13535
|
+
};
|
|
13536
|
+
const add = async (o, c) => {
|
|
13537
|
+
const nullifier = hex32(
|
|
13538
|
+
await computeNullifier({ amount: c.amount, keypair: c.keypair, blinding: c.blinding, mintAddress: c.mint, index: c.leaf, commitment: c.commitment })
|
|
13539
|
+
);
|
|
13540
|
+
const full = { ...c, atRisk: c.atRisk || o.trial.legacy, signature: o.item.signature, page: o.page, seq: o.seq, nullifier };
|
|
13541
|
+
candidates.push(full);
|
|
13542
|
+
if (!byNullifier.has(nullifier)) {
|
|
13543
|
+
byNullifier.set(nullifier, full);
|
|
13544
|
+
for (const s of spendsOf.get(nullifier) ?? []) enqueue(s);
|
|
13545
|
+
}
|
|
13546
|
+
if (c.atRisk && c.keypair.publicKey !== owner.publicKey && !legacyKeys.has(c.keypair.publicKey)) {
|
|
13547
|
+
legacyKeys.set(c.keypair.publicKey, c.keypair);
|
|
13548
|
+
for (const s of byOutKey.get(c.keypair.publicKey) ?? []) enqueue(s);
|
|
13549
|
+
}
|
|
13550
|
+
};
|
|
13551
|
+
const tryDeposit = async (o, item, amount) => {
|
|
13552
|
+
const note = o.note;
|
|
13553
|
+
const mint = addressFromBytes(item.mint);
|
|
13554
|
+
const deposit = await matchDepositNote({
|
|
13555
|
+
viewingKeyNk: o.trial.nk,
|
|
13556
|
+
noteSalt: note.noteSalt,
|
|
13557
|
+
amount,
|
|
13558
|
+
mintAddress: mint,
|
|
13559
|
+
outputCommitments: txOutputs(item),
|
|
13560
|
+
ownerUtxoKeypair: owner
|
|
13561
|
+
});
|
|
13562
|
+
const leaf = deposit ? leafOfTxOutput(item, deposit.commitment) : null;
|
|
13563
|
+
if (!deposit || leaf === null) return false;
|
|
13564
|
+
await add(o, {
|
|
13565
|
+
kind: "deposit",
|
|
13566
|
+
atRisk: deposit.legacyExposed,
|
|
13567
|
+
amount: deposit.amount,
|
|
13568
|
+
blinding: deposit.blinding,
|
|
13569
|
+
keypair: deposit.legacyExposed ? deposit.keypair : owner,
|
|
13570
|
+
mint,
|
|
13571
|
+
commitment: deposit.commitment,
|
|
13572
|
+
leaf
|
|
13573
|
+
});
|
|
13574
|
+
return true;
|
|
13575
|
+
};
|
|
13576
|
+
const tryChange0 = async (o, item, keypair, atRisk) => {
|
|
13577
|
+
const note = o.note;
|
|
13578
|
+
const mint = addressFromBytes(item.mint);
|
|
13579
|
+
const change = await matchChangeNote({
|
|
13580
|
+
viewingKeyNk: o.trial.nk,
|
|
13581
|
+
noteSalt: note.noteSalt,
|
|
13582
|
+
amount: note.outAmount0,
|
|
13583
|
+
keypair,
|
|
13584
|
+
mintAddress: mint,
|
|
13585
|
+
outputIndex: 0,
|
|
13586
|
+
outputCommitments: [toHex2(item.comm0)],
|
|
13587
|
+
ownerUtxoPublicKey: owner.publicKey
|
|
13588
|
+
});
|
|
13589
|
+
if (!change) return false;
|
|
13590
|
+
await add(o, {
|
|
13591
|
+
kind: "change",
|
|
13592
|
+
atRisk,
|
|
13593
|
+
amount: change.amount,
|
|
13594
|
+
blinding: change.blinding,
|
|
13595
|
+
keypair,
|
|
13596
|
+
mint,
|
|
13597
|
+
commitment: change.commitment,
|
|
13598
|
+
leaf: Number(item.leaf0)
|
|
13599
|
+
});
|
|
13600
|
+
return true;
|
|
13601
|
+
};
|
|
13602
|
+
const direct = async (o) => {
|
|
13603
|
+
const item = o.item;
|
|
13604
|
+
if (item.kind === 1 && o.note?.noteSalt !== void 0) {
|
|
13605
|
+
const note = o.note;
|
|
13606
|
+
if (note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
|
|
13607
|
+
if (await tryDeposit(o, item, item.publicAmount)) claimed.add(`${o.seq}:0`);
|
|
13608
|
+
}
|
|
13609
|
+
if (note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 === owner.publicKey) {
|
|
13610
|
+
if (await tryChange0(o, item, owner, false)) claimed.add(`${o.seq}:0`);
|
|
13611
|
+
}
|
|
13612
|
+
} else if (item.kind === 2 && o.delivery) {
|
|
13613
|
+
const mint = addressFromBytes(item.mint);
|
|
13614
|
+
if (o.delivery.amount <= 0n || o.delivery.blinding === 0n) {
|
|
13615
|
+
onReject(o);
|
|
13616
|
+
return;
|
|
13617
|
+
}
|
|
13618
|
+
const commitment = await computeCommitment2({
|
|
13619
|
+
amount: o.delivery.amount,
|
|
13620
|
+
keypair: { privateKey: 0n, publicKey: owner.publicKey },
|
|
13621
|
+
blinding: o.delivery.blinding,
|
|
13622
|
+
mintAddress: mint
|
|
13623
|
+
});
|
|
13624
|
+
if (commitment !== bytesToBigint3(item.commitment)) {
|
|
13625
|
+
onReject(o);
|
|
13626
|
+
return;
|
|
13627
|
+
}
|
|
13628
|
+
await add(o, {
|
|
13629
|
+
kind: "received",
|
|
13630
|
+
atRisk: false,
|
|
13631
|
+
amount: o.delivery.amount,
|
|
13632
|
+
blinding: o.delivery.blinding,
|
|
13633
|
+
keypair: owner,
|
|
13634
|
+
mint,
|
|
13635
|
+
commitment,
|
|
13636
|
+
leaf: Number(item.leaf)
|
|
13637
|
+
});
|
|
13638
|
+
} else if (item.kind === 3 && o.refund) {
|
|
13639
|
+
await add(o, {
|
|
13640
|
+
kind: "swap_refund",
|
|
13641
|
+
atRisk: o.refund.legacyExposed,
|
|
13642
|
+
amount: o.refund.amount,
|
|
13643
|
+
blinding: o.refund.blinding,
|
|
13644
|
+
keypair: o.refund.legacyExposed ? o.refund.keypair : owner,
|
|
13645
|
+
mint: NATIVE_SOL_MINT,
|
|
13646
|
+
commitment: o.refund.commitment,
|
|
13647
|
+
leaf: Number(item.leaf)
|
|
13648
|
+
});
|
|
13649
|
+
}
|
|
13650
|
+
};
|
|
13651
|
+
for (const o of own) {
|
|
13652
|
+
try {
|
|
13653
|
+
await direct(o);
|
|
13654
|
+
} catch {
|
|
13655
|
+
onSkip(o);
|
|
13656
|
+
}
|
|
13657
|
+
}
|
|
13658
|
+
const processTx = async (o) => {
|
|
13659
|
+
const item = o.item;
|
|
13660
|
+
const note = o.note;
|
|
13661
|
+
if (!claimed.has(`${o.seq}:0`) && note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 !== void 0) {
|
|
13662
|
+
const legacy = legacyKeys.get(note.outPubkey0);
|
|
13663
|
+
if (legacy && await tryChange0(o, item, legacy, true)) claimed.add(`${o.seq}:0`);
|
|
13664
|
+
}
|
|
13665
|
+
const mint = addressFromBytes(item.mint);
|
|
13666
|
+
const inputs = [item.nullifier0, item.nullifier1].filter((n) => !isAllZero3(n)).map((n) => byNullifier.get(toHex2(n))).filter((c) => c !== void 0 && c.mint === mint);
|
|
13667
|
+
if (inputs.length === 0) return;
|
|
13668
|
+
const sumIn = inputs.reduce((acc, c) => acc + c.amount, 0n);
|
|
13669
|
+
if (!claimed.has(`${o.seq}:1`) && note.outAmount0 !== void 0 && !isAllZero3(item.comm1)) {
|
|
13670
|
+
const out1 = sumIn + item.publicAmount - note.outAmount0;
|
|
13671
|
+
const blinding = out1 > 0n ? changeBlindingOrNull(o.trial.nk, note.noteSalt, 1) : null;
|
|
13672
|
+
if (out1 > 0n && blinding === null) onSkip(o);
|
|
13673
|
+
else if (blinding !== null) {
|
|
13674
|
+
const owners = [{ keypair: owner, atRisk: false }];
|
|
13675
|
+
const legacyInput = legacyKeys.get(inputs[0].keypair.publicKey);
|
|
13676
|
+
if (legacyInput && legacyInput.publicKey !== owner.publicKey) owners.push({ keypair: legacyInput, atRisk: true });
|
|
13677
|
+
for (const { keypair, atRisk } of owners) {
|
|
13678
|
+
const commitment = await computeCommitment2({ amount: out1, keypair, blinding, mintAddress: mint });
|
|
13679
|
+
if (commitment !== bytesToBigint3(item.comm1)) continue;
|
|
13680
|
+
claimed.add(`${o.seq}:1`);
|
|
13681
|
+
await add(o, { kind: "change", atRisk, amount: out1, blinding, keypair, mint, commitment, leaf: Number(item.leaf1) });
|
|
13682
|
+
break;
|
|
13683
|
+
}
|
|
13684
|
+
}
|
|
13685
|
+
}
|
|
13686
|
+
if (!claimed.has(`${o.seq}:0`) && note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
|
|
13687
|
+
if (await tryDeposit(o, item, item.publicAmount + sumIn)) claimed.add(`${o.seq}:0`);
|
|
13688
|
+
}
|
|
13689
|
+
};
|
|
13690
|
+
for (const o of ownTxs) enqueue(o);
|
|
13691
|
+
for (let i = 0; i < queue.length; i++) {
|
|
13692
|
+
const o = queue[i];
|
|
13693
|
+
queued.delete(o);
|
|
13694
|
+
try {
|
|
13695
|
+
await processTx(o);
|
|
13696
|
+
} catch {
|
|
13697
|
+
onSkip(o);
|
|
13698
|
+
}
|
|
13699
|
+
}
|
|
13700
|
+
return candidates;
|
|
13701
|
+
}
|
|
13702
|
+
async function replayStream(start, pages, overrides, chain, targetPage) {
|
|
13703
|
+
const frontier = await MerkleFrontier.create(start.frontier ?? void 0, MERKLE_TREE_HEIGHT2);
|
|
13704
|
+
const startN = frontier.nextIndex;
|
|
13705
|
+
const pending = new Map(start.pending);
|
|
13706
|
+
const flushed = new LeafBuffer();
|
|
13707
|
+
const corrections = /* @__PURE__ */ new Map();
|
|
13708
|
+
let conflicts = 0;
|
|
13709
|
+
let verifiedPrefix = 0;
|
|
13710
|
+
let mismatch = false;
|
|
13711
|
+
const checks = [];
|
|
13712
|
+
const setBits = [];
|
|
13713
|
+
if (chain && chain.nextIndex > 0) {
|
|
13714
|
+
const last = chain.nextIndex - 1;
|
|
13715
|
+
for (let l = 0; l < MERKLE_TREE_HEIGHT2; l++) if (Math.floor(last / 2 ** l) % 2 === 1) setBits.push(l);
|
|
13716
|
+
for (const l of setBits) {
|
|
13717
|
+
const at = Math.floor(last / 2 ** l) * 2 ** l;
|
|
13718
|
+
if (at >= startN) checks.push({ at, level: l });
|
|
13719
|
+
}
|
|
13720
|
+
if (chain.nextIndex >= startN) checks.push({ at: chain.nextIndex, level: -1 });
|
|
13721
|
+
checks.sort((a, b) => a.at - b.at);
|
|
13722
|
+
}
|
|
13723
|
+
let nextCheck = 0;
|
|
13724
|
+
const runChecks = () => {
|
|
13725
|
+
while (nextCheck < checks.length && checks[nextCheck].at === frontier.nextIndex) {
|
|
13726
|
+
const { at, level } = checks[nextCheck++];
|
|
13727
|
+
const ok = level < 0 ? frontier.root() === chain.root : setBits.every((j) => j < level || frontier.leftAt(j) === chain.subtrees[j]);
|
|
13728
|
+
if (ok) verifiedPrefix = Math.max(verifiedPrefix, at);
|
|
13729
|
+
else mismatch = true;
|
|
13730
|
+
}
|
|
13731
|
+
};
|
|
13732
|
+
const append = (values) => {
|
|
13733
|
+
let i = 0;
|
|
13734
|
+
while (i < values.length) {
|
|
13735
|
+
const room = nextCheck < checks.length ? checks[nextCheck].at - frontier.nextIndex : values.length - i;
|
|
13736
|
+
const take = Math.min(values.length - i, room);
|
|
13737
|
+
if (take > 0) {
|
|
13738
|
+
const part = values.slice(i, i + take);
|
|
13739
|
+
frontier.append(part);
|
|
13740
|
+
flushed.push(part);
|
|
13741
|
+
i += take;
|
|
13742
|
+
}
|
|
13743
|
+
runChecks();
|
|
13744
|
+
}
|
|
13745
|
+
};
|
|
13746
|
+
const valueAt = (leaf) => leaf >= startN && leaf < startN + flushed.length ? flushed.get(leaf - startN) : pending.get(leaf);
|
|
13747
|
+
const flush = () => {
|
|
13748
|
+
const batch = [];
|
|
13749
|
+
let next = frontier.nextIndex;
|
|
13750
|
+
while (pending.has(next)) {
|
|
13751
|
+
batch.push(pending.get(next));
|
|
13752
|
+
pending.delete(next);
|
|
13753
|
+
next++;
|
|
13754
|
+
}
|
|
13755
|
+
if (batch.length > 0) append(batch);
|
|
13756
|
+
};
|
|
13757
|
+
let snapshot = null;
|
|
13758
|
+
let taken = false;
|
|
13759
|
+
const takeSnapshot = () => {
|
|
13760
|
+
taken = true;
|
|
13761
|
+
if (pending.size > MAX_PERSISTED_PENDING_LEAVES) return;
|
|
13762
|
+
snapshot = { frontier: frontier.toState(), pending: new Map(pending), nextIndex: frontier.nextIndex };
|
|
13763
|
+
};
|
|
13764
|
+
runChecks();
|
|
13765
|
+
flush();
|
|
13766
|
+
for (const { page, entries } of pages) {
|
|
13767
|
+
if (!taken && page >= targetPage) takeSnapshot();
|
|
13768
|
+
for (const e of entries) {
|
|
13769
|
+
if (e.leaf < startN) continue;
|
|
13770
|
+
const prior = valueAt(e.leaf);
|
|
13771
|
+
if (prior !== void 0) {
|
|
13772
|
+
if (prior !== e.commitment) {
|
|
13773
|
+
conflicts++;
|
|
13774
|
+
corrections.set(e.leaf, e.commitment);
|
|
13775
|
+
}
|
|
13776
|
+
continue;
|
|
13777
|
+
}
|
|
13778
|
+
pending.set(e.leaf, overrides.get(e.leaf) ?? e.commitment);
|
|
13779
|
+
}
|
|
13780
|
+
flush();
|
|
13781
|
+
}
|
|
13782
|
+
if (!taken) takeSnapshot();
|
|
13783
|
+
if (chain && treeAccountAcceptsRoot(chain.data, hex32(frontier.root()))) {
|
|
13784
|
+
verifiedPrefix = Math.max(verifiedPrefix, Math.min(frontier.nextIndex, chain.nextIndex));
|
|
13785
|
+
}
|
|
13786
|
+
return { endCount: frontier.nextIndex, valueAt, snapshot, conflicts, corrections, verifiedPrefix, mismatch };
|
|
13787
|
+
}
|
|
13788
|
+
var HEX64 = /^[0-9a-f]{64}$/;
|
|
13789
|
+
var HEX32 = /^[0-9a-f]{32}$/;
|
|
13790
|
+
var ADDRESS = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
|
|
13791
|
+
var VERIFIED_KEY = /^[1-9A-HJ-NP-Za-km-z]{32,44}:(0|[1-9][0-9]{0,9}):[0-9a-f]{64}$/;
|
|
13792
|
+
function isRecord(v) {
|
|
13793
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
13794
|
+
}
|
|
13795
|
+
function isIntIn(v, min, max) {
|
|
13796
|
+
return typeof v === "number" && Number.isSafeInteger(v) && v >= min && v <= max;
|
|
13797
|
+
}
|
|
13798
|
+
function isBoundedArray(v, max) {
|
|
13799
|
+
return Array.isArray(v) && v.length <= max;
|
|
13800
|
+
}
|
|
13801
|
+
function emptyStartTree() {
|
|
13802
|
+
return {
|
|
13803
|
+
frontier: null,
|
|
13804
|
+
nextIndex: 0,
|
|
13805
|
+
pending: /* @__PURE__ */ new Map(),
|
|
13806
|
+
window: [],
|
|
13807
|
+
windowStart: 0,
|
|
13808
|
+
verified: 0,
|
|
13809
|
+
overrides: /* @__PURE__ */ new Map(),
|
|
13810
|
+
mismatch: false,
|
|
13811
|
+
hiBefore: -1
|
|
13812
|
+
};
|
|
13813
|
+
}
|
|
13814
|
+
async function parseCursor(cursor, poolMints) {
|
|
13815
|
+
try {
|
|
13816
|
+
if (!isRecord(cursor)) return "not an object";
|
|
13817
|
+
if (cursor.v !== CURSOR_VERSION) return "unsupported cursor version";
|
|
13818
|
+
const c = cursor;
|
|
13819
|
+
if (typeof c.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(c.epoch) || BigInt(c.epoch) > U64_MAX4) return "bad epoch";
|
|
13820
|
+
if (!isIntIn(c.page, 0, MAX_CURSOR_PAGE) || c.page % CURSOR_PAGE_ALIGN !== 0) return "bad page";
|
|
13821
|
+
if (typeof c.chain !== "string" || !HEX64.test(c.chain)) return "bad chain";
|
|
13822
|
+
if (!isIntIn(c.watermark, 0, Number.MAX_SAFE_INTEGER) || c.page * NOTE_INDEX_PAGE_SIZE > c.watermark) return "bad watermark";
|
|
13823
|
+
if (!isIntIn(c.fullPassSeq, 0, c.watermark)) return "bad full-pass mark";
|
|
13824
|
+
if (!isRecord(c.trees) || Object.keys(c.trees).length > MAX_CURSOR_POOLS) return "bad trees";
|
|
13825
|
+
const trees = /* @__PURE__ */ new Map();
|
|
13826
|
+
for (const mint of poolMints) {
|
|
13827
|
+
const t = c.trees[mint];
|
|
13828
|
+
if (!isRecord(t)) return "a listed pool is missing from the cursor";
|
|
13829
|
+
const tree = t;
|
|
13830
|
+
if (!isRecord(tree.frontier)) return "bad frontier";
|
|
13831
|
+
let frontier;
|
|
13832
|
+
try {
|
|
13833
|
+
frontier = await MerkleFrontier.create(tree.frontier, MERKLE_TREE_HEIGHT2);
|
|
13834
|
+
} catch {
|
|
13835
|
+
return "bad frontier";
|
|
13836
|
+
}
|
|
13837
|
+
const nextIndex = frontier.nextIndex;
|
|
13838
|
+
if (!isBoundedArray(tree.pending, MAX_PERSISTED_PENDING_LEAVES)) return "bad pending leaves";
|
|
13839
|
+
const pending = /* @__PURE__ */ new Map();
|
|
13840
|
+
let hiBefore = nextIndex - 1;
|
|
13841
|
+
for (const entry of tree.pending) {
|
|
13842
|
+
if (!Array.isArray(entry) || entry.length !== 2) return "bad pending leaves";
|
|
13843
|
+
const [leaf, value] = entry;
|
|
13844
|
+
if (!isIntIn(leaf, nextIndex + 1, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value) || pending.has(leaf)) {
|
|
13845
|
+
return "bad pending leaves";
|
|
13846
|
+
}
|
|
13847
|
+
pending.set(leaf, BigInt("0x" + value));
|
|
13848
|
+
hiBefore = Math.max(hiBefore, leaf);
|
|
13849
|
+
}
|
|
13850
|
+
if (typeof tree.window !== "string" || tree.window.length % 64 !== 0 || !/^[0-9a-f]*$/.test(tree.window)) return "bad window";
|
|
13851
|
+
const windowLen = tree.window.length / 64;
|
|
13852
|
+
if (windowLen > LEAF_WINDOW || windowLen > nextIndex) return "bad window";
|
|
13853
|
+
const window2 = [];
|
|
13854
|
+
for (let i = 0; i < windowLen; i++) window2.push(BigInt("0x" + tree.window.slice(i * 64, (i + 1) * 64)));
|
|
13855
|
+
if (!isIntIn(tree.verified, 0, nextIndex)) return "bad verified prefix";
|
|
13856
|
+
if (!isBoundedArray(tree.overrides, MAX_OVERRIDES)) return "bad overrides";
|
|
13857
|
+
const overrides = /* @__PURE__ */ new Map();
|
|
13858
|
+
for (const entry of tree.overrides) {
|
|
13859
|
+
if (!Array.isArray(entry) || entry.length !== 2) return "bad overrides";
|
|
13860
|
+
const [leaf, value] = entry;
|
|
13861
|
+
if (!isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) return "bad overrides";
|
|
13862
|
+
overrides.set(leaf, BigInt("0x" + value));
|
|
13863
|
+
}
|
|
13864
|
+
if (typeof tree.mismatch !== "boolean") return "bad mismatch flag";
|
|
13865
|
+
trees.set(mint, {
|
|
13866
|
+
frontier: frontier.toState(),
|
|
13867
|
+
nextIndex,
|
|
13868
|
+
pending,
|
|
13869
|
+
window: window2,
|
|
13870
|
+
windowStart: nextIndex - windowLen,
|
|
13871
|
+
verified: tree.verified,
|
|
13872
|
+
overrides,
|
|
13873
|
+
mismatch: tree.mismatch,
|
|
13874
|
+
hiBefore
|
|
13875
|
+
});
|
|
13876
|
+
}
|
|
13877
|
+
const own = c.own;
|
|
13878
|
+
if (!isRecord(own)) return "bad own state";
|
|
13879
|
+
if (!isBoundedArray(own.items, MAX_CURSOR_OWN_ITEMS)) return "bad own items";
|
|
13880
|
+
const items = [];
|
|
13881
|
+
const seqs = /* @__PURE__ */ new Set();
|
|
13882
|
+
for (const entry of own.items) {
|
|
13883
|
+
if (!isRecord(entry)) return "bad own items";
|
|
13884
|
+
const { seq, item } = entry;
|
|
13885
|
+
if (!isIntIn(seq, 0, c.page * NOTE_INDEX_PAGE_SIZE - 1) || seqs.has(seq)) return "bad own items";
|
|
13886
|
+
if (typeof item !== "string" || item.length % 2 !== 0 || item.length > 2 * 4096 || !/^[0-9a-f]+$/.test(item)) return "bad own items";
|
|
13887
|
+
seqs.add(seq);
|
|
13888
|
+
const raw = fromHex(item);
|
|
13889
|
+
items.push({ seq, raw, item: parseNoteIndexItem(raw) });
|
|
13890
|
+
}
|
|
13891
|
+
if (!isBoundedArray(own.verified, MAX_CURSOR_KEYS) || !own.verified.every((k) => typeof k === "string" && VERIFIED_KEY.test(k))) {
|
|
13892
|
+
return "bad verified notes";
|
|
13893
|
+
}
|
|
13894
|
+
if (!isBoundedArray(own.spent, MAX_CURSOR_KEYS) || !own.spent.every((k) => typeof k === "string" && HEX64.test(k))) return "bad spent set";
|
|
13895
|
+
if (!isBoundedArray(own.pendingLeaves, MAX_CARRIED_PENDING)) return "bad pending notes";
|
|
13896
|
+
const pendingLeaves = /* @__PURE__ */ new Map();
|
|
13897
|
+
for (const entry of own.pendingLeaves) {
|
|
13898
|
+
if (!Array.isArray(entry) || entry.length !== 3) return "bad pending notes";
|
|
13899
|
+
const [mint, leaf, value] = entry;
|
|
13900
|
+
if (typeof mint !== "string" || !ADDRESS.test(mint) || !isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) {
|
|
13901
|
+
return "bad pending notes";
|
|
13902
|
+
}
|
|
13903
|
+
pendingLeaves.set(`${mint}:${leaf}`, BigInt("0x" + value));
|
|
13904
|
+
}
|
|
13905
|
+
if (!isBoundedArray(own.rejected, MAX_REJECTED_IDS) || !own.rejected.every((k) => typeof k === "string" && HEX32.test(k))) {
|
|
13906
|
+
return "bad rejected set";
|
|
13907
|
+
}
|
|
13908
|
+
return {
|
|
13909
|
+
raw: c,
|
|
13910
|
+
trees,
|
|
13911
|
+
items,
|
|
13912
|
+
verified: new Set(own.verified),
|
|
13913
|
+
spent: new Set(own.spent),
|
|
13914
|
+
pendingLeaves,
|
|
13915
|
+
rejected: own.rejected
|
|
13916
|
+
};
|
|
13917
|
+
} catch {
|
|
13918
|
+
return "unreadable state";
|
|
13919
|
+
}
|
|
13920
|
+
}
|
|
13921
|
+
async function recoverNotesFromIndex(params) {
|
|
13922
|
+
const startedAt = Date.now();
|
|
13923
|
+
const { relayUrl, connection, viewingKeyNk, programId } = params;
|
|
13924
|
+
assertAllowedRelayOrigin(relayUrl);
|
|
13925
|
+
assertAllowedRpcConnection(connection);
|
|
13926
|
+
if (!(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) throw new Error("viewingKeyNk must be 32 bytes");
|
|
13927
|
+
const owner = await assertOwnerUtxoKeypair(params.ownerUtxoKeypair);
|
|
13928
|
+
if (!Array.isArray(params.poolMints)) throw new Error("poolMints must list every active pool mint");
|
|
13929
|
+
const concurrency = params.concurrency ?? DEFAULT_CONCURRENCY;
|
|
13930
|
+
if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > MAX_CONCURRENCY) {
|
|
13931
|
+
throw new Error(`concurrency must be an integer in 1..${MAX_CONCURRENCY}`);
|
|
13932
|
+
}
|
|
13933
|
+
if (params.signal?.aborted) throw abortError2();
|
|
13934
|
+
const stats = {
|
|
13935
|
+
pages: 0,
|
|
13936
|
+
items: 0,
|
|
13937
|
+
bytes: 0,
|
|
13938
|
+
rpcCalls: 0,
|
|
13939
|
+
ms: 0,
|
|
13940
|
+
dropped: 0,
|
|
13941
|
+
decrypted: 0,
|
|
13942
|
+
candidates: 0,
|
|
13943
|
+
spent: 0,
|
|
13944
|
+
conflicts: 0,
|
|
13945
|
+
pendingDropped: 0,
|
|
13946
|
+
skipped: 0
|
|
13947
|
+
};
|
|
13948
|
+
const rpc = new Proxy(connection, {
|
|
13949
|
+
get(target, prop, receiver) {
|
|
13950
|
+
const value = Reflect.get(target, prop, receiver);
|
|
13951
|
+
if (typeof value !== "function") return value;
|
|
13952
|
+
return (...args) => {
|
|
13953
|
+
const pending = value.apply(target, args);
|
|
13954
|
+
if (pending && typeof pending.send === "function") {
|
|
13955
|
+
const send = pending.send.bind(pending);
|
|
13956
|
+
return {
|
|
13957
|
+
...pending,
|
|
13958
|
+
send: (...sendArgs) => {
|
|
13959
|
+
stats.rpcCalls++;
|
|
13960
|
+
return send(...sendArgs);
|
|
13961
|
+
}
|
|
13962
|
+
};
|
|
13963
|
+
}
|
|
13964
|
+
return pending;
|
|
13965
|
+
};
|
|
13966
|
+
}
|
|
13967
|
+
});
|
|
13968
|
+
const makeTrial = async (nk, legacy) => ({
|
|
13969
|
+
nk,
|
|
13970
|
+
legacy,
|
|
13971
|
+
owner,
|
|
13972
|
+
decrypt: await createCompactChainNoteDecryptor(nk),
|
|
13973
|
+
open: await createRecipientDeliveryOpener(deriveViewingKeyFromNk(nk).privateKey)
|
|
13974
|
+
});
|
|
13975
|
+
const trials = [await makeTrial(viewingKeyNk, false)];
|
|
13976
|
+
const legacyNks = params.legacyViewingKeyNks ?? [];
|
|
13977
|
+
if (!Array.isArray(legacyNks)) throw new Error("legacyViewingKeyNks must be an array of 32-byte keys");
|
|
13978
|
+
if (legacyNks.length > MAX_LEGACY_VIEWING_KEYS) throw new Error(`legacyViewingKeyNks takes at most ${MAX_LEGACY_VIEWING_KEYS} keys`);
|
|
13979
|
+
const seenNks = /* @__PURE__ */ new Set([toHex2(viewingKeyNk)]);
|
|
13980
|
+
for (const nk of legacyNks) {
|
|
13981
|
+
if (!(nk instanceof Uint8Array) || nk.length !== 32) throw new Error("legacyViewingKeyNks entries must be 32 bytes");
|
|
13982
|
+
const key = toHex2(nk);
|
|
13983
|
+
if (seenNks.has(key)) continue;
|
|
13984
|
+
seenNks.add(key);
|
|
13985
|
+
trials.push(await makeTrial(Uint8Array.from(nk), true));
|
|
13986
|
+
}
|
|
13987
|
+
const poolMints = Array.from(new Set(params.poolMints));
|
|
13988
|
+
const warnings = [];
|
|
13989
|
+
const head = await fetchNoteIndexHead(relayUrl, { signal: params.signal });
|
|
13990
|
+
let cursor;
|
|
13991
|
+
if (params.cursor !== void 0) {
|
|
13992
|
+
const checked = await parseCursor(params.cursor, poolMints);
|
|
13993
|
+
if (typeof checked === "string") warnings.push(`note index cursor is unusable (${checked}); re-syncing from page 0`);
|
|
13994
|
+
else if (BigInt(checked.raw.epoch) !== head.epoch) warnings.push("note index epoch changed; re-syncing from page 0");
|
|
13995
|
+
else if (head.watermark < checked.raw.watermark || head.completePages < checked.raw.page) {
|
|
13996
|
+
throw new NoteIndexHeadBehindError(checked.raw.watermark, head.watermark);
|
|
13997
|
+
} else cursor = checked;
|
|
13998
|
+
}
|
|
13999
|
+
const treePdas = await Promise.all(poolMints.map(async (mint) => (await getShieldPoolPDAs(programId, mint)).merkleTree));
|
|
14000
|
+
let treeRead;
|
|
14001
|
+
const readTrees = () => treeRead ?? (treeRead = (async () => {
|
|
14002
|
+
const accounts = poolMints.length > 0 ? await fetchMultipleAccountBytes(rpc, treePdas, "confirmed") : [];
|
|
14003
|
+
return poolMints.map((_, i) => {
|
|
14004
|
+
const account = accounts[i];
|
|
14005
|
+
const parsed = account ? readTreeAccountFrontier(account.data) : null;
|
|
14006
|
+
return account && parsed ? { ...parsed, data: account.data } : null;
|
|
14007
|
+
});
|
|
14008
|
+
})());
|
|
14009
|
+
const ctx = { params, head, trials, owner, stats, poolMints, warnings, readTrees };
|
|
14010
|
+
let outcome = await runOnce(ctx, cursor);
|
|
14011
|
+
if (outcome instanceof FullPassSignal) {
|
|
14012
|
+
warnings.push(`${outcome.reason}; re-syncing from page 0`);
|
|
14013
|
+
Object.assign(stats, { dropped: 0, decrypted: 0, candidates: 0, spent: 0, conflicts: 0, pendingDropped: 0, skipped: 0 });
|
|
14014
|
+
outcome = await runOnce(ctx, void 0);
|
|
14015
|
+
if (outcome instanceof FullPassSignal) throw new Error(`note index recovery failed: ${outcome.reason}`);
|
|
14016
|
+
}
|
|
14017
|
+
if (stats.skipped > 0) warnings.push(`${stats.skipped} note index entries could not be processed and were skipped`);
|
|
14018
|
+
stats.ms = Date.now() - startedAt;
|
|
14019
|
+
return { ...outcome, stats, warnings };
|
|
14020
|
+
}
|
|
14021
|
+
async function runOnce(ctx, cursor) {
|
|
14022
|
+
const { params, head, trials, owner, stats, poolMints } = ctx;
|
|
14023
|
+
const { relayUrl, onProgress } = params;
|
|
14024
|
+
const poolSet = new Set(poolMints);
|
|
14025
|
+
const startPage = cursor?.raw.page ?? 0;
|
|
14026
|
+
const startChain = cursor?.raw.chain ?? ZERO_CHAIN;
|
|
14027
|
+
const fullPassSeq = cursor?.raw.fullPassSeq ?? 0;
|
|
14028
|
+
const pagesTotal = Math.ceil(head.watermark / NOTE_INDEX_PAGE_SIZE);
|
|
14029
|
+
const targetPage = Math.max(startPage, floorAlign(head.completePages));
|
|
14030
|
+
const startTrees = new Map(poolMints.map((m) => [m, cursor?.trees.get(m) ?? emptyStartTree()]));
|
|
14031
|
+
const rejectedIds = new Set(cursor?.rejected ?? []);
|
|
14032
|
+
const controller = new AbortController();
|
|
14033
|
+
const onCallerAbort = () => controller.abort();
|
|
14034
|
+
params.signal?.addEventListener("abort", onCallerAbort, { once: true });
|
|
14035
|
+
const signal = controller.signal;
|
|
14036
|
+
try {
|
|
14037
|
+
const pageData = /* @__PURE__ */ new Map();
|
|
14038
|
+
const ownItems = [];
|
|
14039
|
+
const nullifiers = /* @__PURE__ */ new Set();
|
|
14040
|
+
let fullPassReason = null;
|
|
14041
|
+
const lateReference = (mint, leaf, value, seq) => {
|
|
14042
|
+
if (!cursor || seq < fullPassSeq) return null;
|
|
14043
|
+
const t = startTrees.get(mint);
|
|
14044
|
+
if (leaf < t.nextIndex) {
|
|
14045
|
+
if (leaf < t.windowStart) return "a later item refers to the tree before the cursor";
|
|
14046
|
+
if (value !== void 0 && value !== t.window[leaf - t.windowStart]) return "a later item rewrites the tree before the cursor";
|
|
14047
|
+
return null;
|
|
14048
|
+
}
|
|
14049
|
+
const held = t.pending.get(leaf);
|
|
14050
|
+
if (held !== void 0) return value !== void 0 && value !== held ? "a later item rewrites the tree before the cursor" : null;
|
|
14051
|
+
if (value !== void 0 && leaf < t.hiBefore) return "a later item fills the tree before the cursor";
|
|
14052
|
+
return null;
|
|
14053
|
+
};
|
|
14054
|
+
const chainAt = /* @__PURE__ */ new Map([[startPage, startChain]]);
|
|
14055
|
+
const waiting = /* @__PURE__ */ new Map();
|
|
14056
|
+
let chainNext = startPage;
|
|
14057
|
+
let chainError = null;
|
|
14058
|
+
let wakers = [];
|
|
14059
|
+
const wakeAll = () => {
|
|
14060
|
+
const w = wakers;
|
|
14061
|
+
wakers = [];
|
|
14062
|
+
for (const f of w) f();
|
|
14063
|
+
};
|
|
14064
|
+
signal.addEventListener("abort", wakeAll);
|
|
14065
|
+
const advanceChain = () => {
|
|
14066
|
+
while (!chainError && waiting.has(chainNext)) {
|
|
14067
|
+
const w = waiting.get(chainNext);
|
|
14068
|
+
waiting.delete(chainNext);
|
|
14069
|
+
const expected = chainAt.get(chainNext);
|
|
14070
|
+
if (w.prevChain !== expected) {
|
|
14071
|
+
chainError = cursor && chainNext === startPage ? new FullPassSignal("note index hash chain does not continue from the cursor") : new NoteIndexFormatError(`hash chain broken at page ${chainNext}`);
|
|
14072
|
+
controller.abort();
|
|
14073
|
+
return;
|
|
14074
|
+
}
|
|
14075
|
+
if (!w.complete) break;
|
|
14076
|
+
chainAt.set(chainNext + 1, toHex2(computeNoteIndexChain(fromHex(expected), w.bytes)));
|
|
14077
|
+
chainNext++;
|
|
14078
|
+
}
|
|
14079
|
+
wakeAll();
|
|
14080
|
+
};
|
|
14081
|
+
const workerCount = Math.max(1, Math.min(params.concurrency ?? DEFAULT_CONCURRENCY, pagesTotal - startPage));
|
|
14082
|
+
const lookahead = 2 * workerCount + 2;
|
|
14083
|
+
let nextToFetch = startPage;
|
|
14084
|
+
let pagesDone = 0;
|
|
14085
|
+
const worker = async () => {
|
|
14086
|
+
for (; ; ) {
|
|
14087
|
+
if (signal.aborted) throw abortError2();
|
|
14088
|
+
const pageNo = nextToFetch++;
|
|
14089
|
+
if (pageNo >= pagesTotal) return;
|
|
14090
|
+
while (pageNo - chainNext >= lookahead && !signal.aborted) await new Promise((resolve) => wakers.push(resolve));
|
|
14091
|
+
if (signal.aborted) throw abortError2();
|
|
14092
|
+
const bytes = await fetchNoteIndexPage(relayUrl, head.epoch, pageNo, { signal });
|
|
14093
|
+
stats.bytes += bytes.length;
|
|
14094
|
+
const page2 = parseNoteIndexPage(bytes, { epoch: head.epoch, page: pageNo }, { skipMalformedItems: true });
|
|
14095
|
+
if (pageNo < head.completePages && !page2.complete) {
|
|
14096
|
+
throw new NoteIndexFormatError(`page ${pageNo} is below complete_pages but not complete`);
|
|
14097
|
+
}
|
|
14098
|
+
stats.pages++;
|
|
14099
|
+
stats.skipped += page2.skippedMalformed;
|
|
14100
|
+
const seqOf = (i) => pageNo * NOTE_INDEX_PAGE_SIZE + page2.itemPositions[i];
|
|
14101
|
+
waiting.set(pageNo, { bytes: page2.complete ? bytes : new Uint8Array(0), prevChain: toHex2(page2.prevChain), complete: page2.complete });
|
|
14102
|
+
advanceChain();
|
|
14103
|
+
const data = { complete: page2.complete, leaves: /* @__PURE__ */ new Map() };
|
|
14104
|
+
const late = (reason) => {
|
|
14105
|
+
if (reason && !fullPassReason) {
|
|
14106
|
+
fullPassReason = reason;
|
|
14107
|
+
controller.abort();
|
|
14108
|
+
}
|
|
14109
|
+
};
|
|
14110
|
+
const addLeaf = (mintBytes, commitment, leaf, seq) => {
|
|
14111
|
+
if (isAllZero3(commitment)) return;
|
|
14112
|
+
const mint = addressFromBytes(mintBytes);
|
|
14113
|
+
if (!poolSet.has(mint)) return;
|
|
14114
|
+
const entry = { leaf: Number(leaf), commitment: bytesToBigint3(commitment) };
|
|
14115
|
+
late(lateReference(mint, entry.leaf, entry.commitment, seq));
|
|
14116
|
+
const list = data.leaves.get(mint);
|
|
14117
|
+
if (list) list.push(entry);
|
|
14118
|
+
else data.leaves.set(mint, [entry]);
|
|
14119
|
+
};
|
|
14120
|
+
page2.items.forEach((item, i) => {
|
|
14121
|
+
const seq = seqOf(i);
|
|
14122
|
+
if (item.kind === 1) {
|
|
14123
|
+
addLeaf(item.mint, item.comm0, item.leaf0, seq);
|
|
14124
|
+
addLeaf(item.mint, item.comm1, item.leaf1, seq);
|
|
14125
|
+
if (!isAllZero3(item.nullifier0)) nullifiers.add(toHex2(item.nullifier0));
|
|
14126
|
+
if (!isAllZero3(item.nullifier1)) nullifiers.add(toHex2(item.nullifier1));
|
|
14127
|
+
} else if (item.kind === 3) {
|
|
14128
|
+
addLeaf(item.mint, item.commitment, item.leaf, seq);
|
|
14129
|
+
} else {
|
|
14130
|
+
const mint = addressFromBytes(item.mint);
|
|
14131
|
+
if (poolSet.has(mint)) late(lateReference(mint, Number(item.leaf), void 0, seq));
|
|
14132
|
+
}
|
|
14133
|
+
});
|
|
14134
|
+
if (signal.aborted) throw abortError2();
|
|
14135
|
+
for (let i = 0; i < page2.items.length; i += ITEM_BATCH) {
|
|
14136
|
+
if (signal.aborted) throw abortError2();
|
|
14137
|
+
const batch = page2.items.slice(i, i + ITEM_BATCH);
|
|
14138
|
+
const opened = await Promise.all(batch.map((item) => trialItemIsolated(item, trials, stats)));
|
|
14139
|
+
opened.forEach((o, k) => {
|
|
14140
|
+
if (!o) return;
|
|
14141
|
+
stats.decrypted++;
|
|
14142
|
+
const raw = page2.rawItems[i + k];
|
|
14143
|
+
const id = itemIdentity(raw);
|
|
14144
|
+
if (rejectedIds.has(id)) {
|
|
14145
|
+
stats.dropped++;
|
|
14146
|
+
return;
|
|
14147
|
+
}
|
|
14148
|
+
ownItems.push({ page: pageNo, seq: seqOf(i + k), raw, id, item: batch[k], fromCursor: false, ...o, trial: o.trial });
|
|
14149
|
+
});
|
|
14150
|
+
stats.items += batch.length;
|
|
14151
|
+
}
|
|
14152
|
+
pageData.set(pageNo, data);
|
|
14153
|
+
pagesDone++;
|
|
14154
|
+
onProgress?.({ pagesDone, pagesTotal: pagesTotal - startPage, itemsChecked: stats.items, notesFound: ownItems.length });
|
|
14155
|
+
}
|
|
14156
|
+
};
|
|
14157
|
+
const workers = Array.from(
|
|
14158
|
+
{ length: workerCount },
|
|
14159
|
+
() => worker().catch((error) => {
|
|
14160
|
+
controller.abort();
|
|
14161
|
+
throw error;
|
|
14162
|
+
})
|
|
14163
|
+
);
|
|
14164
|
+
const settled = await Promise.allSettled(workers);
|
|
14165
|
+
signal.removeEventListener("abort", wakeAll);
|
|
14166
|
+
if (params.signal?.aborted) throw abortError2();
|
|
14167
|
+
const lateReason = fullPassReason;
|
|
14168
|
+
if (lateReason) return new FullPassSignal(lateReason);
|
|
14169
|
+
const chainFailure = chainError;
|
|
14170
|
+
if (chainFailure) {
|
|
14171
|
+
if (chainFailure instanceof FullPassSignal) return chainFailure;
|
|
14172
|
+
throw chainFailure;
|
|
14173
|
+
}
|
|
14174
|
+
const failure = settled.find((s) => s.status === "rejected" && s.reason?.name !== "AbortError") ?? settled.find((s) => s.status === "rejected");
|
|
14175
|
+
if (failure) throw failure.reason;
|
|
14176
|
+
if (head.completePages >= startPage && chainAt.get(head.completePages) !== head.chainTip) {
|
|
14177
|
+
if (cursor) return new FullPassSignal("note index hash chain does not reach the head's chain_tip");
|
|
14178
|
+
throw new NoteIndexFormatError("hash chain does not reach the head's chain_tip");
|
|
14179
|
+
}
|
|
14180
|
+
for (const entry of cursor?.items ?? []) {
|
|
14181
|
+
const o = await trialItemIsolated(entry.item, trials, stats);
|
|
14182
|
+
if (!o) continue;
|
|
14183
|
+
const page2 = Math.floor(entry.seq / NOTE_INDEX_PAGE_SIZE);
|
|
14184
|
+
ownItems.push({ page: page2, seq: entry.seq, raw: entry.raw, id: itemIdentity(entry.raw), item: entry.item, fromCursor: true, ...o, trial: o.trial });
|
|
14185
|
+
if (entry.item.kind === 1) {
|
|
14186
|
+
if (!isAllZero3(entry.item.nullifier0)) nullifiers.add(toHex2(entry.item.nullifier0));
|
|
14187
|
+
if (!isAllZero3(entry.item.nullifier1)) nullifiers.add(toHex2(entry.item.nullifier1));
|
|
14188
|
+
}
|
|
14189
|
+
}
|
|
14190
|
+
const knownSpent = cursor?.spent ?? /* @__PURE__ */ new Set();
|
|
14191
|
+
ownItems.sort((a, b) => a.seq - b.seq);
|
|
14192
|
+
const rejectedNow = /* @__PURE__ */ new Set();
|
|
14193
|
+
const skippedNow = /* @__PURE__ */ new Set();
|
|
14194
|
+
const allCandidates = await matchOwnItems(
|
|
14195
|
+
ownItems,
|
|
14196
|
+
owner,
|
|
14197
|
+
(o) => {
|
|
14198
|
+
stats.dropped++;
|
|
14199
|
+
rejectedNow.add(o.id);
|
|
14200
|
+
},
|
|
14201
|
+
(o) => {
|
|
14202
|
+
if (skippedNow.has(o)) return;
|
|
14203
|
+
skippedNow.add(o);
|
|
14204
|
+
stats.skipped++;
|
|
14205
|
+
}
|
|
14206
|
+
);
|
|
14207
|
+
stats.candidates = allCandidates.length;
|
|
14208
|
+
const cutoff = params.legacyCutoffLeaf ?? {};
|
|
14209
|
+
const candidates = allCandidates.filter((c) => {
|
|
14210
|
+
const limit = cutoff[c.mint];
|
|
14211
|
+
if (c.atRisk && limit !== void 0 && BigInt(c.leaf) >= limit) {
|
|
14212
|
+
stats.dropped++;
|
|
14213
|
+
return false;
|
|
14214
|
+
}
|
|
14215
|
+
return true;
|
|
14216
|
+
});
|
|
14217
|
+
const chainTrees = await ctx.readTrees();
|
|
14218
|
+
const orderedPages = Array.from(pageData.keys()).sort((a, b) => a - b);
|
|
14219
|
+
const replays = /* @__PURE__ */ new Map();
|
|
14220
|
+
for (let i = 0; i < poolMints.length; i++) {
|
|
14221
|
+
const mint = poolMints[i];
|
|
14222
|
+
const start = startTrees.get(mint);
|
|
14223
|
+
const chainTree = chainTrees[i] ?? null;
|
|
14224
|
+
const pages = orderedPages.map((page2) => ({ page: page2, entries: pageData.get(page2).leaves.get(mint) ?? [] }));
|
|
14225
|
+
let r = await replayStream(start, pages, start.overrides, chainTree, targetPage);
|
|
14226
|
+
let overrides = start.overrides;
|
|
14227
|
+
stats.conflicts += r.conflicts;
|
|
14228
|
+
if (r.corrections.size > 0 && (r.mismatch || r.verifiedPrefix < r.endCount)) {
|
|
14229
|
+
const merged = new Map([...start.overrides, ...r.corrections]);
|
|
14230
|
+
const alternative = await replayStream(start, pages, merged, chainTree, targetPage);
|
|
14231
|
+
if (alternative.verifiedPrefix > r.verifiedPrefix || r.mismatch && !alternative.mismatch) {
|
|
14232
|
+
r = alternative;
|
|
14233
|
+
overrides = merged;
|
|
14234
|
+
}
|
|
14235
|
+
}
|
|
14236
|
+
if (r.mismatch && cursor && !start.mismatch) return new FullPassSignal("a rebuilt tree disagrees with the chain");
|
|
14237
|
+
replays.set(mint, { r, overrides });
|
|
14238
|
+
}
|
|
14239
|
+
const verifiedUpTo = (mint) => Math.max(startTrees.get(mint).verified, replays.get(mint).r.verifiedPrefix);
|
|
14240
|
+
const streamValue = (mint, leaf) => {
|
|
14241
|
+
const v = replays.get(mint)?.r.valueAt(leaf);
|
|
14242
|
+
if (v !== void 0) return v;
|
|
14243
|
+
const carried = cursor?.pendingLeaves.get(`${mint}:${leaf}`);
|
|
14244
|
+
if (carried !== void 0) return carried;
|
|
14245
|
+
const t = startTrees.get(mint);
|
|
14246
|
+
if (t && leaf >= t.windowStart && leaf < t.nextIndex) return t.window[leaf - t.windowStart];
|
|
14247
|
+
return void 0;
|
|
14248
|
+
};
|
|
14249
|
+
const knownVerified = cursor?.verified ?? /* @__PURE__ */ new Set();
|
|
14250
|
+
const verified = [];
|
|
14251
|
+
const pendingByKey = /* @__PURE__ */ new Map();
|
|
14252
|
+
const rejectedCandidates = /* @__PURE__ */ new Set();
|
|
14253
|
+
const outcomeOf = /* @__PURE__ */ new Map();
|
|
14254
|
+
const tally = (c, what) => {
|
|
14255
|
+
const t = outcomeOf.get(c.seq) ?? { kept: false, rejected: 0, total: 0 };
|
|
14256
|
+
t.total++;
|
|
14257
|
+
if (what === "kept") t.kept = true;
|
|
14258
|
+
if (what === "rejected") t.rejected++;
|
|
14259
|
+
outcomeOf.set(c.seq, t);
|
|
14260
|
+
};
|
|
14261
|
+
const pend = (c, rank) => {
|
|
14262
|
+
const key = verifiedKey(c.mint, c.leaf, c.commitment);
|
|
14263
|
+
const prior = pendingByKey.get(key);
|
|
14264
|
+
if (!prior || prior.c.seq > c.seq) pendingByKey.set(key, { c, rank });
|
|
14265
|
+
};
|
|
14266
|
+
for (const c of candidates) {
|
|
14267
|
+
if (knownVerified.has(verifiedKey(c.mint, c.leaf, c.commitment))) {
|
|
14268
|
+
verified.push(c);
|
|
14269
|
+
continue;
|
|
14270
|
+
}
|
|
14271
|
+
if (!poolSet.has(c.mint)) {
|
|
14272
|
+
pend(c, 3);
|
|
14273
|
+
continue;
|
|
14274
|
+
}
|
|
14275
|
+
const value = streamValue(c.mint, c.leaf);
|
|
14276
|
+
if (value === void 0) {
|
|
14277
|
+
if (c.leaf < startTrees.get(c.mint).nextIndex) {
|
|
14278
|
+
stats.dropped++;
|
|
14279
|
+
tally(c, "other");
|
|
14280
|
+
} else pend(c, 1);
|
|
14281
|
+
} else if (c.leaf >= verifiedUpTo(c.mint)) {
|
|
14282
|
+
pend(c, value === c.commitment ? 0 : 2);
|
|
14283
|
+
} else if (value === c.commitment) {
|
|
14284
|
+
verified.push(c);
|
|
14285
|
+
} else {
|
|
14286
|
+
stats.dropped++;
|
|
14287
|
+
rejectedCandidates.add(c);
|
|
14288
|
+
tally(c, "rejected");
|
|
14289
|
+
}
|
|
14290
|
+
}
|
|
14291
|
+
verified.sort((a, b) => a.seq - b.seq);
|
|
14292
|
+
const byLeaf = /* @__PURE__ */ new Map();
|
|
14293
|
+
for (const c of verified) {
|
|
14294
|
+
const key = `${c.mint}:${c.leaf}`;
|
|
14295
|
+
if (byLeaf.has(key)) {
|
|
14296
|
+
stats.dropped++;
|
|
14297
|
+
tally(c, "other");
|
|
14298
|
+
continue;
|
|
14299
|
+
}
|
|
14300
|
+
byLeaf.set(key, c);
|
|
14301
|
+
}
|
|
14302
|
+
const notes = [];
|
|
14303
|
+
const atRisk = [];
|
|
14304
|
+
const spentOut = new Set(knownSpent);
|
|
14305
|
+
const verifiedOut = new Set(knownVerified);
|
|
14306
|
+
const keyChecked = /* @__PURE__ */ new Map();
|
|
14307
|
+
for (const c of byLeaf.values()) {
|
|
14308
|
+
const pubOk = keyChecked.get(c.keypair.privateKey) ?? (c.keypair.privateKey !== 0n && await derivePublicKey(c.keypair.privateKey) === c.keypair.publicKey);
|
|
14309
|
+
keyChecked.set(c.keypair.privateKey, pubOk);
|
|
14310
|
+
if (!pubOk || !c.atRisk && c.keypair.publicKey !== owner.publicKey) {
|
|
14311
|
+
stats.dropped++;
|
|
14312
|
+
tally(c, "rejected");
|
|
14313
|
+
continue;
|
|
14314
|
+
}
|
|
14315
|
+
tally(c, "kept");
|
|
14316
|
+
verifiedOut.add(verifiedKey(c.mint, c.leaf, c.commitment));
|
|
14317
|
+
const utxo = {
|
|
14318
|
+
amount: c.amount,
|
|
14319
|
+
keypair: c.atRisk ? { ...c.keypair } : owner,
|
|
14320
|
+
blinding: c.blinding,
|
|
14321
|
+
mintAddress: c.mint,
|
|
14322
|
+
index: c.leaf,
|
|
14323
|
+
commitment: c.commitment
|
|
14324
|
+
};
|
|
14325
|
+
if (nullifiers.has(c.nullifier) || knownSpent.has(c.nullifier)) {
|
|
14326
|
+
stats.spent++;
|
|
14327
|
+
spentOut.add(c.nullifier);
|
|
14328
|
+
continue;
|
|
14329
|
+
}
|
|
14330
|
+
const note = {
|
|
14331
|
+
kind: c.kind,
|
|
14332
|
+
utxo,
|
|
14333
|
+
signature: bs584.encode(c.signature),
|
|
14334
|
+
legacyExposed: c.atRisk
|
|
14335
|
+
};
|
|
14336
|
+
(c.atRisk ? atRisk : notes).push(note);
|
|
14337
|
+
}
|
|
14338
|
+
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);
|
|
14339
|
+
sortNotes(notes);
|
|
14340
|
+
sortNotes(atRisk);
|
|
14341
|
+
const pendingList = Array.from(pendingByKey.values()).sort((a, b) => a.rank - b.rank || a.c.seq - b.c.seq);
|
|
14342
|
+
const carriedPending = pendingList.slice(0, MAX_CARRIED_PENDING).map((p) => p.c);
|
|
14343
|
+
const overflow = pendingList.length - carriedPending.length;
|
|
14344
|
+
if (overflow > 0) {
|
|
14345
|
+
stats.pendingDropped += overflow;
|
|
14346
|
+
ctx.warnings.push(`${overflow} unverified candidates over the carry limit were not carried to the next run`);
|
|
14347
|
+
}
|
|
14348
|
+
for (const { c } of pendingList) if (nullifiers.has(c.nullifier)) spentOut.add(c.nullifier);
|
|
14349
|
+
for (const c of carriedPending) tally(c, "kept");
|
|
14350
|
+
for (const { c } of pendingList.slice(MAX_CARRIED_PENDING)) tally(c, "other");
|
|
14351
|
+
let page = targetPage;
|
|
14352
|
+
for (const { r } of replays.values()) if (r.snapshot === null) page = startPage;
|
|
14353
|
+
const trees = {};
|
|
14354
|
+
const treeEnd = /* @__PURE__ */ new Map();
|
|
14355
|
+
for (const mint of poolMints) {
|
|
14356
|
+
const start = startTrees.get(mint);
|
|
14357
|
+
const { r, overrides } = replays.get(mint);
|
|
14358
|
+
const snap = page === startPage ? { frontier: start.frontier ?? (await MerkleFrontier.create()).toState(), pending: start.pending, nextIndex: start.nextIndex } : r.snapshot;
|
|
14359
|
+
const n = snap.nextIndex;
|
|
14360
|
+
const window2 = [];
|
|
14361
|
+
for (let leaf = n - 1; leaf >= Math.max(0, n - LEAF_WINDOW); leaf--) {
|
|
14362
|
+
const v = leaf >= start.nextIndex ? r.valueAt(leaf) : leaf >= start.windowStart ? start.window[leaf - start.windowStart] : void 0;
|
|
14363
|
+
if (v === void 0) break;
|
|
14364
|
+
window2.push(hex32(v));
|
|
14365
|
+
}
|
|
14366
|
+
window2.reverse();
|
|
14367
|
+
trees[mint] = {
|
|
14368
|
+
frontier: snap.frontier,
|
|
14369
|
+
pending: Array.from(snap.pending.entries(), ([leaf, v]) => [leaf, hex32(v)]).sort((a, b) => a[0] - b[0]),
|
|
14370
|
+
window: window2.join(""),
|
|
14371
|
+
verified: Math.min(verifiedUpTo(mint), n),
|
|
14372
|
+
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)]),
|
|
14373
|
+
mismatch: r.mismatch
|
|
14374
|
+
};
|
|
14375
|
+
treeEnd.set(mint, { nextIndex: n, pending: snap.pending });
|
|
14376
|
+
}
|
|
14377
|
+
const pendingLeaves = [];
|
|
14378
|
+
const pendingLeafSeen = /* @__PURE__ */ new Set();
|
|
14379
|
+
for (const c of carriedPending) {
|
|
14380
|
+
const end = treeEnd.get(c.mint);
|
|
14381
|
+
if (!end || c.leaf >= end.nextIndex) continue;
|
|
14382
|
+
const value = streamValue(c.mint, c.leaf);
|
|
14383
|
+
const key = `${c.mint}:${c.leaf}`;
|
|
14384
|
+
if (value === void 0 || pendingLeafSeen.has(key)) continue;
|
|
14385
|
+
pendingLeafSeen.add(key);
|
|
14386
|
+
pendingLeaves.push([c.mint, c.leaf, hex32(value)]);
|
|
14387
|
+
}
|
|
14388
|
+
const keptItems = [];
|
|
14389
|
+
const keptIds = /* @__PURE__ */ new Set();
|
|
14390
|
+
for (const o of ownItems) {
|
|
14391
|
+
const t = outcomeOf.get(o.seq);
|
|
14392
|
+
if (rejectedNow.has(o.id) || t && t.total > 0 && t.rejected === t.total) {
|
|
14393
|
+
rejectedNow.add(o.id);
|
|
14394
|
+
continue;
|
|
14395
|
+
}
|
|
14396
|
+
if (o.page >= page || !t?.kept || keptIds.has(o.id)) continue;
|
|
14397
|
+
keptIds.add(o.id);
|
|
14398
|
+
keptItems.push({ seq: o.seq, item: toHex2(o.raw) });
|
|
14399
|
+
}
|
|
14400
|
+
const rejected = Array.from(/* @__PURE__ */ new Set([...cursor?.rejected ?? [], ...rejectedNow]));
|
|
14401
|
+
const nextCursor = {
|
|
14402
|
+
v: CURSOR_VERSION,
|
|
14403
|
+
epoch: head.epoch.toString(10),
|
|
14404
|
+
page,
|
|
14405
|
+
chain: chainAt.get(page) ?? startChain,
|
|
14406
|
+
watermark: Math.max(cursor?.raw.watermark ?? 0, head.watermark),
|
|
14407
|
+
fullPassSeq: cursor ? fullPassSeq : head.watermark,
|
|
14408
|
+
trees,
|
|
14409
|
+
own: {
|
|
14410
|
+
items: keptItems,
|
|
14411
|
+
verified: Array.from(verifiedOut),
|
|
14412
|
+
spent: Array.from(spentOut),
|
|
14413
|
+
pendingLeaves,
|
|
14414
|
+
rejected: rejected.slice(Math.max(0, rejected.length - MAX_REJECTED_IDS))
|
|
14415
|
+
}
|
|
14416
|
+
};
|
|
14417
|
+
return { notes, atRisk, pending: pendingByKey.size, cursor: nextCursor };
|
|
14418
|
+
} finally {
|
|
14419
|
+
params.signal?.removeEventListener("abort", onCallerAbort);
|
|
14420
|
+
}
|
|
14421
|
+
}
|
|
14422
|
+
|
|
14423
|
+
// src/wallet/utxo-wallet.ts
|
|
14424
|
+
init_address();
|
|
14425
|
+
init_utxo();
|
|
14426
|
+
var UtxoWallet = class _UtxoWallet {
|
|
14427
|
+
constructor(viewingKey) {
|
|
14428
|
+
this.wallets = /* @__PURE__ */ new Map();
|
|
14429
|
+
this.viewingKey = viewingKey;
|
|
14430
|
+
}
|
|
14431
|
+
/**
|
|
14432
|
+
* Add a UTXO to the wallet (discovered from chain or created)
|
|
14433
|
+
*/
|
|
14434
|
+
addUtxo(utxo, mint = NATIVE_SOL_MINT) {
|
|
14435
|
+
const mintKey = mint;
|
|
14436
|
+
if (!this.wallets.has(mintKey)) {
|
|
14437
|
+
this.wallets.set(mintKey, {
|
|
14438
|
+
mint,
|
|
14439
|
+
utxos: []
|
|
14440
|
+
});
|
|
14441
|
+
}
|
|
14442
|
+
const wallet = this.wallets.get(mintKey);
|
|
14443
|
+
const exists = wallet.utxos.some(
|
|
14444
|
+
(u) => u.amount === utxo.amount && u.keypair.publicKey === utxo.keypair.publicKey && u.blinding === utxo.blinding
|
|
14445
|
+
);
|
|
12279
14446
|
if (!exists) {
|
|
12280
14447
|
wallet.utxos.push({
|
|
12281
14448
|
...utxo,
|
|
@@ -12912,7 +15079,7 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
|
|
|
12912
15079
|
})
|
|
12913
15080
|
});
|
|
12914
15081
|
const prepared = await parseBridgeResponse2(prepareRes, "paymaster prepare");
|
|
12915
|
-
if (
|
|
15082
|
+
if (relayNowSeconds() >= prepared.expires_at_unix) {
|
|
12916
15083
|
throw new Error(
|
|
12917
15084
|
"paymaster prepare returned a voucher that is already expired \u2014 refusing to sign a stale top-up rather than fail confusingly at cosign"
|
|
12918
15085
|
);
|
|
@@ -12949,9 +15116,13 @@ async function fundReceiverViaPaymaster(relayUrl, receiver, grantLamports) {
|
|
|
12949
15116
|
// src/bridge/derive.ts
|
|
12950
15117
|
var import_hmac = require("@noble/hashes/hmac");
|
|
12951
15118
|
var import_sha512 = require("@noble/hashes/sha512");
|
|
15119
|
+
var import_blake37 = require("@noble/hashes/blake3");
|
|
15120
|
+
init_utxo();
|
|
12952
15121
|
var BRIDGE_ESCROW_LABEL = "cloak_bridge_escrow";
|
|
15122
|
+
var BRIDGE_ESCROW_LABEL_V2 = "cloak_bridge_escrow_v2";
|
|
15123
|
+
var BRIDGE_RECEIVER_KEY_DOMAIN = new TextEncoder().encode("cloak_bridge_receiver_key_v2");
|
|
12953
15124
|
var MAX_RECEIVER_INDEX = 1e4;
|
|
12954
|
-
|
|
15125
|
+
function assertReceiverIndex(index) {
|
|
12955
15126
|
if (!Number.isInteger(index) || index < 0) {
|
|
12956
15127
|
throw new Error(`index must be a non-negative integer, got ${index}`);
|
|
12957
15128
|
}
|
|
@@ -12960,6 +15131,26 @@ async function deriveBridgeReceiver(nk, index) {
|
|
|
12960
15131
|
`index ${index} exceeds MAX_RECEIVER_INDEX (${MAX_RECEIVER_INDEX}). Indices must be a small sequential counter \u2014 discovery derives 0\u2026N and reads each on chain, so a timestamp index is unreachable by any scan and the deposit would be invisible to every device but this one.`
|
|
12961
15132
|
);
|
|
12962
15133
|
}
|
|
15134
|
+
}
|
|
15135
|
+
async function deriveBridgeReceiver(ownerUtxoKeypair, index) {
|
|
15136
|
+
if (ownerUtxoKeypair instanceof Uint8Array) {
|
|
15137
|
+
throw new Error(
|
|
15138
|
+
"deriveBridgeReceiver takes the wallet's UTXO keypair, not a byte key. Receivers are no longer derived from nk; use deriveLegacyBridgeReceiver(nk, index) only to find old deposits."
|
|
15139
|
+
);
|
|
15140
|
+
}
|
|
15141
|
+
assertReceiverIndex(index);
|
|
15142
|
+
const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
|
|
15143
|
+
const priv = bigintToBytes323(owner.privateKey);
|
|
15144
|
+
const preimage = new Uint8Array(BRIDGE_RECEIVER_KEY_DOMAIN.length + priv.length);
|
|
15145
|
+
preimage.set(BRIDGE_RECEIVER_KEY_DOMAIN, 0);
|
|
15146
|
+
preimage.set(priv, BRIDGE_RECEIVER_KEY_DOMAIN.length);
|
|
15147
|
+
const key = (0, import_blake37.blake3)(preimage);
|
|
15148
|
+
const h = (0, import_hmac.hmac)(import_sha512.sha512, key, new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL_V2}:${index}`));
|
|
15149
|
+
return signerFromSecretKey(h.slice(0, 32));
|
|
15150
|
+
}
|
|
15151
|
+
async function deriveLegacyBridgeReceiver(nk, index) {
|
|
15152
|
+
assertReceiverIndex(index);
|
|
15153
|
+
if (!nk || nk.length !== 32) throw new Error("nk must be 32 bytes");
|
|
12963
15154
|
const h = (0, import_hmac.hmac)(import_sha512.sha512, new Uint8Array(nk), new TextEncoder().encode(`${BRIDGE_ESCROW_LABEL}:${index}`));
|
|
12964
15155
|
return signerFromSecretKey(h.slice(0, 32));
|
|
12965
15156
|
}
|
|
@@ -12970,13 +15161,44 @@ var import_token4 = require("@solana-program/token");
|
|
|
12970
15161
|
function describeError(err) {
|
|
12971
15162
|
return err instanceof Error ? err.message : String(err);
|
|
12972
15163
|
}
|
|
12973
|
-
async function listBridgeDeposits(rpc,
|
|
15164
|
+
async function listBridgeDeposits(rpc, ownerUtxoKeypair, opts) {
|
|
15165
|
+
if (ownerUtxoKeypair instanceof Uint8Array) {
|
|
15166
|
+
throw new Error(
|
|
15167
|
+
"listBridgeDeposits takes the wallet's UTXO keypair, not nk. Receivers are no longer derived from nk; legacy nk receivers are scanned automatically (see DiscoverOptions.includeLegacy)."
|
|
15168
|
+
);
|
|
15169
|
+
}
|
|
15170
|
+
const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
|
|
15171
|
+
const out = await scanReceivers(rpc, opts, (index) => deriveBridgeReceiver(owner, index), {
|
|
15172
|
+
legacyExposed: false
|
|
15173
|
+
});
|
|
15174
|
+
if (opts.includeLegacy === false) return out;
|
|
15175
|
+
const nks = [];
|
|
15176
|
+
const seen = /* @__PURE__ */ new Set();
|
|
15177
|
+
for (const nk of [getNkFromUtxoPrivateKey(owner.privateKey), ...opts.legacyViewingKeyNks ?? []]) {
|
|
15178
|
+
if (!(nk instanceof Uint8Array) || nk.length !== 32) {
|
|
15179
|
+
throw new Error("legacyViewingKeyNks entries must be 32 bytes");
|
|
15180
|
+
}
|
|
15181
|
+
const key = Array.from(nk, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
15182
|
+
if (seen.has(key)) continue;
|
|
15183
|
+
seen.add(key);
|
|
15184
|
+
nks.push(nk);
|
|
15185
|
+
}
|
|
15186
|
+
for (const nk of nks) {
|
|
15187
|
+
const legacy = await scanReceivers(rpc, opts, (index) => deriveLegacyBridgeReceiver(nk, index), {
|
|
15188
|
+
legacyExposed: true,
|
|
15189
|
+
legacyViewingKeyNk: nk
|
|
15190
|
+
});
|
|
15191
|
+
out.push(...legacy);
|
|
15192
|
+
}
|
|
15193
|
+
return out;
|
|
15194
|
+
}
|
|
15195
|
+
async function scanReceivers(rpc, opts, receiverAt, provenance) {
|
|
12974
15196
|
const scanDepth = Math.min(opts.scanDepth ?? 20, MAX_RECEIVER_INDEX + 1);
|
|
12975
15197
|
const stopAfterUnused = opts.stopAfterUnused ?? 5;
|
|
12976
15198
|
const out = [];
|
|
12977
15199
|
let consecutiveUnused = 0;
|
|
12978
15200
|
for (let index = 0; index < scanDepth; index++) {
|
|
12979
|
-
const kp = await
|
|
15201
|
+
const kp = await receiverAt(index);
|
|
12980
15202
|
const receiver = kp.address;
|
|
12981
15203
|
const [tokenAccount] = await (0, import_token4.findAssociatedTokenPda)({
|
|
12982
15204
|
mint: opts.mint,
|
|
@@ -13028,7 +15250,8 @@ async function listBridgeDeposits(rpc, nk, opts) {
|
|
|
13028
15250
|
tokenBalance,
|
|
13029
15251
|
lamports,
|
|
13030
15252
|
shieldSignature,
|
|
13031
|
-
...indexReused ? { indexReused, shieldSignatures } : {}
|
|
15253
|
+
...indexReused ? { indexReused, shieldSignatures } : {},
|
|
15254
|
+
...provenance
|
|
13032
15255
|
});
|
|
13033
15256
|
} catch (err) {
|
|
13034
15257
|
out.push({
|
|
@@ -13038,7 +15261,8 @@ async function listBridgeDeposits(rpc, nk, opts) {
|
|
|
13038
15261
|
state: "unknown",
|
|
13039
15262
|
tokenBalance: 0n,
|
|
13040
15263
|
lamports: 0n,
|
|
13041
|
-
error: describeError(err)
|
|
15264
|
+
error: describeError(err),
|
|
15265
|
+
...provenance
|
|
13042
15266
|
});
|
|
13043
15267
|
}
|
|
13044
15268
|
}
|
|
@@ -13192,7 +15416,12 @@ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log,
|
|
|
13192
15416
|
const signMessage = (m) => signMessageBytes(R, m);
|
|
13193
15417
|
const utxoKeypair = await deriveUtxoKeypairFromSpendKey(opts.noteSpendKey);
|
|
13194
15418
|
const nk = getNkFromUtxoPrivateKey(utxoKeypair.privateKey);
|
|
13195
|
-
const { utxo, noteSalt } = await createRecoverableDepositUtxo(
|
|
15419
|
+
const { utxo, noteSalt } = await createRecoverableDepositUtxo({
|
|
15420
|
+
amount,
|
|
15421
|
+
viewingKeyNk: nk,
|
|
15422
|
+
ownerUtxoKeypair: utxoKeypair,
|
|
15423
|
+
mintAddress: mint
|
|
15424
|
+
});
|
|
13196
15425
|
const zeroInput = await createZeroUtxo(mint);
|
|
13197
15426
|
const rBefore = (await rpc.getBalance(R.address).send()).value;
|
|
13198
15427
|
let result;
|
|
@@ -13211,6 +15440,7 @@ async function depositFromDerivedKey(rpc, R, funder, amount, log = console.log,
|
|
|
13211
15440
|
signMessage,
|
|
13212
15441
|
chainNoteViewingKeyNk: nk,
|
|
13213
15442
|
chainNoteSalt: noteSalt,
|
|
15443
|
+
ownerUtxoKeypair: utxoKeypair,
|
|
13214
15444
|
relaySupplementalAlt: true,
|
|
13215
15445
|
onProgress: (s) => log(` \xB7 ${s}`)
|
|
13216
15446
|
}
|
|
@@ -13398,13 +15628,13 @@ var DoNotRetry = class extends Error {
|
|
|
13398
15628
|
};
|
|
13399
15629
|
async function withShieldRetries(attempt, hooks = {}) {
|
|
13400
15630
|
const attempts = hooks.attempts ?? 3;
|
|
13401
|
-
const
|
|
15631
|
+
const sleep5 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
13402
15632
|
let last = "";
|
|
13403
15633
|
for (let n = 1; n <= attempts; n++) {
|
|
13404
15634
|
if (n > 1) {
|
|
13405
15635
|
const delay = retryDelayMs(n);
|
|
13406
15636
|
hooks.onRetry?.(n, delay, last);
|
|
13407
|
-
await
|
|
15637
|
+
await sleep5(delay);
|
|
13408
15638
|
}
|
|
13409
15639
|
try {
|
|
13410
15640
|
return await attempt(n);
|
|
@@ -13424,6 +15654,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
13424
15654
|
0 && (module.exports = {
|
|
13425
15655
|
AccountRole,
|
|
13426
15656
|
BRIDGE_ESCROW_LABEL,
|
|
15657
|
+
BRIDGE_ESCROW_LABEL_V2,
|
|
13427
15658
|
BUILD_ALLOWS_LOCAL_ENDPOINTS,
|
|
13428
15659
|
CHAIN_NOTE_SALT_BITS,
|
|
13429
15660
|
CLEANUP_FEE_BUDGET,
|
|
@@ -13452,6 +15683,10 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
13452
15683
|
MemoryStorageAdapter,
|
|
13453
15684
|
MerkleTree,
|
|
13454
15685
|
NATIVE_SOL_MINT,
|
|
15686
|
+
NOTE_INDEX_NO_LEAF,
|
|
15687
|
+
NOTE_INDEX_PAGE_SIZE,
|
|
15688
|
+
NoteIndexFormatError,
|
|
15689
|
+
NoteIndexHeadBehindError,
|
|
13455
15690
|
ONECLICK_PUBKEY_B58,
|
|
13456
15691
|
RECIPIENT_DELIVERY_CIPHERTEXT_LEN,
|
|
13457
15692
|
RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
|
|
@@ -13528,6 +15763,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
13528
15763
|
computeChainNoteHash,
|
|
13529
15764
|
computeExtDataHash,
|
|
13530
15765
|
computeMerkleRoot,
|
|
15766
|
+
computeNoteIndexChain,
|
|
13531
15767
|
computeProofForLatestDeposit,
|
|
13532
15768
|
computeProofFromChain,
|
|
13533
15769
|
computeSignature,
|
|
@@ -13552,14 +15788,18 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
13552
15788
|
depositFromDerivedKey,
|
|
13553
15789
|
deriveBridgeReceiver,
|
|
13554
15790
|
deriveChangeNoteBlinding,
|
|
13555
|
-
|
|
15791
|
+
deriveDepositNoteBlinding,
|
|
13556
15792
|
deriveDiversifiedViewingKey,
|
|
13557
15793
|
deriveDiversifier,
|
|
13558
15794
|
deriveFundingTargets,
|
|
13559
15795
|
deriveInputNullifierPdas,
|
|
15796
|
+
deriveLegacyBridgeReceiver,
|
|
15797
|
+
deriveLegacyDepositNoteSecrets,
|
|
15798
|
+
deriveLegacySwapRefundAuthorization,
|
|
13560
15799
|
derivePublicKey,
|
|
13561
15800
|
deriveSpendKey,
|
|
13562
15801
|
deriveSwapRefundAuthorization,
|
|
15802
|
+
deriveSwapRefundBlinding,
|
|
13563
15803
|
deriveUserCompliancePublicKey,
|
|
13564
15804
|
deriveUserComplianceScalar,
|
|
13565
15805
|
deriveUtxoKeypairFromSpendKey,
|
|
@@ -13572,6 +15812,8 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
13572
15812
|
discoverSwapRefunds,
|
|
13573
15813
|
downloadNote,
|
|
13574
15814
|
encodeDeliveryCarrierMemo,
|
|
15815
|
+
encodeNoteIndexItem,
|
|
15816
|
+
encodeNoteIndexPage,
|
|
13575
15817
|
encodeNoteSimple,
|
|
13576
15818
|
encodeRecipientDeliveryNote,
|
|
13577
15819
|
encryptCompactChainNote,
|
|
@@ -13587,6 +15829,8 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
13587
15829
|
fetchCommitments,
|
|
13588
15830
|
fetchLatestBlockhash,
|
|
13589
15831
|
fetchLookupTables,
|
|
15832
|
+
fetchNoteIndexHead,
|
|
15833
|
+
fetchNoteIndexPage,
|
|
13590
15834
|
fetchRiskQuoteInstruction,
|
|
13591
15835
|
fetchRiskQuoteIx,
|
|
13592
15836
|
fetchSignaturesForAddress,
|
|
@@ -13659,6 +15903,8 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
13659
15903
|
parseDeliveryCarrierMemo,
|
|
13660
15904
|
parseError,
|
|
13661
15905
|
parseNote,
|
|
15906
|
+
parseNoteIndexItem,
|
|
15907
|
+
parseNoteIndexPage,
|
|
13662
15908
|
parseRelayErrorResponse,
|
|
13663
15909
|
parseRelayErrorSignature,
|
|
13664
15910
|
parseTransactionError,
|
|
@@ -13680,6 +15926,7 @@ var SCANNER_SUPPORTS_TRANSACT_SWAP = true;
|
|
|
13680
15926
|
readMerkleTreeState,
|
|
13681
15927
|
readRent,
|
|
13682
15928
|
recipientDeliveryNoteToBase64,
|
|
15929
|
+
recoverNotesFromIndex,
|
|
13683
15930
|
registerViewingKey,
|
|
13684
15931
|
relayRequestDigestHex,
|
|
13685
15932
|
removePendingDeposit,
|