@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.js
CHANGED
|
@@ -756,7 +756,7 @@ var BUILD_ALLOWS_LOCAL_ENDPOINTS = RELAY_ORIGIN_ALLOWLIST.some(isLoopbackHost);
|
|
|
756
756
|
// src/relay/clock.ts
|
|
757
757
|
var RELAY_SERVER_TIME_HEADER = "x-cloak-server-time";
|
|
758
758
|
var MAX_CLOCK_DIVERGENCE_MS = 2e3;
|
|
759
|
-
var MAX_PLAUSIBLE_OFFSET_MS =
|
|
759
|
+
var MAX_PLAUSIBLE_OFFSET_MS = 24 * 60 * 60 * 1e3;
|
|
760
760
|
var sample = null;
|
|
761
761
|
function monotonicNowMs() {
|
|
762
762
|
const perf = globalThis.performance;
|
|
@@ -843,7 +843,7 @@ async function relayFetch(url, init, options) {
|
|
|
843
843
|
assertAllowedRelayOrigin(url);
|
|
844
844
|
const extra = sanitizeExtraHeaders(options?.extraHeaders);
|
|
845
845
|
const response = extra ? await fetch(url, { ...init, headers: mergeRelayHeaders(init?.headers, extra) }) : await fetch(url, init);
|
|
846
|
-
observeRelayClock(response);
|
|
846
|
+
if (options?.observeClock !== false) observeRelayClock(response);
|
|
847
847
|
return response;
|
|
848
848
|
}
|
|
849
849
|
var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
@@ -1945,6 +1945,14 @@ function isSubmissionOutcomeUnknownResponse(responseText) {
|
|
|
1945
1945
|
return false;
|
|
1946
1946
|
}
|
|
1947
1947
|
}
|
|
1948
|
+
function isRelayRequestInFlightResponse(responseText) {
|
|
1949
|
+
try {
|
|
1950
|
+
const parsed = JSON.parse(responseText);
|
|
1951
|
+
return parsed?.code === "transient_upstream" && typeof parsed.message === "string" && parsed.message.includes("is already processing");
|
|
1952
|
+
} catch {
|
|
1953
|
+
return false;
|
|
1954
|
+
}
|
|
1955
|
+
}
|
|
1948
1956
|
function classifyRelayError(responseText, httpStatus) {
|
|
1949
1957
|
let inner = "";
|
|
1950
1958
|
try {
|
|
@@ -3970,6 +3978,27 @@ function isRootAccepted(data, rootHex) {
|
|
|
3970
3978
|
const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
|
|
3971
3979
|
return readRootHistory(data).some((r) => r === want);
|
|
3972
3980
|
}
|
|
3981
|
+
function treeAccountAcceptsRoot(data, rootHex) {
|
|
3982
|
+
const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
|
|
3983
|
+
if (data.length >= ROOT_OFFSET + 32) {
|
|
3984
|
+
const current = Buffer.from(data.subarray(ROOT_OFFSET, ROOT_OFFSET + 32)).toString("hex");
|
|
3985
|
+
if (current === want) return true;
|
|
3986
|
+
}
|
|
3987
|
+
return isRootAccepted(data, want);
|
|
3988
|
+
}
|
|
3989
|
+
function readTreeAccountFrontier(data) {
|
|
3990
|
+
if (!data || data.length < ROOT_INDEX_OFFSET + 8) return null;
|
|
3991
|
+
const buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
|
|
3992
|
+
const next = readBigUInt64LE(buf, 32);
|
|
3993
|
+
if (next > 2n ** BigInt(MERKLE_TREE_HEIGHT)) return null;
|
|
3994
|
+
const subtrees = [];
|
|
3995
|
+
for (let level = 0; level < MERKLE_TREE_HEIGHT; level++) {
|
|
3996
|
+
const offset = SUBTREES_OFFSET + level * 32;
|
|
3997
|
+
subtrees.push(BigInt("0x" + buf.subarray(offset, offset + 32).toString("hex")));
|
|
3998
|
+
}
|
|
3999
|
+
const root = BigInt("0x" + buf.subarray(ROOT_OFFSET, ROOT_OFFSET + 32).toString("hex"));
|
|
4000
|
+
return { nextIndex: Number(next), subtrees, root };
|
|
4001
|
+
}
|
|
3973
4002
|
|
|
3974
4003
|
// src/proving/merkle.ts
|
|
3975
4004
|
import { buildPoseidon } from "circomlibjs";
|
|
@@ -4129,6 +4158,89 @@ var MerkleTree = class _MerkleTree {
|
|
|
4129
4158
|
async function buildMerkleTree(commitments, height = MERKLE_TREE_HEIGHT2) {
|
|
4130
4159
|
return MerkleTree.create(height, commitments);
|
|
4131
4160
|
}
|
|
4161
|
+
var MerkleFrontier = class _MerkleFrontier {
|
|
4162
|
+
constructor(levels, zeros, poseidon2, count, left) {
|
|
4163
|
+
this.levels = levels;
|
|
4164
|
+
this.zeros = zeros;
|
|
4165
|
+
this.poseidon = poseidon2;
|
|
4166
|
+
this.count = count;
|
|
4167
|
+
this.left = left;
|
|
4168
|
+
}
|
|
4169
|
+
static async create(state, levels = MERKLE_TREE_HEIGHT2) {
|
|
4170
|
+
const zeros = await getZeroValues();
|
|
4171
|
+
const poseidon2 = await getPoseidon();
|
|
4172
|
+
const left = new Array(levels).fill(null);
|
|
4173
|
+
let count = 0;
|
|
4174
|
+
if (state) {
|
|
4175
|
+
if (!Number.isSafeInteger(state.nextIndex) || state.nextIndex < 0 || state.nextIndex > 2 ** levels) {
|
|
4176
|
+
throw new Error("MerkleFrontierState.nextIndex out of range");
|
|
4177
|
+
}
|
|
4178
|
+
if (!Array.isArray(state.left) || state.left.length !== levels) {
|
|
4179
|
+
throw new Error(`MerkleFrontierState.left must have ${levels} entries`);
|
|
4180
|
+
}
|
|
4181
|
+
count = state.nextIndex;
|
|
4182
|
+
for (let l = 0; l < levels; l++) {
|
|
4183
|
+
const odd = Math.floor(count / 2 ** l) % 2 === 1;
|
|
4184
|
+
const entry = state.left[l];
|
|
4185
|
+
if (odd !== (entry !== "")) throw new Error(`MerkleFrontierState.left[${l}] disagrees with nextIndex`);
|
|
4186
|
+
if (odd) {
|
|
4187
|
+
if (!/^[0-9a-f]{64}$/.test(entry)) throw new Error(`MerkleFrontierState.left[${l}] is not 32-byte hex`);
|
|
4188
|
+
left[l] = BigInt("0x" + entry);
|
|
4189
|
+
}
|
|
4190
|
+
}
|
|
4191
|
+
}
|
|
4192
|
+
return new _MerkleFrontier(levels, zeros, poseidon2, count, left);
|
|
4193
|
+
}
|
|
4194
|
+
get nextIndex() {
|
|
4195
|
+
return this.count;
|
|
4196
|
+
}
|
|
4197
|
+
/**
|
|
4198
|
+
* The complete LEFT node held at `level`: the node at index `floor(nextIndex / 2^level) - 1`,
|
|
4199
|
+
* present only while that index is even (bit `level` of `nextIndex` is set), else `null`.
|
|
4200
|
+
* With every set bit of `nextIndex`, these nodes cover leaves `[0, nextIndex)` exactly.
|
|
4201
|
+
*/
|
|
4202
|
+
leftAt(level) {
|
|
4203
|
+
if (!Number.isInteger(level) || level < 0 || level >= this.levels) return null;
|
|
4204
|
+
return this.left[level];
|
|
4205
|
+
}
|
|
4206
|
+
hash(a, b) {
|
|
4207
|
+
return this.poseidon.F.toObject(this.poseidon([a, b]));
|
|
4208
|
+
}
|
|
4209
|
+
/** Append leaves at indices `nextIndex .. nextIndex + leaves.length - 1`. */
|
|
4210
|
+
append(leaves) {
|
|
4211
|
+
if (leaves.length === 0) return;
|
|
4212
|
+
if (this.count + leaves.length > 2 ** this.levels) throw new Error("Tree is full");
|
|
4213
|
+
let nodes = leaves;
|
|
4214
|
+
for (let l = 0; l < this.levels && nodes.length > 0; l++) {
|
|
4215
|
+
const before = Math.floor(this.count / 2 ** l);
|
|
4216
|
+
const seq = before % 2 === 1 ? [this.left[l], ...nodes] : nodes;
|
|
4217
|
+
const parents = [];
|
|
4218
|
+
for (let i = 0; i + 1 < seq.length; i += 2) parents.push(this.hash(seq[i], seq[i + 1]));
|
|
4219
|
+
this.left[l] = (before + nodes.length) % 2 === 1 ? seq[seq.length - 1] : null;
|
|
4220
|
+
nodes = parents;
|
|
4221
|
+
}
|
|
4222
|
+
this.count += leaves.length;
|
|
4223
|
+
}
|
|
4224
|
+
/** The root of the first `nextIndex` leaves, zero-padded to the right. */
|
|
4225
|
+
root() {
|
|
4226
|
+
let partial = this.zeros[0];
|
|
4227
|
+
for (let l = 0; l < this.levels; l++) {
|
|
4228
|
+
const odd = Math.floor(this.count / 2 ** l) % 2 === 1;
|
|
4229
|
+
if (odd) partial = this.hash(this.left[l], partial);
|
|
4230
|
+
else partial = partial === this.zeros[l] ? this.zeros[l + 1] : this.hash(partial, this.zeros[l]);
|
|
4231
|
+
}
|
|
4232
|
+
return partial;
|
|
4233
|
+
}
|
|
4234
|
+
toState() {
|
|
4235
|
+
return {
|
|
4236
|
+
nextIndex: this.count,
|
|
4237
|
+
left: this.left.map((v) => v === null ? "" : v.toString(16).padStart(64, "0"))
|
|
4238
|
+
};
|
|
4239
|
+
}
|
|
4240
|
+
clone() {
|
|
4241
|
+
return new _MerkleFrontier(this.levels, this.zeros, this.poseidon, this.count, [...this.left]);
|
|
4242
|
+
}
|
|
4243
|
+
};
|
|
4132
4244
|
|
|
4133
4245
|
// src/config/transaction-version.ts
|
|
4134
4246
|
var MAX_SUPPORTED_TRANSACTION_VERSION = 1;
|
|
@@ -4641,38 +4753,77 @@ async function aesGcmDecrypt2(ciphertext, keyBytes, nonce) {
|
|
|
4641
4753
|
const plaintext = await subtle.decrypt({ name: "AES-GCM", iv: toArrayBuffer2(nonce) }, key, toArrayBuffer2(ciphertext));
|
|
4642
4754
|
return new Uint8Array(plaintext);
|
|
4643
4755
|
}
|
|
4644
|
-
async function
|
|
4756
|
+
async function importNkHkdfKey(nk) {
|
|
4645
4757
|
if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
|
|
4646
4758
|
throw new Error("nk must be 32 bytes");
|
|
4647
4759
|
}
|
|
4760
|
+
return getSubtleCrypto2().importKey("raw", toArrayBuffer2(nk), "HKDF", false, ["deriveBits"]);
|
|
4761
|
+
}
|
|
4762
|
+
async function deriveAesKeyAndNonceFromIkm(ikm, salt) {
|
|
4648
4763
|
const subtle = getSubtleCrypto2();
|
|
4649
|
-
const
|
|
4650
|
-
|
|
4651
|
-
|
|
4652
|
-
|
|
4653
|
-
|
|
4654
|
-
|
|
4655
|
-
|
|
4656
|
-
|
|
4657
|
-
|
|
4658
|
-
|
|
4659
|
-
|
|
4660
|
-
|
|
4661
|
-
|
|
4662
|
-
|
|
4663
|
-
|
|
4664
|
-
|
|
4665
|
-
|
|
4666
|
-
|
|
4667
|
-
|
|
4668
|
-
|
|
4669
|
-
|
|
4670
|
-
);
|
|
4764
|
+
const [keyBits, nonceBits] = await Promise.all([
|
|
4765
|
+
subtle.deriveBits(
|
|
4766
|
+
{
|
|
4767
|
+
name: "HKDF",
|
|
4768
|
+
hash: "SHA-256",
|
|
4769
|
+
salt: toArrayBuffer2(salt),
|
|
4770
|
+
info: toArrayBuffer2(CHAIN_NOTE_KEY_INFO)
|
|
4771
|
+
},
|
|
4772
|
+
ikm,
|
|
4773
|
+
256
|
|
4774
|
+
),
|
|
4775
|
+
subtle.deriveBits(
|
|
4776
|
+
{
|
|
4777
|
+
name: "HKDF",
|
|
4778
|
+
hash: "SHA-256",
|
|
4779
|
+
salt: toArrayBuffer2(salt),
|
|
4780
|
+
info: toArrayBuffer2(CHAIN_NOTE_NONCE_INFO)
|
|
4781
|
+
},
|
|
4782
|
+
ikm,
|
|
4783
|
+
96
|
|
4784
|
+
)
|
|
4785
|
+
]);
|
|
4671
4786
|
return {
|
|
4672
4787
|
key: new Uint8Array(keyBits),
|
|
4673
4788
|
nonce: new Uint8Array(nonceBits)
|
|
4674
4789
|
};
|
|
4675
4790
|
}
|
|
4791
|
+
async function deriveAesKeyAndNonce(nk, commitmentHex) {
|
|
4792
|
+
const ikm = await importNkHkdfKey(nk);
|
|
4793
|
+
return deriveAesKeyAndNonceFromIkm(ikm, hexToBytes32(commitmentHex));
|
|
4794
|
+
}
|
|
4795
|
+
function decodeChainNotePlaintext(version, plaintext, commitmentHex) {
|
|
4796
|
+
if (version === NOTE_VERSION_V4) {
|
|
4797
|
+
if (plaintext.length !== PLAINTEXT_LEN_V4) {
|
|
4798
|
+
throw new Error(`Invalid v4 chain note plaintext length: ${plaintext.length}`);
|
|
4799
|
+
}
|
|
4800
|
+
return {
|
|
4801
|
+
timestamp: readU64LE(plaintext, 0),
|
|
4802
|
+
commitment: commitmentHex.toLowerCase(),
|
|
4803
|
+
noteSalt: readU256BE(plaintext, TIMESTAMP_LEN),
|
|
4804
|
+
outAmount0: readU64LE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN),
|
|
4805
|
+
outPubkey0: readU256BE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN + OUT_AMOUNT_LEN),
|
|
4806
|
+
isSendToSelfKey0: BigInt(plaintext[PLAINTEXT_LEN_V4 - 1])
|
|
4807
|
+
};
|
|
4808
|
+
}
|
|
4809
|
+
if (version === NOTE_VERSION_V3) {
|
|
4810
|
+
if (plaintext.length !== PLAINTEXT_LEN_V3) {
|
|
4811
|
+
throw new Error(`Invalid v3 chain note plaintext length: ${plaintext.length}`);
|
|
4812
|
+
}
|
|
4813
|
+
return {
|
|
4814
|
+
timestamp: readU64LE(plaintext, 0),
|
|
4815
|
+
commitment: commitmentHex.toLowerCase(),
|
|
4816
|
+
noteSalt: readU256BE(plaintext, TIMESTAMP_LEN)
|
|
4817
|
+
};
|
|
4818
|
+
}
|
|
4819
|
+
if (plaintext.length !== PLAINTEXT_LEN_V2) {
|
|
4820
|
+
throw new Error(`Invalid v2 chain note plaintext length: ${plaintext.length}`);
|
|
4821
|
+
}
|
|
4822
|
+
return {
|
|
4823
|
+
timestamp: readU64LE(plaintext, 0),
|
|
4824
|
+
commitment: commitmentHex.toLowerCase()
|
|
4825
|
+
};
|
|
4826
|
+
}
|
|
4676
4827
|
async function encryptCompactChainNote(timestamp, nk, commitmentHex, noteSalt, semantics) {
|
|
4677
4828
|
if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
|
|
4678
4829
|
throw new Error("nk must be 32 bytes");
|
|
@@ -4736,36 +4887,7 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
|
|
|
4736
4887
|
try {
|
|
4737
4888
|
const { key, nonce } = await deriveAesKeyAndNonce(nk, commitment);
|
|
4738
4889
|
const plaintext = await aesGcmDecrypt2(ciphertext, key, nonce);
|
|
4739
|
-
|
|
4740
|
-
if (plaintext.length !== PLAINTEXT_LEN_V4) {
|
|
4741
|
-
throw new Error(`Invalid v4 chain note plaintext length: ${plaintext.length}`);
|
|
4742
|
-
}
|
|
4743
|
-
return {
|
|
4744
|
-
timestamp: readU64LE(plaintext, 0),
|
|
4745
|
-
commitment: commitment.toLowerCase(),
|
|
4746
|
-
noteSalt: readU256BE(plaintext, TIMESTAMP_LEN),
|
|
4747
|
-
outAmount0: readU64LE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN),
|
|
4748
|
-
outPubkey0: readU256BE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN + OUT_AMOUNT_LEN),
|
|
4749
|
-
isSendToSelfKey0: BigInt(plaintext[PLAINTEXT_LEN_V4 - 1])
|
|
4750
|
-
};
|
|
4751
|
-
}
|
|
4752
|
-
if (version === NOTE_VERSION_V3) {
|
|
4753
|
-
if (plaintext.length !== PLAINTEXT_LEN_V3) {
|
|
4754
|
-
throw new Error(`Invalid v3 chain note plaintext length: ${plaintext.length}`);
|
|
4755
|
-
}
|
|
4756
|
-
return {
|
|
4757
|
-
timestamp: readU64LE(plaintext, 0),
|
|
4758
|
-
commitment: commitment.toLowerCase(),
|
|
4759
|
-
noteSalt: readU256BE(plaintext, TIMESTAMP_LEN)
|
|
4760
|
-
};
|
|
4761
|
-
}
|
|
4762
|
-
if (plaintext.length !== PLAINTEXT_LEN_V2) {
|
|
4763
|
-
throw new Error(`Invalid v2 chain note plaintext length: ${plaintext.length}`);
|
|
4764
|
-
}
|
|
4765
|
-
return {
|
|
4766
|
-
timestamp: readU64LE(plaintext, 0),
|
|
4767
|
-
commitment: commitment.toLowerCase()
|
|
4768
|
-
};
|
|
4890
|
+
return decodeChainNotePlaintext(version, plaintext, commitment);
|
|
4769
4891
|
} catch (error) {
|
|
4770
4892
|
lastError = error;
|
|
4771
4893
|
}
|
|
@@ -4774,6 +4896,26 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
|
|
|
4774
4896
|
`Failed to decrypt compact chain note with provided commitments: ${lastError instanceof Error ? lastError.message : String(lastError)}`
|
|
4775
4897
|
);
|
|
4776
4898
|
}
|
|
4899
|
+
async function createCompactChainNoteDecryptor(nk) {
|
|
4900
|
+
const ikm = await importNkHkdfKey(nk);
|
|
4901
|
+
return async (noteBytes, commitment) => {
|
|
4902
|
+
if (!(noteBytes instanceof Uint8Array) || noteBytes.length <= 1) return null;
|
|
4903
|
+
if (!(commitment instanceof Uint8Array) || commitment.length !== 32) return null;
|
|
4904
|
+
const version = noteBytes[0];
|
|
4905
|
+
if (version !== NOTE_VERSION_V4 && version !== NOTE_VERSION_V3 && version !== NOTE_VERSION_V2) {
|
|
4906
|
+
return null;
|
|
4907
|
+
}
|
|
4908
|
+
try {
|
|
4909
|
+
const { key, nonce } = await deriveAesKeyAndNonceFromIkm(ikm, commitment);
|
|
4910
|
+
const plaintext = await aesGcmDecrypt2(noteBytes.subarray(1), key, nonce);
|
|
4911
|
+
let hex = "";
|
|
4912
|
+
for (let i = 0; i < 32; i++) hex += commitment[i].toString(16).padStart(2, "0");
|
|
4913
|
+
return decodeChainNotePlaintext(version, plaintext, hex);
|
|
4914
|
+
} catch {
|
|
4915
|
+
return null;
|
|
4916
|
+
}
|
|
4917
|
+
};
|
|
4918
|
+
}
|
|
4777
4919
|
function chainNoteToBase64(noteBytes) {
|
|
4778
4920
|
return Buffer.from(noteBytes).toString("base64");
|
|
4779
4921
|
}
|
|
@@ -4870,6 +5012,80 @@ function openRecipientDeliveryNote(envelope, viewingSecretKey) {
|
|
|
4870
5012
|
return null;
|
|
4871
5013
|
}
|
|
4872
5014
|
}
|
|
5015
|
+
var X25519_PKCS8_PREFIX = Uint8Array.from([
|
|
5016
|
+
48,
|
|
5017
|
+
46,
|
|
5018
|
+
2,
|
|
5019
|
+
1,
|
|
5020
|
+
0,
|
|
5021
|
+
48,
|
|
5022
|
+
5,
|
|
5023
|
+
6,
|
|
5024
|
+
3,
|
|
5025
|
+
43,
|
|
5026
|
+
101,
|
|
5027
|
+
110,
|
|
5028
|
+
4,
|
|
5029
|
+
34,
|
|
5030
|
+
4,
|
|
5031
|
+
32
|
|
5032
|
+
]);
|
|
5033
|
+
var HSALSA_SIGMA = new TextEncoder().encode("expand 32-byte k");
|
|
5034
|
+
function decodeOpened(plaintext) {
|
|
5035
|
+
if (!plaintext || plaintext.length !== RECIPIENT_DELIVERY_PLAINTEXT_LEN) return null;
|
|
5036
|
+
return { amount: readU64LE2(plaintext, 0), blinding: readU256BE2(plaintext, 8) };
|
|
5037
|
+
}
|
|
5038
|
+
async function createRecipientDeliveryOpener(viewingSecretKey) {
|
|
5039
|
+
if (!(viewingSecretKey instanceof Uint8Array) || viewingSecretKey.length !== 32) {
|
|
5040
|
+
throw new Error("viewingSecretKey must be 32 bytes");
|
|
5041
|
+
}
|
|
5042
|
+
const slow = async (envelope) => openRecipientDeliveryNote(envelope, viewingSecretKey);
|
|
5043
|
+
const subtle = globalThis.crypto?.subtle;
|
|
5044
|
+
const hsalsa = nacl4.lowlevel?.crypto_core_hsalsa20;
|
|
5045
|
+
if (!subtle || typeof hsalsa !== "function") return slow;
|
|
5046
|
+
let privateKey;
|
|
5047
|
+
const sharedKey = async (ephemeralPk) => {
|
|
5048
|
+
const publicKey = await subtle.importKey("raw", new Uint8Array(ephemeralPk), { name: "X25519" }, false, []);
|
|
5049
|
+
const shared = new Uint8Array(
|
|
5050
|
+
await subtle.deriveBits({ name: "X25519", public: publicKey }, privateKey, 256)
|
|
5051
|
+
);
|
|
5052
|
+
const key = new Uint8Array(32);
|
|
5053
|
+
hsalsa(key, new Uint8Array(16), shared, HSALSA_SIGMA);
|
|
5054
|
+
return key;
|
|
5055
|
+
};
|
|
5056
|
+
try {
|
|
5057
|
+
const pkcs8 = new Uint8Array(X25519_PKCS8_PREFIX.length + 32);
|
|
5058
|
+
pkcs8.set(X25519_PKCS8_PREFIX);
|
|
5059
|
+
pkcs8.set(viewingSecretKey, X25519_PKCS8_PREFIX.length);
|
|
5060
|
+
privateKey = await subtle.importKey("pkcs8", pkcs8, { name: "X25519" }, false, ["deriveBits"]);
|
|
5061
|
+
const probe = nacl4.box.keyPair().publicKey;
|
|
5062
|
+
const fast = await sharedKey(probe);
|
|
5063
|
+
const reference = nacl4.box.before(probe, viewingSecretKey);
|
|
5064
|
+
if (fast.length !== reference.length || fast.some((b, i) => b !== reference[i])) return slow;
|
|
5065
|
+
} catch {
|
|
5066
|
+
return slow;
|
|
5067
|
+
}
|
|
5068
|
+
return async (envelope) => {
|
|
5069
|
+
if (!(envelope instanceof Uint8Array) || envelope.length !== RECIPIENT_DELIVERY_NOTE_BYTES) return null;
|
|
5070
|
+
const ephemeralPk = envelope.subarray(0, RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN);
|
|
5071
|
+
const nonce = envelope.subarray(
|
|
5072
|
+
RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
|
|
5073
|
+
RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN
|
|
5074
|
+
);
|
|
5075
|
+
const ciphertext = envelope.subarray(RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN);
|
|
5076
|
+
let key;
|
|
5077
|
+
try {
|
|
5078
|
+
key = await sharedKey(ephemeralPk);
|
|
5079
|
+
} catch {
|
|
5080
|
+
return openRecipientDeliveryNote(envelope, viewingSecretKey);
|
|
5081
|
+
}
|
|
5082
|
+
try {
|
|
5083
|
+
return decodeOpened(nacl4.secretbox.open(ciphertext, nonce, key));
|
|
5084
|
+
} catch {
|
|
5085
|
+
return null;
|
|
5086
|
+
}
|
|
5087
|
+
};
|
|
5088
|
+
}
|
|
4873
5089
|
function recipientDeliveryNoteToBase64(envelope) {
|
|
4874
5090
|
return Buffer.from(envelope).toString("base64");
|
|
4875
5091
|
}
|
|
@@ -4956,6 +5172,8 @@ function normalizeOwnerPublicKey(publicKey, label) {
|
|
|
4956
5172
|
// src/notes/swap-refund.ts
|
|
4957
5173
|
var bs582 = _bs582.default || _bs582;
|
|
4958
5174
|
var REFUND_SEED_DOMAIN = new TextEncoder().encode("cloak_swap_refund_v1");
|
|
5175
|
+
var REFUND_KEY_DOMAIN_V2 = new TextEncoder().encode("cloak_swap_refund_v2");
|
|
5176
|
+
var REFUND_PRIVATE_KEY_INFO_V2 = new TextEncoder().encode("sk_v2");
|
|
4959
5177
|
var LEGACY_REFUND_PRIVATE_KEY_INFO = new TextEncoder().encode("sk");
|
|
4960
5178
|
var REFUND_BLINDING_INFO = new TextEncoder().encode("blinding");
|
|
4961
5179
|
function normalizeNullifier(inputNullifier) {
|
|
@@ -5000,13 +5218,35 @@ function deriveSwapRefundBlinding(viewingKeyNk, inputNullifier) {
|
|
|
5000
5218
|
const nk = assertNk(viewingKeyNk);
|
|
5001
5219
|
return toFieldSecret(derive(nk, normalizeNullifier(inputNullifier), REFUND_BLINDING_INFO));
|
|
5002
5220
|
}
|
|
5003
|
-
|
|
5221
|
+
function privateKeyBytes(privateKey) {
|
|
5222
|
+
return Uint8Array.from(Buffer.from(privateKey.toString(16).padStart(64, "0"), "hex"));
|
|
5223
|
+
}
|
|
5224
|
+
async function deriveSwapRefundKeypair(ownerUtxoKeypair, inputNullifier) {
|
|
5004
5225
|
const owner = await assertOwnerUtxoKeypair(ownerUtxoKeypair);
|
|
5226
|
+
const nullifier = normalizeNullifier(inputNullifier);
|
|
5227
|
+
const preimage = new Uint8Array(
|
|
5228
|
+
REFUND_KEY_DOMAIN_V2.length + 32 + nullifier.length + REFUND_PRIVATE_KEY_INFO_V2.length
|
|
5229
|
+
);
|
|
5230
|
+
let off = 0;
|
|
5231
|
+
preimage.set(REFUND_KEY_DOMAIN_V2, off);
|
|
5232
|
+
off += REFUND_KEY_DOMAIN_V2.length;
|
|
5233
|
+
preimage.set(privateKeyBytes(owner.privateKey), off);
|
|
5234
|
+
off += 32;
|
|
5235
|
+
preimage.set(nullifier, off);
|
|
5236
|
+
off += nullifier.length;
|
|
5237
|
+
preimage.set(REFUND_PRIVATE_KEY_INFO_V2, off);
|
|
5238
|
+
const privateKey = toFieldSecret(blake33(preimage));
|
|
5239
|
+
const publicKey = await derivePublicKey(privateKey);
|
|
5240
|
+
if (publicKey === 0n) throw new Error("refund authorization is degenerate");
|
|
5241
|
+
return { privateKey, publicKey };
|
|
5242
|
+
}
|
|
5243
|
+
async function deriveSwapRefundAuthorization(viewingKeyNk, inputNullifier, ownerUtxoKeypair) {
|
|
5005
5244
|
const blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
|
|
5006
|
-
|
|
5245
|
+
const keypair = await deriveSwapRefundKeypair(ownerUtxoKeypair, inputNullifier);
|
|
5246
|
+
if (keypair.publicKey === 0n || blinding === 0n) {
|
|
5007
5247
|
throw new Error("refund authorization is degenerate");
|
|
5008
5248
|
}
|
|
5009
|
-
return { privateKey:
|
|
5249
|
+
return { privateKey: keypair.privateKey, publicKey: keypair.publicKey, blinding };
|
|
5010
5250
|
}
|
|
5011
5251
|
async function deriveLegacySwapRefundAuthorization(viewingKeyNk, inputNullifier) {
|
|
5012
5252
|
const nk = assertNk(viewingKeyNk);
|
|
@@ -5027,9 +5267,12 @@ async function computeSwapRefundCommitment(amountAfterFee, refundPublicKey, refu
|
|
|
5027
5267
|
mintAddress: NATIVE_SOL_MINT
|
|
5028
5268
|
});
|
|
5029
5269
|
}
|
|
5270
|
+
function toField(value) {
|
|
5271
|
+
return value instanceof Uint8Array ? BigInt("0x" + Buffer.from(value).toString("hex")) : value;
|
|
5272
|
+
}
|
|
5030
5273
|
async function matchSwapRefundLeaf(params) {
|
|
5031
5274
|
const { viewingKeyNk, inputNullifier, amountAfterFee } = params;
|
|
5032
|
-
const expected =
|
|
5275
|
+
const expected = toField(params.commitment);
|
|
5033
5276
|
let blinding;
|
|
5034
5277
|
try {
|
|
5035
5278
|
blinding = deriveSwapRefundBlinding(viewingKeyNk, inputNullifier);
|
|
@@ -5037,11 +5280,55 @@ async function matchSwapRefundLeaf(params) {
|
|
|
5037
5280
|
return null;
|
|
5038
5281
|
}
|
|
5039
5282
|
const ownerPub = normalizeOwnerPublicKey(params.ownerUtxoKeypair?.publicKey, "ownerUtxoKeypair.publicKey");
|
|
5283
|
+
const ownerPriv = params.ownerUtxoKeypair?.privateKey ?? 0n;
|
|
5284
|
+
let perSwapPub;
|
|
5285
|
+
let perSwapPriv = 0n;
|
|
5286
|
+
if (ownerPriv > 0n && ownerPub !== void 0) {
|
|
5287
|
+
try {
|
|
5288
|
+
const kp = await deriveSwapRefundKeypair({ privateKey: ownerPriv, publicKey: ownerPub }, inputNullifier);
|
|
5289
|
+
perSwapPub = kp.publicKey;
|
|
5290
|
+
perSwapPriv = kp.privateKey;
|
|
5291
|
+
} catch {
|
|
5292
|
+
return null;
|
|
5293
|
+
}
|
|
5294
|
+
}
|
|
5295
|
+
if (params.publishedRefundPubkey !== void 0 && params.publishedRefundBlinding !== void 0) {
|
|
5296
|
+
const published = toField(params.publishedRefundPubkey);
|
|
5297
|
+
const publishedBlinding = toField(params.publishedRefundBlinding);
|
|
5298
|
+
if (published !== 0n && publishedBlinding === blinding) {
|
|
5299
|
+
if (perSwapPub === void 0 || perSwapPub === published) {
|
|
5300
|
+
const candidate = await computeSwapRefundCommitment(amountAfterFee, published, blinding);
|
|
5301
|
+
if (candidate === expected && published !== ownerPub) {
|
|
5302
|
+
return {
|
|
5303
|
+
keypair: { privateKey: perSwapPub === published ? perSwapPriv : 0n, publicKey: published },
|
|
5304
|
+
shape: "per-swap",
|
|
5305
|
+
blinding,
|
|
5306
|
+
amount: amountAfterFee,
|
|
5307
|
+
commitment: candidate,
|
|
5308
|
+
legacyExposed: false
|
|
5309
|
+
};
|
|
5310
|
+
}
|
|
5311
|
+
}
|
|
5312
|
+
}
|
|
5313
|
+
} else if (perSwapPub !== void 0) {
|
|
5314
|
+
const candidate = await computeSwapRefundCommitment(amountAfterFee, perSwapPub, blinding);
|
|
5315
|
+
if (candidate === expected) {
|
|
5316
|
+
return {
|
|
5317
|
+
keypair: { privateKey: perSwapPriv, publicKey: perSwapPub },
|
|
5318
|
+
shape: "per-swap",
|
|
5319
|
+
blinding,
|
|
5320
|
+
amount: amountAfterFee,
|
|
5321
|
+
commitment: candidate,
|
|
5322
|
+
legacyExposed: false
|
|
5323
|
+
};
|
|
5324
|
+
}
|
|
5325
|
+
}
|
|
5040
5326
|
if (ownerPub !== void 0) {
|
|
5041
5327
|
const candidate = await computeSwapRefundCommitment(amountAfterFee, ownerPub, blinding);
|
|
5042
5328
|
if (candidate === expected) {
|
|
5043
5329
|
return {
|
|
5044
|
-
keypair: { privateKey:
|
|
5330
|
+
keypair: { privateKey: ownerPriv, publicKey: ownerPub },
|
|
5331
|
+
shape: "owner",
|
|
5045
5332
|
blinding,
|
|
5046
5333
|
amount: amountAfterFee,
|
|
5047
5334
|
commitment: candidate,
|
|
@@ -5059,6 +5346,7 @@ async function matchSwapRefundLeaf(params) {
|
|
|
5059
5346
|
if (legacyCandidate !== expected) return null;
|
|
5060
5347
|
return {
|
|
5061
5348
|
keypair: { privateKey: legacy.privateKey, publicKey: legacy.publicKey },
|
|
5349
|
+
shape: "legacy-nk",
|
|
5062
5350
|
blinding: legacy.blinding,
|
|
5063
5351
|
amount: amountAfterFee,
|
|
5064
5352
|
commitment: legacyCandidate,
|
|
@@ -5070,6 +5358,9 @@ var PROOF_LEN2 = 256;
|
|
|
5070
5358
|
var NULLIFIER_0_OFFSET = 1 + PROOF_LEN2 + 104;
|
|
5071
5359
|
var PUBLIC_INPUTS_LEN2 = 264;
|
|
5072
5360
|
var MIN_TRANSACT_SWAP_LEN = 1 + PROOF_LEN2 + PUBLIC_INPUTS_LEN2;
|
|
5361
|
+
var REFUND_PUBKEY_OFFSET = 1 + PROOF_LEN2 + PUBLIC_INPUTS_LEN2 + 72;
|
|
5362
|
+
var REFUND_BLINDING_OFFSET = REFUND_PUBKEY_OFFSET + 32;
|
|
5363
|
+
var MIN_TRANSACT_SWAP_WITH_PARAMS_LEN = REFUND_BLINDING_OFFSET + 32;
|
|
5073
5364
|
function toBase58(key) {
|
|
5074
5365
|
if (!key) return void 0;
|
|
5075
5366
|
if (typeof key === "string") return key;
|
|
@@ -5132,7 +5423,7 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options)
|
|
|
5132
5423
|
}
|
|
5133
5424
|
if (!options || normalizeOwnerPublicKey(options.ownerUtxoKeypair?.publicKey, "options.ownerUtxoKeypair.publicKey") === void 0) {
|
|
5134
5425
|
throw new Error(
|
|
5135
|
-
"discoverSwapRefunds requires options.ownerUtxoKeypair (the wallet's long-lived UTXO keypair): refund leaves are
|
|
5426
|
+
"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."
|
|
5136
5427
|
);
|
|
5137
5428
|
}
|
|
5138
5429
|
const ownerUtxoKeypair = options.ownerUtxoKeypair;
|
|
@@ -5192,7 +5483,15 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options)
|
|
|
5192
5483
|
programId
|
|
5193
5484
|
);
|
|
5194
5485
|
const key = swapState;
|
|
5195
|
-
|
|
5486
|
+
const hasParams = data.length >= MIN_TRANSACT_SWAP_WITH_PARAMS_LEN;
|
|
5487
|
+
if (!nullifierBySwapState.has(key)) {
|
|
5488
|
+
nullifierBySwapState.set(key, {
|
|
5489
|
+
nullifier,
|
|
5490
|
+
signature,
|
|
5491
|
+
refundPubkey: hasParams ? data.slice(REFUND_PUBKEY_OFFSET, REFUND_PUBKEY_OFFSET + 32) : void 0,
|
|
5492
|
+
refundBlinding: hasParams ? data.slice(REFUND_BLINDING_OFFSET, REFUND_BLINDING_OFFSET + 32) : void 0
|
|
5493
|
+
});
|
|
5494
|
+
}
|
|
5196
5495
|
}
|
|
5197
5496
|
const logs = tx.meta?.logMessages;
|
|
5198
5497
|
const scan = scanRefundLeafEvents(logs, programIdBase58);
|
|
@@ -5211,7 +5510,9 @@ async function discoverSwapRefunds(connection, programId, viewingKeyNk, options)
|
|
|
5211
5510
|
inputNullifier: candidate.nullifier,
|
|
5212
5511
|
amountAfterFee: event.amountAfterFee,
|
|
5213
5512
|
commitment: event.commitmentField,
|
|
5214
|
-
ownerUtxoKeypair
|
|
5513
|
+
ownerUtxoKeypair,
|
|
5514
|
+
publishedRefundPubkey: candidate.refundPubkey,
|
|
5515
|
+
publishedRefundBlinding: candidate.refundBlinding
|
|
5215
5516
|
});
|
|
5216
5517
|
if (!recovered) continue;
|
|
5217
5518
|
const dedupe = `${close.signature}:${event.leafIndex}`;
|
|
@@ -5758,6 +6059,12 @@ var NEAR_TIP_ONCHAIN_FALLBACK_MAX_DISTANCE_LOCAL_RPC = 8;
|
|
|
5758
6059
|
var DEFAULT_RELAY_REQUEST_TIMEOUT_MS = 45e3;
|
|
5759
6060
|
var DEFAULT_RELAY_NETWORK_RETRIES = 6;
|
|
5760
6061
|
var RETRYABLE_RELAY_STATUSES = /* @__PURE__ */ new Set([408, 409, 425, 429, 500, 502, 503, 504, 522, 524]);
|
|
6062
|
+
var RELAY_SOURCE_LEASE_MS = 18e4;
|
|
6063
|
+
var RELAY_SOURCE_LEASE_MARGIN_MS = 5e3;
|
|
6064
|
+
var MAX_LEASE_EXPIRY_REPLAYS = 2;
|
|
6065
|
+
var RELAY_IN_FLIGHT_POLL_MS = 5e3;
|
|
6066
|
+
var RELAY_LANDED_POLL_MS = 1e3;
|
|
6067
|
+
var MAX_LANDED_POLLS = 5;
|
|
5761
6068
|
function parseMissingRelayIndexError(message) {
|
|
5762
6069
|
const match = message.match(
|
|
5763
6070
|
/Relay tree missing required commitment index\s+(\d+)\s+\(tree length:\s*(\d+)\)/i
|
|
@@ -7342,6 +7649,20 @@ async function reconcileCommitmentIndicesWithRelay(relayUrl, mint, suggestedIndi
|
|
|
7342
7649
|
function sleep2(ms) {
|
|
7343
7650
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
7344
7651
|
}
|
|
7652
|
+
function sleepUnlessAborted(ms, signal) {
|
|
7653
|
+
if (signal?.aborted) return Promise.resolve(false);
|
|
7654
|
+
return new Promise((resolve) => {
|
|
7655
|
+
const onAbort = () => {
|
|
7656
|
+
clearTimeout(timer);
|
|
7657
|
+
resolve(false);
|
|
7658
|
+
};
|
|
7659
|
+
const timer = setTimeout(() => {
|
|
7660
|
+
signal?.removeEventListener("abort", onAbort);
|
|
7661
|
+
resolve(true);
|
|
7662
|
+
}, ms);
|
|
7663
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
7664
|
+
});
|
|
7665
|
+
}
|
|
7345
7666
|
function hexToBytes2(hex) {
|
|
7346
7667
|
const bytes = new Uint8Array(hex.length / 2);
|
|
7347
7668
|
for (let i = 0; i < hex.length; i += 2) {
|
|
@@ -7576,6 +7897,9 @@ async function submitTransactToRelay(args) {
|
|
|
7576
7897
|
let unknownOutcomeSignature = null;
|
|
7577
7898
|
let possiblySubmitted = false;
|
|
7578
7899
|
let networkRetry = 0;
|
|
7900
|
+
let leaseReplays = 0;
|
|
7901
|
+
let landedPolls = 0;
|
|
7902
|
+
let leaseBaseMs = null;
|
|
7579
7903
|
const verifySettlement = (signature, timeoutMs) => confirmTransactSettlement({
|
|
7580
7904
|
connection: settlement.connection,
|
|
7581
7905
|
programId: settlement.programId,
|
|
@@ -7631,6 +7955,7 @@ async function submitTransactToRelay(args) {
|
|
|
7631
7955
|
const controller = new AbortController();
|
|
7632
7956
|
const timeoutId = setTimeout(() => controller.abort(), requestTimeoutMs);
|
|
7633
7957
|
let response;
|
|
7958
|
+
leaseBaseMs ?? (leaseBaseMs = Date.now());
|
|
7634
7959
|
try {
|
|
7635
7960
|
response = await doFetch(`${relayUrl}/transact`, {
|
|
7636
7961
|
method: "POST",
|
|
@@ -7649,6 +7974,49 @@ async function submitTransactToRelay(args) {
|
|
|
7649
7974
|
if (isSubmissionOutcomeUnknownResponse(responseText) || isRetryableRelayStatus(response.status)) {
|
|
7650
7975
|
possiblySubmitted = true;
|
|
7651
7976
|
}
|
|
7977
|
+
if ((isRelayRequestInFlightResponse(responseText) || isSubmissionOutcomeUnknownResponse(responseText)) && leaseReplays < MAX_LEASE_EXPIRY_REPLAYS) {
|
|
7978
|
+
networkRetry = 0;
|
|
7979
|
+
const leaseEndsMs = (leaseBaseMs ?? Date.now()) + RELAY_SOURCE_LEASE_MS + RELAY_SOURCE_LEASE_MARGIN_MS;
|
|
7980
|
+
const polling = Date.now() < leaseEndsMs;
|
|
7981
|
+
const probe = await verifySettlement(
|
|
7982
|
+
unknownOutcomeSignature,
|
|
7983
|
+
polling ? 0 : args.failureProbeTimeoutMs ?? Math.min(settlementTimeoutMs(), 1e4)
|
|
7984
|
+
);
|
|
7985
|
+
if (probe.status === "landed") {
|
|
7986
|
+
landedPolls++;
|
|
7987
|
+
if (!polling || landedPolls > MAX_LANDED_POLLS) {
|
|
7988
|
+
return await resolveFailure(
|
|
7989
|
+
new Error(relayFailureMessage("Relay error", responseText, requestBody))
|
|
7990
|
+
);
|
|
7991
|
+
}
|
|
7992
|
+
if (!await sleepUnlessAborted(RELAY_LANDED_POLL_MS, args.signal)) {
|
|
7993
|
+
return await resolveFailure(new Error("Relay lease-expiry replay aborted by caller"));
|
|
7994
|
+
}
|
|
7995
|
+
continue;
|
|
7996
|
+
}
|
|
7997
|
+
if (polling) {
|
|
7998
|
+
onProgress?.("Relay is still processing this request; checking again shortly...");
|
|
7999
|
+
const pollMs = Math.min(RELAY_IN_FLIGHT_POLL_MS, leaseEndsMs - Date.now());
|
|
8000
|
+
if (!await sleepUnlessAborted(pollMs, args.signal)) {
|
|
8001
|
+
return await resolveFailure(new Error("Relay lease-expiry replay aborted by caller"));
|
|
8002
|
+
}
|
|
8003
|
+
continue;
|
|
8004
|
+
}
|
|
8005
|
+
leaseReplays++;
|
|
8006
|
+
const waitMs = Math.max(
|
|
8007
|
+
0,
|
|
8008
|
+
(leaseBaseMs ?? Date.now()) + RELAY_SOURCE_LEASE_MS + RELAY_SOURCE_LEASE_MARGIN_MS - Date.now()
|
|
8009
|
+
);
|
|
8010
|
+
onProgress?.(
|
|
8011
|
+
`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})...`
|
|
8012
|
+
);
|
|
8013
|
+
if (!await sleepUnlessAborted(waitMs, args.signal)) {
|
|
8014
|
+
return await resolveFailure(new Error("Relay lease-expiry replay aborted by caller"));
|
|
8015
|
+
}
|
|
8016
|
+
networkRetry = 0;
|
|
8017
|
+
leaseBaseMs = null;
|
|
8018
|
+
continue;
|
|
8019
|
+
}
|
|
7652
8020
|
if (isRetryableRelayStatus(response.status) && networkRetry < maxNetworkRetries) {
|
|
7653
8021
|
networkRetry++;
|
|
7654
8022
|
const delay = relayBackoffMs(networkRetry);
|
|
@@ -11613,6 +11981,1634 @@ function formatComplianceCsv(report) {
|
|
|
11613
11981
|
return header + rows;
|
|
11614
11982
|
}
|
|
11615
11983
|
|
|
11984
|
+
// src/relay/note-index-format.ts
|
|
11985
|
+
import { sha256 as sha2565 } from "@noble/hashes/sha2";
|
|
11986
|
+
var NOTE_INDEX_MAGIC = new Uint8Array([67, 78, 73, 49]);
|
|
11987
|
+
var NOTE_INDEX_FORMAT_VERSION = 1;
|
|
11988
|
+
var NOTE_INDEX_PAGE_SIZE = 1024;
|
|
11989
|
+
var NOTE_INDEX_NO_LEAF = 0xffffffffffffffffn;
|
|
11990
|
+
var NOTE_INDEX_MAX_PAGE_BYTES = 2 * 1024 * 1024;
|
|
11991
|
+
var NOTE_INDEX_HEADER_LEN = 68;
|
|
11992
|
+
var NOTE_INDEX_KIND_TX = 1;
|
|
11993
|
+
var NOTE_INDEX_KIND_DELIVERY = 2;
|
|
11994
|
+
var NOTE_INDEX_KIND_SWAP_REFUND = 3;
|
|
11995
|
+
var NOTE_SOURCE_NONE = 0;
|
|
11996
|
+
var NOTE_SOURCE_CARRIER = 2;
|
|
11997
|
+
var ITEM_HEADER_LEN = 3;
|
|
11998
|
+
var TX_FIXED_LEN = 263;
|
|
11999
|
+
var DELIVERY_BODY_LEN = 256;
|
|
12000
|
+
var SWAP_REFUND_BODY_LEN = 184;
|
|
12001
|
+
var MAX_UNKNOWN_BODY_LEN = 1024;
|
|
12002
|
+
var DELIVERY_ENVELOPE_LEN = 112;
|
|
12003
|
+
var SIGNATURE_LEN = 64;
|
|
12004
|
+
var NOTE_VERSION_BY_LEN = /* @__PURE__ */ new Map([
|
|
12005
|
+
[25, 2],
|
|
12006
|
+
[57, 3],
|
|
12007
|
+
[98, 4]
|
|
12008
|
+
]);
|
|
12009
|
+
var COMPLETE_FLAG = 1;
|
|
12010
|
+
var U64_MAX2 = (1n << 64n) - 1n;
|
|
12011
|
+
var U32_MAX = 4294967295;
|
|
12012
|
+
var MAX_LEAF_INDEX = (1n << 32n) - 1n;
|
|
12013
|
+
var WSOL_BYTES = addressBytes(NATIVE_SOL_MINT);
|
|
12014
|
+
var NoteIndexFormatError = class extends Error {
|
|
12015
|
+
constructor(message) {
|
|
12016
|
+
super(`Note index format error: ${message}`);
|
|
12017
|
+
this.name = "NoteIndexFormatError";
|
|
12018
|
+
}
|
|
12019
|
+
};
|
|
12020
|
+
function isAllZero2(bytes) {
|
|
12021
|
+
for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
|
|
12022
|
+
return true;
|
|
12023
|
+
}
|
|
12024
|
+
function bytesEqual(a, b) {
|
|
12025
|
+
if (a.length !== b.length) return false;
|
|
12026
|
+
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
|
|
12027
|
+
return true;
|
|
12028
|
+
}
|
|
12029
|
+
function checkLeafPair(commitment, leaf, label) {
|
|
12030
|
+
if (isAllZero2(commitment)) {
|
|
12031
|
+
if (leaf !== NOTE_INDEX_NO_LEAF) throw new NoteIndexFormatError(`${label}: zero commitment must carry NO_LEAF`);
|
|
12032
|
+
return;
|
|
12033
|
+
}
|
|
12034
|
+
if (leaf > MAX_LEAF_INDEX) throw new NoteIndexFormatError(`${label}: leaf ${leaf} is not a leaf of the tree`);
|
|
12035
|
+
}
|
|
12036
|
+
var Reader = class {
|
|
12037
|
+
constructor(bytes, start, end) {
|
|
12038
|
+
this.bytes = bytes;
|
|
12039
|
+
this.end = end;
|
|
12040
|
+
this.offset = start;
|
|
12041
|
+
this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
12042
|
+
}
|
|
12043
|
+
take(len) {
|
|
12044
|
+
if (this.offset + len > this.end) throw new NoteIndexFormatError("truncated item body");
|
|
12045
|
+
const at = this.offset;
|
|
12046
|
+
this.offset += len;
|
|
12047
|
+
return at;
|
|
12048
|
+
}
|
|
12049
|
+
u8() {
|
|
12050
|
+
return this.bytes[this.take(1)];
|
|
12051
|
+
}
|
|
12052
|
+
u32() {
|
|
12053
|
+
return this.view.getUint32(this.take(4), true);
|
|
12054
|
+
}
|
|
12055
|
+
u64() {
|
|
12056
|
+
return this.view.getBigUint64(this.take(8), true);
|
|
12057
|
+
}
|
|
12058
|
+
i64() {
|
|
12059
|
+
return this.view.getBigInt64(this.take(8), true);
|
|
12060
|
+
}
|
|
12061
|
+
raw(len) {
|
|
12062
|
+
const at = this.take(len);
|
|
12063
|
+
return this.bytes.slice(at, at + len);
|
|
12064
|
+
}
|
|
12065
|
+
get position() {
|
|
12066
|
+
return this.offset;
|
|
12067
|
+
}
|
|
12068
|
+
};
|
|
12069
|
+
function parseTx(r, bodyLen) {
|
|
12070
|
+
const mint = r.raw(32);
|
|
12071
|
+
const slot = r.u64();
|
|
12072
|
+
const blockPos = r.u32();
|
|
12073
|
+
const ixTag = r.u8();
|
|
12074
|
+
if (ixTag !== 0 && ixTag !== 1) throw new NoteIndexFormatError(`TX: ix_tag ${ixTag}`);
|
|
12075
|
+
const publicAmount = r.i64();
|
|
12076
|
+
const nullifier0 = r.raw(32);
|
|
12077
|
+
const nullifier1 = r.raw(32);
|
|
12078
|
+
const comm0 = r.raw(32);
|
|
12079
|
+
const leaf0 = r.u64();
|
|
12080
|
+
const comm1 = r.raw(32);
|
|
12081
|
+
const leaf1 = r.u64();
|
|
12082
|
+
const noteSource = r.u8();
|
|
12083
|
+
if (noteSource > NOTE_SOURCE_CARRIER) throw new NoteIndexFormatError(`TX: note_source ${noteSource}`);
|
|
12084
|
+
const noteLen = r.u8();
|
|
12085
|
+
if (noteSource === NOTE_SOURCE_NONE) {
|
|
12086
|
+
if (noteLen !== 0) throw new NoteIndexFormatError(`TX: note_len ${noteLen} without a note source`);
|
|
12087
|
+
} else if (!NOTE_VERSION_BY_LEN.has(noteLen)) {
|
|
12088
|
+
throw new NoteIndexFormatError(`TX: note_len ${noteLen}`);
|
|
12089
|
+
}
|
|
12090
|
+
if (bodyLen !== TX_FIXED_LEN + noteLen) {
|
|
12091
|
+
throw new NoteIndexFormatError(`TX: body_len ${bodyLen} != ${TX_FIXED_LEN + noteLen} for note_len ${noteLen}`);
|
|
12092
|
+
}
|
|
12093
|
+
const note = r.raw(noteLen);
|
|
12094
|
+
if (noteLen > 0 && note[0] !== NOTE_VERSION_BY_LEN.get(noteLen)) {
|
|
12095
|
+
throw new NoteIndexFormatError(`TX: note version ${note[0]} does not match note_len ${noteLen}`);
|
|
12096
|
+
}
|
|
12097
|
+
const signature = r.raw(SIGNATURE_LEN);
|
|
12098
|
+
checkLeafPair(comm0, leaf0, "TX comm0");
|
|
12099
|
+
checkLeafPair(comm1, leaf1, "TX comm1");
|
|
12100
|
+
return {
|
|
12101
|
+
kind: 1,
|
|
12102
|
+
mint,
|
|
12103
|
+
slot,
|
|
12104
|
+
blockPos,
|
|
12105
|
+
ixTag,
|
|
12106
|
+
publicAmount,
|
|
12107
|
+
nullifier0,
|
|
12108
|
+
nullifier1,
|
|
12109
|
+
comm0,
|
|
12110
|
+
leaf0,
|
|
12111
|
+
comm1,
|
|
12112
|
+
leaf1,
|
|
12113
|
+
noteSource,
|
|
12114
|
+
note,
|
|
12115
|
+
signature
|
|
12116
|
+
};
|
|
12117
|
+
}
|
|
12118
|
+
function parseDelivery(r) {
|
|
12119
|
+
const mint = r.raw(32);
|
|
12120
|
+
const slot = r.u64();
|
|
12121
|
+
const commitment = r.raw(32);
|
|
12122
|
+
const leaf = r.u64();
|
|
12123
|
+
const envelope = r.raw(DELIVERY_ENVELOPE_LEN);
|
|
12124
|
+
const signature = r.raw(SIGNATURE_LEN);
|
|
12125
|
+
if (isAllZero2(commitment)) throw new NoteIndexFormatError("DELIVERY: zero commitment");
|
|
12126
|
+
checkLeafPair(commitment, leaf, "DELIVERY");
|
|
12127
|
+
return { kind: 2, mint, slot, commitment, leaf, envelope, signature };
|
|
12128
|
+
}
|
|
12129
|
+
function parseSwapRefund(r) {
|
|
12130
|
+
const mint = r.raw(32);
|
|
12131
|
+
if (!bytesEqual(mint, WSOL_BYTES)) throw new NoteIndexFormatError("SWAP_REFUND: mint is not WSOL");
|
|
12132
|
+
const slot = r.u64();
|
|
12133
|
+
const commitment = r.raw(32);
|
|
12134
|
+
const leaf = r.u64();
|
|
12135
|
+
const amountAfterFee = r.u64();
|
|
12136
|
+
const nullifier0 = r.raw(32);
|
|
12137
|
+
const signature = r.raw(SIGNATURE_LEN);
|
|
12138
|
+
if (isAllZero2(commitment)) throw new NoteIndexFormatError("SWAP_REFUND: zero commitment");
|
|
12139
|
+
checkLeafPair(commitment, leaf, "SWAP_REFUND");
|
|
12140
|
+
return { kind: 3, mint, slot, commitment, leaf, amountAfterFee, nullifier0, signature };
|
|
12141
|
+
}
|
|
12142
|
+
function parseNoteIndexPage(bytes, expect, options = {}) {
|
|
12143
|
+
if (!(bytes instanceof Uint8Array)) throw new NoteIndexFormatError("page must be a Uint8Array");
|
|
12144
|
+
if (bytes.length > NOTE_INDEX_MAX_PAGE_BYTES) {
|
|
12145
|
+
throw new NoteIndexFormatError(`page is ${bytes.length} bytes, over the ${NOTE_INDEX_MAX_PAGE_BYTES}-byte bound`);
|
|
12146
|
+
}
|
|
12147
|
+
if (bytes.length < NOTE_INDEX_HEADER_LEN) throw new NoteIndexFormatError("truncated page header");
|
|
12148
|
+
for (let i = 0; i < NOTE_INDEX_MAGIC.length; i++) {
|
|
12149
|
+
if (bytes[i] !== NOTE_INDEX_MAGIC[i]) throw new NoteIndexFormatError("bad magic");
|
|
12150
|
+
}
|
|
12151
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
12152
|
+
const version = bytes[4];
|
|
12153
|
+
if (version !== NOTE_INDEX_FORMAT_VERSION) throw new NoteIndexFormatError(`unsupported version ${version}`);
|
|
12154
|
+
const flags = bytes[5];
|
|
12155
|
+
if ((flags & ~COMPLETE_FLAG) !== 0) throw new NoteIndexFormatError(`unknown flag bits 0x${flags.toString(16)}`);
|
|
12156
|
+
if (view.getUint16(6, true) !== 0) throw new NoteIndexFormatError("reserved bytes are not zero");
|
|
12157
|
+
const epoch = view.getBigUint64(8, true);
|
|
12158
|
+
const page = view.getBigUint64(16, true);
|
|
12159
|
+
const firstSeq = view.getBigUint64(24, true);
|
|
12160
|
+
const count = view.getUint32(32, true);
|
|
12161
|
+
const prevChain = bytes.slice(36, 68);
|
|
12162
|
+
const complete = (flags & COMPLETE_FLAG) !== 0;
|
|
12163
|
+
if (expect) {
|
|
12164
|
+
if (epoch !== expect.epoch) throw new NoteIndexFormatError(`epoch ${epoch} is not the requested ${expect.epoch}`);
|
|
12165
|
+
if (page !== BigInt(expect.page)) throw new NoteIndexFormatError(`page ${page} is not the requested ${expect.page}`);
|
|
12166
|
+
}
|
|
12167
|
+
if (count > NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`count ${count} exceeds ${NOTE_INDEX_PAGE_SIZE}`);
|
|
12168
|
+
if (complete && count !== NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`complete page with count ${count}`);
|
|
12169
|
+
if (firstSeq !== page * BigInt(NOTE_INDEX_PAGE_SIZE)) {
|
|
12170
|
+
throw new NoteIndexFormatError(`first_seq ${firstSeq} is not page ${page} * ${NOTE_INDEX_PAGE_SIZE}`);
|
|
12171
|
+
}
|
|
12172
|
+
const items = [];
|
|
12173
|
+
const rawItems = [];
|
|
12174
|
+
const itemPositions = [];
|
|
12175
|
+
let skippedUnknown = 0;
|
|
12176
|
+
let skippedMalformed = 0;
|
|
12177
|
+
let offset = NOTE_INDEX_HEADER_LEN;
|
|
12178
|
+
for (let i = 0; i < count; i++) {
|
|
12179
|
+
if (offset + ITEM_HEADER_LEN > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} header`);
|
|
12180
|
+
const kind = bytes[offset];
|
|
12181
|
+
const bodyLen = view.getUint16(offset + 1, true);
|
|
12182
|
+
const bodyStart = offset + ITEM_HEADER_LEN;
|
|
12183
|
+
const bodyEnd = bodyStart + bodyLen;
|
|
12184
|
+
if (bodyEnd > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} body`);
|
|
12185
|
+
if (kind !== NOTE_INDEX_KIND_TX && kind !== NOTE_INDEX_KIND_DELIVERY && kind !== NOTE_INDEX_KIND_SWAP_REFUND) {
|
|
12186
|
+
if (bodyLen > MAX_UNKNOWN_BODY_LEN) throw new NoteIndexFormatError(`unknown kind ${kind} with body_len ${bodyLen}`);
|
|
12187
|
+
skippedUnknown++;
|
|
12188
|
+
offset = bodyEnd;
|
|
12189
|
+
continue;
|
|
12190
|
+
}
|
|
12191
|
+
let item;
|
|
12192
|
+
try {
|
|
12193
|
+
item = parseKnownBody(bytes, kind, bodyStart, bodyEnd, i);
|
|
12194
|
+
} catch (error) {
|
|
12195
|
+
if (!options.skipMalformedItems || !(error instanceof NoteIndexFormatError)) throw error;
|
|
12196
|
+
skippedMalformed++;
|
|
12197
|
+
offset = bodyEnd;
|
|
12198
|
+
continue;
|
|
12199
|
+
}
|
|
12200
|
+
items.push(item);
|
|
12201
|
+
rawItems.push(bytes.slice(offset, bodyEnd));
|
|
12202
|
+
itemPositions.push(i);
|
|
12203
|
+
offset = bodyEnd;
|
|
12204
|
+
}
|
|
12205
|
+
if (offset !== bytes.length) throw new NoteIndexFormatError(`${bytes.length - offset} trailing bytes after ${count} items`);
|
|
12206
|
+
return { epoch, page, firstSeq, complete, count, prevChain, items, rawItems, skippedUnknown, itemPositions, skippedMalformed };
|
|
12207
|
+
}
|
|
12208
|
+
function parseKnownBody(bytes, kind, bodyStart, bodyEnd, i) {
|
|
12209
|
+
const bodyLen = bodyEnd - bodyStart;
|
|
12210
|
+
const r = new Reader(bytes, bodyStart, bodyEnd);
|
|
12211
|
+
let item;
|
|
12212
|
+
if (kind === NOTE_INDEX_KIND_TX) {
|
|
12213
|
+
if (bodyLen < TX_FIXED_LEN) throw new NoteIndexFormatError(`TX: body_len ${bodyLen}`);
|
|
12214
|
+
item = parseTx(r, bodyLen);
|
|
12215
|
+
} else if (kind === NOTE_INDEX_KIND_DELIVERY) {
|
|
12216
|
+
if (bodyLen !== DELIVERY_BODY_LEN) throw new NoteIndexFormatError(`DELIVERY: body_len ${bodyLen}`);
|
|
12217
|
+
item = parseDelivery(r);
|
|
12218
|
+
} else {
|
|
12219
|
+
if (bodyLen !== SWAP_REFUND_BODY_LEN) throw new NoteIndexFormatError(`SWAP_REFUND: body_len ${bodyLen}`);
|
|
12220
|
+
item = parseSwapRefund(r);
|
|
12221
|
+
}
|
|
12222
|
+
if (r.position !== bodyEnd) throw new NoteIndexFormatError(`item ${i} body has unread bytes`);
|
|
12223
|
+
return item;
|
|
12224
|
+
}
|
|
12225
|
+
function parseNoteIndexItem(raw) {
|
|
12226
|
+
if (!(raw instanceof Uint8Array) || raw.length < ITEM_HEADER_LEN) throw new NoteIndexFormatError("truncated item");
|
|
12227
|
+
const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
|
|
12228
|
+
const kind = raw[0];
|
|
12229
|
+
const bodyLen = view.getUint16(1, true);
|
|
12230
|
+
if (ITEM_HEADER_LEN + bodyLen !== raw.length) throw new NoteIndexFormatError("item length mismatch");
|
|
12231
|
+
const r = new Reader(raw, ITEM_HEADER_LEN, raw.length);
|
|
12232
|
+
let item;
|
|
12233
|
+
if (kind === NOTE_INDEX_KIND_TX && bodyLen >= TX_FIXED_LEN) item = parseTx(r, bodyLen);
|
|
12234
|
+
else if (kind === NOTE_INDEX_KIND_DELIVERY && bodyLen === DELIVERY_BODY_LEN) item = parseDelivery(r);
|
|
12235
|
+
else if (kind === NOTE_INDEX_KIND_SWAP_REFUND && bodyLen === SWAP_REFUND_BODY_LEN) item = parseSwapRefund(r);
|
|
12236
|
+
else throw new NoteIndexFormatError(`item kind ${kind} with body_len ${bodyLen}`);
|
|
12237
|
+
if (r.position !== raw.length) throw new NoteIndexFormatError("item body has unread bytes");
|
|
12238
|
+
return item;
|
|
12239
|
+
}
|
|
12240
|
+
function computeNoteIndexChain(prevChain, pageBytes) {
|
|
12241
|
+
if (!(prevChain instanceof Uint8Array) || prevChain.length !== 32) throw new NoteIndexFormatError("prevChain must be 32 bytes");
|
|
12242
|
+
if (pageBytes.length < NOTE_INDEX_HEADER_LEN) throw new NoteIndexFormatError("truncated page header");
|
|
12243
|
+
const items = pageBytes.subarray(NOTE_INDEX_HEADER_LEN);
|
|
12244
|
+
const input = new Uint8Array(32 + items.length);
|
|
12245
|
+
input.set(prevChain);
|
|
12246
|
+
input.set(items, 32);
|
|
12247
|
+
return sha2565(input);
|
|
12248
|
+
}
|
|
12249
|
+
var Writer = class {
|
|
12250
|
+
constructor() {
|
|
12251
|
+
this.chunks = [];
|
|
12252
|
+
this.length = 0;
|
|
12253
|
+
}
|
|
12254
|
+
push(bytes) {
|
|
12255
|
+
this.chunks.push(bytes);
|
|
12256
|
+
this.length += bytes.length;
|
|
12257
|
+
}
|
|
12258
|
+
u8(v) {
|
|
12259
|
+
if (!Number.isInteger(v) || v < 0 || v > 255) throw new NoteIndexFormatError(`u8 out of range: ${v}`);
|
|
12260
|
+
this.push(Uint8Array.of(v));
|
|
12261
|
+
}
|
|
12262
|
+
u16(v) {
|
|
12263
|
+
if (!Number.isInteger(v) || v < 0 || v > 65535) throw new NoteIndexFormatError(`u16 out of range: ${v}`);
|
|
12264
|
+
const b = new Uint8Array(2);
|
|
12265
|
+
new DataView(b.buffer).setUint16(0, v, true);
|
|
12266
|
+
this.push(b);
|
|
12267
|
+
}
|
|
12268
|
+
u32(v) {
|
|
12269
|
+
if (!Number.isInteger(v) || v < 0 || v > U32_MAX) throw new NoteIndexFormatError(`u32 out of range: ${v}`);
|
|
12270
|
+
const b = new Uint8Array(4);
|
|
12271
|
+
new DataView(b.buffer).setUint32(0, v, true);
|
|
12272
|
+
this.push(b);
|
|
12273
|
+
}
|
|
12274
|
+
u64(v) {
|
|
12275
|
+
if (v < 0n || v > U64_MAX2) throw new NoteIndexFormatError(`u64 out of range: ${v}`);
|
|
12276
|
+
const b = new Uint8Array(8);
|
|
12277
|
+
new DataView(b.buffer).setBigUint64(0, v, true);
|
|
12278
|
+
this.push(b);
|
|
12279
|
+
}
|
|
12280
|
+
i64(v) {
|
|
12281
|
+
if (v < -(1n << 63n) || v >= 1n << 63n) throw new NoteIndexFormatError(`i64 out of range: ${v}`);
|
|
12282
|
+
const b = new Uint8Array(8);
|
|
12283
|
+
new DataView(b.buffer).setBigInt64(0, v, true);
|
|
12284
|
+
this.push(b);
|
|
12285
|
+
}
|
|
12286
|
+
fixed(bytes, len, label) {
|
|
12287
|
+
if (!(bytes instanceof Uint8Array) || bytes.length !== len) throw new NoteIndexFormatError(`${label} must be ${len} bytes`);
|
|
12288
|
+
this.push(bytes);
|
|
12289
|
+
}
|
|
12290
|
+
finish() {
|
|
12291
|
+
const out = new Uint8Array(this.length);
|
|
12292
|
+
let off = 0;
|
|
12293
|
+
for (const c of this.chunks) {
|
|
12294
|
+
out.set(c, off);
|
|
12295
|
+
off += c.length;
|
|
12296
|
+
}
|
|
12297
|
+
return out;
|
|
12298
|
+
}
|
|
12299
|
+
};
|
|
12300
|
+
function encodeItemBody(item) {
|
|
12301
|
+
const w = new Writer();
|
|
12302
|
+
switch (item.kind) {
|
|
12303
|
+
case NOTE_INDEX_KIND_TX: {
|
|
12304
|
+
w.fixed(item.mint, 32, "mint");
|
|
12305
|
+
w.u64(item.slot);
|
|
12306
|
+
w.u32(item.blockPos);
|
|
12307
|
+
w.u8(item.ixTag);
|
|
12308
|
+
w.i64(item.publicAmount);
|
|
12309
|
+
w.fixed(item.nullifier0, 32, "nullifier0");
|
|
12310
|
+
w.fixed(item.nullifier1, 32, "nullifier1");
|
|
12311
|
+
w.fixed(item.comm0, 32, "comm0");
|
|
12312
|
+
w.u64(item.leaf0);
|
|
12313
|
+
w.fixed(item.comm1, 32, "comm1");
|
|
12314
|
+
w.u64(item.leaf1);
|
|
12315
|
+
w.u8(item.noteSource);
|
|
12316
|
+
const noteLen = item.note.length;
|
|
12317
|
+
if (item.noteSource === NOTE_SOURCE_NONE ? noteLen !== 0 : !NOTE_VERSION_BY_LEN.has(noteLen)) {
|
|
12318
|
+
throw new NoteIndexFormatError(`note_len ${noteLen} invalid for note_source ${item.noteSource}`);
|
|
12319
|
+
}
|
|
12320
|
+
w.u8(noteLen);
|
|
12321
|
+
w.push(item.note);
|
|
12322
|
+
w.fixed(item.signature, SIGNATURE_LEN, "signature");
|
|
12323
|
+
break;
|
|
12324
|
+
}
|
|
12325
|
+
case NOTE_INDEX_KIND_DELIVERY:
|
|
12326
|
+
w.fixed(item.mint, 32, "mint");
|
|
12327
|
+
w.u64(item.slot);
|
|
12328
|
+
w.fixed(item.commitment, 32, "commitment");
|
|
12329
|
+
w.u64(item.leaf);
|
|
12330
|
+
w.fixed(item.envelope, DELIVERY_ENVELOPE_LEN, "envelope");
|
|
12331
|
+
w.fixed(item.signature, SIGNATURE_LEN, "signature");
|
|
12332
|
+
break;
|
|
12333
|
+
case NOTE_INDEX_KIND_SWAP_REFUND:
|
|
12334
|
+
w.fixed(item.mint, 32, "mint");
|
|
12335
|
+
w.u64(item.slot);
|
|
12336
|
+
w.fixed(item.commitment, 32, "commitment");
|
|
12337
|
+
w.u64(item.leaf);
|
|
12338
|
+
w.u64(item.amountAfterFee);
|
|
12339
|
+
w.fixed(item.nullifier0, 32, "nullifier0");
|
|
12340
|
+
w.fixed(item.signature, SIGNATURE_LEN, "signature");
|
|
12341
|
+
break;
|
|
12342
|
+
default:
|
|
12343
|
+
throw new NoteIndexFormatError(`cannot encode kind ${item.kind}`);
|
|
12344
|
+
}
|
|
12345
|
+
return w.finish();
|
|
12346
|
+
}
|
|
12347
|
+
function encodeNoteIndexItem(item) {
|
|
12348
|
+
const body = encodeItemBody(item);
|
|
12349
|
+
const w = new Writer();
|
|
12350
|
+
w.u8(item.kind);
|
|
12351
|
+
w.u16(body.length);
|
|
12352
|
+
w.push(body);
|
|
12353
|
+
return w.finish();
|
|
12354
|
+
}
|
|
12355
|
+
function encodeNoteIndexPage(params) {
|
|
12356
|
+
const items = params.items ?? [];
|
|
12357
|
+
if (items.length > NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`count ${items.length} exceeds ${NOTE_INDEX_PAGE_SIZE}`);
|
|
12358
|
+
const w = new Writer();
|
|
12359
|
+
w.push(NOTE_INDEX_MAGIC);
|
|
12360
|
+
w.u8(NOTE_INDEX_FORMAT_VERSION);
|
|
12361
|
+
w.u8(params.complete ? COMPLETE_FLAG : 0);
|
|
12362
|
+
w.u16(0);
|
|
12363
|
+
w.u64(BigInt(params.epoch));
|
|
12364
|
+
w.u64(BigInt(params.page));
|
|
12365
|
+
w.u64(BigInt(params.firstSeq));
|
|
12366
|
+
w.u32(items.length);
|
|
12367
|
+
w.fixed(params.prevChain, 32, "prevChain");
|
|
12368
|
+
for (const item of items) w.push(encodeNoteIndexItem(item));
|
|
12369
|
+
return w.finish();
|
|
12370
|
+
}
|
|
12371
|
+
|
|
12372
|
+
// src/relay/note-index-client.ts
|
|
12373
|
+
var DEFAULT_TIMEOUT_MS2 = 3e4;
|
|
12374
|
+
var DEFAULT_MAX_RETRIES2 = 3;
|
|
12375
|
+
var RETRY_BASE_DELAY_MS = 500;
|
|
12376
|
+
var U64_MAX3 = (1n << 64n) - 1n;
|
|
12377
|
+
function joinPath(relayUrl, path) {
|
|
12378
|
+
const url = new URL(relayUrl);
|
|
12379
|
+
url.pathname = url.pathname.replace(/\/$/, "") + path;
|
|
12380
|
+
return url;
|
|
12381
|
+
}
|
|
12382
|
+
function abortError() {
|
|
12383
|
+
const error = new Error("Note index request aborted");
|
|
12384
|
+
error.name = "AbortError";
|
|
12385
|
+
return error;
|
|
12386
|
+
}
|
|
12387
|
+
function sleep4(ms, signal) {
|
|
12388
|
+
return new Promise((resolve, reject) => {
|
|
12389
|
+
if (signal?.aborted) return reject(abortError());
|
|
12390
|
+
const timer = setTimeout(() => {
|
|
12391
|
+
signal?.removeEventListener("abort", onAbort);
|
|
12392
|
+
resolve();
|
|
12393
|
+
}, ms);
|
|
12394
|
+
const onAbort = () => {
|
|
12395
|
+
clearTimeout(timer);
|
|
12396
|
+
reject(abortError());
|
|
12397
|
+
};
|
|
12398
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
12399
|
+
});
|
|
12400
|
+
}
|
|
12401
|
+
var RetryableStatusError = class extends Error {
|
|
12402
|
+
};
|
|
12403
|
+
var HttpStatusError = class extends Error {
|
|
12404
|
+
constructor(status, message) {
|
|
12405
|
+
super(message);
|
|
12406
|
+
this.status = status;
|
|
12407
|
+
this.name = "HttpStatusError";
|
|
12408
|
+
}
|
|
12409
|
+
};
|
|
12410
|
+
async function requestWithRetry(url, options, read) {
|
|
12411
|
+
assertAllowedRelayOrigin(url);
|
|
12412
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
|
|
12413
|
+
const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES2;
|
|
12414
|
+
let lastError;
|
|
12415
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
12416
|
+
if (options.signal?.aborted) throw abortError();
|
|
12417
|
+
const controller = new AbortController();
|
|
12418
|
+
const onAbort = () => controller.abort();
|
|
12419
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
12420
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
12421
|
+
try {
|
|
12422
|
+
const response = await relayFetch(url, { signal: controller.signal }, { observeClock: false });
|
|
12423
|
+
if (response.status === 429 || response.status >= 500) {
|
|
12424
|
+
throw new RetryableStatusError(`HTTP ${response.status} from ${new URL(url).pathname}`);
|
|
12425
|
+
}
|
|
12426
|
+
return await read(response, controller.signal);
|
|
12427
|
+
} catch (error) {
|
|
12428
|
+
if (options.signal?.aborted) throw abortError();
|
|
12429
|
+
const retryable = error instanceof RetryableStatusError || error instanceof Error && !(error instanceof NoteIndexFormatError) && !(error instanceof HttpStatusError);
|
|
12430
|
+
if (!retryable || attempt >= maxRetries) throw error;
|
|
12431
|
+
lastError = error;
|
|
12432
|
+
await sleep4(RETRY_BASE_DELAY_MS * 2 ** attempt + Math.random() * 250, options.signal);
|
|
12433
|
+
} finally {
|
|
12434
|
+
clearTimeout(timer);
|
|
12435
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
12436
|
+
}
|
|
12437
|
+
}
|
|
12438
|
+
throw lastError instanceof Error ? lastError : new Error(String(lastError));
|
|
12439
|
+
}
|
|
12440
|
+
async function readBoundedBody(response, maxBytes) {
|
|
12441
|
+
const declaredHeader = response.headers?.get?.("content-length") ?? null;
|
|
12442
|
+
const declared = declaredHeader === null ? NaN : Number(declaredHeader);
|
|
12443
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
12444
|
+
throw new NoteIndexFormatError(`response declares ${declared} bytes, over the ${maxBytes}-byte bound`);
|
|
12445
|
+
}
|
|
12446
|
+
const reader = response.body?.getReader?.();
|
|
12447
|
+
if (!reader) {
|
|
12448
|
+
const encoding = (response.headers?.get?.("content-encoding") ?? "").trim().toLowerCase();
|
|
12449
|
+
if (!Number.isSafeInteger(declared) || declared < 0) {
|
|
12450
|
+
throw new NoteIndexFormatError("response has no stream reader and no Content-Length: its size cannot be bounded");
|
|
12451
|
+
}
|
|
12452
|
+
if (encoding !== "" && encoding !== "identity") {
|
|
12453
|
+
throw new NoteIndexFormatError("response has no stream reader and a Content-Encoding: its decoded size cannot be bounded");
|
|
12454
|
+
}
|
|
12455
|
+
const buffer = new Uint8Array(await response.arrayBuffer());
|
|
12456
|
+
if (buffer.length > maxBytes || buffer.length !== declared) {
|
|
12457
|
+
throw new NoteIndexFormatError(`response is ${buffer.length} bytes, not the declared ${declared} within the ${maxBytes}-byte bound`);
|
|
12458
|
+
}
|
|
12459
|
+
return buffer;
|
|
12460
|
+
}
|
|
12461
|
+
const chunks = [];
|
|
12462
|
+
let total = 0;
|
|
12463
|
+
for (; ; ) {
|
|
12464
|
+
const { done, value } = await reader.read();
|
|
12465
|
+
if (done) break;
|
|
12466
|
+
total += value.length;
|
|
12467
|
+
if (total > maxBytes) {
|
|
12468
|
+
await reader.cancel().catch(() => void 0);
|
|
12469
|
+
throw new NoteIndexFormatError(`response exceeds the ${maxBytes}-byte bound`);
|
|
12470
|
+
}
|
|
12471
|
+
chunks.push(value);
|
|
12472
|
+
}
|
|
12473
|
+
const out = new Uint8Array(total);
|
|
12474
|
+
let off = 0;
|
|
12475
|
+
for (const c of chunks) {
|
|
12476
|
+
out.set(c, off);
|
|
12477
|
+
off += c.length;
|
|
12478
|
+
}
|
|
12479
|
+
return out;
|
|
12480
|
+
}
|
|
12481
|
+
function isNonNegativeSafeInteger(value) {
|
|
12482
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
12483
|
+
}
|
|
12484
|
+
async function fetchNoteIndexHead(relayUrl, options = {}) {
|
|
12485
|
+
const url = joinPath(relayUrl, "/note-index/v1/head").toString();
|
|
12486
|
+
const raw = await requestWithRetry(url, options, async (response) => {
|
|
12487
|
+
if (!response.ok) {
|
|
12488
|
+
throw new HttpStatusError(response.status, `note index head: HTTP ${response.status}`);
|
|
12489
|
+
}
|
|
12490
|
+
const text = new TextDecoder().decode(await readBoundedBody(response, 64 * 1024));
|
|
12491
|
+
try {
|
|
12492
|
+
return JSON.parse(text);
|
|
12493
|
+
} catch {
|
|
12494
|
+
throw new NoteIndexFormatError("head is not JSON");
|
|
12495
|
+
}
|
|
12496
|
+
});
|
|
12497
|
+
if (!raw || typeof raw !== "object") throw new NoteIndexFormatError("head is not an object");
|
|
12498
|
+
if (raw.format !== NOTE_INDEX_FORMAT_VERSION) {
|
|
12499
|
+
throw new NoteIndexFormatError(`unsupported head format ${String(raw.format)}`);
|
|
12500
|
+
}
|
|
12501
|
+
if (raw.page_size !== NOTE_INDEX_PAGE_SIZE) {
|
|
12502
|
+
throw new NoteIndexFormatError(`unsupported page_size ${String(raw.page_size)}`);
|
|
12503
|
+
}
|
|
12504
|
+
if (!isNonNegativeSafeInteger(raw.watermark) || !isNonNegativeSafeInteger(raw.complete_pages)) {
|
|
12505
|
+
throw new NoteIndexFormatError("head watermark/complete_pages are not non-negative integers");
|
|
12506
|
+
}
|
|
12507
|
+
if (raw.complete_pages !== Math.floor(raw.watermark / NOTE_INDEX_PAGE_SIZE)) {
|
|
12508
|
+
throw new NoteIndexFormatError(
|
|
12509
|
+
`complete_pages ${raw.complete_pages} disagrees with watermark ${raw.watermark}`
|
|
12510
|
+
);
|
|
12511
|
+
}
|
|
12512
|
+
if (typeof raw.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(raw.epoch) || BigInt(raw.epoch) > U64_MAX3) {
|
|
12513
|
+
throw new NoteIndexFormatError("head epoch is not a u64 decimal string");
|
|
12514
|
+
}
|
|
12515
|
+
if (typeof raw.chain_tip !== "string" || !/^[0-9a-fA-F]{64}$/.test(raw.chain_tip)) {
|
|
12516
|
+
throw new NoteIndexFormatError("head chain_tip is not 32-byte hex");
|
|
12517
|
+
}
|
|
12518
|
+
return {
|
|
12519
|
+
format: 1,
|
|
12520
|
+
epoch: BigInt(raw.epoch),
|
|
12521
|
+
pageSize: NOTE_INDEX_PAGE_SIZE,
|
|
12522
|
+
watermark: raw.watermark,
|
|
12523
|
+
completePages: raw.complete_pages,
|
|
12524
|
+
chainTip: raw.chain_tip.toLowerCase()
|
|
12525
|
+
};
|
|
12526
|
+
}
|
|
12527
|
+
async function fetchNoteIndexPage(relayUrl, epoch, page, options = {}) {
|
|
12528
|
+
if (typeof epoch !== "bigint" || epoch < 0n || epoch > U64_MAX3) throw new Error("epoch must be a u64 bigint");
|
|
12529
|
+
if (!isNonNegativeSafeInteger(page)) throw new Error(`page must be a non-negative integer, got ${page}`);
|
|
12530
|
+
const url = joinPath(relayUrl, `/note-index/v1/e/${epoch.toString(10)}/pages/${page}`).toString();
|
|
12531
|
+
return requestWithRetry(url, options, async (response) => {
|
|
12532
|
+
if (!response.ok) {
|
|
12533
|
+
throw new HttpStatusError(response.status, `note index page ${page}: HTTP ${response.status}`);
|
|
12534
|
+
}
|
|
12535
|
+
return readBoundedBody(response, NOTE_INDEX_MAX_PAGE_BYTES);
|
|
12536
|
+
});
|
|
12537
|
+
}
|
|
12538
|
+
|
|
12539
|
+
// src/scanning/note-index.ts
|
|
12540
|
+
import _bs584 from "bs58";
|
|
12541
|
+
import { sha256 as sha2566 } from "@noble/hashes/sha2";
|
|
12542
|
+
var bs584 = _bs584.default || _bs584;
|
|
12543
|
+
var CURSOR_VERSION = 2;
|
|
12544
|
+
var DEFAULT_CONCURRENCY = 6;
|
|
12545
|
+
var MAX_CONCURRENCY = 32;
|
|
12546
|
+
var ITEM_BATCH = 64;
|
|
12547
|
+
var CURSOR_PAGE_ALIGN = 8;
|
|
12548
|
+
var MAX_PERSISTED_PENDING_LEAVES = 4096;
|
|
12549
|
+
var MAX_CARRIED_PENDING = 256;
|
|
12550
|
+
var MAX_REJECTED_IDS = 1024;
|
|
12551
|
+
var LEAF_WINDOW = 512;
|
|
12552
|
+
var MAX_OVERRIDES = 256;
|
|
12553
|
+
var MAX_CURSOR_OWN_ITEMS = 65536;
|
|
12554
|
+
var MAX_LEGACY_VIEWING_KEYS = 8;
|
|
12555
|
+
var MAX_CURSOR_KEYS = 131072;
|
|
12556
|
+
var MAX_CURSOR_POOLS = 256;
|
|
12557
|
+
var MAX_CURSOR_PAGE = 2 ** 32;
|
|
12558
|
+
var TREE_CAPACITY = 2 ** MERKLE_TREE_HEIGHT2;
|
|
12559
|
+
var ZERO_CHAIN = "00".repeat(32);
|
|
12560
|
+
var U64_MAX4 = (1n << 64n) - 1n;
|
|
12561
|
+
var NoteIndexHeadBehindError = class extends Error {
|
|
12562
|
+
constructor(cursorWatermark, headWatermark) {
|
|
12563
|
+
super(
|
|
12564
|
+
`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`
|
|
12565
|
+
);
|
|
12566
|
+
this.cursorWatermark = cursorWatermark;
|
|
12567
|
+
this.headWatermark = headWatermark;
|
|
12568
|
+
this.retryable = true;
|
|
12569
|
+
this.name = "NoteIndexHeadBehindError";
|
|
12570
|
+
}
|
|
12571
|
+
};
|
|
12572
|
+
var FullPassSignal = class {
|
|
12573
|
+
constructor(reason) {
|
|
12574
|
+
this.reason = reason;
|
|
12575
|
+
}
|
|
12576
|
+
};
|
|
12577
|
+
function abortError2() {
|
|
12578
|
+
const error = new Error("recoverNotesFromIndex aborted");
|
|
12579
|
+
error.name = "AbortError";
|
|
12580
|
+
return error;
|
|
12581
|
+
}
|
|
12582
|
+
function bytesToBigint2(bytes) {
|
|
12583
|
+
let v = 0n;
|
|
12584
|
+
for (let i = 0; i < bytes.length; i++) v = v << 8n | BigInt(bytes[i]);
|
|
12585
|
+
return v;
|
|
12586
|
+
}
|
|
12587
|
+
function toHex2(bytes) {
|
|
12588
|
+
let s = "";
|
|
12589
|
+
for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, "0");
|
|
12590
|
+
return s;
|
|
12591
|
+
}
|
|
12592
|
+
function fromHex(hex) {
|
|
12593
|
+
return Uint8Array.from(Buffer.from(hex, "hex"));
|
|
12594
|
+
}
|
|
12595
|
+
function hex32(v) {
|
|
12596
|
+
return v.toString(16).padStart(64, "0");
|
|
12597
|
+
}
|
|
12598
|
+
function isAllZero3(bytes) {
|
|
12599
|
+
for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
|
|
12600
|
+
return true;
|
|
12601
|
+
}
|
|
12602
|
+
function floorAlign(page) {
|
|
12603
|
+
return page - page % CURSOR_PAGE_ALIGN;
|
|
12604
|
+
}
|
|
12605
|
+
function verifiedKey(mint, leaf, commitment) {
|
|
12606
|
+
return `${mint}:${leaf}:${hex32(commitment)}`;
|
|
12607
|
+
}
|
|
12608
|
+
function itemIdentity(raw) {
|
|
12609
|
+
return toHex2(sha2566(raw).subarray(0, 16));
|
|
12610
|
+
}
|
|
12611
|
+
var LeafBuffer = class {
|
|
12612
|
+
constructor() {
|
|
12613
|
+
this.bytes = new Uint8Array(32 * 1024);
|
|
12614
|
+
this.view = new DataView(this.bytes.buffer);
|
|
12615
|
+
this.count = 0;
|
|
12616
|
+
}
|
|
12617
|
+
get length() {
|
|
12618
|
+
return this.count;
|
|
12619
|
+
}
|
|
12620
|
+
push(values) {
|
|
12621
|
+
const need = (this.count + values.length) * 32;
|
|
12622
|
+
if (need > this.bytes.length) {
|
|
12623
|
+
let size = this.bytes.length;
|
|
12624
|
+
while (size < need) size *= 2;
|
|
12625
|
+
const next = new Uint8Array(size);
|
|
12626
|
+
next.set(this.bytes.subarray(0, this.count * 32));
|
|
12627
|
+
this.bytes = next;
|
|
12628
|
+
this.view = new DataView(next.buffer);
|
|
12629
|
+
}
|
|
12630
|
+
for (const v of values) {
|
|
12631
|
+
const o = this.count * 32;
|
|
12632
|
+
this.view.setBigUint64(o, v >> 192n & 0xffffffffffffffffn);
|
|
12633
|
+
this.view.setBigUint64(o + 8, v >> 128n & 0xffffffffffffffffn);
|
|
12634
|
+
this.view.setBigUint64(o + 16, v >> 64n & 0xffffffffffffffffn);
|
|
12635
|
+
this.view.setBigUint64(o + 24, v & 0xffffffffffffffffn);
|
|
12636
|
+
this.count++;
|
|
12637
|
+
}
|
|
12638
|
+
}
|
|
12639
|
+
get(i) {
|
|
12640
|
+
if (i < 0 || i >= this.count) return void 0;
|
|
12641
|
+
const o = i * 32;
|
|
12642
|
+
return this.view.getBigUint64(o) << 192n | this.view.getBigUint64(o + 8) << 128n | this.view.getBigUint64(o + 16) << 64n | this.view.getBigUint64(o + 24);
|
|
12643
|
+
}
|
|
12644
|
+
};
|
|
12645
|
+
async function trialItem(item, trials) {
|
|
12646
|
+
for (const trial of trials) {
|
|
12647
|
+
if (trial.legacy && item.kind === 2) continue;
|
|
12648
|
+
const opened = await trialItemWith(item, trial);
|
|
12649
|
+
if (opened) return { ...opened, trial };
|
|
12650
|
+
}
|
|
12651
|
+
return null;
|
|
12652
|
+
}
|
|
12653
|
+
async function trialItemIsolated(item, trials, stats) {
|
|
12654
|
+
try {
|
|
12655
|
+
return await trialItem(item, trials);
|
|
12656
|
+
} catch {
|
|
12657
|
+
stats.skipped++;
|
|
12658
|
+
return null;
|
|
12659
|
+
}
|
|
12660
|
+
}
|
|
12661
|
+
async function trialItemWith(item, trial) {
|
|
12662
|
+
if (item.kind === 1) {
|
|
12663
|
+
if (item.note.length === 0) return null;
|
|
12664
|
+
let note = isAllZero3(item.comm0) ? null : await trial.decrypt(item.note, item.comm0);
|
|
12665
|
+
if (!note && item.note[0] === 2 && !isAllZero3(item.comm1)) note = await trial.decrypt(item.note, item.comm1);
|
|
12666
|
+
return note ? { note } : null;
|
|
12667
|
+
}
|
|
12668
|
+
if (item.kind === 2) {
|
|
12669
|
+
const delivery = await trial.open(item.envelope);
|
|
12670
|
+
return delivery ? { delivery } : null;
|
|
12671
|
+
}
|
|
12672
|
+
if (item.amountAfterFee === 0n) return null;
|
|
12673
|
+
const refund = await matchSwapRefundLeaf({
|
|
12674
|
+
viewingKeyNk: trial.nk,
|
|
12675
|
+
inputNullifier: item.nullifier0,
|
|
12676
|
+
amountAfterFee: item.amountAfterFee,
|
|
12677
|
+
commitment: item.commitment,
|
|
12678
|
+
ownerUtxoKeypair: trial.owner
|
|
12679
|
+
});
|
|
12680
|
+
return refund ? { refund } : null;
|
|
12681
|
+
}
|
|
12682
|
+
function txOutputs(item) {
|
|
12683
|
+
const out = [toHex2(item.comm0)];
|
|
12684
|
+
if (!isAllZero3(item.comm1)) out.push(toHex2(item.comm1));
|
|
12685
|
+
return out;
|
|
12686
|
+
}
|
|
12687
|
+
function leafOfTxOutput(item, commitment) {
|
|
12688
|
+
if (!isAllZero3(item.comm0) && commitment === bytesToBigint2(item.comm0)) return Number(item.leaf0);
|
|
12689
|
+
if (!isAllZero3(item.comm1) && commitment === bytesToBigint2(item.comm1)) return Number(item.leaf1);
|
|
12690
|
+
return null;
|
|
12691
|
+
}
|
|
12692
|
+
function changeBlindingOrNull(nk, noteSalt, outputIndex) {
|
|
12693
|
+
try {
|
|
12694
|
+
return deriveChangeNoteBlinding(nk, noteSalt, outputIndex);
|
|
12695
|
+
} catch {
|
|
12696
|
+
return null;
|
|
12697
|
+
}
|
|
12698
|
+
}
|
|
12699
|
+
async function matchOwnItems(own, owner, onReject, onSkip) {
|
|
12700
|
+
const candidates = [];
|
|
12701
|
+
const claimed = /* @__PURE__ */ new Set();
|
|
12702
|
+
const byNullifier = /* @__PURE__ */ new Map();
|
|
12703
|
+
const legacyKeys = /* @__PURE__ */ new Map();
|
|
12704
|
+
const ownTxs = own.filter((o) => o.item.kind === 1 && o.note?.noteSalt !== void 0);
|
|
12705
|
+
const spendsOf = /* @__PURE__ */ new Map();
|
|
12706
|
+
const byOutKey = /* @__PURE__ */ new Map();
|
|
12707
|
+
const index = (map, key, o) => {
|
|
12708
|
+
const list = map.get(key);
|
|
12709
|
+
if (list) list.push(o);
|
|
12710
|
+
else map.set(key, [o]);
|
|
12711
|
+
};
|
|
12712
|
+
for (const o of ownTxs) {
|
|
12713
|
+
for (const n of [o.item.nullifier0, o.item.nullifier1]) if (!isAllZero3(n)) index(spendsOf, toHex2(n), o);
|
|
12714
|
+
if (o.note.outPubkey0 !== void 0) index(byOutKey, o.note.outPubkey0, o);
|
|
12715
|
+
}
|
|
12716
|
+
const queue = [];
|
|
12717
|
+
const queued = /* @__PURE__ */ new Set();
|
|
12718
|
+
const enqueue = (o) => {
|
|
12719
|
+
if (queued.has(o)) return;
|
|
12720
|
+
queued.add(o);
|
|
12721
|
+
queue.push(o);
|
|
12722
|
+
};
|
|
12723
|
+
const add = async (o, c) => {
|
|
12724
|
+
const nullifier = hex32(
|
|
12725
|
+
await computeNullifier({ amount: c.amount, keypair: c.keypair, blinding: c.blinding, mintAddress: c.mint, index: c.leaf, commitment: c.commitment })
|
|
12726
|
+
);
|
|
12727
|
+
const full = { ...c, atRisk: c.atRisk || o.trial.legacy, signature: o.item.signature, page: o.page, seq: o.seq, nullifier };
|
|
12728
|
+
candidates.push(full);
|
|
12729
|
+
if (!byNullifier.has(nullifier)) {
|
|
12730
|
+
byNullifier.set(nullifier, full);
|
|
12731
|
+
for (const s of spendsOf.get(nullifier) ?? []) enqueue(s);
|
|
12732
|
+
}
|
|
12733
|
+
if (c.atRisk && c.keypair.publicKey !== owner.publicKey && !legacyKeys.has(c.keypair.publicKey)) {
|
|
12734
|
+
legacyKeys.set(c.keypair.publicKey, c.keypair);
|
|
12735
|
+
for (const s of byOutKey.get(c.keypair.publicKey) ?? []) enqueue(s);
|
|
12736
|
+
}
|
|
12737
|
+
};
|
|
12738
|
+
const tryDeposit = async (o, item, amount) => {
|
|
12739
|
+
const note = o.note;
|
|
12740
|
+
const mint = addressFromBytes(item.mint);
|
|
12741
|
+
const deposit = await matchDepositNote({
|
|
12742
|
+
viewingKeyNk: o.trial.nk,
|
|
12743
|
+
noteSalt: note.noteSalt,
|
|
12744
|
+
amount,
|
|
12745
|
+
mintAddress: mint,
|
|
12746
|
+
outputCommitments: txOutputs(item),
|
|
12747
|
+
ownerUtxoKeypair: owner
|
|
12748
|
+
});
|
|
12749
|
+
const leaf = deposit ? leafOfTxOutput(item, deposit.commitment) : null;
|
|
12750
|
+
if (!deposit || leaf === null) return false;
|
|
12751
|
+
await add(o, {
|
|
12752
|
+
kind: "deposit",
|
|
12753
|
+
atRisk: deposit.legacyExposed,
|
|
12754
|
+
amount: deposit.amount,
|
|
12755
|
+
blinding: deposit.blinding,
|
|
12756
|
+
keypair: deposit.legacyExposed ? deposit.keypair : owner,
|
|
12757
|
+
mint,
|
|
12758
|
+
commitment: deposit.commitment,
|
|
12759
|
+
leaf
|
|
12760
|
+
});
|
|
12761
|
+
return true;
|
|
12762
|
+
};
|
|
12763
|
+
const tryChange0 = async (o, item, keypair, atRisk) => {
|
|
12764
|
+
const note = o.note;
|
|
12765
|
+
const mint = addressFromBytes(item.mint);
|
|
12766
|
+
const change = await matchChangeNote({
|
|
12767
|
+
viewingKeyNk: o.trial.nk,
|
|
12768
|
+
noteSalt: note.noteSalt,
|
|
12769
|
+
amount: note.outAmount0,
|
|
12770
|
+
keypair,
|
|
12771
|
+
mintAddress: mint,
|
|
12772
|
+
outputIndex: 0,
|
|
12773
|
+
outputCommitments: [toHex2(item.comm0)],
|
|
12774
|
+
ownerUtxoPublicKey: owner.publicKey
|
|
12775
|
+
});
|
|
12776
|
+
if (!change) return false;
|
|
12777
|
+
await add(o, {
|
|
12778
|
+
kind: "change",
|
|
12779
|
+
atRisk,
|
|
12780
|
+
amount: change.amount,
|
|
12781
|
+
blinding: change.blinding,
|
|
12782
|
+
keypair,
|
|
12783
|
+
mint,
|
|
12784
|
+
commitment: change.commitment,
|
|
12785
|
+
leaf: Number(item.leaf0)
|
|
12786
|
+
});
|
|
12787
|
+
return true;
|
|
12788
|
+
};
|
|
12789
|
+
const direct = async (o) => {
|
|
12790
|
+
const item = o.item;
|
|
12791
|
+
if (item.kind === 1 && o.note?.noteSalt !== void 0) {
|
|
12792
|
+
const note = o.note;
|
|
12793
|
+
if (note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
|
|
12794
|
+
if (await tryDeposit(o, item, item.publicAmount)) claimed.add(`${o.seq}:0`);
|
|
12795
|
+
}
|
|
12796
|
+
if (note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 === owner.publicKey) {
|
|
12797
|
+
if (await tryChange0(o, item, owner, false)) claimed.add(`${o.seq}:0`);
|
|
12798
|
+
}
|
|
12799
|
+
} else if (item.kind === 2 && o.delivery) {
|
|
12800
|
+
const mint = addressFromBytes(item.mint);
|
|
12801
|
+
if (o.delivery.amount <= 0n || o.delivery.blinding === 0n) {
|
|
12802
|
+
onReject(o);
|
|
12803
|
+
return;
|
|
12804
|
+
}
|
|
12805
|
+
const commitment = await computeCommitment({
|
|
12806
|
+
amount: o.delivery.amount,
|
|
12807
|
+
keypair: { privateKey: 0n, publicKey: owner.publicKey },
|
|
12808
|
+
blinding: o.delivery.blinding,
|
|
12809
|
+
mintAddress: mint
|
|
12810
|
+
});
|
|
12811
|
+
if (commitment !== bytesToBigint2(item.commitment)) {
|
|
12812
|
+
onReject(o);
|
|
12813
|
+
return;
|
|
12814
|
+
}
|
|
12815
|
+
await add(o, {
|
|
12816
|
+
kind: "received",
|
|
12817
|
+
atRisk: false,
|
|
12818
|
+
amount: o.delivery.amount,
|
|
12819
|
+
blinding: o.delivery.blinding,
|
|
12820
|
+
keypair: owner,
|
|
12821
|
+
mint,
|
|
12822
|
+
commitment,
|
|
12823
|
+
leaf: Number(item.leaf)
|
|
12824
|
+
});
|
|
12825
|
+
} else if (item.kind === 3 && o.refund) {
|
|
12826
|
+
await add(o, {
|
|
12827
|
+
kind: "swap_refund",
|
|
12828
|
+
atRisk: o.refund.legacyExposed,
|
|
12829
|
+
amount: o.refund.amount,
|
|
12830
|
+
blinding: o.refund.blinding,
|
|
12831
|
+
// per-swap refunds carry their derived keypair; owner-shape ones carry the owner
|
|
12832
|
+
keypair: o.refund.keypair,
|
|
12833
|
+
mint: NATIVE_SOL_MINT,
|
|
12834
|
+
commitment: o.refund.commitment,
|
|
12835
|
+
leaf: Number(item.leaf)
|
|
12836
|
+
});
|
|
12837
|
+
}
|
|
12838
|
+
};
|
|
12839
|
+
for (const o of own) {
|
|
12840
|
+
try {
|
|
12841
|
+
await direct(o);
|
|
12842
|
+
} catch {
|
|
12843
|
+
onSkip(o);
|
|
12844
|
+
}
|
|
12845
|
+
}
|
|
12846
|
+
const processTx = async (o) => {
|
|
12847
|
+
const item = o.item;
|
|
12848
|
+
const note = o.note;
|
|
12849
|
+
if (!claimed.has(`${o.seq}:0`) && note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 !== void 0) {
|
|
12850
|
+
const legacy = legacyKeys.get(note.outPubkey0);
|
|
12851
|
+
if (legacy && await tryChange0(o, item, legacy, true)) claimed.add(`${o.seq}:0`);
|
|
12852
|
+
}
|
|
12853
|
+
const mint = addressFromBytes(item.mint);
|
|
12854
|
+
const inputs = [item.nullifier0, item.nullifier1].filter((n) => !isAllZero3(n)).map((n) => byNullifier.get(toHex2(n))).filter((c) => c !== void 0 && c.mint === mint);
|
|
12855
|
+
if (inputs.length === 0) return;
|
|
12856
|
+
const sumIn = inputs.reduce((acc, c) => acc + c.amount, 0n);
|
|
12857
|
+
if (!claimed.has(`${o.seq}:1`) && note.outAmount0 !== void 0 && !isAllZero3(item.comm1)) {
|
|
12858
|
+
const out1 = sumIn + item.publicAmount - note.outAmount0;
|
|
12859
|
+
const blinding = out1 > 0n ? changeBlindingOrNull(o.trial.nk, note.noteSalt, 1) : null;
|
|
12860
|
+
if (out1 > 0n && blinding === null) onSkip(o);
|
|
12861
|
+
else if (blinding !== null) {
|
|
12862
|
+
const owners = [{ keypair: owner, atRisk: false }];
|
|
12863
|
+
const legacyInput = legacyKeys.get(inputs[0].keypair.publicKey);
|
|
12864
|
+
if (legacyInput && legacyInput.publicKey !== owner.publicKey) owners.push({ keypair: legacyInput, atRisk: true });
|
|
12865
|
+
for (const { keypair, atRisk } of owners) {
|
|
12866
|
+
const commitment = await computeCommitment({ amount: out1, keypair, blinding, mintAddress: mint });
|
|
12867
|
+
if (commitment !== bytesToBigint2(item.comm1)) continue;
|
|
12868
|
+
claimed.add(`${o.seq}:1`);
|
|
12869
|
+
await add(o, { kind: "change", atRisk, amount: out1, blinding, keypair, mint, commitment, leaf: Number(item.leaf1) });
|
|
12870
|
+
break;
|
|
12871
|
+
}
|
|
12872
|
+
}
|
|
12873
|
+
}
|
|
12874
|
+
if (!claimed.has(`${o.seq}:0`) && note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
|
|
12875
|
+
if (await tryDeposit(o, item, item.publicAmount + sumIn)) claimed.add(`${o.seq}:0`);
|
|
12876
|
+
}
|
|
12877
|
+
};
|
|
12878
|
+
for (const o of ownTxs) enqueue(o);
|
|
12879
|
+
for (let i = 0; i < queue.length; i++) {
|
|
12880
|
+
const o = queue[i];
|
|
12881
|
+
queued.delete(o);
|
|
12882
|
+
try {
|
|
12883
|
+
await processTx(o);
|
|
12884
|
+
} catch {
|
|
12885
|
+
onSkip(o);
|
|
12886
|
+
}
|
|
12887
|
+
}
|
|
12888
|
+
return candidates;
|
|
12889
|
+
}
|
|
12890
|
+
async function replayStream(start, pages, overrides, chain, targetPage) {
|
|
12891
|
+
const frontier = await MerkleFrontier.create(start.frontier ?? void 0, MERKLE_TREE_HEIGHT2);
|
|
12892
|
+
const startN = frontier.nextIndex;
|
|
12893
|
+
const pending = new Map(start.pending);
|
|
12894
|
+
const flushed = new LeafBuffer();
|
|
12895
|
+
const corrections = /* @__PURE__ */ new Map();
|
|
12896
|
+
let conflicts = 0;
|
|
12897
|
+
let verifiedPrefix = 0;
|
|
12898
|
+
let mismatch = false;
|
|
12899
|
+
const checks = [];
|
|
12900
|
+
const setBits = [];
|
|
12901
|
+
if (chain && chain.nextIndex > 0) {
|
|
12902
|
+
const last = chain.nextIndex - 1;
|
|
12903
|
+
for (let l = 0; l < MERKLE_TREE_HEIGHT2; l++) if (Math.floor(last / 2 ** l) % 2 === 1) setBits.push(l);
|
|
12904
|
+
for (const l of setBits) {
|
|
12905
|
+
const at = Math.floor(last / 2 ** l) * 2 ** l;
|
|
12906
|
+
if (at >= startN) checks.push({ at, level: l });
|
|
12907
|
+
}
|
|
12908
|
+
if (chain.nextIndex >= startN) checks.push({ at: chain.nextIndex, level: -1 });
|
|
12909
|
+
checks.sort((a, b) => a.at - b.at);
|
|
12910
|
+
}
|
|
12911
|
+
let nextCheck = 0;
|
|
12912
|
+
const runChecks = () => {
|
|
12913
|
+
while (nextCheck < checks.length && checks[nextCheck].at === frontier.nextIndex) {
|
|
12914
|
+
const { at, level } = checks[nextCheck++];
|
|
12915
|
+
const ok = level < 0 ? frontier.root() === chain.root : setBits.every((j) => j < level || frontier.leftAt(j) === chain.subtrees[j]);
|
|
12916
|
+
if (ok) verifiedPrefix = Math.max(verifiedPrefix, at);
|
|
12917
|
+
else mismatch = true;
|
|
12918
|
+
}
|
|
12919
|
+
};
|
|
12920
|
+
const append = (values) => {
|
|
12921
|
+
let i = 0;
|
|
12922
|
+
while (i < values.length) {
|
|
12923
|
+
const room = nextCheck < checks.length ? checks[nextCheck].at - frontier.nextIndex : values.length - i;
|
|
12924
|
+
const take = Math.min(values.length - i, room);
|
|
12925
|
+
if (take > 0) {
|
|
12926
|
+
const part = values.slice(i, i + take);
|
|
12927
|
+
frontier.append(part);
|
|
12928
|
+
flushed.push(part);
|
|
12929
|
+
i += take;
|
|
12930
|
+
}
|
|
12931
|
+
runChecks();
|
|
12932
|
+
}
|
|
12933
|
+
};
|
|
12934
|
+
const valueAt = (leaf) => leaf >= startN && leaf < startN + flushed.length ? flushed.get(leaf - startN) : pending.get(leaf);
|
|
12935
|
+
const flush = () => {
|
|
12936
|
+
const batch = [];
|
|
12937
|
+
let next = frontier.nextIndex;
|
|
12938
|
+
while (pending.has(next)) {
|
|
12939
|
+
batch.push(pending.get(next));
|
|
12940
|
+
pending.delete(next);
|
|
12941
|
+
next++;
|
|
12942
|
+
}
|
|
12943
|
+
if (batch.length > 0) append(batch);
|
|
12944
|
+
};
|
|
12945
|
+
let snapshot = null;
|
|
12946
|
+
let taken = false;
|
|
12947
|
+
const takeSnapshot = () => {
|
|
12948
|
+
taken = true;
|
|
12949
|
+
if (pending.size > MAX_PERSISTED_PENDING_LEAVES) return;
|
|
12950
|
+
snapshot = { frontier: frontier.toState(), pending: new Map(pending), nextIndex: frontier.nextIndex };
|
|
12951
|
+
};
|
|
12952
|
+
runChecks();
|
|
12953
|
+
flush();
|
|
12954
|
+
for (const { page, entries } of pages) {
|
|
12955
|
+
if (!taken && page >= targetPage) takeSnapshot();
|
|
12956
|
+
for (const e of entries) {
|
|
12957
|
+
if (e.leaf < startN) continue;
|
|
12958
|
+
const prior = valueAt(e.leaf);
|
|
12959
|
+
if (prior !== void 0) {
|
|
12960
|
+
if (prior !== e.commitment) {
|
|
12961
|
+
conflicts++;
|
|
12962
|
+
corrections.set(e.leaf, e.commitment);
|
|
12963
|
+
}
|
|
12964
|
+
continue;
|
|
12965
|
+
}
|
|
12966
|
+
pending.set(e.leaf, overrides.get(e.leaf) ?? e.commitment);
|
|
12967
|
+
}
|
|
12968
|
+
flush();
|
|
12969
|
+
}
|
|
12970
|
+
if (!taken) takeSnapshot();
|
|
12971
|
+
if (chain && treeAccountAcceptsRoot(chain.data, hex32(frontier.root()))) {
|
|
12972
|
+
verifiedPrefix = Math.max(verifiedPrefix, Math.min(frontier.nextIndex, chain.nextIndex));
|
|
12973
|
+
}
|
|
12974
|
+
return { endCount: frontier.nextIndex, valueAt, snapshot, conflicts, corrections, verifiedPrefix, mismatch };
|
|
12975
|
+
}
|
|
12976
|
+
var HEX64 = /^[0-9a-f]{64}$/;
|
|
12977
|
+
var HEX32 = /^[0-9a-f]{32}$/;
|
|
12978
|
+
var ADDRESS = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
|
|
12979
|
+
var VERIFIED_KEY = /^[1-9A-HJ-NP-Za-km-z]{32,44}:(0|[1-9][0-9]{0,9}):[0-9a-f]{64}$/;
|
|
12980
|
+
function isRecord(v) {
|
|
12981
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
12982
|
+
}
|
|
12983
|
+
function isIntIn(v, min, max) {
|
|
12984
|
+
return typeof v === "number" && Number.isSafeInteger(v) && v >= min && v <= max;
|
|
12985
|
+
}
|
|
12986
|
+
function isBoundedArray(v, max) {
|
|
12987
|
+
return Array.isArray(v) && v.length <= max;
|
|
12988
|
+
}
|
|
12989
|
+
function emptyStartTree() {
|
|
12990
|
+
return {
|
|
12991
|
+
frontier: null,
|
|
12992
|
+
nextIndex: 0,
|
|
12993
|
+
pending: /* @__PURE__ */ new Map(),
|
|
12994
|
+
window: [],
|
|
12995
|
+
windowStart: 0,
|
|
12996
|
+
verified: 0,
|
|
12997
|
+
overrides: /* @__PURE__ */ new Map(),
|
|
12998
|
+
mismatch: false,
|
|
12999
|
+
hiBefore: -1
|
|
13000
|
+
};
|
|
13001
|
+
}
|
|
13002
|
+
async function parseCursor(cursor, poolMints) {
|
|
13003
|
+
try {
|
|
13004
|
+
if (!isRecord(cursor)) return "not an object";
|
|
13005
|
+
if (cursor.v !== CURSOR_VERSION) return "unsupported cursor version";
|
|
13006
|
+
const c = cursor;
|
|
13007
|
+
if (typeof c.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(c.epoch) || BigInt(c.epoch) > U64_MAX4) return "bad epoch";
|
|
13008
|
+
if (!isIntIn(c.page, 0, MAX_CURSOR_PAGE) || c.page % CURSOR_PAGE_ALIGN !== 0) return "bad page";
|
|
13009
|
+
if (typeof c.chain !== "string" || !HEX64.test(c.chain)) return "bad chain";
|
|
13010
|
+
if (!isIntIn(c.watermark, 0, Number.MAX_SAFE_INTEGER) || c.page * NOTE_INDEX_PAGE_SIZE > c.watermark) return "bad watermark";
|
|
13011
|
+
if (!isIntIn(c.fullPassSeq, 0, c.watermark)) return "bad full-pass mark";
|
|
13012
|
+
if (!isRecord(c.trees) || Object.keys(c.trees).length > MAX_CURSOR_POOLS) return "bad trees";
|
|
13013
|
+
const trees = /* @__PURE__ */ new Map();
|
|
13014
|
+
for (const mint of poolMints) {
|
|
13015
|
+
const t = c.trees[mint];
|
|
13016
|
+
if (!isRecord(t)) return "a listed pool is missing from the cursor";
|
|
13017
|
+
const tree = t;
|
|
13018
|
+
if (!isRecord(tree.frontier)) return "bad frontier";
|
|
13019
|
+
let frontier;
|
|
13020
|
+
try {
|
|
13021
|
+
frontier = await MerkleFrontier.create(tree.frontier, MERKLE_TREE_HEIGHT2);
|
|
13022
|
+
} catch {
|
|
13023
|
+
return "bad frontier";
|
|
13024
|
+
}
|
|
13025
|
+
const nextIndex = frontier.nextIndex;
|
|
13026
|
+
if (!isBoundedArray(tree.pending, MAX_PERSISTED_PENDING_LEAVES)) return "bad pending leaves";
|
|
13027
|
+
const pending = /* @__PURE__ */ new Map();
|
|
13028
|
+
let hiBefore = nextIndex - 1;
|
|
13029
|
+
for (const entry of tree.pending) {
|
|
13030
|
+
if (!Array.isArray(entry) || entry.length !== 2) return "bad pending leaves";
|
|
13031
|
+
const [leaf, value] = entry;
|
|
13032
|
+
if (!isIntIn(leaf, nextIndex + 1, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value) || pending.has(leaf)) {
|
|
13033
|
+
return "bad pending leaves";
|
|
13034
|
+
}
|
|
13035
|
+
pending.set(leaf, BigInt("0x" + value));
|
|
13036
|
+
hiBefore = Math.max(hiBefore, leaf);
|
|
13037
|
+
}
|
|
13038
|
+
if (typeof tree.window !== "string" || tree.window.length % 64 !== 0 || !/^[0-9a-f]*$/.test(tree.window)) return "bad window";
|
|
13039
|
+
const windowLen = tree.window.length / 64;
|
|
13040
|
+
if (windowLen > LEAF_WINDOW || windowLen > nextIndex) return "bad window";
|
|
13041
|
+
const window2 = [];
|
|
13042
|
+
for (let i = 0; i < windowLen; i++) window2.push(BigInt("0x" + tree.window.slice(i * 64, (i + 1) * 64)));
|
|
13043
|
+
if (!isIntIn(tree.verified, 0, nextIndex)) return "bad verified prefix";
|
|
13044
|
+
if (!isBoundedArray(tree.overrides, MAX_OVERRIDES)) return "bad overrides";
|
|
13045
|
+
const overrides = /* @__PURE__ */ new Map();
|
|
13046
|
+
for (const entry of tree.overrides) {
|
|
13047
|
+
if (!Array.isArray(entry) || entry.length !== 2) return "bad overrides";
|
|
13048
|
+
const [leaf, value] = entry;
|
|
13049
|
+
if (!isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) return "bad overrides";
|
|
13050
|
+
overrides.set(leaf, BigInt("0x" + value));
|
|
13051
|
+
}
|
|
13052
|
+
if (typeof tree.mismatch !== "boolean") return "bad mismatch flag";
|
|
13053
|
+
trees.set(mint, {
|
|
13054
|
+
frontier: frontier.toState(),
|
|
13055
|
+
nextIndex,
|
|
13056
|
+
pending,
|
|
13057
|
+
window: window2,
|
|
13058
|
+
windowStart: nextIndex - windowLen,
|
|
13059
|
+
verified: tree.verified,
|
|
13060
|
+
overrides,
|
|
13061
|
+
mismatch: tree.mismatch,
|
|
13062
|
+
hiBefore
|
|
13063
|
+
});
|
|
13064
|
+
}
|
|
13065
|
+
const own = c.own;
|
|
13066
|
+
if (!isRecord(own)) return "bad own state";
|
|
13067
|
+
if (!isBoundedArray(own.items, MAX_CURSOR_OWN_ITEMS)) return "bad own items";
|
|
13068
|
+
const items = [];
|
|
13069
|
+
const seqs = /* @__PURE__ */ new Set();
|
|
13070
|
+
for (const entry of own.items) {
|
|
13071
|
+
if (!isRecord(entry)) return "bad own items";
|
|
13072
|
+
const { seq, item } = entry;
|
|
13073
|
+
if (!isIntIn(seq, 0, c.page * NOTE_INDEX_PAGE_SIZE - 1) || seqs.has(seq)) return "bad own items";
|
|
13074
|
+
if (typeof item !== "string" || item.length % 2 !== 0 || item.length > 2 * 4096 || !/^[0-9a-f]+$/.test(item)) return "bad own items";
|
|
13075
|
+
seqs.add(seq);
|
|
13076
|
+
const raw = fromHex(item);
|
|
13077
|
+
items.push({ seq, raw, item: parseNoteIndexItem(raw) });
|
|
13078
|
+
}
|
|
13079
|
+
if (!isBoundedArray(own.verified, MAX_CURSOR_KEYS) || !own.verified.every((k) => typeof k === "string" && VERIFIED_KEY.test(k))) {
|
|
13080
|
+
return "bad verified notes";
|
|
13081
|
+
}
|
|
13082
|
+
if (!isBoundedArray(own.spent, MAX_CURSOR_KEYS) || !own.spent.every((k) => typeof k === "string" && HEX64.test(k))) return "bad spent set";
|
|
13083
|
+
if (!isBoundedArray(own.pendingLeaves, MAX_CARRIED_PENDING)) return "bad pending notes";
|
|
13084
|
+
const pendingLeaves = /* @__PURE__ */ new Map();
|
|
13085
|
+
for (const entry of own.pendingLeaves) {
|
|
13086
|
+
if (!Array.isArray(entry) || entry.length !== 3) return "bad pending notes";
|
|
13087
|
+
const [mint, leaf, value] = entry;
|
|
13088
|
+
if (typeof mint !== "string" || !ADDRESS.test(mint) || !isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) {
|
|
13089
|
+
return "bad pending notes";
|
|
13090
|
+
}
|
|
13091
|
+
pendingLeaves.set(`${mint}:${leaf}`, BigInt("0x" + value));
|
|
13092
|
+
}
|
|
13093
|
+
if (!isBoundedArray(own.rejected, MAX_REJECTED_IDS) || !own.rejected.every((k) => typeof k === "string" && HEX32.test(k))) {
|
|
13094
|
+
return "bad rejected set";
|
|
13095
|
+
}
|
|
13096
|
+
return {
|
|
13097
|
+
raw: c,
|
|
13098
|
+
trees,
|
|
13099
|
+
items,
|
|
13100
|
+
verified: new Set(own.verified),
|
|
13101
|
+
spent: new Set(own.spent),
|
|
13102
|
+
pendingLeaves,
|
|
13103
|
+
rejected: own.rejected
|
|
13104
|
+
};
|
|
13105
|
+
} catch {
|
|
13106
|
+
return "unreadable state";
|
|
13107
|
+
}
|
|
13108
|
+
}
|
|
13109
|
+
async function recoverNotesFromIndex(params) {
|
|
13110
|
+
const startedAt = Date.now();
|
|
13111
|
+
const { relayUrl, connection, viewingKeyNk, programId } = params;
|
|
13112
|
+
assertAllowedRelayOrigin(relayUrl);
|
|
13113
|
+
assertAllowedRpcConnection(connection);
|
|
13114
|
+
if (!(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) throw new Error("viewingKeyNk must be 32 bytes");
|
|
13115
|
+
const owner = await assertOwnerUtxoKeypair(params.ownerUtxoKeypair);
|
|
13116
|
+
if (!Array.isArray(params.poolMints)) throw new Error("poolMints must list every active pool mint");
|
|
13117
|
+
const concurrency = params.concurrency ?? DEFAULT_CONCURRENCY;
|
|
13118
|
+
if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > MAX_CONCURRENCY) {
|
|
13119
|
+
throw new Error(`concurrency must be an integer in 1..${MAX_CONCURRENCY}`);
|
|
13120
|
+
}
|
|
13121
|
+
if (params.signal?.aborted) throw abortError2();
|
|
13122
|
+
const stats = {
|
|
13123
|
+
pages: 0,
|
|
13124
|
+
items: 0,
|
|
13125
|
+
bytes: 0,
|
|
13126
|
+
rpcCalls: 0,
|
|
13127
|
+
ms: 0,
|
|
13128
|
+
dropped: 0,
|
|
13129
|
+
decrypted: 0,
|
|
13130
|
+
candidates: 0,
|
|
13131
|
+
spent: 0,
|
|
13132
|
+
conflicts: 0,
|
|
13133
|
+
pendingDropped: 0,
|
|
13134
|
+
skipped: 0
|
|
13135
|
+
};
|
|
13136
|
+
const rpc = new Proxy(connection, {
|
|
13137
|
+
get(target, prop, receiver) {
|
|
13138
|
+
const value = Reflect.get(target, prop, receiver);
|
|
13139
|
+
if (typeof value !== "function") return value;
|
|
13140
|
+
return (...args) => {
|
|
13141
|
+
const pending = value.apply(target, args);
|
|
13142
|
+
if (pending && typeof pending.send === "function") {
|
|
13143
|
+
const send = pending.send.bind(pending);
|
|
13144
|
+
return {
|
|
13145
|
+
...pending,
|
|
13146
|
+
send: (...sendArgs) => {
|
|
13147
|
+
stats.rpcCalls++;
|
|
13148
|
+
return send(...sendArgs);
|
|
13149
|
+
}
|
|
13150
|
+
};
|
|
13151
|
+
}
|
|
13152
|
+
return pending;
|
|
13153
|
+
};
|
|
13154
|
+
}
|
|
13155
|
+
});
|
|
13156
|
+
const makeTrial = async (nk, legacy) => ({
|
|
13157
|
+
nk,
|
|
13158
|
+
legacy,
|
|
13159
|
+
owner,
|
|
13160
|
+
decrypt: await createCompactChainNoteDecryptor(nk),
|
|
13161
|
+
open: await createRecipientDeliveryOpener(deriveViewingKeyFromNk(nk).privateKey)
|
|
13162
|
+
});
|
|
13163
|
+
const trials = [await makeTrial(viewingKeyNk, false)];
|
|
13164
|
+
const legacyNks = params.legacyViewingKeyNks ?? [];
|
|
13165
|
+
if (!Array.isArray(legacyNks)) throw new Error("legacyViewingKeyNks must be an array of 32-byte keys");
|
|
13166
|
+
if (legacyNks.length > MAX_LEGACY_VIEWING_KEYS) throw new Error(`legacyViewingKeyNks takes at most ${MAX_LEGACY_VIEWING_KEYS} keys`);
|
|
13167
|
+
const seenNks = /* @__PURE__ */ new Set([toHex2(viewingKeyNk)]);
|
|
13168
|
+
for (const nk of legacyNks) {
|
|
13169
|
+
if (!(nk instanceof Uint8Array) || nk.length !== 32) throw new Error("legacyViewingKeyNks entries must be 32 bytes");
|
|
13170
|
+
const key = toHex2(nk);
|
|
13171
|
+
if (seenNks.has(key)) continue;
|
|
13172
|
+
seenNks.add(key);
|
|
13173
|
+
trials.push(await makeTrial(Uint8Array.from(nk), true));
|
|
13174
|
+
}
|
|
13175
|
+
const poolMints = Array.from(new Set(params.poolMints));
|
|
13176
|
+
const warnings = [];
|
|
13177
|
+
const head = await fetchNoteIndexHead(relayUrl, { signal: params.signal });
|
|
13178
|
+
let cursor;
|
|
13179
|
+
if (params.cursor !== void 0) {
|
|
13180
|
+
const checked = await parseCursor(params.cursor, poolMints);
|
|
13181
|
+
if (typeof checked === "string") warnings.push(`note index cursor is unusable (${checked}); re-syncing from page 0`);
|
|
13182
|
+
else if (BigInt(checked.raw.epoch) !== head.epoch) warnings.push("note index epoch changed; re-syncing from page 0");
|
|
13183
|
+
else if (head.watermark < checked.raw.watermark || head.completePages < checked.raw.page) {
|
|
13184
|
+
throw new NoteIndexHeadBehindError(checked.raw.watermark, head.watermark);
|
|
13185
|
+
} else cursor = checked;
|
|
13186
|
+
}
|
|
13187
|
+
const treePdas = await Promise.all(poolMints.map(async (mint) => (await getShieldPoolPDAs(programId, mint)).merkleTree));
|
|
13188
|
+
let treeRead;
|
|
13189
|
+
const readTrees = () => treeRead ?? (treeRead = (async () => {
|
|
13190
|
+
const accounts = poolMints.length > 0 ? await fetchMultipleAccountBytes(rpc, treePdas, "confirmed") : [];
|
|
13191
|
+
return poolMints.map((_, i) => {
|
|
13192
|
+
const account = accounts[i];
|
|
13193
|
+
const parsed = account ? readTreeAccountFrontier(account.data) : null;
|
|
13194
|
+
return account && parsed ? { ...parsed, data: account.data } : null;
|
|
13195
|
+
});
|
|
13196
|
+
})());
|
|
13197
|
+
const ctx = { params, head, trials, owner, stats, poolMints, warnings, readTrees };
|
|
13198
|
+
let outcome = await runOnce(ctx, cursor);
|
|
13199
|
+
if (outcome instanceof FullPassSignal) {
|
|
13200
|
+
warnings.push(`${outcome.reason}; re-syncing from page 0`);
|
|
13201
|
+
Object.assign(stats, { dropped: 0, decrypted: 0, candidates: 0, spent: 0, conflicts: 0, pendingDropped: 0, skipped: 0 });
|
|
13202
|
+
outcome = await runOnce(ctx, void 0);
|
|
13203
|
+
if (outcome instanceof FullPassSignal) throw new Error(`note index recovery failed: ${outcome.reason}`);
|
|
13204
|
+
}
|
|
13205
|
+
if (stats.skipped > 0) warnings.push(`${stats.skipped} note index entries could not be processed and were skipped`);
|
|
13206
|
+
stats.ms = Date.now() - startedAt;
|
|
13207
|
+
return { ...outcome, stats, warnings };
|
|
13208
|
+
}
|
|
13209
|
+
async function runOnce(ctx, cursor) {
|
|
13210
|
+
const { params, head, trials, owner, stats, poolMints } = ctx;
|
|
13211
|
+
const { relayUrl, onProgress } = params;
|
|
13212
|
+
const poolSet = new Set(poolMints);
|
|
13213
|
+
const startPage = cursor?.raw.page ?? 0;
|
|
13214
|
+
const startChain = cursor?.raw.chain ?? ZERO_CHAIN;
|
|
13215
|
+
const fullPassSeq = cursor?.raw.fullPassSeq ?? 0;
|
|
13216
|
+
const pagesTotal = Math.ceil(head.watermark / NOTE_INDEX_PAGE_SIZE);
|
|
13217
|
+
const targetPage = Math.max(startPage, floorAlign(head.completePages));
|
|
13218
|
+
const startTrees = new Map(poolMints.map((m) => [m, cursor?.trees.get(m) ?? emptyStartTree()]));
|
|
13219
|
+
const rejectedIds = new Set(cursor?.rejected ?? []);
|
|
13220
|
+
const controller = new AbortController();
|
|
13221
|
+
const onCallerAbort = () => controller.abort();
|
|
13222
|
+
params.signal?.addEventListener("abort", onCallerAbort, { once: true });
|
|
13223
|
+
const signal = controller.signal;
|
|
13224
|
+
try {
|
|
13225
|
+
const pageData = /* @__PURE__ */ new Map();
|
|
13226
|
+
const ownItems = [];
|
|
13227
|
+
const nullifiers = /* @__PURE__ */ new Set();
|
|
13228
|
+
let fullPassReason = null;
|
|
13229
|
+
const lateReference = (mint, leaf, value, seq) => {
|
|
13230
|
+
if (!cursor || seq < fullPassSeq) return null;
|
|
13231
|
+
const t = startTrees.get(mint);
|
|
13232
|
+
if (leaf < t.nextIndex) {
|
|
13233
|
+
if (leaf < t.windowStart) return "a later item refers to the tree before the cursor";
|
|
13234
|
+
if (value !== void 0 && value !== t.window[leaf - t.windowStart]) return "a later item rewrites the tree before the cursor";
|
|
13235
|
+
return null;
|
|
13236
|
+
}
|
|
13237
|
+
const held = t.pending.get(leaf);
|
|
13238
|
+
if (held !== void 0) return value !== void 0 && value !== held ? "a later item rewrites the tree before the cursor" : null;
|
|
13239
|
+
if (value !== void 0 && leaf < t.hiBefore) return "a later item fills the tree before the cursor";
|
|
13240
|
+
return null;
|
|
13241
|
+
};
|
|
13242
|
+
const chainAt = /* @__PURE__ */ new Map([[startPage, startChain]]);
|
|
13243
|
+
const waiting = /* @__PURE__ */ new Map();
|
|
13244
|
+
let chainNext = startPage;
|
|
13245
|
+
let chainError = null;
|
|
13246
|
+
let wakers = [];
|
|
13247
|
+
const wakeAll = () => {
|
|
13248
|
+
const w = wakers;
|
|
13249
|
+
wakers = [];
|
|
13250
|
+
for (const f of w) f();
|
|
13251
|
+
};
|
|
13252
|
+
signal.addEventListener("abort", wakeAll);
|
|
13253
|
+
const advanceChain = () => {
|
|
13254
|
+
while (!chainError && waiting.has(chainNext)) {
|
|
13255
|
+
const w = waiting.get(chainNext);
|
|
13256
|
+
waiting.delete(chainNext);
|
|
13257
|
+
const expected = chainAt.get(chainNext);
|
|
13258
|
+
if (w.prevChain !== expected) {
|
|
13259
|
+
chainError = cursor && chainNext === startPage ? new FullPassSignal("note index hash chain does not continue from the cursor") : new NoteIndexFormatError(`hash chain broken at page ${chainNext}`);
|
|
13260
|
+
controller.abort();
|
|
13261
|
+
return;
|
|
13262
|
+
}
|
|
13263
|
+
if (!w.complete) break;
|
|
13264
|
+
chainAt.set(chainNext + 1, toHex2(computeNoteIndexChain(fromHex(expected), w.bytes)));
|
|
13265
|
+
chainNext++;
|
|
13266
|
+
}
|
|
13267
|
+
wakeAll();
|
|
13268
|
+
};
|
|
13269
|
+
const workerCount = Math.max(1, Math.min(params.concurrency ?? DEFAULT_CONCURRENCY, pagesTotal - startPage));
|
|
13270
|
+
const lookahead = 2 * workerCount + 2;
|
|
13271
|
+
let nextToFetch = startPage;
|
|
13272
|
+
let pagesDone = 0;
|
|
13273
|
+
const worker = async () => {
|
|
13274
|
+
for (; ; ) {
|
|
13275
|
+
if (signal.aborted) throw abortError2();
|
|
13276
|
+
const pageNo = nextToFetch++;
|
|
13277
|
+
if (pageNo >= pagesTotal) return;
|
|
13278
|
+
while (pageNo - chainNext >= lookahead && !signal.aborted) await new Promise((resolve) => wakers.push(resolve));
|
|
13279
|
+
if (signal.aborted) throw abortError2();
|
|
13280
|
+
const bytes = await fetchNoteIndexPage(relayUrl, head.epoch, pageNo, { signal });
|
|
13281
|
+
stats.bytes += bytes.length;
|
|
13282
|
+
const page2 = parseNoteIndexPage(bytes, { epoch: head.epoch, page: pageNo }, { skipMalformedItems: true });
|
|
13283
|
+
if (pageNo < head.completePages && !page2.complete) {
|
|
13284
|
+
throw new NoteIndexFormatError(`page ${pageNo} is below complete_pages but not complete`);
|
|
13285
|
+
}
|
|
13286
|
+
stats.pages++;
|
|
13287
|
+
stats.skipped += page2.skippedMalformed;
|
|
13288
|
+
const seqOf = (i) => pageNo * NOTE_INDEX_PAGE_SIZE + page2.itemPositions[i];
|
|
13289
|
+
waiting.set(pageNo, { bytes: page2.complete ? bytes : new Uint8Array(0), prevChain: toHex2(page2.prevChain), complete: page2.complete });
|
|
13290
|
+
advanceChain();
|
|
13291
|
+
const data = { complete: page2.complete, leaves: /* @__PURE__ */ new Map() };
|
|
13292
|
+
const late = (reason) => {
|
|
13293
|
+
if (reason && !fullPassReason) {
|
|
13294
|
+
fullPassReason = reason;
|
|
13295
|
+
controller.abort();
|
|
13296
|
+
}
|
|
13297
|
+
};
|
|
13298
|
+
const addLeaf = (mintBytes, commitment, leaf, seq) => {
|
|
13299
|
+
if (isAllZero3(commitment)) return;
|
|
13300
|
+
const mint = addressFromBytes(mintBytes);
|
|
13301
|
+
if (!poolSet.has(mint)) return;
|
|
13302
|
+
const entry = { leaf: Number(leaf), commitment: bytesToBigint2(commitment) };
|
|
13303
|
+
late(lateReference(mint, entry.leaf, entry.commitment, seq));
|
|
13304
|
+
const list = data.leaves.get(mint);
|
|
13305
|
+
if (list) list.push(entry);
|
|
13306
|
+
else data.leaves.set(mint, [entry]);
|
|
13307
|
+
};
|
|
13308
|
+
page2.items.forEach((item, i) => {
|
|
13309
|
+
const seq = seqOf(i);
|
|
13310
|
+
if (item.kind === 1) {
|
|
13311
|
+
addLeaf(item.mint, item.comm0, item.leaf0, seq);
|
|
13312
|
+
addLeaf(item.mint, item.comm1, item.leaf1, seq);
|
|
13313
|
+
if (!isAllZero3(item.nullifier0)) nullifiers.add(toHex2(item.nullifier0));
|
|
13314
|
+
if (!isAllZero3(item.nullifier1)) nullifiers.add(toHex2(item.nullifier1));
|
|
13315
|
+
} else if (item.kind === 3) {
|
|
13316
|
+
addLeaf(item.mint, item.commitment, item.leaf, seq);
|
|
13317
|
+
} else {
|
|
13318
|
+
const mint = addressFromBytes(item.mint);
|
|
13319
|
+
if (poolSet.has(mint)) late(lateReference(mint, Number(item.leaf), void 0, seq));
|
|
13320
|
+
}
|
|
13321
|
+
});
|
|
13322
|
+
if (signal.aborted) throw abortError2();
|
|
13323
|
+
for (let i = 0; i < page2.items.length; i += ITEM_BATCH) {
|
|
13324
|
+
if (signal.aborted) throw abortError2();
|
|
13325
|
+
const batch = page2.items.slice(i, i + ITEM_BATCH);
|
|
13326
|
+
const opened = await Promise.all(batch.map((item) => trialItemIsolated(item, trials, stats)));
|
|
13327
|
+
opened.forEach((o, k) => {
|
|
13328
|
+
if (!o) return;
|
|
13329
|
+
stats.decrypted++;
|
|
13330
|
+
const raw = page2.rawItems[i + k];
|
|
13331
|
+
const id = itemIdentity(raw);
|
|
13332
|
+
if (rejectedIds.has(id)) {
|
|
13333
|
+
stats.dropped++;
|
|
13334
|
+
return;
|
|
13335
|
+
}
|
|
13336
|
+
ownItems.push({ page: pageNo, seq: seqOf(i + k), raw, id, item: batch[k], fromCursor: false, ...o, trial: o.trial });
|
|
13337
|
+
});
|
|
13338
|
+
stats.items += batch.length;
|
|
13339
|
+
}
|
|
13340
|
+
pageData.set(pageNo, data);
|
|
13341
|
+
pagesDone++;
|
|
13342
|
+
onProgress?.({ pagesDone, pagesTotal: pagesTotal - startPage, itemsChecked: stats.items, notesFound: ownItems.length });
|
|
13343
|
+
}
|
|
13344
|
+
};
|
|
13345
|
+
const workers = Array.from(
|
|
13346
|
+
{ length: workerCount },
|
|
13347
|
+
() => worker().catch((error) => {
|
|
13348
|
+
controller.abort();
|
|
13349
|
+
throw error;
|
|
13350
|
+
})
|
|
13351
|
+
);
|
|
13352
|
+
const settled = await Promise.allSettled(workers);
|
|
13353
|
+
signal.removeEventListener("abort", wakeAll);
|
|
13354
|
+
if (params.signal?.aborted) throw abortError2();
|
|
13355
|
+
const lateReason = fullPassReason;
|
|
13356
|
+
if (lateReason) return new FullPassSignal(lateReason);
|
|
13357
|
+
const chainFailure = chainError;
|
|
13358
|
+
if (chainFailure) {
|
|
13359
|
+
if (chainFailure instanceof FullPassSignal) return chainFailure;
|
|
13360
|
+
throw chainFailure;
|
|
13361
|
+
}
|
|
13362
|
+
const failure = settled.find((s) => s.status === "rejected" && s.reason?.name !== "AbortError") ?? settled.find((s) => s.status === "rejected");
|
|
13363
|
+
if (failure) throw failure.reason;
|
|
13364
|
+
if (head.completePages >= startPage && chainAt.get(head.completePages) !== head.chainTip) {
|
|
13365
|
+
if (cursor) return new FullPassSignal("note index hash chain does not reach the head's chain_tip");
|
|
13366
|
+
throw new NoteIndexFormatError("hash chain does not reach the head's chain_tip");
|
|
13367
|
+
}
|
|
13368
|
+
for (const entry of cursor?.items ?? []) {
|
|
13369
|
+
const o = await trialItemIsolated(entry.item, trials, stats);
|
|
13370
|
+
if (!o) continue;
|
|
13371
|
+
const page2 = Math.floor(entry.seq / NOTE_INDEX_PAGE_SIZE);
|
|
13372
|
+
ownItems.push({ page: page2, seq: entry.seq, raw: entry.raw, id: itemIdentity(entry.raw), item: entry.item, fromCursor: true, ...o, trial: o.trial });
|
|
13373
|
+
if (entry.item.kind === 1) {
|
|
13374
|
+
if (!isAllZero3(entry.item.nullifier0)) nullifiers.add(toHex2(entry.item.nullifier0));
|
|
13375
|
+
if (!isAllZero3(entry.item.nullifier1)) nullifiers.add(toHex2(entry.item.nullifier1));
|
|
13376
|
+
}
|
|
13377
|
+
}
|
|
13378
|
+
const knownSpent = cursor?.spent ?? /* @__PURE__ */ new Set();
|
|
13379
|
+
ownItems.sort((a, b) => a.seq - b.seq);
|
|
13380
|
+
const rejectedNow = /* @__PURE__ */ new Set();
|
|
13381
|
+
const skippedNow = /* @__PURE__ */ new Set();
|
|
13382
|
+
const allCandidates = await matchOwnItems(
|
|
13383
|
+
ownItems,
|
|
13384
|
+
owner,
|
|
13385
|
+
(o) => {
|
|
13386
|
+
stats.dropped++;
|
|
13387
|
+
rejectedNow.add(o.id);
|
|
13388
|
+
},
|
|
13389
|
+
(o) => {
|
|
13390
|
+
if (skippedNow.has(o)) return;
|
|
13391
|
+
skippedNow.add(o);
|
|
13392
|
+
stats.skipped++;
|
|
13393
|
+
}
|
|
13394
|
+
);
|
|
13395
|
+
stats.candidates = allCandidates.length;
|
|
13396
|
+
const cutoff = params.legacyCutoffLeaf ?? {};
|
|
13397
|
+
const candidates = allCandidates.filter((c) => {
|
|
13398
|
+
const limit = cutoff[c.mint];
|
|
13399
|
+
if (c.atRisk && limit !== void 0 && BigInt(c.leaf) >= limit) {
|
|
13400
|
+
stats.dropped++;
|
|
13401
|
+
return false;
|
|
13402
|
+
}
|
|
13403
|
+
return true;
|
|
13404
|
+
});
|
|
13405
|
+
const chainTrees = await ctx.readTrees();
|
|
13406
|
+
const orderedPages = Array.from(pageData.keys()).sort((a, b) => a - b);
|
|
13407
|
+
const replays = /* @__PURE__ */ new Map();
|
|
13408
|
+
for (let i = 0; i < poolMints.length; i++) {
|
|
13409
|
+
const mint = poolMints[i];
|
|
13410
|
+
const start = startTrees.get(mint);
|
|
13411
|
+
const chainTree = chainTrees[i] ?? null;
|
|
13412
|
+
const pages = orderedPages.map((page2) => ({ page: page2, entries: pageData.get(page2).leaves.get(mint) ?? [] }));
|
|
13413
|
+
let r = await replayStream(start, pages, start.overrides, chainTree, targetPage);
|
|
13414
|
+
let overrides = start.overrides;
|
|
13415
|
+
stats.conflicts += r.conflicts;
|
|
13416
|
+
if (r.corrections.size > 0 && (r.mismatch || r.verifiedPrefix < r.endCount)) {
|
|
13417
|
+
const merged = new Map([...start.overrides, ...r.corrections]);
|
|
13418
|
+
const alternative = await replayStream(start, pages, merged, chainTree, targetPage);
|
|
13419
|
+
if (alternative.verifiedPrefix > r.verifiedPrefix || r.mismatch && !alternative.mismatch) {
|
|
13420
|
+
r = alternative;
|
|
13421
|
+
overrides = merged;
|
|
13422
|
+
}
|
|
13423
|
+
}
|
|
13424
|
+
if (r.mismatch && cursor && !start.mismatch) return new FullPassSignal("a rebuilt tree disagrees with the chain");
|
|
13425
|
+
replays.set(mint, { r, overrides });
|
|
13426
|
+
}
|
|
13427
|
+
const verifiedUpTo = (mint) => Math.max(startTrees.get(mint).verified, replays.get(mint).r.verifiedPrefix);
|
|
13428
|
+
const streamValue = (mint, leaf) => {
|
|
13429
|
+
const v = replays.get(mint)?.r.valueAt(leaf);
|
|
13430
|
+
if (v !== void 0) return v;
|
|
13431
|
+
const carried = cursor?.pendingLeaves.get(`${mint}:${leaf}`);
|
|
13432
|
+
if (carried !== void 0) return carried;
|
|
13433
|
+
const t = startTrees.get(mint);
|
|
13434
|
+
if (t && leaf >= t.windowStart && leaf < t.nextIndex) return t.window[leaf - t.windowStart];
|
|
13435
|
+
return void 0;
|
|
13436
|
+
};
|
|
13437
|
+
const knownVerified = cursor?.verified ?? /* @__PURE__ */ new Set();
|
|
13438
|
+
const verified = [];
|
|
13439
|
+
const pendingByKey = /* @__PURE__ */ new Map();
|
|
13440
|
+
const rejectedCandidates = /* @__PURE__ */ new Set();
|
|
13441
|
+
const outcomeOf = /* @__PURE__ */ new Map();
|
|
13442
|
+
const tally = (c, what) => {
|
|
13443
|
+
const t = outcomeOf.get(c.seq) ?? { kept: false, rejected: 0, total: 0 };
|
|
13444
|
+
t.total++;
|
|
13445
|
+
if (what === "kept") t.kept = true;
|
|
13446
|
+
if (what === "rejected") t.rejected++;
|
|
13447
|
+
outcomeOf.set(c.seq, t);
|
|
13448
|
+
};
|
|
13449
|
+
const pend = (c, rank) => {
|
|
13450
|
+
const key = verifiedKey(c.mint, c.leaf, c.commitment);
|
|
13451
|
+
const prior = pendingByKey.get(key);
|
|
13452
|
+
if (!prior || prior.c.seq > c.seq) pendingByKey.set(key, { c, rank });
|
|
13453
|
+
};
|
|
13454
|
+
for (const c of candidates) {
|
|
13455
|
+
if (knownVerified.has(verifiedKey(c.mint, c.leaf, c.commitment))) {
|
|
13456
|
+
verified.push(c);
|
|
13457
|
+
continue;
|
|
13458
|
+
}
|
|
13459
|
+
if (!poolSet.has(c.mint)) {
|
|
13460
|
+
pend(c, 3);
|
|
13461
|
+
continue;
|
|
13462
|
+
}
|
|
13463
|
+
const value = streamValue(c.mint, c.leaf);
|
|
13464
|
+
if (value === void 0) {
|
|
13465
|
+
if (c.leaf < startTrees.get(c.mint).nextIndex) {
|
|
13466
|
+
stats.dropped++;
|
|
13467
|
+
tally(c, "other");
|
|
13468
|
+
} else pend(c, 1);
|
|
13469
|
+
} else if (c.leaf >= verifiedUpTo(c.mint)) {
|
|
13470
|
+
pend(c, value === c.commitment ? 0 : 2);
|
|
13471
|
+
} else if (value === c.commitment) {
|
|
13472
|
+
verified.push(c);
|
|
13473
|
+
} else {
|
|
13474
|
+
stats.dropped++;
|
|
13475
|
+
rejectedCandidates.add(c);
|
|
13476
|
+
tally(c, "rejected");
|
|
13477
|
+
}
|
|
13478
|
+
}
|
|
13479
|
+
verified.sort((a, b) => a.seq - b.seq);
|
|
13480
|
+
const byLeaf = /* @__PURE__ */ new Map();
|
|
13481
|
+
for (const c of verified) {
|
|
13482
|
+
const key = `${c.mint}:${c.leaf}`;
|
|
13483
|
+
if (byLeaf.has(key)) {
|
|
13484
|
+
stats.dropped++;
|
|
13485
|
+
tally(c, "other");
|
|
13486
|
+
continue;
|
|
13487
|
+
}
|
|
13488
|
+
byLeaf.set(key, c);
|
|
13489
|
+
}
|
|
13490
|
+
const notes = [];
|
|
13491
|
+
const atRisk = [];
|
|
13492
|
+
const spentOut = new Set(knownSpent);
|
|
13493
|
+
const verifiedOut = new Set(knownVerified);
|
|
13494
|
+
const keyChecked = /* @__PURE__ */ new Map();
|
|
13495
|
+
for (const c of byLeaf.values()) {
|
|
13496
|
+
const pubOk = keyChecked.get(c.keypair.privateKey) ?? (c.keypair.privateKey !== 0n && await derivePublicKey(c.keypair.privateKey) === c.keypair.publicKey);
|
|
13497
|
+
keyChecked.set(c.keypair.privateKey, pubOk);
|
|
13498
|
+
const ownerOk = c.keypair.publicKey === owner.publicKey || c.kind === "swap_refund";
|
|
13499
|
+
if (!pubOk || !c.atRisk && !ownerOk) {
|
|
13500
|
+
stats.dropped++;
|
|
13501
|
+
tally(c, "rejected");
|
|
13502
|
+
continue;
|
|
13503
|
+
}
|
|
13504
|
+
tally(c, "kept");
|
|
13505
|
+
verifiedOut.add(verifiedKey(c.mint, c.leaf, c.commitment));
|
|
13506
|
+
const utxo = {
|
|
13507
|
+
amount: c.amount,
|
|
13508
|
+
keypair: c.atRisk || c.kind === "swap_refund" ? { ...c.keypair } : owner,
|
|
13509
|
+
blinding: c.blinding,
|
|
13510
|
+
mintAddress: c.mint,
|
|
13511
|
+
index: c.leaf,
|
|
13512
|
+
commitment: c.commitment
|
|
13513
|
+
};
|
|
13514
|
+
if (nullifiers.has(c.nullifier) || knownSpent.has(c.nullifier)) {
|
|
13515
|
+
stats.spent++;
|
|
13516
|
+
spentOut.add(c.nullifier);
|
|
13517
|
+
continue;
|
|
13518
|
+
}
|
|
13519
|
+
const note = {
|
|
13520
|
+
kind: c.kind,
|
|
13521
|
+
utxo,
|
|
13522
|
+
signature: bs584.encode(c.signature),
|
|
13523
|
+
legacyExposed: c.atRisk
|
|
13524
|
+
};
|
|
13525
|
+
(c.atRisk ? atRisk : notes).push(note);
|
|
13526
|
+
}
|
|
13527
|
+
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);
|
|
13528
|
+
sortNotes(notes);
|
|
13529
|
+
sortNotes(atRisk);
|
|
13530
|
+
const pendingList = Array.from(pendingByKey.values()).sort((a, b) => a.rank - b.rank || a.c.seq - b.c.seq);
|
|
13531
|
+
const carriedPending = pendingList.slice(0, MAX_CARRIED_PENDING).map((p) => p.c);
|
|
13532
|
+
const overflow = pendingList.length - carriedPending.length;
|
|
13533
|
+
if (overflow > 0) {
|
|
13534
|
+
stats.pendingDropped += overflow;
|
|
13535
|
+
ctx.warnings.push(`${overflow} unverified candidates over the carry limit were not carried to the next run`);
|
|
13536
|
+
}
|
|
13537
|
+
for (const { c } of pendingList) if (nullifiers.has(c.nullifier)) spentOut.add(c.nullifier);
|
|
13538
|
+
for (const c of carriedPending) tally(c, "kept");
|
|
13539
|
+
for (const { c } of pendingList.slice(MAX_CARRIED_PENDING)) tally(c, "other");
|
|
13540
|
+
let page = targetPage;
|
|
13541
|
+
for (const { r } of replays.values()) if (r.snapshot === null) page = startPage;
|
|
13542
|
+
const trees = {};
|
|
13543
|
+
const treeEnd = /* @__PURE__ */ new Map();
|
|
13544
|
+
for (const mint of poolMints) {
|
|
13545
|
+
const start = startTrees.get(mint);
|
|
13546
|
+
const { r, overrides } = replays.get(mint);
|
|
13547
|
+
const snap = page === startPage ? { frontier: start.frontier ?? (await MerkleFrontier.create()).toState(), pending: start.pending, nextIndex: start.nextIndex } : r.snapshot;
|
|
13548
|
+
const n = snap.nextIndex;
|
|
13549
|
+
const window2 = [];
|
|
13550
|
+
for (let leaf = n - 1; leaf >= Math.max(0, n - LEAF_WINDOW); leaf--) {
|
|
13551
|
+
const v = leaf >= start.nextIndex ? r.valueAt(leaf) : leaf >= start.windowStart ? start.window[leaf - start.windowStart] : void 0;
|
|
13552
|
+
if (v === void 0) break;
|
|
13553
|
+
window2.push(hex32(v));
|
|
13554
|
+
}
|
|
13555
|
+
window2.reverse();
|
|
13556
|
+
trees[mint] = {
|
|
13557
|
+
frontier: snap.frontier,
|
|
13558
|
+
pending: Array.from(snap.pending.entries(), ([leaf, v]) => [leaf, hex32(v)]).sort((a, b) => a[0] - b[0]),
|
|
13559
|
+
window: window2.join(""),
|
|
13560
|
+
verified: Math.min(verifiedUpTo(mint), n),
|
|
13561
|
+
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)]),
|
|
13562
|
+
mismatch: r.mismatch
|
|
13563
|
+
};
|
|
13564
|
+
treeEnd.set(mint, { nextIndex: n, pending: snap.pending });
|
|
13565
|
+
}
|
|
13566
|
+
const pendingLeaves = [];
|
|
13567
|
+
const pendingLeafSeen = /* @__PURE__ */ new Set();
|
|
13568
|
+
for (const c of carriedPending) {
|
|
13569
|
+
const end = treeEnd.get(c.mint);
|
|
13570
|
+
if (!end || c.leaf >= end.nextIndex) continue;
|
|
13571
|
+
const value = streamValue(c.mint, c.leaf);
|
|
13572
|
+
const key = `${c.mint}:${c.leaf}`;
|
|
13573
|
+
if (value === void 0 || pendingLeafSeen.has(key)) continue;
|
|
13574
|
+
pendingLeafSeen.add(key);
|
|
13575
|
+
pendingLeaves.push([c.mint, c.leaf, hex32(value)]);
|
|
13576
|
+
}
|
|
13577
|
+
const keptItems = [];
|
|
13578
|
+
const keptIds = /* @__PURE__ */ new Set();
|
|
13579
|
+
for (const o of ownItems) {
|
|
13580
|
+
const t = outcomeOf.get(o.seq);
|
|
13581
|
+
if (rejectedNow.has(o.id) || t && t.total > 0 && t.rejected === t.total) {
|
|
13582
|
+
rejectedNow.add(o.id);
|
|
13583
|
+
continue;
|
|
13584
|
+
}
|
|
13585
|
+
if (o.page >= page || !t?.kept || keptIds.has(o.id)) continue;
|
|
13586
|
+
keptIds.add(o.id);
|
|
13587
|
+
keptItems.push({ seq: o.seq, item: toHex2(o.raw) });
|
|
13588
|
+
}
|
|
13589
|
+
const rejected = Array.from(/* @__PURE__ */ new Set([...cursor?.rejected ?? [], ...rejectedNow]));
|
|
13590
|
+
const nextCursor = {
|
|
13591
|
+
v: CURSOR_VERSION,
|
|
13592
|
+
epoch: head.epoch.toString(10),
|
|
13593
|
+
page,
|
|
13594
|
+
chain: chainAt.get(page) ?? startChain,
|
|
13595
|
+
watermark: Math.max(cursor?.raw.watermark ?? 0, head.watermark),
|
|
13596
|
+
fullPassSeq: cursor ? fullPassSeq : head.watermark,
|
|
13597
|
+
trees,
|
|
13598
|
+
own: {
|
|
13599
|
+
items: keptItems,
|
|
13600
|
+
verified: Array.from(verifiedOut),
|
|
13601
|
+
spent: Array.from(spentOut),
|
|
13602
|
+
pendingLeaves,
|
|
13603
|
+
rejected: rejected.slice(Math.max(0, rejected.length - MAX_REJECTED_IDS))
|
|
13604
|
+
}
|
|
13605
|
+
};
|
|
13606
|
+
return { notes, atRisk, pending: pendingByKey.size, cursor: nextCursor };
|
|
13607
|
+
} finally {
|
|
13608
|
+
params.signal?.removeEventListener("abort", onCallerAbort);
|
|
13609
|
+
}
|
|
13610
|
+
}
|
|
13611
|
+
|
|
11616
13612
|
// src/wallet/utxo-wallet.ts
|
|
11617
13613
|
var UtxoWallet = class _UtxoWallet {
|
|
11618
13614
|
constructor(viewingKey) {
|
|
@@ -11967,7 +13963,7 @@ async function loadWeb3() {
|
|
|
11967
13963
|
|
|
11968
13964
|
// src/bridge/rail-verify.ts
|
|
11969
13965
|
import nacl6 from "tweetnacl";
|
|
11970
|
-
import { sha256 as
|
|
13966
|
+
import { sha256 as sha2567 } from "@noble/hashes/sha256";
|
|
11971
13967
|
var ONECLICK_PUBKEY_B58 = "reYaWhvwu8Jzo3WUM3zhn6VrhuMEF4eADL17qtRVifc";
|
|
11972
13968
|
var b58 = /* @__PURE__ */ (() => {
|
|
11973
13969
|
const A = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
@@ -12073,7 +14069,7 @@ function canonicalPayloadString(resp) {
|
|
|
12073
14069
|
function verifyQuoteSignature(resp) {
|
|
12074
14070
|
if (!resp?.signature) return { valid: false, reason: "no signature on the response" };
|
|
12075
14071
|
const payload = { ...signedRequest(resp), ...signedQuote(resp), timestamp: resp.timestamp };
|
|
12076
|
-
const digest =
|
|
14072
|
+
const digest = sha2567(new TextEncoder().encode(stable(payload)));
|
|
12077
14073
|
const message = new TextEncoder().encode(b58.encode(new Uint8Array(digest)));
|
|
12078
14074
|
const sig = resp.signature.replace(/^ed25519:/, "");
|
|
12079
14075
|
try {
|
|
@@ -12823,13 +14819,13 @@ var DoNotRetry = class extends Error {
|
|
|
12823
14819
|
};
|
|
12824
14820
|
async function withShieldRetries(attempt, hooks = {}) {
|
|
12825
14821
|
const attempts = hooks.attempts ?? 3;
|
|
12826
|
-
const
|
|
14822
|
+
const sleep5 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
12827
14823
|
let last = "";
|
|
12828
14824
|
for (let n = 1; n <= attempts; n++) {
|
|
12829
14825
|
if (n > 1) {
|
|
12830
14826
|
const delay = retryDelayMs(n);
|
|
12831
14827
|
hooks.onRetry?.(n, delay, last);
|
|
12832
|
-
await
|
|
14828
|
+
await sleep5(delay);
|
|
12833
14829
|
}
|
|
12834
14830
|
try {
|
|
12835
14831
|
return await attempt(n);
|
|
@@ -12877,6 +14873,10 @@ export {
|
|
|
12877
14873
|
MemoryStorageAdapter,
|
|
12878
14874
|
MerkleTree,
|
|
12879
14875
|
NATIVE_SOL_MINT,
|
|
14876
|
+
NOTE_INDEX_NO_LEAF,
|
|
14877
|
+
NOTE_INDEX_PAGE_SIZE,
|
|
14878
|
+
NoteIndexFormatError,
|
|
14879
|
+
NoteIndexHeadBehindError,
|
|
12880
14880
|
ONECLICK_PUBKEY_B58,
|
|
12881
14881
|
RECIPIENT_DELIVERY_CIPHERTEXT_LEN,
|
|
12882
14882
|
RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
|
|
@@ -12953,6 +14953,7 @@ export {
|
|
|
12953
14953
|
computeChainNoteHash,
|
|
12954
14954
|
computeExtDataHash,
|
|
12955
14955
|
computeMerkleRoot,
|
|
14956
|
+
computeNoteIndexChain,
|
|
12956
14957
|
computeProofForLatestDeposit,
|
|
12957
14958
|
computeProofFromChain,
|
|
12958
14959
|
computeSignature,
|
|
@@ -12989,6 +14990,7 @@ export {
|
|
|
12989
14990
|
deriveSpendKey,
|
|
12990
14991
|
deriveSwapRefundAuthorization,
|
|
12991
14992
|
deriveSwapRefundBlinding,
|
|
14993
|
+
deriveSwapRefundKeypair,
|
|
12992
14994
|
deriveUserCompliancePublicKey,
|
|
12993
14995
|
deriveUserComplianceScalar,
|
|
12994
14996
|
deriveUtxoKeypairFromSpendKey,
|
|
@@ -13001,6 +15003,8 @@ export {
|
|
|
13001
15003
|
discoverSwapRefunds,
|
|
13002
15004
|
downloadNote,
|
|
13003
15005
|
encodeDeliveryCarrierMemo,
|
|
15006
|
+
encodeNoteIndexItem,
|
|
15007
|
+
encodeNoteIndexPage,
|
|
13004
15008
|
encodeNoteSimple,
|
|
13005
15009
|
encodeRecipientDeliveryNote,
|
|
13006
15010
|
encryptCompactChainNote,
|
|
@@ -13016,6 +15020,8 @@ export {
|
|
|
13016
15020
|
fetchCommitments,
|
|
13017
15021
|
fetchLatestBlockhash,
|
|
13018
15022
|
fetchLookupTables,
|
|
15023
|
+
fetchNoteIndexHead,
|
|
15024
|
+
fetchNoteIndexPage,
|
|
13019
15025
|
fetchRiskQuoteInstruction,
|
|
13020
15026
|
fetchRiskQuoteIx,
|
|
13021
15027
|
fetchSignaturesForAddress,
|
|
@@ -13088,6 +15094,8 @@ export {
|
|
|
13088
15094
|
parseDeliveryCarrierMemo,
|
|
13089
15095
|
parseError,
|
|
13090
15096
|
parseNote2 as parseNote,
|
|
15097
|
+
parseNoteIndexItem,
|
|
15098
|
+
parseNoteIndexPage,
|
|
13091
15099
|
parseRelayErrorResponse,
|
|
13092
15100
|
parseRelayErrorSignature,
|
|
13093
15101
|
parseTransactionError,
|
|
@@ -13109,6 +15117,7 @@ export {
|
|
|
13109
15117
|
readMerkleTreeState,
|
|
13110
15118
|
readRent,
|
|
13111
15119
|
recipientDeliveryNoteToBase64,
|
|
15120
|
+
recoverNotesFromIndex,
|
|
13112
15121
|
registerViewingKey,
|
|
13113
15122
|
relayRequestDigestHex,
|
|
13114
15123
|
removePendingDeposit,
|