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