@cloak.dev/sdk 0.2.6-staging.af2dfc0 → 0.2.6
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 +1920 -58
- package/dist/index.d.cts +468 -1
- package/dist/index.d.ts +468 -1
- package/dist/index.js +1906 -60
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -676,7 +676,7 @@ function parseStrictViewingKeyChallenge(response, userPubkey, viewingKeyHex) {
|
|
|
676
676
|
|
|
677
677
|
// src/config/relay.ts
|
|
678
678
|
var CLOAK_PRODUCTION_RELAY_URL = "https://api.cloak.ag";
|
|
679
|
-
var RELAY_ORIGIN_ALLOWLIST = [
|
|
679
|
+
var RELAY_ORIGIN_ALLOWLIST = [CLOAK_PRODUCTION_RELAY_URL];
|
|
680
680
|
var ABSOLUTE_URL = /^[a-z][a-z0-9+.-]*:\/\//i;
|
|
681
681
|
var LOOPBACK_IPV4 = /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
|
|
682
682
|
var THIS_NETWORK_IPV4 = /^0\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
|
|
@@ -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-]+$/;
|
|
@@ -3970,6 +3970,27 @@ function isRootAccepted(data, rootHex) {
|
|
|
3970
3970
|
const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
|
|
3971
3971
|
return readRootHistory(data).some((r) => r === want);
|
|
3972
3972
|
}
|
|
3973
|
+
function treeAccountAcceptsRoot(data, rootHex) {
|
|
3974
|
+
const want = rootHex.toLowerCase().replace(/^0x/, "").padStart(64, "0");
|
|
3975
|
+
if (data.length >= ROOT_OFFSET + 32) {
|
|
3976
|
+
const current = Buffer.from(data.subarray(ROOT_OFFSET, ROOT_OFFSET + 32)).toString("hex");
|
|
3977
|
+
if (current === want) return true;
|
|
3978
|
+
}
|
|
3979
|
+
return isRootAccepted(data, want);
|
|
3980
|
+
}
|
|
3981
|
+
function readTreeAccountFrontier(data) {
|
|
3982
|
+
if (!data || data.length < ROOT_INDEX_OFFSET + 8) return null;
|
|
3983
|
+
const buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
|
|
3984
|
+
const next = readBigUInt64LE(buf, 32);
|
|
3985
|
+
if (next > 2n ** BigInt(MERKLE_TREE_HEIGHT)) return null;
|
|
3986
|
+
const subtrees = [];
|
|
3987
|
+
for (let level = 0; level < MERKLE_TREE_HEIGHT; level++) {
|
|
3988
|
+
const offset = SUBTREES_OFFSET + level * 32;
|
|
3989
|
+
subtrees.push(BigInt("0x" + buf.subarray(offset, offset + 32).toString("hex")));
|
|
3990
|
+
}
|
|
3991
|
+
const root = BigInt("0x" + buf.subarray(ROOT_OFFSET, ROOT_OFFSET + 32).toString("hex"));
|
|
3992
|
+
return { nextIndex: Number(next), subtrees, root };
|
|
3993
|
+
}
|
|
3973
3994
|
|
|
3974
3995
|
// src/proving/merkle.ts
|
|
3975
3996
|
import { buildPoseidon } from "circomlibjs";
|
|
@@ -4129,6 +4150,89 @@ var MerkleTree = class _MerkleTree {
|
|
|
4129
4150
|
async function buildMerkleTree(commitments, height = MERKLE_TREE_HEIGHT2) {
|
|
4130
4151
|
return MerkleTree.create(height, commitments);
|
|
4131
4152
|
}
|
|
4153
|
+
var MerkleFrontier = class _MerkleFrontier {
|
|
4154
|
+
constructor(levels, zeros, poseidon2, count, left) {
|
|
4155
|
+
this.levels = levels;
|
|
4156
|
+
this.zeros = zeros;
|
|
4157
|
+
this.poseidon = poseidon2;
|
|
4158
|
+
this.count = count;
|
|
4159
|
+
this.left = left;
|
|
4160
|
+
}
|
|
4161
|
+
static async create(state, levels = MERKLE_TREE_HEIGHT2) {
|
|
4162
|
+
const zeros = await getZeroValues();
|
|
4163
|
+
const poseidon2 = await getPoseidon();
|
|
4164
|
+
const left = new Array(levels).fill(null);
|
|
4165
|
+
let count = 0;
|
|
4166
|
+
if (state) {
|
|
4167
|
+
if (!Number.isSafeInteger(state.nextIndex) || state.nextIndex < 0 || state.nextIndex > 2 ** levels) {
|
|
4168
|
+
throw new Error("MerkleFrontierState.nextIndex out of range");
|
|
4169
|
+
}
|
|
4170
|
+
if (!Array.isArray(state.left) || state.left.length !== levels) {
|
|
4171
|
+
throw new Error(`MerkleFrontierState.left must have ${levels} entries`);
|
|
4172
|
+
}
|
|
4173
|
+
count = state.nextIndex;
|
|
4174
|
+
for (let l = 0; l < levels; l++) {
|
|
4175
|
+
const odd = Math.floor(count / 2 ** l) % 2 === 1;
|
|
4176
|
+
const entry = state.left[l];
|
|
4177
|
+
if (odd !== (entry !== "")) throw new Error(`MerkleFrontierState.left[${l}] disagrees with nextIndex`);
|
|
4178
|
+
if (odd) {
|
|
4179
|
+
if (!/^[0-9a-f]{64}$/.test(entry)) throw new Error(`MerkleFrontierState.left[${l}] is not 32-byte hex`);
|
|
4180
|
+
left[l] = BigInt("0x" + entry);
|
|
4181
|
+
}
|
|
4182
|
+
}
|
|
4183
|
+
}
|
|
4184
|
+
return new _MerkleFrontier(levels, zeros, poseidon2, count, left);
|
|
4185
|
+
}
|
|
4186
|
+
get nextIndex() {
|
|
4187
|
+
return this.count;
|
|
4188
|
+
}
|
|
4189
|
+
/**
|
|
4190
|
+
* The complete LEFT node held at `level`: the node at index `floor(nextIndex / 2^level) - 1`,
|
|
4191
|
+
* present only while that index is even (bit `level` of `nextIndex` is set), else `null`.
|
|
4192
|
+
* With every set bit of `nextIndex`, these nodes cover leaves `[0, nextIndex)` exactly.
|
|
4193
|
+
*/
|
|
4194
|
+
leftAt(level) {
|
|
4195
|
+
if (!Number.isInteger(level) || level < 0 || level >= this.levels) return null;
|
|
4196
|
+
return this.left[level];
|
|
4197
|
+
}
|
|
4198
|
+
hash(a, b) {
|
|
4199
|
+
return this.poseidon.F.toObject(this.poseidon([a, b]));
|
|
4200
|
+
}
|
|
4201
|
+
/** Append leaves at indices `nextIndex .. nextIndex + leaves.length - 1`. */
|
|
4202
|
+
append(leaves) {
|
|
4203
|
+
if (leaves.length === 0) return;
|
|
4204
|
+
if (this.count + leaves.length > 2 ** this.levels) throw new Error("Tree is full");
|
|
4205
|
+
let nodes = leaves;
|
|
4206
|
+
for (let l = 0; l < this.levels && nodes.length > 0; l++) {
|
|
4207
|
+
const before = Math.floor(this.count / 2 ** l);
|
|
4208
|
+
const seq = before % 2 === 1 ? [this.left[l], ...nodes] : nodes;
|
|
4209
|
+
const parents = [];
|
|
4210
|
+
for (let i = 0; i + 1 < seq.length; i += 2) parents.push(this.hash(seq[i], seq[i + 1]));
|
|
4211
|
+
this.left[l] = (before + nodes.length) % 2 === 1 ? seq[seq.length - 1] : null;
|
|
4212
|
+
nodes = parents;
|
|
4213
|
+
}
|
|
4214
|
+
this.count += leaves.length;
|
|
4215
|
+
}
|
|
4216
|
+
/** The root of the first `nextIndex` leaves, zero-padded to the right. */
|
|
4217
|
+
root() {
|
|
4218
|
+
let partial = this.zeros[0];
|
|
4219
|
+
for (let l = 0; l < this.levels; l++) {
|
|
4220
|
+
const odd = Math.floor(this.count / 2 ** l) % 2 === 1;
|
|
4221
|
+
if (odd) partial = this.hash(this.left[l], partial);
|
|
4222
|
+
else partial = partial === this.zeros[l] ? this.zeros[l + 1] : this.hash(partial, this.zeros[l]);
|
|
4223
|
+
}
|
|
4224
|
+
return partial;
|
|
4225
|
+
}
|
|
4226
|
+
toState() {
|
|
4227
|
+
return {
|
|
4228
|
+
nextIndex: this.count,
|
|
4229
|
+
left: this.left.map((v) => v === null ? "" : v.toString(16).padStart(64, "0"))
|
|
4230
|
+
};
|
|
4231
|
+
}
|
|
4232
|
+
clone() {
|
|
4233
|
+
return new _MerkleFrontier(this.levels, this.zeros, this.poseidon, this.count, [...this.left]);
|
|
4234
|
+
}
|
|
4235
|
+
};
|
|
4132
4236
|
|
|
4133
4237
|
// src/config/transaction-version.ts
|
|
4134
4238
|
var MAX_SUPPORTED_TRANSACTION_VERSION = 1;
|
|
@@ -4641,38 +4745,77 @@ async function aesGcmDecrypt2(ciphertext, keyBytes, nonce) {
|
|
|
4641
4745
|
const plaintext = await subtle.decrypt({ name: "AES-GCM", iv: toArrayBuffer2(nonce) }, key, toArrayBuffer2(ciphertext));
|
|
4642
4746
|
return new Uint8Array(plaintext);
|
|
4643
4747
|
}
|
|
4644
|
-
async function
|
|
4748
|
+
async function importNkHkdfKey(nk) {
|
|
4645
4749
|
if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
|
|
4646
4750
|
throw new Error("nk must be 32 bytes");
|
|
4647
4751
|
}
|
|
4752
|
+
return getSubtleCrypto2().importKey("raw", toArrayBuffer2(nk), "HKDF", false, ["deriveBits"]);
|
|
4753
|
+
}
|
|
4754
|
+
async function deriveAesKeyAndNonceFromIkm(ikm, salt) {
|
|
4648
4755
|
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
|
-
);
|
|
4756
|
+
const [keyBits, nonceBits] = await Promise.all([
|
|
4757
|
+
subtle.deriveBits(
|
|
4758
|
+
{
|
|
4759
|
+
name: "HKDF",
|
|
4760
|
+
hash: "SHA-256",
|
|
4761
|
+
salt: toArrayBuffer2(salt),
|
|
4762
|
+
info: toArrayBuffer2(CHAIN_NOTE_KEY_INFO)
|
|
4763
|
+
},
|
|
4764
|
+
ikm,
|
|
4765
|
+
256
|
|
4766
|
+
),
|
|
4767
|
+
subtle.deriveBits(
|
|
4768
|
+
{
|
|
4769
|
+
name: "HKDF",
|
|
4770
|
+
hash: "SHA-256",
|
|
4771
|
+
salt: toArrayBuffer2(salt),
|
|
4772
|
+
info: toArrayBuffer2(CHAIN_NOTE_NONCE_INFO)
|
|
4773
|
+
},
|
|
4774
|
+
ikm,
|
|
4775
|
+
96
|
|
4776
|
+
)
|
|
4777
|
+
]);
|
|
4671
4778
|
return {
|
|
4672
4779
|
key: new Uint8Array(keyBits),
|
|
4673
4780
|
nonce: new Uint8Array(nonceBits)
|
|
4674
4781
|
};
|
|
4675
4782
|
}
|
|
4783
|
+
async function deriveAesKeyAndNonce(nk, commitmentHex) {
|
|
4784
|
+
const ikm = await importNkHkdfKey(nk);
|
|
4785
|
+
return deriveAesKeyAndNonceFromIkm(ikm, hexToBytes32(commitmentHex));
|
|
4786
|
+
}
|
|
4787
|
+
function decodeChainNotePlaintext(version, plaintext, commitmentHex) {
|
|
4788
|
+
if (version === NOTE_VERSION_V4) {
|
|
4789
|
+
if (plaintext.length !== PLAINTEXT_LEN_V4) {
|
|
4790
|
+
throw new Error(`Invalid v4 chain note plaintext length: ${plaintext.length}`);
|
|
4791
|
+
}
|
|
4792
|
+
return {
|
|
4793
|
+
timestamp: readU64LE(plaintext, 0),
|
|
4794
|
+
commitment: commitmentHex.toLowerCase(),
|
|
4795
|
+
noteSalt: readU256BE(plaintext, TIMESTAMP_LEN),
|
|
4796
|
+
outAmount0: readU64LE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN),
|
|
4797
|
+
outPubkey0: readU256BE(plaintext, TIMESTAMP_LEN + NOTE_SALT_LEN + OUT_AMOUNT_LEN),
|
|
4798
|
+
isSendToSelfKey0: BigInt(plaintext[PLAINTEXT_LEN_V4 - 1])
|
|
4799
|
+
};
|
|
4800
|
+
}
|
|
4801
|
+
if (version === NOTE_VERSION_V3) {
|
|
4802
|
+
if (plaintext.length !== PLAINTEXT_LEN_V3) {
|
|
4803
|
+
throw new Error(`Invalid v3 chain note plaintext length: ${plaintext.length}`);
|
|
4804
|
+
}
|
|
4805
|
+
return {
|
|
4806
|
+
timestamp: readU64LE(plaintext, 0),
|
|
4807
|
+
commitment: commitmentHex.toLowerCase(),
|
|
4808
|
+
noteSalt: readU256BE(plaintext, TIMESTAMP_LEN)
|
|
4809
|
+
};
|
|
4810
|
+
}
|
|
4811
|
+
if (plaintext.length !== PLAINTEXT_LEN_V2) {
|
|
4812
|
+
throw new Error(`Invalid v2 chain note plaintext length: ${plaintext.length}`);
|
|
4813
|
+
}
|
|
4814
|
+
return {
|
|
4815
|
+
timestamp: readU64LE(plaintext, 0),
|
|
4816
|
+
commitment: commitmentHex.toLowerCase()
|
|
4817
|
+
};
|
|
4818
|
+
}
|
|
4676
4819
|
async function encryptCompactChainNote(timestamp, nk, commitmentHex, noteSalt, semantics) {
|
|
4677
4820
|
if (!nk || !(nk instanceof Uint8Array) || nk.length !== 32) {
|
|
4678
4821
|
throw new Error("nk must be 32 bytes");
|
|
@@ -4736,36 +4879,7 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
|
|
|
4736
4879
|
try {
|
|
4737
4880
|
const { key, nonce } = await deriveAesKeyAndNonce(nk, commitment);
|
|
4738
4881
|
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
|
-
};
|
|
4882
|
+
return decodeChainNotePlaintext(version, plaintext, commitment);
|
|
4769
4883
|
} catch (error) {
|
|
4770
4884
|
lastError = error;
|
|
4771
4885
|
}
|
|
@@ -4774,6 +4888,26 @@ async function decryptCompactChainNote(noteBytes, nk, candidateCommitments) {
|
|
|
4774
4888
|
`Failed to decrypt compact chain note with provided commitments: ${lastError instanceof Error ? lastError.message : String(lastError)}`
|
|
4775
4889
|
);
|
|
4776
4890
|
}
|
|
4891
|
+
async function createCompactChainNoteDecryptor(nk) {
|
|
4892
|
+
const ikm = await importNkHkdfKey(nk);
|
|
4893
|
+
return async (noteBytes, commitment) => {
|
|
4894
|
+
if (!(noteBytes instanceof Uint8Array) || noteBytes.length <= 1) return null;
|
|
4895
|
+
if (!(commitment instanceof Uint8Array) || commitment.length !== 32) return null;
|
|
4896
|
+
const version = noteBytes[0];
|
|
4897
|
+
if (version !== NOTE_VERSION_V4 && version !== NOTE_VERSION_V3 && version !== NOTE_VERSION_V2) {
|
|
4898
|
+
return null;
|
|
4899
|
+
}
|
|
4900
|
+
try {
|
|
4901
|
+
const { key, nonce } = await deriveAesKeyAndNonceFromIkm(ikm, commitment);
|
|
4902
|
+
const plaintext = await aesGcmDecrypt2(noteBytes.subarray(1), key, nonce);
|
|
4903
|
+
let hex = "";
|
|
4904
|
+
for (let i = 0; i < 32; i++) hex += commitment[i].toString(16).padStart(2, "0");
|
|
4905
|
+
return decodeChainNotePlaintext(version, plaintext, hex);
|
|
4906
|
+
} catch {
|
|
4907
|
+
return null;
|
|
4908
|
+
}
|
|
4909
|
+
};
|
|
4910
|
+
}
|
|
4777
4911
|
function chainNoteToBase64(noteBytes) {
|
|
4778
4912
|
return Buffer.from(noteBytes).toString("base64");
|
|
4779
4913
|
}
|
|
@@ -4870,6 +5004,80 @@ function openRecipientDeliveryNote(envelope, viewingSecretKey) {
|
|
|
4870
5004
|
return null;
|
|
4871
5005
|
}
|
|
4872
5006
|
}
|
|
5007
|
+
var X25519_PKCS8_PREFIX = Uint8Array.from([
|
|
5008
|
+
48,
|
|
5009
|
+
46,
|
|
5010
|
+
2,
|
|
5011
|
+
1,
|
|
5012
|
+
0,
|
|
5013
|
+
48,
|
|
5014
|
+
5,
|
|
5015
|
+
6,
|
|
5016
|
+
3,
|
|
5017
|
+
43,
|
|
5018
|
+
101,
|
|
5019
|
+
110,
|
|
5020
|
+
4,
|
|
5021
|
+
34,
|
|
5022
|
+
4,
|
|
5023
|
+
32
|
|
5024
|
+
]);
|
|
5025
|
+
var HSALSA_SIGMA = new TextEncoder().encode("expand 32-byte k");
|
|
5026
|
+
function decodeOpened(plaintext) {
|
|
5027
|
+
if (!plaintext || plaintext.length !== RECIPIENT_DELIVERY_PLAINTEXT_LEN) return null;
|
|
5028
|
+
return { amount: readU64LE2(plaintext, 0), blinding: readU256BE2(plaintext, 8) };
|
|
5029
|
+
}
|
|
5030
|
+
async function createRecipientDeliveryOpener(viewingSecretKey) {
|
|
5031
|
+
if (!(viewingSecretKey instanceof Uint8Array) || viewingSecretKey.length !== 32) {
|
|
5032
|
+
throw new Error("viewingSecretKey must be 32 bytes");
|
|
5033
|
+
}
|
|
5034
|
+
const slow = async (envelope) => openRecipientDeliveryNote(envelope, viewingSecretKey);
|
|
5035
|
+
const subtle = globalThis.crypto?.subtle;
|
|
5036
|
+
const hsalsa = nacl4.lowlevel?.crypto_core_hsalsa20;
|
|
5037
|
+
if (!subtle || typeof hsalsa !== "function") return slow;
|
|
5038
|
+
let privateKey;
|
|
5039
|
+
const sharedKey = async (ephemeralPk) => {
|
|
5040
|
+
const publicKey = await subtle.importKey("raw", new Uint8Array(ephemeralPk), { name: "X25519" }, false, []);
|
|
5041
|
+
const shared = new Uint8Array(
|
|
5042
|
+
await subtle.deriveBits({ name: "X25519", public: publicKey }, privateKey, 256)
|
|
5043
|
+
);
|
|
5044
|
+
const key = new Uint8Array(32);
|
|
5045
|
+
hsalsa(key, new Uint8Array(16), shared, HSALSA_SIGMA);
|
|
5046
|
+
return key;
|
|
5047
|
+
};
|
|
5048
|
+
try {
|
|
5049
|
+
const pkcs8 = new Uint8Array(X25519_PKCS8_PREFIX.length + 32);
|
|
5050
|
+
pkcs8.set(X25519_PKCS8_PREFIX);
|
|
5051
|
+
pkcs8.set(viewingSecretKey, X25519_PKCS8_PREFIX.length);
|
|
5052
|
+
privateKey = await subtle.importKey("pkcs8", pkcs8, { name: "X25519" }, false, ["deriveBits"]);
|
|
5053
|
+
const probe = nacl4.box.keyPair().publicKey;
|
|
5054
|
+
const fast = await sharedKey(probe);
|
|
5055
|
+
const reference = nacl4.box.before(probe, viewingSecretKey);
|
|
5056
|
+
if (fast.length !== reference.length || fast.some((b, i) => b !== reference[i])) return slow;
|
|
5057
|
+
} catch {
|
|
5058
|
+
return slow;
|
|
5059
|
+
}
|
|
5060
|
+
return async (envelope) => {
|
|
5061
|
+
if (!(envelope instanceof Uint8Array) || envelope.length !== RECIPIENT_DELIVERY_NOTE_BYTES) return null;
|
|
5062
|
+
const ephemeralPk = envelope.subarray(0, RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN);
|
|
5063
|
+
const nonce = envelope.subarray(
|
|
5064
|
+
RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
|
|
5065
|
+
RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN
|
|
5066
|
+
);
|
|
5067
|
+
const ciphertext = envelope.subarray(RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN + RECIPIENT_DELIVERY_NONCE_LEN);
|
|
5068
|
+
let key;
|
|
5069
|
+
try {
|
|
5070
|
+
key = await sharedKey(ephemeralPk);
|
|
5071
|
+
} catch {
|
|
5072
|
+
return openRecipientDeliveryNote(envelope, viewingSecretKey);
|
|
5073
|
+
}
|
|
5074
|
+
try {
|
|
5075
|
+
return decodeOpened(nacl4.secretbox.open(ciphertext, nonce, key));
|
|
5076
|
+
} catch {
|
|
5077
|
+
return null;
|
|
5078
|
+
}
|
|
5079
|
+
};
|
|
5080
|
+
}
|
|
4873
5081
|
function recipientDeliveryNoteToBase64(envelope) {
|
|
4874
5082
|
return Buffer.from(envelope).toString("base64");
|
|
4875
5083
|
}
|
|
@@ -11613,6 +11821,1632 @@ function formatComplianceCsv(report) {
|
|
|
11613
11821
|
return header + rows;
|
|
11614
11822
|
}
|
|
11615
11823
|
|
|
11824
|
+
// src/relay/note-index-format.ts
|
|
11825
|
+
import { sha256 as sha2565 } from "@noble/hashes/sha2";
|
|
11826
|
+
var NOTE_INDEX_MAGIC = new Uint8Array([67, 78, 73, 49]);
|
|
11827
|
+
var NOTE_INDEX_FORMAT_VERSION = 1;
|
|
11828
|
+
var NOTE_INDEX_PAGE_SIZE = 1024;
|
|
11829
|
+
var NOTE_INDEX_NO_LEAF = 0xffffffffffffffffn;
|
|
11830
|
+
var NOTE_INDEX_MAX_PAGE_BYTES = 2 * 1024 * 1024;
|
|
11831
|
+
var NOTE_INDEX_HEADER_LEN = 68;
|
|
11832
|
+
var NOTE_INDEX_KIND_TX = 1;
|
|
11833
|
+
var NOTE_INDEX_KIND_DELIVERY = 2;
|
|
11834
|
+
var NOTE_INDEX_KIND_SWAP_REFUND = 3;
|
|
11835
|
+
var NOTE_SOURCE_NONE = 0;
|
|
11836
|
+
var NOTE_SOURCE_CARRIER = 2;
|
|
11837
|
+
var ITEM_HEADER_LEN = 3;
|
|
11838
|
+
var TX_FIXED_LEN = 263;
|
|
11839
|
+
var DELIVERY_BODY_LEN = 256;
|
|
11840
|
+
var SWAP_REFUND_BODY_LEN = 184;
|
|
11841
|
+
var MAX_UNKNOWN_BODY_LEN = 1024;
|
|
11842
|
+
var DELIVERY_ENVELOPE_LEN = 112;
|
|
11843
|
+
var SIGNATURE_LEN = 64;
|
|
11844
|
+
var NOTE_VERSION_BY_LEN = /* @__PURE__ */ new Map([
|
|
11845
|
+
[25, 2],
|
|
11846
|
+
[57, 3],
|
|
11847
|
+
[98, 4]
|
|
11848
|
+
]);
|
|
11849
|
+
var COMPLETE_FLAG = 1;
|
|
11850
|
+
var U64_MAX2 = (1n << 64n) - 1n;
|
|
11851
|
+
var U32_MAX = 4294967295;
|
|
11852
|
+
var MAX_LEAF_INDEX = (1n << 32n) - 1n;
|
|
11853
|
+
var WSOL_BYTES = addressBytes(NATIVE_SOL_MINT);
|
|
11854
|
+
var NoteIndexFormatError = class extends Error {
|
|
11855
|
+
constructor(message) {
|
|
11856
|
+
super(`Note index format error: ${message}`);
|
|
11857
|
+
this.name = "NoteIndexFormatError";
|
|
11858
|
+
}
|
|
11859
|
+
};
|
|
11860
|
+
function isAllZero2(bytes) {
|
|
11861
|
+
for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
|
|
11862
|
+
return true;
|
|
11863
|
+
}
|
|
11864
|
+
function bytesEqual(a, b) {
|
|
11865
|
+
if (a.length !== b.length) return false;
|
|
11866
|
+
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
|
|
11867
|
+
return true;
|
|
11868
|
+
}
|
|
11869
|
+
function checkLeafPair(commitment, leaf, label) {
|
|
11870
|
+
if (isAllZero2(commitment)) {
|
|
11871
|
+
if (leaf !== NOTE_INDEX_NO_LEAF) throw new NoteIndexFormatError(`${label}: zero commitment must carry NO_LEAF`);
|
|
11872
|
+
return;
|
|
11873
|
+
}
|
|
11874
|
+
if (leaf > MAX_LEAF_INDEX) throw new NoteIndexFormatError(`${label}: leaf ${leaf} is not a leaf of the tree`);
|
|
11875
|
+
}
|
|
11876
|
+
var Reader = class {
|
|
11877
|
+
constructor(bytes, start, end) {
|
|
11878
|
+
this.bytes = bytes;
|
|
11879
|
+
this.end = end;
|
|
11880
|
+
this.offset = start;
|
|
11881
|
+
this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
11882
|
+
}
|
|
11883
|
+
take(len) {
|
|
11884
|
+
if (this.offset + len > this.end) throw new NoteIndexFormatError("truncated item body");
|
|
11885
|
+
const at = this.offset;
|
|
11886
|
+
this.offset += len;
|
|
11887
|
+
return at;
|
|
11888
|
+
}
|
|
11889
|
+
u8() {
|
|
11890
|
+
return this.bytes[this.take(1)];
|
|
11891
|
+
}
|
|
11892
|
+
u32() {
|
|
11893
|
+
return this.view.getUint32(this.take(4), true);
|
|
11894
|
+
}
|
|
11895
|
+
u64() {
|
|
11896
|
+
return this.view.getBigUint64(this.take(8), true);
|
|
11897
|
+
}
|
|
11898
|
+
i64() {
|
|
11899
|
+
return this.view.getBigInt64(this.take(8), true);
|
|
11900
|
+
}
|
|
11901
|
+
raw(len) {
|
|
11902
|
+
const at = this.take(len);
|
|
11903
|
+
return this.bytes.slice(at, at + len);
|
|
11904
|
+
}
|
|
11905
|
+
get position() {
|
|
11906
|
+
return this.offset;
|
|
11907
|
+
}
|
|
11908
|
+
};
|
|
11909
|
+
function parseTx(r, bodyLen) {
|
|
11910
|
+
const mint = r.raw(32);
|
|
11911
|
+
const slot = r.u64();
|
|
11912
|
+
const blockPos = r.u32();
|
|
11913
|
+
const ixTag = r.u8();
|
|
11914
|
+
if (ixTag !== 0 && ixTag !== 1) throw new NoteIndexFormatError(`TX: ix_tag ${ixTag}`);
|
|
11915
|
+
const publicAmount = r.i64();
|
|
11916
|
+
const nullifier0 = r.raw(32);
|
|
11917
|
+
const nullifier1 = r.raw(32);
|
|
11918
|
+
const comm0 = r.raw(32);
|
|
11919
|
+
const leaf0 = r.u64();
|
|
11920
|
+
const comm1 = r.raw(32);
|
|
11921
|
+
const leaf1 = r.u64();
|
|
11922
|
+
const noteSource = r.u8();
|
|
11923
|
+
if (noteSource > NOTE_SOURCE_CARRIER) throw new NoteIndexFormatError(`TX: note_source ${noteSource}`);
|
|
11924
|
+
const noteLen = r.u8();
|
|
11925
|
+
if (noteSource === NOTE_SOURCE_NONE) {
|
|
11926
|
+
if (noteLen !== 0) throw new NoteIndexFormatError(`TX: note_len ${noteLen} without a note source`);
|
|
11927
|
+
} else if (!NOTE_VERSION_BY_LEN.has(noteLen)) {
|
|
11928
|
+
throw new NoteIndexFormatError(`TX: note_len ${noteLen}`);
|
|
11929
|
+
}
|
|
11930
|
+
if (bodyLen !== TX_FIXED_LEN + noteLen) {
|
|
11931
|
+
throw new NoteIndexFormatError(`TX: body_len ${bodyLen} != ${TX_FIXED_LEN + noteLen} for note_len ${noteLen}`);
|
|
11932
|
+
}
|
|
11933
|
+
const note = r.raw(noteLen);
|
|
11934
|
+
if (noteLen > 0 && note[0] !== NOTE_VERSION_BY_LEN.get(noteLen)) {
|
|
11935
|
+
throw new NoteIndexFormatError(`TX: note version ${note[0]} does not match note_len ${noteLen}`);
|
|
11936
|
+
}
|
|
11937
|
+
const signature = r.raw(SIGNATURE_LEN);
|
|
11938
|
+
checkLeafPair(comm0, leaf0, "TX comm0");
|
|
11939
|
+
checkLeafPair(comm1, leaf1, "TX comm1");
|
|
11940
|
+
return {
|
|
11941
|
+
kind: 1,
|
|
11942
|
+
mint,
|
|
11943
|
+
slot,
|
|
11944
|
+
blockPos,
|
|
11945
|
+
ixTag,
|
|
11946
|
+
publicAmount,
|
|
11947
|
+
nullifier0,
|
|
11948
|
+
nullifier1,
|
|
11949
|
+
comm0,
|
|
11950
|
+
leaf0,
|
|
11951
|
+
comm1,
|
|
11952
|
+
leaf1,
|
|
11953
|
+
noteSource,
|
|
11954
|
+
note,
|
|
11955
|
+
signature
|
|
11956
|
+
};
|
|
11957
|
+
}
|
|
11958
|
+
function parseDelivery(r) {
|
|
11959
|
+
const mint = r.raw(32);
|
|
11960
|
+
const slot = r.u64();
|
|
11961
|
+
const commitment = r.raw(32);
|
|
11962
|
+
const leaf = r.u64();
|
|
11963
|
+
const envelope = r.raw(DELIVERY_ENVELOPE_LEN);
|
|
11964
|
+
const signature = r.raw(SIGNATURE_LEN);
|
|
11965
|
+
if (isAllZero2(commitment)) throw new NoteIndexFormatError("DELIVERY: zero commitment");
|
|
11966
|
+
checkLeafPair(commitment, leaf, "DELIVERY");
|
|
11967
|
+
return { kind: 2, mint, slot, commitment, leaf, envelope, signature };
|
|
11968
|
+
}
|
|
11969
|
+
function parseSwapRefund(r) {
|
|
11970
|
+
const mint = r.raw(32);
|
|
11971
|
+
if (!bytesEqual(mint, WSOL_BYTES)) throw new NoteIndexFormatError("SWAP_REFUND: mint is not WSOL");
|
|
11972
|
+
const slot = r.u64();
|
|
11973
|
+
const commitment = r.raw(32);
|
|
11974
|
+
const leaf = r.u64();
|
|
11975
|
+
const amountAfterFee = r.u64();
|
|
11976
|
+
const nullifier0 = r.raw(32);
|
|
11977
|
+
const signature = r.raw(SIGNATURE_LEN);
|
|
11978
|
+
if (isAllZero2(commitment)) throw new NoteIndexFormatError("SWAP_REFUND: zero commitment");
|
|
11979
|
+
checkLeafPair(commitment, leaf, "SWAP_REFUND");
|
|
11980
|
+
return { kind: 3, mint, slot, commitment, leaf, amountAfterFee, nullifier0, signature };
|
|
11981
|
+
}
|
|
11982
|
+
function parseNoteIndexPage(bytes, expect, options = {}) {
|
|
11983
|
+
if (!(bytes instanceof Uint8Array)) throw new NoteIndexFormatError("page must be a Uint8Array");
|
|
11984
|
+
if (bytes.length > NOTE_INDEX_MAX_PAGE_BYTES) {
|
|
11985
|
+
throw new NoteIndexFormatError(`page is ${bytes.length} bytes, over the ${NOTE_INDEX_MAX_PAGE_BYTES}-byte bound`);
|
|
11986
|
+
}
|
|
11987
|
+
if (bytes.length < NOTE_INDEX_HEADER_LEN) throw new NoteIndexFormatError("truncated page header");
|
|
11988
|
+
for (let i = 0; i < NOTE_INDEX_MAGIC.length; i++) {
|
|
11989
|
+
if (bytes[i] !== NOTE_INDEX_MAGIC[i]) throw new NoteIndexFormatError("bad magic");
|
|
11990
|
+
}
|
|
11991
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
11992
|
+
const version = bytes[4];
|
|
11993
|
+
if (version !== NOTE_INDEX_FORMAT_VERSION) throw new NoteIndexFormatError(`unsupported version ${version}`);
|
|
11994
|
+
const flags = bytes[5];
|
|
11995
|
+
if ((flags & ~COMPLETE_FLAG) !== 0) throw new NoteIndexFormatError(`unknown flag bits 0x${flags.toString(16)}`);
|
|
11996
|
+
if (view.getUint16(6, true) !== 0) throw new NoteIndexFormatError("reserved bytes are not zero");
|
|
11997
|
+
const epoch = view.getBigUint64(8, true);
|
|
11998
|
+
const page = view.getBigUint64(16, true);
|
|
11999
|
+
const firstSeq = view.getBigUint64(24, true);
|
|
12000
|
+
const count = view.getUint32(32, true);
|
|
12001
|
+
const prevChain = bytes.slice(36, 68);
|
|
12002
|
+
const complete = (flags & COMPLETE_FLAG) !== 0;
|
|
12003
|
+
if (expect) {
|
|
12004
|
+
if (epoch !== expect.epoch) throw new NoteIndexFormatError(`epoch ${epoch} is not the requested ${expect.epoch}`);
|
|
12005
|
+
if (page !== BigInt(expect.page)) throw new NoteIndexFormatError(`page ${page} is not the requested ${expect.page}`);
|
|
12006
|
+
}
|
|
12007
|
+
if (count > NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`count ${count} exceeds ${NOTE_INDEX_PAGE_SIZE}`);
|
|
12008
|
+
if (complete && count !== NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`complete page with count ${count}`);
|
|
12009
|
+
if (firstSeq !== page * BigInt(NOTE_INDEX_PAGE_SIZE)) {
|
|
12010
|
+
throw new NoteIndexFormatError(`first_seq ${firstSeq} is not page ${page} * ${NOTE_INDEX_PAGE_SIZE}`);
|
|
12011
|
+
}
|
|
12012
|
+
const items = [];
|
|
12013
|
+
const rawItems = [];
|
|
12014
|
+
const itemPositions = [];
|
|
12015
|
+
let skippedUnknown = 0;
|
|
12016
|
+
let skippedMalformed = 0;
|
|
12017
|
+
let offset = NOTE_INDEX_HEADER_LEN;
|
|
12018
|
+
for (let i = 0; i < count; i++) {
|
|
12019
|
+
if (offset + ITEM_HEADER_LEN > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} header`);
|
|
12020
|
+
const kind = bytes[offset];
|
|
12021
|
+
const bodyLen = view.getUint16(offset + 1, true);
|
|
12022
|
+
const bodyStart = offset + ITEM_HEADER_LEN;
|
|
12023
|
+
const bodyEnd = bodyStart + bodyLen;
|
|
12024
|
+
if (bodyEnd > bytes.length) throw new NoteIndexFormatError(`truncated item ${i} body`);
|
|
12025
|
+
if (kind !== NOTE_INDEX_KIND_TX && kind !== NOTE_INDEX_KIND_DELIVERY && kind !== NOTE_INDEX_KIND_SWAP_REFUND) {
|
|
12026
|
+
if (bodyLen > MAX_UNKNOWN_BODY_LEN) throw new NoteIndexFormatError(`unknown kind ${kind} with body_len ${bodyLen}`);
|
|
12027
|
+
skippedUnknown++;
|
|
12028
|
+
offset = bodyEnd;
|
|
12029
|
+
continue;
|
|
12030
|
+
}
|
|
12031
|
+
let item;
|
|
12032
|
+
try {
|
|
12033
|
+
item = parseKnownBody(bytes, kind, bodyStart, bodyEnd, i);
|
|
12034
|
+
} catch (error) {
|
|
12035
|
+
if (!options.skipMalformedItems || !(error instanceof NoteIndexFormatError)) throw error;
|
|
12036
|
+
skippedMalformed++;
|
|
12037
|
+
offset = bodyEnd;
|
|
12038
|
+
continue;
|
|
12039
|
+
}
|
|
12040
|
+
items.push(item);
|
|
12041
|
+
rawItems.push(bytes.slice(offset, bodyEnd));
|
|
12042
|
+
itemPositions.push(i);
|
|
12043
|
+
offset = bodyEnd;
|
|
12044
|
+
}
|
|
12045
|
+
if (offset !== bytes.length) throw new NoteIndexFormatError(`${bytes.length - offset} trailing bytes after ${count} items`);
|
|
12046
|
+
return { epoch, page, firstSeq, complete, count, prevChain, items, rawItems, skippedUnknown, itemPositions, skippedMalformed };
|
|
12047
|
+
}
|
|
12048
|
+
function parseKnownBody(bytes, kind, bodyStart, bodyEnd, i) {
|
|
12049
|
+
const bodyLen = bodyEnd - bodyStart;
|
|
12050
|
+
const r = new Reader(bytes, bodyStart, bodyEnd);
|
|
12051
|
+
let item;
|
|
12052
|
+
if (kind === NOTE_INDEX_KIND_TX) {
|
|
12053
|
+
if (bodyLen < TX_FIXED_LEN) throw new NoteIndexFormatError(`TX: body_len ${bodyLen}`);
|
|
12054
|
+
item = parseTx(r, bodyLen);
|
|
12055
|
+
} else if (kind === NOTE_INDEX_KIND_DELIVERY) {
|
|
12056
|
+
if (bodyLen !== DELIVERY_BODY_LEN) throw new NoteIndexFormatError(`DELIVERY: body_len ${bodyLen}`);
|
|
12057
|
+
item = parseDelivery(r);
|
|
12058
|
+
} else {
|
|
12059
|
+
if (bodyLen !== SWAP_REFUND_BODY_LEN) throw new NoteIndexFormatError(`SWAP_REFUND: body_len ${bodyLen}`);
|
|
12060
|
+
item = parseSwapRefund(r);
|
|
12061
|
+
}
|
|
12062
|
+
if (r.position !== bodyEnd) throw new NoteIndexFormatError(`item ${i} body has unread bytes`);
|
|
12063
|
+
return item;
|
|
12064
|
+
}
|
|
12065
|
+
function parseNoteIndexItem(raw) {
|
|
12066
|
+
if (!(raw instanceof Uint8Array) || raw.length < ITEM_HEADER_LEN) throw new NoteIndexFormatError("truncated item");
|
|
12067
|
+
const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
|
|
12068
|
+
const kind = raw[0];
|
|
12069
|
+
const bodyLen = view.getUint16(1, true);
|
|
12070
|
+
if (ITEM_HEADER_LEN + bodyLen !== raw.length) throw new NoteIndexFormatError("item length mismatch");
|
|
12071
|
+
const r = new Reader(raw, ITEM_HEADER_LEN, raw.length);
|
|
12072
|
+
let item;
|
|
12073
|
+
if (kind === NOTE_INDEX_KIND_TX && bodyLen >= TX_FIXED_LEN) item = parseTx(r, bodyLen);
|
|
12074
|
+
else if (kind === NOTE_INDEX_KIND_DELIVERY && bodyLen === DELIVERY_BODY_LEN) item = parseDelivery(r);
|
|
12075
|
+
else if (kind === NOTE_INDEX_KIND_SWAP_REFUND && bodyLen === SWAP_REFUND_BODY_LEN) item = parseSwapRefund(r);
|
|
12076
|
+
else throw new NoteIndexFormatError(`item kind ${kind} with body_len ${bodyLen}`);
|
|
12077
|
+
if (r.position !== raw.length) throw new NoteIndexFormatError("item body has unread bytes");
|
|
12078
|
+
return item;
|
|
12079
|
+
}
|
|
12080
|
+
function computeNoteIndexChain(prevChain, pageBytes) {
|
|
12081
|
+
if (!(prevChain instanceof Uint8Array) || prevChain.length !== 32) throw new NoteIndexFormatError("prevChain must be 32 bytes");
|
|
12082
|
+
if (pageBytes.length < NOTE_INDEX_HEADER_LEN) throw new NoteIndexFormatError("truncated page header");
|
|
12083
|
+
const items = pageBytes.subarray(NOTE_INDEX_HEADER_LEN);
|
|
12084
|
+
const input = new Uint8Array(32 + items.length);
|
|
12085
|
+
input.set(prevChain);
|
|
12086
|
+
input.set(items, 32);
|
|
12087
|
+
return sha2565(input);
|
|
12088
|
+
}
|
|
12089
|
+
var Writer = class {
|
|
12090
|
+
constructor() {
|
|
12091
|
+
this.chunks = [];
|
|
12092
|
+
this.length = 0;
|
|
12093
|
+
}
|
|
12094
|
+
push(bytes) {
|
|
12095
|
+
this.chunks.push(bytes);
|
|
12096
|
+
this.length += bytes.length;
|
|
12097
|
+
}
|
|
12098
|
+
u8(v) {
|
|
12099
|
+
if (!Number.isInteger(v) || v < 0 || v > 255) throw new NoteIndexFormatError(`u8 out of range: ${v}`);
|
|
12100
|
+
this.push(Uint8Array.of(v));
|
|
12101
|
+
}
|
|
12102
|
+
u16(v) {
|
|
12103
|
+
if (!Number.isInteger(v) || v < 0 || v > 65535) throw new NoteIndexFormatError(`u16 out of range: ${v}`);
|
|
12104
|
+
const b = new Uint8Array(2);
|
|
12105
|
+
new DataView(b.buffer).setUint16(0, v, true);
|
|
12106
|
+
this.push(b);
|
|
12107
|
+
}
|
|
12108
|
+
u32(v) {
|
|
12109
|
+
if (!Number.isInteger(v) || v < 0 || v > U32_MAX) throw new NoteIndexFormatError(`u32 out of range: ${v}`);
|
|
12110
|
+
const b = new Uint8Array(4);
|
|
12111
|
+
new DataView(b.buffer).setUint32(0, v, true);
|
|
12112
|
+
this.push(b);
|
|
12113
|
+
}
|
|
12114
|
+
u64(v) {
|
|
12115
|
+
if (v < 0n || v > U64_MAX2) throw new NoteIndexFormatError(`u64 out of range: ${v}`);
|
|
12116
|
+
const b = new Uint8Array(8);
|
|
12117
|
+
new DataView(b.buffer).setBigUint64(0, v, true);
|
|
12118
|
+
this.push(b);
|
|
12119
|
+
}
|
|
12120
|
+
i64(v) {
|
|
12121
|
+
if (v < -(1n << 63n) || v >= 1n << 63n) throw new NoteIndexFormatError(`i64 out of range: ${v}`);
|
|
12122
|
+
const b = new Uint8Array(8);
|
|
12123
|
+
new DataView(b.buffer).setBigInt64(0, v, true);
|
|
12124
|
+
this.push(b);
|
|
12125
|
+
}
|
|
12126
|
+
fixed(bytes, len, label) {
|
|
12127
|
+
if (!(bytes instanceof Uint8Array) || bytes.length !== len) throw new NoteIndexFormatError(`${label} must be ${len} bytes`);
|
|
12128
|
+
this.push(bytes);
|
|
12129
|
+
}
|
|
12130
|
+
finish() {
|
|
12131
|
+
const out = new Uint8Array(this.length);
|
|
12132
|
+
let off = 0;
|
|
12133
|
+
for (const c of this.chunks) {
|
|
12134
|
+
out.set(c, off);
|
|
12135
|
+
off += c.length;
|
|
12136
|
+
}
|
|
12137
|
+
return out;
|
|
12138
|
+
}
|
|
12139
|
+
};
|
|
12140
|
+
function encodeItemBody(item) {
|
|
12141
|
+
const w = new Writer();
|
|
12142
|
+
switch (item.kind) {
|
|
12143
|
+
case NOTE_INDEX_KIND_TX: {
|
|
12144
|
+
w.fixed(item.mint, 32, "mint");
|
|
12145
|
+
w.u64(item.slot);
|
|
12146
|
+
w.u32(item.blockPos);
|
|
12147
|
+
w.u8(item.ixTag);
|
|
12148
|
+
w.i64(item.publicAmount);
|
|
12149
|
+
w.fixed(item.nullifier0, 32, "nullifier0");
|
|
12150
|
+
w.fixed(item.nullifier1, 32, "nullifier1");
|
|
12151
|
+
w.fixed(item.comm0, 32, "comm0");
|
|
12152
|
+
w.u64(item.leaf0);
|
|
12153
|
+
w.fixed(item.comm1, 32, "comm1");
|
|
12154
|
+
w.u64(item.leaf1);
|
|
12155
|
+
w.u8(item.noteSource);
|
|
12156
|
+
const noteLen = item.note.length;
|
|
12157
|
+
if (item.noteSource === NOTE_SOURCE_NONE ? noteLen !== 0 : !NOTE_VERSION_BY_LEN.has(noteLen)) {
|
|
12158
|
+
throw new NoteIndexFormatError(`note_len ${noteLen} invalid for note_source ${item.noteSource}`);
|
|
12159
|
+
}
|
|
12160
|
+
w.u8(noteLen);
|
|
12161
|
+
w.push(item.note);
|
|
12162
|
+
w.fixed(item.signature, SIGNATURE_LEN, "signature");
|
|
12163
|
+
break;
|
|
12164
|
+
}
|
|
12165
|
+
case NOTE_INDEX_KIND_DELIVERY:
|
|
12166
|
+
w.fixed(item.mint, 32, "mint");
|
|
12167
|
+
w.u64(item.slot);
|
|
12168
|
+
w.fixed(item.commitment, 32, "commitment");
|
|
12169
|
+
w.u64(item.leaf);
|
|
12170
|
+
w.fixed(item.envelope, DELIVERY_ENVELOPE_LEN, "envelope");
|
|
12171
|
+
w.fixed(item.signature, SIGNATURE_LEN, "signature");
|
|
12172
|
+
break;
|
|
12173
|
+
case NOTE_INDEX_KIND_SWAP_REFUND:
|
|
12174
|
+
w.fixed(item.mint, 32, "mint");
|
|
12175
|
+
w.u64(item.slot);
|
|
12176
|
+
w.fixed(item.commitment, 32, "commitment");
|
|
12177
|
+
w.u64(item.leaf);
|
|
12178
|
+
w.u64(item.amountAfterFee);
|
|
12179
|
+
w.fixed(item.nullifier0, 32, "nullifier0");
|
|
12180
|
+
w.fixed(item.signature, SIGNATURE_LEN, "signature");
|
|
12181
|
+
break;
|
|
12182
|
+
default:
|
|
12183
|
+
throw new NoteIndexFormatError(`cannot encode kind ${item.kind}`);
|
|
12184
|
+
}
|
|
12185
|
+
return w.finish();
|
|
12186
|
+
}
|
|
12187
|
+
function encodeNoteIndexItem(item) {
|
|
12188
|
+
const body = encodeItemBody(item);
|
|
12189
|
+
const w = new Writer();
|
|
12190
|
+
w.u8(item.kind);
|
|
12191
|
+
w.u16(body.length);
|
|
12192
|
+
w.push(body);
|
|
12193
|
+
return w.finish();
|
|
12194
|
+
}
|
|
12195
|
+
function encodeNoteIndexPage(params) {
|
|
12196
|
+
const items = params.items ?? [];
|
|
12197
|
+
if (items.length > NOTE_INDEX_PAGE_SIZE) throw new NoteIndexFormatError(`count ${items.length} exceeds ${NOTE_INDEX_PAGE_SIZE}`);
|
|
12198
|
+
const w = new Writer();
|
|
12199
|
+
w.push(NOTE_INDEX_MAGIC);
|
|
12200
|
+
w.u8(NOTE_INDEX_FORMAT_VERSION);
|
|
12201
|
+
w.u8(params.complete ? COMPLETE_FLAG : 0);
|
|
12202
|
+
w.u16(0);
|
|
12203
|
+
w.u64(BigInt(params.epoch));
|
|
12204
|
+
w.u64(BigInt(params.page));
|
|
12205
|
+
w.u64(BigInt(params.firstSeq));
|
|
12206
|
+
w.u32(items.length);
|
|
12207
|
+
w.fixed(params.prevChain, 32, "prevChain");
|
|
12208
|
+
for (const item of items) w.push(encodeNoteIndexItem(item));
|
|
12209
|
+
return w.finish();
|
|
12210
|
+
}
|
|
12211
|
+
|
|
12212
|
+
// src/relay/note-index-client.ts
|
|
12213
|
+
var DEFAULT_TIMEOUT_MS2 = 3e4;
|
|
12214
|
+
var DEFAULT_MAX_RETRIES2 = 3;
|
|
12215
|
+
var RETRY_BASE_DELAY_MS = 500;
|
|
12216
|
+
var U64_MAX3 = (1n << 64n) - 1n;
|
|
12217
|
+
function joinPath(relayUrl, path) {
|
|
12218
|
+
const url = new URL(relayUrl);
|
|
12219
|
+
url.pathname = url.pathname.replace(/\/$/, "") + path;
|
|
12220
|
+
return url;
|
|
12221
|
+
}
|
|
12222
|
+
function abortError() {
|
|
12223
|
+
const error = new Error("Note index request aborted");
|
|
12224
|
+
error.name = "AbortError";
|
|
12225
|
+
return error;
|
|
12226
|
+
}
|
|
12227
|
+
function sleep4(ms, signal) {
|
|
12228
|
+
return new Promise((resolve, reject) => {
|
|
12229
|
+
if (signal?.aborted) return reject(abortError());
|
|
12230
|
+
const timer = setTimeout(() => {
|
|
12231
|
+
signal?.removeEventListener("abort", onAbort);
|
|
12232
|
+
resolve();
|
|
12233
|
+
}, ms);
|
|
12234
|
+
const onAbort = () => {
|
|
12235
|
+
clearTimeout(timer);
|
|
12236
|
+
reject(abortError());
|
|
12237
|
+
};
|
|
12238
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
12239
|
+
});
|
|
12240
|
+
}
|
|
12241
|
+
var RetryableStatusError = class extends Error {
|
|
12242
|
+
};
|
|
12243
|
+
var HttpStatusError = class extends Error {
|
|
12244
|
+
constructor(status, message) {
|
|
12245
|
+
super(message);
|
|
12246
|
+
this.status = status;
|
|
12247
|
+
this.name = "HttpStatusError";
|
|
12248
|
+
}
|
|
12249
|
+
};
|
|
12250
|
+
async function requestWithRetry(url, options, read) {
|
|
12251
|
+
assertAllowedRelayOrigin(url);
|
|
12252
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
|
|
12253
|
+
const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES2;
|
|
12254
|
+
let lastError;
|
|
12255
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
12256
|
+
if (options.signal?.aborted) throw abortError();
|
|
12257
|
+
const controller = new AbortController();
|
|
12258
|
+
const onAbort = () => controller.abort();
|
|
12259
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
12260
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
12261
|
+
try {
|
|
12262
|
+
const response = await relayFetch(url, { signal: controller.signal }, { observeClock: false });
|
|
12263
|
+
if (response.status === 429 || response.status >= 500) {
|
|
12264
|
+
throw new RetryableStatusError(`HTTP ${response.status} from ${new URL(url).pathname}`);
|
|
12265
|
+
}
|
|
12266
|
+
return await read(response, controller.signal);
|
|
12267
|
+
} catch (error) {
|
|
12268
|
+
if (options.signal?.aborted) throw abortError();
|
|
12269
|
+
const retryable = error instanceof RetryableStatusError || error instanceof Error && !(error instanceof NoteIndexFormatError) && !(error instanceof HttpStatusError);
|
|
12270
|
+
if (!retryable || attempt >= maxRetries) throw error;
|
|
12271
|
+
lastError = error;
|
|
12272
|
+
await sleep4(RETRY_BASE_DELAY_MS * 2 ** attempt + Math.random() * 250, options.signal);
|
|
12273
|
+
} finally {
|
|
12274
|
+
clearTimeout(timer);
|
|
12275
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
12276
|
+
}
|
|
12277
|
+
}
|
|
12278
|
+
throw lastError instanceof Error ? lastError : new Error(String(lastError));
|
|
12279
|
+
}
|
|
12280
|
+
async function readBoundedBody(response, maxBytes) {
|
|
12281
|
+
const declaredHeader = response.headers?.get?.("content-length") ?? null;
|
|
12282
|
+
const declared = declaredHeader === null ? NaN : Number(declaredHeader);
|
|
12283
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
12284
|
+
throw new NoteIndexFormatError(`response declares ${declared} bytes, over the ${maxBytes}-byte bound`);
|
|
12285
|
+
}
|
|
12286
|
+
const reader = response.body?.getReader?.();
|
|
12287
|
+
if (!reader) {
|
|
12288
|
+
const encoding = (response.headers?.get?.("content-encoding") ?? "").trim().toLowerCase();
|
|
12289
|
+
if (!Number.isSafeInteger(declared) || declared < 0) {
|
|
12290
|
+
throw new NoteIndexFormatError("response has no stream reader and no Content-Length: its size cannot be bounded");
|
|
12291
|
+
}
|
|
12292
|
+
if (encoding !== "" && encoding !== "identity") {
|
|
12293
|
+
throw new NoteIndexFormatError("response has no stream reader and a Content-Encoding: its decoded size cannot be bounded");
|
|
12294
|
+
}
|
|
12295
|
+
const buffer = new Uint8Array(await response.arrayBuffer());
|
|
12296
|
+
if (buffer.length > maxBytes || buffer.length !== declared) {
|
|
12297
|
+
throw new NoteIndexFormatError(`response is ${buffer.length} bytes, not the declared ${declared} within the ${maxBytes}-byte bound`);
|
|
12298
|
+
}
|
|
12299
|
+
return buffer;
|
|
12300
|
+
}
|
|
12301
|
+
const chunks = [];
|
|
12302
|
+
let total = 0;
|
|
12303
|
+
for (; ; ) {
|
|
12304
|
+
const { done, value } = await reader.read();
|
|
12305
|
+
if (done) break;
|
|
12306
|
+
total += value.length;
|
|
12307
|
+
if (total > maxBytes) {
|
|
12308
|
+
await reader.cancel().catch(() => void 0);
|
|
12309
|
+
throw new NoteIndexFormatError(`response exceeds the ${maxBytes}-byte bound`);
|
|
12310
|
+
}
|
|
12311
|
+
chunks.push(value);
|
|
12312
|
+
}
|
|
12313
|
+
const out = new Uint8Array(total);
|
|
12314
|
+
let off = 0;
|
|
12315
|
+
for (const c of chunks) {
|
|
12316
|
+
out.set(c, off);
|
|
12317
|
+
off += c.length;
|
|
12318
|
+
}
|
|
12319
|
+
return out;
|
|
12320
|
+
}
|
|
12321
|
+
function isNonNegativeSafeInteger(value) {
|
|
12322
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
12323
|
+
}
|
|
12324
|
+
async function fetchNoteIndexHead(relayUrl, options = {}) {
|
|
12325
|
+
const url = joinPath(relayUrl, "/note-index/v1/head").toString();
|
|
12326
|
+
const raw = await requestWithRetry(url, options, async (response) => {
|
|
12327
|
+
if (!response.ok) {
|
|
12328
|
+
throw new HttpStatusError(response.status, `note index head: HTTP ${response.status}`);
|
|
12329
|
+
}
|
|
12330
|
+
const text = new TextDecoder().decode(await readBoundedBody(response, 64 * 1024));
|
|
12331
|
+
try {
|
|
12332
|
+
return JSON.parse(text);
|
|
12333
|
+
} catch {
|
|
12334
|
+
throw new NoteIndexFormatError("head is not JSON");
|
|
12335
|
+
}
|
|
12336
|
+
});
|
|
12337
|
+
if (!raw || typeof raw !== "object") throw new NoteIndexFormatError("head is not an object");
|
|
12338
|
+
if (raw.format !== NOTE_INDEX_FORMAT_VERSION) {
|
|
12339
|
+
throw new NoteIndexFormatError(`unsupported head format ${String(raw.format)}`);
|
|
12340
|
+
}
|
|
12341
|
+
if (raw.page_size !== NOTE_INDEX_PAGE_SIZE) {
|
|
12342
|
+
throw new NoteIndexFormatError(`unsupported page_size ${String(raw.page_size)}`);
|
|
12343
|
+
}
|
|
12344
|
+
if (!isNonNegativeSafeInteger(raw.watermark) || !isNonNegativeSafeInteger(raw.complete_pages)) {
|
|
12345
|
+
throw new NoteIndexFormatError("head watermark/complete_pages are not non-negative integers");
|
|
12346
|
+
}
|
|
12347
|
+
if (raw.complete_pages !== Math.floor(raw.watermark / NOTE_INDEX_PAGE_SIZE)) {
|
|
12348
|
+
throw new NoteIndexFormatError(
|
|
12349
|
+
`complete_pages ${raw.complete_pages} disagrees with watermark ${raw.watermark}`
|
|
12350
|
+
);
|
|
12351
|
+
}
|
|
12352
|
+
if (typeof raw.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(raw.epoch) || BigInt(raw.epoch) > U64_MAX3) {
|
|
12353
|
+
throw new NoteIndexFormatError("head epoch is not a u64 decimal string");
|
|
12354
|
+
}
|
|
12355
|
+
if (typeof raw.chain_tip !== "string" || !/^[0-9a-fA-F]{64}$/.test(raw.chain_tip)) {
|
|
12356
|
+
throw new NoteIndexFormatError("head chain_tip is not 32-byte hex");
|
|
12357
|
+
}
|
|
12358
|
+
return {
|
|
12359
|
+
format: 1,
|
|
12360
|
+
epoch: BigInt(raw.epoch),
|
|
12361
|
+
pageSize: NOTE_INDEX_PAGE_SIZE,
|
|
12362
|
+
watermark: raw.watermark,
|
|
12363
|
+
completePages: raw.complete_pages,
|
|
12364
|
+
chainTip: raw.chain_tip.toLowerCase()
|
|
12365
|
+
};
|
|
12366
|
+
}
|
|
12367
|
+
async function fetchNoteIndexPage(relayUrl, epoch, page, options = {}) {
|
|
12368
|
+
if (typeof epoch !== "bigint" || epoch < 0n || epoch > U64_MAX3) throw new Error("epoch must be a u64 bigint");
|
|
12369
|
+
if (!isNonNegativeSafeInteger(page)) throw new Error(`page must be a non-negative integer, got ${page}`);
|
|
12370
|
+
const url = joinPath(relayUrl, `/note-index/v1/e/${epoch.toString(10)}/pages/${page}`).toString();
|
|
12371
|
+
return requestWithRetry(url, options, async (response) => {
|
|
12372
|
+
if (!response.ok) {
|
|
12373
|
+
throw new HttpStatusError(response.status, `note index page ${page}: HTTP ${response.status}`);
|
|
12374
|
+
}
|
|
12375
|
+
return readBoundedBody(response, NOTE_INDEX_MAX_PAGE_BYTES);
|
|
12376
|
+
});
|
|
12377
|
+
}
|
|
12378
|
+
|
|
12379
|
+
// src/scanning/note-index.ts
|
|
12380
|
+
import _bs584 from "bs58";
|
|
12381
|
+
import { sha256 as sha2566 } from "@noble/hashes/sha2";
|
|
12382
|
+
var bs584 = _bs584.default || _bs584;
|
|
12383
|
+
var CURSOR_VERSION = 2;
|
|
12384
|
+
var DEFAULT_CONCURRENCY = 6;
|
|
12385
|
+
var MAX_CONCURRENCY = 32;
|
|
12386
|
+
var ITEM_BATCH = 64;
|
|
12387
|
+
var CURSOR_PAGE_ALIGN = 8;
|
|
12388
|
+
var MAX_PERSISTED_PENDING_LEAVES = 4096;
|
|
12389
|
+
var MAX_CARRIED_PENDING = 256;
|
|
12390
|
+
var MAX_REJECTED_IDS = 1024;
|
|
12391
|
+
var LEAF_WINDOW = 512;
|
|
12392
|
+
var MAX_OVERRIDES = 256;
|
|
12393
|
+
var MAX_CURSOR_OWN_ITEMS = 65536;
|
|
12394
|
+
var MAX_LEGACY_VIEWING_KEYS = 8;
|
|
12395
|
+
var MAX_CURSOR_KEYS = 131072;
|
|
12396
|
+
var MAX_CURSOR_POOLS = 256;
|
|
12397
|
+
var MAX_CURSOR_PAGE = 2 ** 32;
|
|
12398
|
+
var TREE_CAPACITY = 2 ** MERKLE_TREE_HEIGHT2;
|
|
12399
|
+
var ZERO_CHAIN = "00".repeat(32);
|
|
12400
|
+
var U64_MAX4 = (1n << 64n) - 1n;
|
|
12401
|
+
var NoteIndexHeadBehindError = class extends Error {
|
|
12402
|
+
constructor(cursorWatermark, headWatermark) {
|
|
12403
|
+
super(
|
|
12404
|
+
`note index head is behind this cursor (watermark ${headWatermark} < ${cursorWatermark} seen before in this epoch): a stale cache or a rollback; retry later with the same cursor`
|
|
12405
|
+
);
|
|
12406
|
+
this.cursorWatermark = cursorWatermark;
|
|
12407
|
+
this.headWatermark = headWatermark;
|
|
12408
|
+
this.retryable = true;
|
|
12409
|
+
this.name = "NoteIndexHeadBehindError";
|
|
12410
|
+
}
|
|
12411
|
+
};
|
|
12412
|
+
var FullPassSignal = class {
|
|
12413
|
+
constructor(reason) {
|
|
12414
|
+
this.reason = reason;
|
|
12415
|
+
}
|
|
12416
|
+
};
|
|
12417
|
+
function abortError2() {
|
|
12418
|
+
const error = new Error("recoverNotesFromIndex aborted");
|
|
12419
|
+
error.name = "AbortError";
|
|
12420
|
+
return error;
|
|
12421
|
+
}
|
|
12422
|
+
function bytesToBigint2(bytes) {
|
|
12423
|
+
let v = 0n;
|
|
12424
|
+
for (let i = 0; i < bytes.length; i++) v = v << 8n | BigInt(bytes[i]);
|
|
12425
|
+
return v;
|
|
12426
|
+
}
|
|
12427
|
+
function toHex2(bytes) {
|
|
12428
|
+
let s = "";
|
|
12429
|
+
for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, "0");
|
|
12430
|
+
return s;
|
|
12431
|
+
}
|
|
12432
|
+
function fromHex(hex) {
|
|
12433
|
+
return Uint8Array.from(Buffer.from(hex, "hex"));
|
|
12434
|
+
}
|
|
12435
|
+
function hex32(v) {
|
|
12436
|
+
return v.toString(16).padStart(64, "0");
|
|
12437
|
+
}
|
|
12438
|
+
function isAllZero3(bytes) {
|
|
12439
|
+
for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
|
|
12440
|
+
return true;
|
|
12441
|
+
}
|
|
12442
|
+
function floorAlign(page) {
|
|
12443
|
+
return page - page % CURSOR_PAGE_ALIGN;
|
|
12444
|
+
}
|
|
12445
|
+
function verifiedKey(mint, leaf, commitment) {
|
|
12446
|
+
return `${mint}:${leaf}:${hex32(commitment)}`;
|
|
12447
|
+
}
|
|
12448
|
+
function itemIdentity(raw) {
|
|
12449
|
+
return toHex2(sha2566(raw).subarray(0, 16));
|
|
12450
|
+
}
|
|
12451
|
+
var LeafBuffer = class {
|
|
12452
|
+
constructor() {
|
|
12453
|
+
this.bytes = new Uint8Array(32 * 1024);
|
|
12454
|
+
this.view = new DataView(this.bytes.buffer);
|
|
12455
|
+
this.count = 0;
|
|
12456
|
+
}
|
|
12457
|
+
get length() {
|
|
12458
|
+
return this.count;
|
|
12459
|
+
}
|
|
12460
|
+
push(values) {
|
|
12461
|
+
const need = (this.count + values.length) * 32;
|
|
12462
|
+
if (need > this.bytes.length) {
|
|
12463
|
+
let size = this.bytes.length;
|
|
12464
|
+
while (size < need) size *= 2;
|
|
12465
|
+
const next = new Uint8Array(size);
|
|
12466
|
+
next.set(this.bytes.subarray(0, this.count * 32));
|
|
12467
|
+
this.bytes = next;
|
|
12468
|
+
this.view = new DataView(next.buffer);
|
|
12469
|
+
}
|
|
12470
|
+
for (const v of values) {
|
|
12471
|
+
const o = this.count * 32;
|
|
12472
|
+
this.view.setBigUint64(o, v >> 192n & 0xffffffffffffffffn);
|
|
12473
|
+
this.view.setBigUint64(o + 8, v >> 128n & 0xffffffffffffffffn);
|
|
12474
|
+
this.view.setBigUint64(o + 16, v >> 64n & 0xffffffffffffffffn);
|
|
12475
|
+
this.view.setBigUint64(o + 24, v & 0xffffffffffffffffn);
|
|
12476
|
+
this.count++;
|
|
12477
|
+
}
|
|
12478
|
+
}
|
|
12479
|
+
get(i) {
|
|
12480
|
+
if (i < 0 || i >= this.count) return void 0;
|
|
12481
|
+
const o = i * 32;
|
|
12482
|
+
return this.view.getBigUint64(o) << 192n | this.view.getBigUint64(o + 8) << 128n | this.view.getBigUint64(o + 16) << 64n | this.view.getBigUint64(o + 24);
|
|
12483
|
+
}
|
|
12484
|
+
};
|
|
12485
|
+
async function trialItem(item, trials) {
|
|
12486
|
+
for (const trial of trials) {
|
|
12487
|
+
if (trial.legacy && item.kind === 2) continue;
|
|
12488
|
+
const opened = await trialItemWith(item, trial);
|
|
12489
|
+
if (opened) return { ...opened, trial };
|
|
12490
|
+
}
|
|
12491
|
+
return null;
|
|
12492
|
+
}
|
|
12493
|
+
async function trialItemIsolated(item, trials, stats) {
|
|
12494
|
+
try {
|
|
12495
|
+
return await trialItem(item, trials);
|
|
12496
|
+
} catch {
|
|
12497
|
+
stats.skipped++;
|
|
12498
|
+
return null;
|
|
12499
|
+
}
|
|
12500
|
+
}
|
|
12501
|
+
async function trialItemWith(item, trial) {
|
|
12502
|
+
if (item.kind === 1) {
|
|
12503
|
+
if (item.note.length === 0) return null;
|
|
12504
|
+
let note = isAllZero3(item.comm0) ? null : await trial.decrypt(item.note, item.comm0);
|
|
12505
|
+
if (!note && item.note[0] === 2 && !isAllZero3(item.comm1)) note = await trial.decrypt(item.note, item.comm1);
|
|
12506
|
+
return note ? { note } : null;
|
|
12507
|
+
}
|
|
12508
|
+
if (item.kind === 2) {
|
|
12509
|
+
const delivery = await trial.open(item.envelope);
|
|
12510
|
+
return delivery ? { delivery } : null;
|
|
12511
|
+
}
|
|
12512
|
+
if (item.amountAfterFee === 0n) return null;
|
|
12513
|
+
const refund = await matchSwapRefundLeaf({
|
|
12514
|
+
viewingKeyNk: trial.nk,
|
|
12515
|
+
inputNullifier: item.nullifier0,
|
|
12516
|
+
amountAfterFee: item.amountAfterFee,
|
|
12517
|
+
commitment: item.commitment,
|
|
12518
|
+
ownerUtxoKeypair: trial.owner
|
|
12519
|
+
});
|
|
12520
|
+
return refund ? { refund } : null;
|
|
12521
|
+
}
|
|
12522
|
+
function txOutputs(item) {
|
|
12523
|
+
const out = [toHex2(item.comm0)];
|
|
12524
|
+
if (!isAllZero3(item.comm1)) out.push(toHex2(item.comm1));
|
|
12525
|
+
return out;
|
|
12526
|
+
}
|
|
12527
|
+
function leafOfTxOutput(item, commitment) {
|
|
12528
|
+
if (!isAllZero3(item.comm0) && commitment === bytesToBigint2(item.comm0)) return Number(item.leaf0);
|
|
12529
|
+
if (!isAllZero3(item.comm1) && commitment === bytesToBigint2(item.comm1)) return Number(item.leaf1);
|
|
12530
|
+
return null;
|
|
12531
|
+
}
|
|
12532
|
+
function changeBlindingOrNull(nk, noteSalt, outputIndex) {
|
|
12533
|
+
try {
|
|
12534
|
+
return deriveChangeNoteBlinding(nk, noteSalt, outputIndex);
|
|
12535
|
+
} catch {
|
|
12536
|
+
return null;
|
|
12537
|
+
}
|
|
12538
|
+
}
|
|
12539
|
+
async function matchOwnItems(own, owner, onReject, onSkip) {
|
|
12540
|
+
const candidates = [];
|
|
12541
|
+
const claimed = /* @__PURE__ */ new Set();
|
|
12542
|
+
const byNullifier = /* @__PURE__ */ new Map();
|
|
12543
|
+
const legacyKeys = /* @__PURE__ */ new Map();
|
|
12544
|
+
const ownTxs = own.filter((o) => o.item.kind === 1 && o.note?.noteSalt !== void 0);
|
|
12545
|
+
const spendsOf = /* @__PURE__ */ new Map();
|
|
12546
|
+
const byOutKey = /* @__PURE__ */ new Map();
|
|
12547
|
+
const index = (map, key, o) => {
|
|
12548
|
+
const list = map.get(key);
|
|
12549
|
+
if (list) list.push(o);
|
|
12550
|
+
else map.set(key, [o]);
|
|
12551
|
+
};
|
|
12552
|
+
for (const o of ownTxs) {
|
|
12553
|
+
for (const n of [o.item.nullifier0, o.item.nullifier1]) if (!isAllZero3(n)) index(spendsOf, toHex2(n), o);
|
|
12554
|
+
if (o.note.outPubkey0 !== void 0) index(byOutKey, o.note.outPubkey0, o);
|
|
12555
|
+
}
|
|
12556
|
+
const queue = [];
|
|
12557
|
+
const queued = /* @__PURE__ */ new Set();
|
|
12558
|
+
const enqueue = (o) => {
|
|
12559
|
+
if (queued.has(o)) return;
|
|
12560
|
+
queued.add(o);
|
|
12561
|
+
queue.push(o);
|
|
12562
|
+
};
|
|
12563
|
+
const add = async (o, c) => {
|
|
12564
|
+
const nullifier = hex32(
|
|
12565
|
+
await computeNullifier({ amount: c.amount, keypair: c.keypair, blinding: c.blinding, mintAddress: c.mint, index: c.leaf, commitment: c.commitment })
|
|
12566
|
+
);
|
|
12567
|
+
const full = { ...c, atRisk: c.atRisk || o.trial.legacy, signature: o.item.signature, page: o.page, seq: o.seq, nullifier };
|
|
12568
|
+
candidates.push(full);
|
|
12569
|
+
if (!byNullifier.has(nullifier)) {
|
|
12570
|
+
byNullifier.set(nullifier, full);
|
|
12571
|
+
for (const s of spendsOf.get(nullifier) ?? []) enqueue(s);
|
|
12572
|
+
}
|
|
12573
|
+
if (c.atRisk && c.keypair.publicKey !== owner.publicKey && !legacyKeys.has(c.keypair.publicKey)) {
|
|
12574
|
+
legacyKeys.set(c.keypair.publicKey, c.keypair);
|
|
12575
|
+
for (const s of byOutKey.get(c.keypair.publicKey) ?? []) enqueue(s);
|
|
12576
|
+
}
|
|
12577
|
+
};
|
|
12578
|
+
const tryDeposit = async (o, item, amount) => {
|
|
12579
|
+
const note = o.note;
|
|
12580
|
+
const mint = addressFromBytes(item.mint);
|
|
12581
|
+
const deposit = await matchDepositNote({
|
|
12582
|
+
viewingKeyNk: o.trial.nk,
|
|
12583
|
+
noteSalt: note.noteSalt,
|
|
12584
|
+
amount,
|
|
12585
|
+
mintAddress: mint,
|
|
12586
|
+
outputCommitments: txOutputs(item),
|
|
12587
|
+
ownerUtxoKeypair: owner
|
|
12588
|
+
});
|
|
12589
|
+
const leaf = deposit ? leafOfTxOutput(item, deposit.commitment) : null;
|
|
12590
|
+
if (!deposit || leaf === null) return false;
|
|
12591
|
+
await add(o, {
|
|
12592
|
+
kind: "deposit",
|
|
12593
|
+
atRisk: deposit.legacyExposed,
|
|
12594
|
+
amount: deposit.amount,
|
|
12595
|
+
blinding: deposit.blinding,
|
|
12596
|
+
keypair: deposit.legacyExposed ? deposit.keypair : owner,
|
|
12597
|
+
mint,
|
|
12598
|
+
commitment: deposit.commitment,
|
|
12599
|
+
leaf
|
|
12600
|
+
});
|
|
12601
|
+
return true;
|
|
12602
|
+
};
|
|
12603
|
+
const tryChange0 = async (o, item, keypair, atRisk) => {
|
|
12604
|
+
const note = o.note;
|
|
12605
|
+
const mint = addressFromBytes(item.mint);
|
|
12606
|
+
const change = await matchChangeNote({
|
|
12607
|
+
viewingKeyNk: o.trial.nk,
|
|
12608
|
+
noteSalt: note.noteSalt,
|
|
12609
|
+
amount: note.outAmount0,
|
|
12610
|
+
keypair,
|
|
12611
|
+
mintAddress: mint,
|
|
12612
|
+
outputIndex: 0,
|
|
12613
|
+
outputCommitments: [toHex2(item.comm0)],
|
|
12614
|
+
ownerUtxoPublicKey: owner.publicKey
|
|
12615
|
+
});
|
|
12616
|
+
if (!change) return false;
|
|
12617
|
+
await add(o, {
|
|
12618
|
+
kind: "change",
|
|
12619
|
+
atRisk,
|
|
12620
|
+
amount: change.amount,
|
|
12621
|
+
blinding: change.blinding,
|
|
12622
|
+
keypair,
|
|
12623
|
+
mint,
|
|
12624
|
+
commitment: change.commitment,
|
|
12625
|
+
leaf: Number(item.leaf0)
|
|
12626
|
+
});
|
|
12627
|
+
return true;
|
|
12628
|
+
};
|
|
12629
|
+
const direct = async (o) => {
|
|
12630
|
+
const item = o.item;
|
|
12631
|
+
if (item.kind === 1 && o.note?.noteSalt !== void 0) {
|
|
12632
|
+
const note = o.note;
|
|
12633
|
+
if (note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
|
|
12634
|
+
if (await tryDeposit(o, item, item.publicAmount)) claimed.add(`${o.seq}:0`);
|
|
12635
|
+
}
|
|
12636
|
+
if (note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 === owner.publicKey) {
|
|
12637
|
+
if (await tryChange0(o, item, owner, false)) claimed.add(`${o.seq}:0`);
|
|
12638
|
+
}
|
|
12639
|
+
} else if (item.kind === 2 && o.delivery) {
|
|
12640
|
+
const mint = addressFromBytes(item.mint);
|
|
12641
|
+
if (o.delivery.amount <= 0n || o.delivery.blinding === 0n) {
|
|
12642
|
+
onReject(o);
|
|
12643
|
+
return;
|
|
12644
|
+
}
|
|
12645
|
+
const commitment = await computeCommitment({
|
|
12646
|
+
amount: o.delivery.amount,
|
|
12647
|
+
keypair: { privateKey: 0n, publicKey: owner.publicKey },
|
|
12648
|
+
blinding: o.delivery.blinding,
|
|
12649
|
+
mintAddress: mint
|
|
12650
|
+
});
|
|
12651
|
+
if (commitment !== bytesToBigint2(item.commitment)) {
|
|
12652
|
+
onReject(o);
|
|
12653
|
+
return;
|
|
12654
|
+
}
|
|
12655
|
+
await add(o, {
|
|
12656
|
+
kind: "received",
|
|
12657
|
+
atRisk: false,
|
|
12658
|
+
amount: o.delivery.amount,
|
|
12659
|
+
blinding: o.delivery.blinding,
|
|
12660
|
+
keypair: owner,
|
|
12661
|
+
mint,
|
|
12662
|
+
commitment,
|
|
12663
|
+
leaf: Number(item.leaf)
|
|
12664
|
+
});
|
|
12665
|
+
} else if (item.kind === 3 && o.refund) {
|
|
12666
|
+
await add(o, {
|
|
12667
|
+
kind: "swap_refund",
|
|
12668
|
+
atRisk: o.refund.legacyExposed,
|
|
12669
|
+
amount: o.refund.amount,
|
|
12670
|
+
blinding: o.refund.blinding,
|
|
12671
|
+
keypair: o.refund.legacyExposed ? o.refund.keypair : owner,
|
|
12672
|
+
mint: NATIVE_SOL_MINT,
|
|
12673
|
+
commitment: o.refund.commitment,
|
|
12674
|
+
leaf: Number(item.leaf)
|
|
12675
|
+
});
|
|
12676
|
+
}
|
|
12677
|
+
};
|
|
12678
|
+
for (const o of own) {
|
|
12679
|
+
try {
|
|
12680
|
+
await direct(o);
|
|
12681
|
+
} catch {
|
|
12682
|
+
onSkip(o);
|
|
12683
|
+
}
|
|
12684
|
+
}
|
|
12685
|
+
const processTx = async (o) => {
|
|
12686
|
+
const item = o.item;
|
|
12687
|
+
const note = o.note;
|
|
12688
|
+
if (!claimed.has(`${o.seq}:0`) && note.outAmount0 !== void 0 && note.outAmount0 > 0n && note.outPubkey0 !== void 0) {
|
|
12689
|
+
const legacy = legacyKeys.get(note.outPubkey0);
|
|
12690
|
+
if (legacy && await tryChange0(o, item, legacy, true)) claimed.add(`${o.seq}:0`);
|
|
12691
|
+
}
|
|
12692
|
+
const mint = addressFromBytes(item.mint);
|
|
12693
|
+
const inputs = [item.nullifier0, item.nullifier1].filter((n) => !isAllZero3(n)).map((n) => byNullifier.get(toHex2(n))).filter((c) => c !== void 0 && c.mint === mint);
|
|
12694
|
+
if (inputs.length === 0) return;
|
|
12695
|
+
const sumIn = inputs.reduce((acc, c) => acc + c.amount, 0n);
|
|
12696
|
+
if (!claimed.has(`${o.seq}:1`) && note.outAmount0 !== void 0 && !isAllZero3(item.comm1)) {
|
|
12697
|
+
const out1 = sumIn + item.publicAmount - note.outAmount0;
|
|
12698
|
+
const blinding = out1 > 0n ? changeBlindingOrNull(o.trial.nk, note.noteSalt, 1) : null;
|
|
12699
|
+
if (out1 > 0n && blinding === null) onSkip(o);
|
|
12700
|
+
else if (blinding !== null) {
|
|
12701
|
+
const owners = [{ keypair: owner, atRisk: false }];
|
|
12702
|
+
const legacyInput = legacyKeys.get(inputs[0].keypair.publicKey);
|
|
12703
|
+
if (legacyInput && legacyInput.publicKey !== owner.publicKey) owners.push({ keypair: legacyInput, atRisk: true });
|
|
12704
|
+
for (const { keypair, atRisk } of owners) {
|
|
12705
|
+
const commitment = await computeCommitment({ amount: out1, keypair, blinding, mintAddress: mint });
|
|
12706
|
+
if (commitment !== bytesToBigint2(item.comm1)) continue;
|
|
12707
|
+
claimed.add(`${o.seq}:1`);
|
|
12708
|
+
await add(o, { kind: "change", atRisk, amount: out1, blinding, keypair, mint, commitment, leaf: Number(item.leaf1) });
|
|
12709
|
+
break;
|
|
12710
|
+
}
|
|
12711
|
+
}
|
|
12712
|
+
}
|
|
12713
|
+
if (!claimed.has(`${o.seq}:0`) && note.outAmount0 === void 0 && item.ixTag === 0 && item.publicAmount > 0n) {
|
|
12714
|
+
if (await tryDeposit(o, item, item.publicAmount + sumIn)) claimed.add(`${o.seq}:0`);
|
|
12715
|
+
}
|
|
12716
|
+
};
|
|
12717
|
+
for (const o of ownTxs) enqueue(o);
|
|
12718
|
+
for (let i = 0; i < queue.length; i++) {
|
|
12719
|
+
const o = queue[i];
|
|
12720
|
+
queued.delete(o);
|
|
12721
|
+
try {
|
|
12722
|
+
await processTx(o);
|
|
12723
|
+
} catch {
|
|
12724
|
+
onSkip(o);
|
|
12725
|
+
}
|
|
12726
|
+
}
|
|
12727
|
+
return candidates;
|
|
12728
|
+
}
|
|
12729
|
+
async function replayStream(start, pages, overrides, chain, targetPage) {
|
|
12730
|
+
const frontier = await MerkleFrontier.create(start.frontier ?? void 0, MERKLE_TREE_HEIGHT2);
|
|
12731
|
+
const startN = frontier.nextIndex;
|
|
12732
|
+
const pending = new Map(start.pending);
|
|
12733
|
+
const flushed = new LeafBuffer();
|
|
12734
|
+
const corrections = /* @__PURE__ */ new Map();
|
|
12735
|
+
let conflicts = 0;
|
|
12736
|
+
let verifiedPrefix = 0;
|
|
12737
|
+
let mismatch = false;
|
|
12738
|
+
const checks = [];
|
|
12739
|
+
const setBits = [];
|
|
12740
|
+
if (chain && chain.nextIndex > 0) {
|
|
12741
|
+
const last = chain.nextIndex - 1;
|
|
12742
|
+
for (let l = 0; l < MERKLE_TREE_HEIGHT2; l++) if (Math.floor(last / 2 ** l) % 2 === 1) setBits.push(l);
|
|
12743
|
+
for (const l of setBits) {
|
|
12744
|
+
const at = Math.floor(last / 2 ** l) * 2 ** l;
|
|
12745
|
+
if (at >= startN) checks.push({ at, level: l });
|
|
12746
|
+
}
|
|
12747
|
+
if (chain.nextIndex >= startN) checks.push({ at: chain.nextIndex, level: -1 });
|
|
12748
|
+
checks.sort((a, b) => a.at - b.at);
|
|
12749
|
+
}
|
|
12750
|
+
let nextCheck = 0;
|
|
12751
|
+
const runChecks = () => {
|
|
12752
|
+
while (nextCheck < checks.length && checks[nextCheck].at === frontier.nextIndex) {
|
|
12753
|
+
const { at, level } = checks[nextCheck++];
|
|
12754
|
+
const ok = level < 0 ? frontier.root() === chain.root : setBits.every((j) => j < level || frontier.leftAt(j) === chain.subtrees[j]);
|
|
12755
|
+
if (ok) verifiedPrefix = Math.max(verifiedPrefix, at);
|
|
12756
|
+
else mismatch = true;
|
|
12757
|
+
}
|
|
12758
|
+
};
|
|
12759
|
+
const append = (values) => {
|
|
12760
|
+
let i = 0;
|
|
12761
|
+
while (i < values.length) {
|
|
12762
|
+
const room = nextCheck < checks.length ? checks[nextCheck].at - frontier.nextIndex : values.length - i;
|
|
12763
|
+
const take = Math.min(values.length - i, room);
|
|
12764
|
+
if (take > 0) {
|
|
12765
|
+
const part = values.slice(i, i + take);
|
|
12766
|
+
frontier.append(part);
|
|
12767
|
+
flushed.push(part);
|
|
12768
|
+
i += take;
|
|
12769
|
+
}
|
|
12770
|
+
runChecks();
|
|
12771
|
+
}
|
|
12772
|
+
};
|
|
12773
|
+
const valueAt = (leaf) => leaf >= startN && leaf < startN + flushed.length ? flushed.get(leaf - startN) : pending.get(leaf);
|
|
12774
|
+
const flush = () => {
|
|
12775
|
+
const batch = [];
|
|
12776
|
+
let next = frontier.nextIndex;
|
|
12777
|
+
while (pending.has(next)) {
|
|
12778
|
+
batch.push(pending.get(next));
|
|
12779
|
+
pending.delete(next);
|
|
12780
|
+
next++;
|
|
12781
|
+
}
|
|
12782
|
+
if (batch.length > 0) append(batch);
|
|
12783
|
+
};
|
|
12784
|
+
let snapshot = null;
|
|
12785
|
+
let taken = false;
|
|
12786
|
+
const takeSnapshot = () => {
|
|
12787
|
+
taken = true;
|
|
12788
|
+
if (pending.size > MAX_PERSISTED_PENDING_LEAVES) return;
|
|
12789
|
+
snapshot = { frontier: frontier.toState(), pending: new Map(pending), nextIndex: frontier.nextIndex };
|
|
12790
|
+
};
|
|
12791
|
+
runChecks();
|
|
12792
|
+
flush();
|
|
12793
|
+
for (const { page, entries } of pages) {
|
|
12794
|
+
if (!taken && page >= targetPage) takeSnapshot();
|
|
12795
|
+
for (const e of entries) {
|
|
12796
|
+
if (e.leaf < startN) continue;
|
|
12797
|
+
const prior = valueAt(e.leaf);
|
|
12798
|
+
if (prior !== void 0) {
|
|
12799
|
+
if (prior !== e.commitment) {
|
|
12800
|
+
conflicts++;
|
|
12801
|
+
corrections.set(e.leaf, e.commitment);
|
|
12802
|
+
}
|
|
12803
|
+
continue;
|
|
12804
|
+
}
|
|
12805
|
+
pending.set(e.leaf, overrides.get(e.leaf) ?? e.commitment);
|
|
12806
|
+
}
|
|
12807
|
+
flush();
|
|
12808
|
+
}
|
|
12809
|
+
if (!taken) takeSnapshot();
|
|
12810
|
+
if (chain && treeAccountAcceptsRoot(chain.data, hex32(frontier.root()))) {
|
|
12811
|
+
verifiedPrefix = Math.max(verifiedPrefix, Math.min(frontier.nextIndex, chain.nextIndex));
|
|
12812
|
+
}
|
|
12813
|
+
return { endCount: frontier.nextIndex, valueAt, snapshot, conflicts, corrections, verifiedPrefix, mismatch };
|
|
12814
|
+
}
|
|
12815
|
+
var HEX64 = /^[0-9a-f]{64}$/;
|
|
12816
|
+
var HEX32 = /^[0-9a-f]{32}$/;
|
|
12817
|
+
var ADDRESS = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
|
|
12818
|
+
var VERIFIED_KEY = /^[1-9A-HJ-NP-Za-km-z]{32,44}:(0|[1-9][0-9]{0,9}):[0-9a-f]{64}$/;
|
|
12819
|
+
function isRecord(v) {
|
|
12820
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
12821
|
+
}
|
|
12822
|
+
function isIntIn(v, min, max) {
|
|
12823
|
+
return typeof v === "number" && Number.isSafeInteger(v) && v >= min && v <= max;
|
|
12824
|
+
}
|
|
12825
|
+
function isBoundedArray(v, max) {
|
|
12826
|
+
return Array.isArray(v) && v.length <= max;
|
|
12827
|
+
}
|
|
12828
|
+
function emptyStartTree() {
|
|
12829
|
+
return {
|
|
12830
|
+
frontier: null,
|
|
12831
|
+
nextIndex: 0,
|
|
12832
|
+
pending: /* @__PURE__ */ new Map(),
|
|
12833
|
+
window: [],
|
|
12834
|
+
windowStart: 0,
|
|
12835
|
+
verified: 0,
|
|
12836
|
+
overrides: /* @__PURE__ */ new Map(),
|
|
12837
|
+
mismatch: false,
|
|
12838
|
+
hiBefore: -1
|
|
12839
|
+
};
|
|
12840
|
+
}
|
|
12841
|
+
async function parseCursor(cursor, poolMints) {
|
|
12842
|
+
try {
|
|
12843
|
+
if (!isRecord(cursor)) return "not an object";
|
|
12844
|
+
if (cursor.v !== CURSOR_VERSION) return "unsupported cursor version";
|
|
12845
|
+
const c = cursor;
|
|
12846
|
+
if (typeof c.epoch !== "string" || !/^(0|[1-9][0-9]{0,19})$/.test(c.epoch) || BigInt(c.epoch) > U64_MAX4) return "bad epoch";
|
|
12847
|
+
if (!isIntIn(c.page, 0, MAX_CURSOR_PAGE) || c.page % CURSOR_PAGE_ALIGN !== 0) return "bad page";
|
|
12848
|
+
if (typeof c.chain !== "string" || !HEX64.test(c.chain)) return "bad chain";
|
|
12849
|
+
if (!isIntIn(c.watermark, 0, Number.MAX_SAFE_INTEGER) || c.page * NOTE_INDEX_PAGE_SIZE > c.watermark) return "bad watermark";
|
|
12850
|
+
if (!isIntIn(c.fullPassSeq, 0, c.watermark)) return "bad full-pass mark";
|
|
12851
|
+
if (!isRecord(c.trees) || Object.keys(c.trees).length > MAX_CURSOR_POOLS) return "bad trees";
|
|
12852
|
+
const trees = /* @__PURE__ */ new Map();
|
|
12853
|
+
for (const mint of poolMints) {
|
|
12854
|
+
const t = c.trees[mint];
|
|
12855
|
+
if (!isRecord(t)) return "a listed pool is missing from the cursor";
|
|
12856
|
+
const tree = t;
|
|
12857
|
+
if (!isRecord(tree.frontier)) return "bad frontier";
|
|
12858
|
+
let frontier;
|
|
12859
|
+
try {
|
|
12860
|
+
frontier = await MerkleFrontier.create(tree.frontier, MERKLE_TREE_HEIGHT2);
|
|
12861
|
+
} catch {
|
|
12862
|
+
return "bad frontier";
|
|
12863
|
+
}
|
|
12864
|
+
const nextIndex = frontier.nextIndex;
|
|
12865
|
+
if (!isBoundedArray(tree.pending, MAX_PERSISTED_PENDING_LEAVES)) return "bad pending leaves";
|
|
12866
|
+
const pending = /* @__PURE__ */ new Map();
|
|
12867
|
+
let hiBefore = nextIndex - 1;
|
|
12868
|
+
for (const entry of tree.pending) {
|
|
12869
|
+
if (!Array.isArray(entry) || entry.length !== 2) return "bad pending leaves";
|
|
12870
|
+
const [leaf, value] = entry;
|
|
12871
|
+
if (!isIntIn(leaf, nextIndex + 1, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value) || pending.has(leaf)) {
|
|
12872
|
+
return "bad pending leaves";
|
|
12873
|
+
}
|
|
12874
|
+
pending.set(leaf, BigInt("0x" + value));
|
|
12875
|
+
hiBefore = Math.max(hiBefore, leaf);
|
|
12876
|
+
}
|
|
12877
|
+
if (typeof tree.window !== "string" || tree.window.length % 64 !== 0 || !/^[0-9a-f]*$/.test(tree.window)) return "bad window";
|
|
12878
|
+
const windowLen = tree.window.length / 64;
|
|
12879
|
+
if (windowLen > LEAF_WINDOW || windowLen > nextIndex) return "bad window";
|
|
12880
|
+
const window2 = [];
|
|
12881
|
+
for (let i = 0; i < windowLen; i++) window2.push(BigInt("0x" + tree.window.slice(i * 64, (i + 1) * 64)));
|
|
12882
|
+
if (!isIntIn(tree.verified, 0, nextIndex)) return "bad verified prefix";
|
|
12883
|
+
if (!isBoundedArray(tree.overrides, MAX_OVERRIDES)) return "bad overrides";
|
|
12884
|
+
const overrides = /* @__PURE__ */ new Map();
|
|
12885
|
+
for (const entry of tree.overrides) {
|
|
12886
|
+
if (!Array.isArray(entry) || entry.length !== 2) return "bad overrides";
|
|
12887
|
+
const [leaf, value] = entry;
|
|
12888
|
+
if (!isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) return "bad overrides";
|
|
12889
|
+
overrides.set(leaf, BigInt("0x" + value));
|
|
12890
|
+
}
|
|
12891
|
+
if (typeof tree.mismatch !== "boolean") return "bad mismatch flag";
|
|
12892
|
+
trees.set(mint, {
|
|
12893
|
+
frontier: frontier.toState(),
|
|
12894
|
+
nextIndex,
|
|
12895
|
+
pending,
|
|
12896
|
+
window: window2,
|
|
12897
|
+
windowStart: nextIndex - windowLen,
|
|
12898
|
+
verified: tree.verified,
|
|
12899
|
+
overrides,
|
|
12900
|
+
mismatch: tree.mismatch,
|
|
12901
|
+
hiBefore
|
|
12902
|
+
});
|
|
12903
|
+
}
|
|
12904
|
+
const own = c.own;
|
|
12905
|
+
if (!isRecord(own)) return "bad own state";
|
|
12906
|
+
if (!isBoundedArray(own.items, MAX_CURSOR_OWN_ITEMS)) return "bad own items";
|
|
12907
|
+
const items = [];
|
|
12908
|
+
const seqs = /* @__PURE__ */ new Set();
|
|
12909
|
+
for (const entry of own.items) {
|
|
12910
|
+
if (!isRecord(entry)) return "bad own items";
|
|
12911
|
+
const { seq, item } = entry;
|
|
12912
|
+
if (!isIntIn(seq, 0, c.page * NOTE_INDEX_PAGE_SIZE - 1) || seqs.has(seq)) return "bad own items";
|
|
12913
|
+
if (typeof item !== "string" || item.length % 2 !== 0 || item.length > 2 * 4096 || !/^[0-9a-f]+$/.test(item)) return "bad own items";
|
|
12914
|
+
seqs.add(seq);
|
|
12915
|
+
const raw = fromHex(item);
|
|
12916
|
+
items.push({ seq, raw, item: parseNoteIndexItem(raw) });
|
|
12917
|
+
}
|
|
12918
|
+
if (!isBoundedArray(own.verified, MAX_CURSOR_KEYS) || !own.verified.every((k) => typeof k === "string" && VERIFIED_KEY.test(k))) {
|
|
12919
|
+
return "bad verified notes";
|
|
12920
|
+
}
|
|
12921
|
+
if (!isBoundedArray(own.spent, MAX_CURSOR_KEYS) || !own.spent.every((k) => typeof k === "string" && HEX64.test(k))) return "bad spent set";
|
|
12922
|
+
if (!isBoundedArray(own.pendingLeaves, MAX_CARRIED_PENDING)) return "bad pending notes";
|
|
12923
|
+
const pendingLeaves = /* @__PURE__ */ new Map();
|
|
12924
|
+
for (const entry of own.pendingLeaves) {
|
|
12925
|
+
if (!Array.isArray(entry) || entry.length !== 3) return "bad pending notes";
|
|
12926
|
+
const [mint, leaf, value] = entry;
|
|
12927
|
+
if (typeof mint !== "string" || !ADDRESS.test(mint) || !isIntIn(leaf, 0, TREE_CAPACITY - 1) || typeof value !== "string" || !HEX64.test(value)) {
|
|
12928
|
+
return "bad pending notes";
|
|
12929
|
+
}
|
|
12930
|
+
pendingLeaves.set(`${mint}:${leaf}`, BigInt("0x" + value));
|
|
12931
|
+
}
|
|
12932
|
+
if (!isBoundedArray(own.rejected, MAX_REJECTED_IDS) || !own.rejected.every((k) => typeof k === "string" && HEX32.test(k))) {
|
|
12933
|
+
return "bad rejected set";
|
|
12934
|
+
}
|
|
12935
|
+
return {
|
|
12936
|
+
raw: c,
|
|
12937
|
+
trees,
|
|
12938
|
+
items,
|
|
12939
|
+
verified: new Set(own.verified),
|
|
12940
|
+
spent: new Set(own.spent),
|
|
12941
|
+
pendingLeaves,
|
|
12942
|
+
rejected: own.rejected
|
|
12943
|
+
};
|
|
12944
|
+
} catch {
|
|
12945
|
+
return "unreadable state";
|
|
12946
|
+
}
|
|
12947
|
+
}
|
|
12948
|
+
async function recoverNotesFromIndex(params) {
|
|
12949
|
+
const startedAt = Date.now();
|
|
12950
|
+
const { relayUrl, connection, viewingKeyNk, programId } = params;
|
|
12951
|
+
assertAllowedRelayOrigin(relayUrl);
|
|
12952
|
+
assertAllowedRpcConnection(connection);
|
|
12953
|
+
if (!(viewingKeyNk instanceof Uint8Array) || viewingKeyNk.length !== 32) throw new Error("viewingKeyNk must be 32 bytes");
|
|
12954
|
+
const owner = await assertOwnerUtxoKeypair(params.ownerUtxoKeypair);
|
|
12955
|
+
if (!Array.isArray(params.poolMints)) throw new Error("poolMints must list every active pool mint");
|
|
12956
|
+
const concurrency = params.concurrency ?? DEFAULT_CONCURRENCY;
|
|
12957
|
+
if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > MAX_CONCURRENCY) {
|
|
12958
|
+
throw new Error(`concurrency must be an integer in 1..${MAX_CONCURRENCY}`);
|
|
12959
|
+
}
|
|
12960
|
+
if (params.signal?.aborted) throw abortError2();
|
|
12961
|
+
const stats = {
|
|
12962
|
+
pages: 0,
|
|
12963
|
+
items: 0,
|
|
12964
|
+
bytes: 0,
|
|
12965
|
+
rpcCalls: 0,
|
|
12966
|
+
ms: 0,
|
|
12967
|
+
dropped: 0,
|
|
12968
|
+
decrypted: 0,
|
|
12969
|
+
candidates: 0,
|
|
12970
|
+
spent: 0,
|
|
12971
|
+
conflicts: 0,
|
|
12972
|
+
pendingDropped: 0,
|
|
12973
|
+
skipped: 0
|
|
12974
|
+
};
|
|
12975
|
+
const rpc = new Proxy(connection, {
|
|
12976
|
+
get(target, prop, receiver) {
|
|
12977
|
+
const value = Reflect.get(target, prop, receiver);
|
|
12978
|
+
if (typeof value !== "function") return value;
|
|
12979
|
+
return (...args) => {
|
|
12980
|
+
const pending = value.apply(target, args);
|
|
12981
|
+
if (pending && typeof pending.send === "function") {
|
|
12982
|
+
const send = pending.send.bind(pending);
|
|
12983
|
+
return {
|
|
12984
|
+
...pending,
|
|
12985
|
+
send: (...sendArgs) => {
|
|
12986
|
+
stats.rpcCalls++;
|
|
12987
|
+
return send(...sendArgs);
|
|
12988
|
+
}
|
|
12989
|
+
};
|
|
12990
|
+
}
|
|
12991
|
+
return pending;
|
|
12992
|
+
};
|
|
12993
|
+
}
|
|
12994
|
+
});
|
|
12995
|
+
const makeTrial = async (nk, legacy) => ({
|
|
12996
|
+
nk,
|
|
12997
|
+
legacy,
|
|
12998
|
+
owner,
|
|
12999
|
+
decrypt: await createCompactChainNoteDecryptor(nk),
|
|
13000
|
+
open: await createRecipientDeliveryOpener(deriveViewingKeyFromNk(nk).privateKey)
|
|
13001
|
+
});
|
|
13002
|
+
const trials = [await makeTrial(viewingKeyNk, false)];
|
|
13003
|
+
const legacyNks = params.legacyViewingKeyNks ?? [];
|
|
13004
|
+
if (!Array.isArray(legacyNks)) throw new Error("legacyViewingKeyNks must be an array of 32-byte keys");
|
|
13005
|
+
if (legacyNks.length > MAX_LEGACY_VIEWING_KEYS) throw new Error(`legacyViewingKeyNks takes at most ${MAX_LEGACY_VIEWING_KEYS} keys`);
|
|
13006
|
+
const seenNks = /* @__PURE__ */ new Set([toHex2(viewingKeyNk)]);
|
|
13007
|
+
for (const nk of legacyNks) {
|
|
13008
|
+
if (!(nk instanceof Uint8Array) || nk.length !== 32) throw new Error("legacyViewingKeyNks entries must be 32 bytes");
|
|
13009
|
+
const key = toHex2(nk);
|
|
13010
|
+
if (seenNks.has(key)) continue;
|
|
13011
|
+
seenNks.add(key);
|
|
13012
|
+
trials.push(await makeTrial(Uint8Array.from(nk), true));
|
|
13013
|
+
}
|
|
13014
|
+
const poolMints = Array.from(new Set(params.poolMints));
|
|
13015
|
+
const warnings = [];
|
|
13016
|
+
const head = await fetchNoteIndexHead(relayUrl, { signal: params.signal });
|
|
13017
|
+
let cursor;
|
|
13018
|
+
if (params.cursor !== void 0) {
|
|
13019
|
+
const checked = await parseCursor(params.cursor, poolMints);
|
|
13020
|
+
if (typeof checked === "string") warnings.push(`note index cursor is unusable (${checked}); re-syncing from page 0`);
|
|
13021
|
+
else if (BigInt(checked.raw.epoch) !== head.epoch) warnings.push("note index epoch changed; re-syncing from page 0");
|
|
13022
|
+
else if (head.watermark < checked.raw.watermark || head.completePages < checked.raw.page) {
|
|
13023
|
+
throw new NoteIndexHeadBehindError(checked.raw.watermark, head.watermark);
|
|
13024
|
+
} else cursor = checked;
|
|
13025
|
+
}
|
|
13026
|
+
const treePdas = await Promise.all(poolMints.map(async (mint) => (await getShieldPoolPDAs(programId, mint)).merkleTree));
|
|
13027
|
+
let treeRead;
|
|
13028
|
+
const readTrees = () => treeRead ?? (treeRead = (async () => {
|
|
13029
|
+
const accounts = poolMints.length > 0 ? await fetchMultipleAccountBytes(rpc, treePdas, "confirmed") : [];
|
|
13030
|
+
return poolMints.map((_, i) => {
|
|
13031
|
+
const account = accounts[i];
|
|
13032
|
+
const parsed = account ? readTreeAccountFrontier(account.data) : null;
|
|
13033
|
+
return account && parsed ? { ...parsed, data: account.data } : null;
|
|
13034
|
+
});
|
|
13035
|
+
})());
|
|
13036
|
+
const ctx = { params, head, trials, owner, stats, poolMints, warnings, readTrees };
|
|
13037
|
+
let outcome = await runOnce(ctx, cursor);
|
|
13038
|
+
if (outcome instanceof FullPassSignal) {
|
|
13039
|
+
warnings.push(`${outcome.reason}; re-syncing from page 0`);
|
|
13040
|
+
Object.assign(stats, { dropped: 0, decrypted: 0, candidates: 0, spent: 0, conflicts: 0, pendingDropped: 0, skipped: 0 });
|
|
13041
|
+
outcome = await runOnce(ctx, void 0);
|
|
13042
|
+
if (outcome instanceof FullPassSignal) throw new Error(`note index recovery failed: ${outcome.reason}`);
|
|
13043
|
+
}
|
|
13044
|
+
if (stats.skipped > 0) warnings.push(`${stats.skipped} note index entries could not be processed and were skipped`);
|
|
13045
|
+
stats.ms = Date.now() - startedAt;
|
|
13046
|
+
return { ...outcome, stats, warnings };
|
|
13047
|
+
}
|
|
13048
|
+
async function runOnce(ctx, cursor) {
|
|
13049
|
+
const { params, head, trials, owner, stats, poolMints } = ctx;
|
|
13050
|
+
const { relayUrl, onProgress } = params;
|
|
13051
|
+
const poolSet = new Set(poolMints);
|
|
13052
|
+
const startPage = cursor?.raw.page ?? 0;
|
|
13053
|
+
const startChain = cursor?.raw.chain ?? ZERO_CHAIN;
|
|
13054
|
+
const fullPassSeq = cursor?.raw.fullPassSeq ?? 0;
|
|
13055
|
+
const pagesTotal = Math.ceil(head.watermark / NOTE_INDEX_PAGE_SIZE);
|
|
13056
|
+
const targetPage = Math.max(startPage, floorAlign(head.completePages));
|
|
13057
|
+
const startTrees = new Map(poolMints.map((m) => [m, cursor?.trees.get(m) ?? emptyStartTree()]));
|
|
13058
|
+
const rejectedIds = new Set(cursor?.rejected ?? []);
|
|
13059
|
+
const controller = new AbortController();
|
|
13060
|
+
const onCallerAbort = () => controller.abort();
|
|
13061
|
+
params.signal?.addEventListener("abort", onCallerAbort, { once: true });
|
|
13062
|
+
const signal = controller.signal;
|
|
13063
|
+
try {
|
|
13064
|
+
const pageData = /* @__PURE__ */ new Map();
|
|
13065
|
+
const ownItems = [];
|
|
13066
|
+
const nullifiers = /* @__PURE__ */ new Set();
|
|
13067
|
+
let fullPassReason = null;
|
|
13068
|
+
const lateReference = (mint, leaf, value, seq) => {
|
|
13069
|
+
if (!cursor || seq < fullPassSeq) return null;
|
|
13070
|
+
const t = startTrees.get(mint);
|
|
13071
|
+
if (leaf < t.nextIndex) {
|
|
13072
|
+
if (leaf < t.windowStart) return "a later item refers to the tree before the cursor";
|
|
13073
|
+
if (value !== void 0 && value !== t.window[leaf - t.windowStart]) return "a later item rewrites the tree before the cursor";
|
|
13074
|
+
return null;
|
|
13075
|
+
}
|
|
13076
|
+
const held = t.pending.get(leaf);
|
|
13077
|
+
if (held !== void 0) return value !== void 0 && value !== held ? "a later item rewrites the tree before the cursor" : null;
|
|
13078
|
+
if (value !== void 0 && leaf < t.hiBefore) return "a later item fills the tree before the cursor";
|
|
13079
|
+
return null;
|
|
13080
|
+
};
|
|
13081
|
+
const chainAt = /* @__PURE__ */ new Map([[startPage, startChain]]);
|
|
13082
|
+
const waiting = /* @__PURE__ */ new Map();
|
|
13083
|
+
let chainNext = startPage;
|
|
13084
|
+
let chainError = null;
|
|
13085
|
+
let wakers = [];
|
|
13086
|
+
const wakeAll = () => {
|
|
13087
|
+
const w = wakers;
|
|
13088
|
+
wakers = [];
|
|
13089
|
+
for (const f of w) f();
|
|
13090
|
+
};
|
|
13091
|
+
signal.addEventListener("abort", wakeAll);
|
|
13092
|
+
const advanceChain = () => {
|
|
13093
|
+
while (!chainError && waiting.has(chainNext)) {
|
|
13094
|
+
const w = waiting.get(chainNext);
|
|
13095
|
+
waiting.delete(chainNext);
|
|
13096
|
+
const expected = chainAt.get(chainNext);
|
|
13097
|
+
if (w.prevChain !== expected) {
|
|
13098
|
+
chainError = cursor && chainNext === startPage ? new FullPassSignal("note index hash chain does not continue from the cursor") : new NoteIndexFormatError(`hash chain broken at page ${chainNext}`);
|
|
13099
|
+
controller.abort();
|
|
13100
|
+
return;
|
|
13101
|
+
}
|
|
13102
|
+
if (!w.complete) break;
|
|
13103
|
+
chainAt.set(chainNext + 1, toHex2(computeNoteIndexChain(fromHex(expected), w.bytes)));
|
|
13104
|
+
chainNext++;
|
|
13105
|
+
}
|
|
13106
|
+
wakeAll();
|
|
13107
|
+
};
|
|
13108
|
+
const workerCount = Math.max(1, Math.min(params.concurrency ?? DEFAULT_CONCURRENCY, pagesTotal - startPage));
|
|
13109
|
+
const lookahead = 2 * workerCount + 2;
|
|
13110
|
+
let nextToFetch = startPage;
|
|
13111
|
+
let pagesDone = 0;
|
|
13112
|
+
const worker = async () => {
|
|
13113
|
+
for (; ; ) {
|
|
13114
|
+
if (signal.aborted) throw abortError2();
|
|
13115
|
+
const pageNo = nextToFetch++;
|
|
13116
|
+
if (pageNo >= pagesTotal) return;
|
|
13117
|
+
while (pageNo - chainNext >= lookahead && !signal.aborted) await new Promise((resolve) => wakers.push(resolve));
|
|
13118
|
+
if (signal.aborted) throw abortError2();
|
|
13119
|
+
const bytes = await fetchNoteIndexPage(relayUrl, head.epoch, pageNo, { signal });
|
|
13120
|
+
stats.bytes += bytes.length;
|
|
13121
|
+
const page2 = parseNoteIndexPage(bytes, { epoch: head.epoch, page: pageNo }, { skipMalformedItems: true });
|
|
13122
|
+
if (pageNo < head.completePages && !page2.complete) {
|
|
13123
|
+
throw new NoteIndexFormatError(`page ${pageNo} is below complete_pages but not complete`);
|
|
13124
|
+
}
|
|
13125
|
+
stats.pages++;
|
|
13126
|
+
stats.skipped += page2.skippedMalformed;
|
|
13127
|
+
const seqOf = (i) => pageNo * NOTE_INDEX_PAGE_SIZE + page2.itemPositions[i];
|
|
13128
|
+
waiting.set(pageNo, { bytes: page2.complete ? bytes : new Uint8Array(0), prevChain: toHex2(page2.prevChain), complete: page2.complete });
|
|
13129
|
+
advanceChain();
|
|
13130
|
+
const data = { complete: page2.complete, leaves: /* @__PURE__ */ new Map() };
|
|
13131
|
+
const late = (reason) => {
|
|
13132
|
+
if (reason && !fullPassReason) {
|
|
13133
|
+
fullPassReason = reason;
|
|
13134
|
+
controller.abort();
|
|
13135
|
+
}
|
|
13136
|
+
};
|
|
13137
|
+
const addLeaf = (mintBytes, commitment, leaf, seq) => {
|
|
13138
|
+
if (isAllZero3(commitment)) return;
|
|
13139
|
+
const mint = addressFromBytes(mintBytes);
|
|
13140
|
+
if (!poolSet.has(mint)) return;
|
|
13141
|
+
const entry = { leaf: Number(leaf), commitment: bytesToBigint2(commitment) };
|
|
13142
|
+
late(lateReference(mint, entry.leaf, entry.commitment, seq));
|
|
13143
|
+
const list = data.leaves.get(mint);
|
|
13144
|
+
if (list) list.push(entry);
|
|
13145
|
+
else data.leaves.set(mint, [entry]);
|
|
13146
|
+
};
|
|
13147
|
+
page2.items.forEach((item, i) => {
|
|
13148
|
+
const seq = seqOf(i);
|
|
13149
|
+
if (item.kind === 1) {
|
|
13150
|
+
addLeaf(item.mint, item.comm0, item.leaf0, seq);
|
|
13151
|
+
addLeaf(item.mint, item.comm1, item.leaf1, seq);
|
|
13152
|
+
if (!isAllZero3(item.nullifier0)) nullifiers.add(toHex2(item.nullifier0));
|
|
13153
|
+
if (!isAllZero3(item.nullifier1)) nullifiers.add(toHex2(item.nullifier1));
|
|
13154
|
+
} else if (item.kind === 3) {
|
|
13155
|
+
addLeaf(item.mint, item.commitment, item.leaf, seq);
|
|
13156
|
+
} else {
|
|
13157
|
+
const mint = addressFromBytes(item.mint);
|
|
13158
|
+
if (poolSet.has(mint)) late(lateReference(mint, Number(item.leaf), void 0, seq));
|
|
13159
|
+
}
|
|
13160
|
+
});
|
|
13161
|
+
if (signal.aborted) throw abortError2();
|
|
13162
|
+
for (let i = 0; i < page2.items.length; i += ITEM_BATCH) {
|
|
13163
|
+
if (signal.aborted) throw abortError2();
|
|
13164
|
+
const batch = page2.items.slice(i, i + ITEM_BATCH);
|
|
13165
|
+
const opened = await Promise.all(batch.map((item) => trialItemIsolated(item, trials, stats)));
|
|
13166
|
+
opened.forEach((o, k) => {
|
|
13167
|
+
if (!o) return;
|
|
13168
|
+
stats.decrypted++;
|
|
13169
|
+
const raw = page2.rawItems[i + k];
|
|
13170
|
+
const id = itemIdentity(raw);
|
|
13171
|
+
if (rejectedIds.has(id)) {
|
|
13172
|
+
stats.dropped++;
|
|
13173
|
+
return;
|
|
13174
|
+
}
|
|
13175
|
+
ownItems.push({ page: pageNo, seq: seqOf(i + k), raw, id, item: batch[k], fromCursor: false, ...o, trial: o.trial });
|
|
13176
|
+
});
|
|
13177
|
+
stats.items += batch.length;
|
|
13178
|
+
}
|
|
13179
|
+
pageData.set(pageNo, data);
|
|
13180
|
+
pagesDone++;
|
|
13181
|
+
onProgress?.({ pagesDone, pagesTotal: pagesTotal - startPage, itemsChecked: stats.items, notesFound: ownItems.length });
|
|
13182
|
+
}
|
|
13183
|
+
};
|
|
13184
|
+
const workers = Array.from(
|
|
13185
|
+
{ length: workerCount },
|
|
13186
|
+
() => worker().catch((error) => {
|
|
13187
|
+
controller.abort();
|
|
13188
|
+
throw error;
|
|
13189
|
+
})
|
|
13190
|
+
);
|
|
13191
|
+
const settled = await Promise.allSettled(workers);
|
|
13192
|
+
signal.removeEventListener("abort", wakeAll);
|
|
13193
|
+
if (params.signal?.aborted) throw abortError2();
|
|
13194
|
+
const lateReason = fullPassReason;
|
|
13195
|
+
if (lateReason) return new FullPassSignal(lateReason);
|
|
13196
|
+
const chainFailure = chainError;
|
|
13197
|
+
if (chainFailure) {
|
|
13198
|
+
if (chainFailure instanceof FullPassSignal) return chainFailure;
|
|
13199
|
+
throw chainFailure;
|
|
13200
|
+
}
|
|
13201
|
+
const failure = settled.find((s) => s.status === "rejected" && s.reason?.name !== "AbortError") ?? settled.find((s) => s.status === "rejected");
|
|
13202
|
+
if (failure) throw failure.reason;
|
|
13203
|
+
if (head.completePages >= startPage && chainAt.get(head.completePages) !== head.chainTip) {
|
|
13204
|
+
if (cursor) return new FullPassSignal("note index hash chain does not reach the head's chain_tip");
|
|
13205
|
+
throw new NoteIndexFormatError("hash chain does not reach the head's chain_tip");
|
|
13206
|
+
}
|
|
13207
|
+
for (const entry of cursor?.items ?? []) {
|
|
13208
|
+
const o = await trialItemIsolated(entry.item, trials, stats);
|
|
13209
|
+
if (!o) continue;
|
|
13210
|
+
const page2 = Math.floor(entry.seq / NOTE_INDEX_PAGE_SIZE);
|
|
13211
|
+
ownItems.push({ page: page2, seq: entry.seq, raw: entry.raw, id: itemIdentity(entry.raw), item: entry.item, fromCursor: true, ...o, trial: o.trial });
|
|
13212
|
+
if (entry.item.kind === 1) {
|
|
13213
|
+
if (!isAllZero3(entry.item.nullifier0)) nullifiers.add(toHex2(entry.item.nullifier0));
|
|
13214
|
+
if (!isAllZero3(entry.item.nullifier1)) nullifiers.add(toHex2(entry.item.nullifier1));
|
|
13215
|
+
}
|
|
13216
|
+
}
|
|
13217
|
+
const knownSpent = cursor?.spent ?? /* @__PURE__ */ new Set();
|
|
13218
|
+
ownItems.sort((a, b) => a.seq - b.seq);
|
|
13219
|
+
const rejectedNow = /* @__PURE__ */ new Set();
|
|
13220
|
+
const skippedNow = /* @__PURE__ */ new Set();
|
|
13221
|
+
const allCandidates = await matchOwnItems(
|
|
13222
|
+
ownItems,
|
|
13223
|
+
owner,
|
|
13224
|
+
(o) => {
|
|
13225
|
+
stats.dropped++;
|
|
13226
|
+
rejectedNow.add(o.id);
|
|
13227
|
+
},
|
|
13228
|
+
(o) => {
|
|
13229
|
+
if (skippedNow.has(o)) return;
|
|
13230
|
+
skippedNow.add(o);
|
|
13231
|
+
stats.skipped++;
|
|
13232
|
+
}
|
|
13233
|
+
);
|
|
13234
|
+
stats.candidates = allCandidates.length;
|
|
13235
|
+
const cutoff = params.legacyCutoffLeaf ?? {};
|
|
13236
|
+
const candidates = allCandidates.filter((c) => {
|
|
13237
|
+
const limit = cutoff[c.mint];
|
|
13238
|
+
if (c.atRisk && limit !== void 0 && BigInt(c.leaf) >= limit) {
|
|
13239
|
+
stats.dropped++;
|
|
13240
|
+
return false;
|
|
13241
|
+
}
|
|
13242
|
+
return true;
|
|
13243
|
+
});
|
|
13244
|
+
const chainTrees = await ctx.readTrees();
|
|
13245
|
+
const orderedPages = Array.from(pageData.keys()).sort((a, b) => a - b);
|
|
13246
|
+
const replays = /* @__PURE__ */ new Map();
|
|
13247
|
+
for (let i = 0; i < poolMints.length; i++) {
|
|
13248
|
+
const mint = poolMints[i];
|
|
13249
|
+
const start = startTrees.get(mint);
|
|
13250
|
+
const chainTree = chainTrees[i] ?? null;
|
|
13251
|
+
const pages = orderedPages.map((page2) => ({ page: page2, entries: pageData.get(page2).leaves.get(mint) ?? [] }));
|
|
13252
|
+
let r = await replayStream(start, pages, start.overrides, chainTree, targetPage);
|
|
13253
|
+
let overrides = start.overrides;
|
|
13254
|
+
stats.conflicts += r.conflicts;
|
|
13255
|
+
if (r.corrections.size > 0 && (r.mismatch || r.verifiedPrefix < r.endCount)) {
|
|
13256
|
+
const merged = new Map([...start.overrides, ...r.corrections]);
|
|
13257
|
+
const alternative = await replayStream(start, pages, merged, chainTree, targetPage);
|
|
13258
|
+
if (alternative.verifiedPrefix > r.verifiedPrefix || r.mismatch && !alternative.mismatch) {
|
|
13259
|
+
r = alternative;
|
|
13260
|
+
overrides = merged;
|
|
13261
|
+
}
|
|
13262
|
+
}
|
|
13263
|
+
if (r.mismatch && cursor && !start.mismatch) return new FullPassSignal("a rebuilt tree disagrees with the chain");
|
|
13264
|
+
replays.set(mint, { r, overrides });
|
|
13265
|
+
}
|
|
13266
|
+
const verifiedUpTo = (mint) => Math.max(startTrees.get(mint).verified, replays.get(mint).r.verifiedPrefix);
|
|
13267
|
+
const streamValue = (mint, leaf) => {
|
|
13268
|
+
const v = replays.get(mint)?.r.valueAt(leaf);
|
|
13269
|
+
if (v !== void 0) return v;
|
|
13270
|
+
const carried = cursor?.pendingLeaves.get(`${mint}:${leaf}`);
|
|
13271
|
+
if (carried !== void 0) return carried;
|
|
13272
|
+
const t = startTrees.get(mint);
|
|
13273
|
+
if (t && leaf >= t.windowStart && leaf < t.nextIndex) return t.window[leaf - t.windowStart];
|
|
13274
|
+
return void 0;
|
|
13275
|
+
};
|
|
13276
|
+
const knownVerified = cursor?.verified ?? /* @__PURE__ */ new Set();
|
|
13277
|
+
const verified = [];
|
|
13278
|
+
const pendingByKey = /* @__PURE__ */ new Map();
|
|
13279
|
+
const rejectedCandidates = /* @__PURE__ */ new Set();
|
|
13280
|
+
const outcomeOf = /* @__PURE__ */ new Map();
|
|
13281
|
+
const tally = (c, what) => {
|
|
13282
|
+
const t = outcomeOf.get(c.seq) ?? { kept: false, rejected: 0, total: 0 };
|
|
13283
|
+
t.total++;
|
|
13284
|
+
if (what === "kept") t.kept = true;
|
|
13285
|
+
if (what === "rejected") t.rejected++;
|
|
13286
|
+
outcomeOf.set(c.seq, t);
|
|
13287
|
+
};
|
|
13288
|
+
const pend = (c, rank) => {
|
|
13289
|
+
const key = verifiedKey(c.mint, c.leaf, c.commitment);
|
|
13290
|
+
const prior = pendingByKey.get(key);
|
|
13291
|
+
if (!prior || prior.c.seq > c.seq) pendingByKey.set(key, { c, rank });
|
|
13292
|
+
};
|
|
13293
|
+
for (const c of candidates) {
|
|
13294
|
+
if (knownVerified.has(verifiedKey(c.mint, c.leaf, c.commitment))) {
|
|
13295
|
+
verified.push(c);
|
|
13296
|
+
continue;
|
|
13297
|
+
}
|
|
13298
|
+
if (!poolSet.has(c.mint)) {
|
|
13299
|
+
pend(c, 3);
|
|
13300
|
+
continue;
|
|
13301
|
+
}
|
|
13302
|
+
const value = streamValue(c.mint, c.leaf);
|
|
13303
|
+
if (value === void 0) {
|
|
13304
|
+
if (c.leaf < startTrees.get(c.mint).nextIndex) {
|
|
13305
|
+
stats.dropped++;
|
|
13306
|
+
tally(c, "other");
|
|
13307
|
+
} else pend(c, 1);
|
|
13308
|
+
} else if (c.leaf >= verifiedUpTo(c.mint)) {
|
|
13309
|
+
pend(c, value === c.commitment ? 0 : 2);
|
|
13310
|
+
} else if (value === c.commitment) {
|
|
13311
|
+
verified.push(c);
|
|
13312
|
+
} else {
|
|
13313
|
+
stats.dropped++;
|
|
13314
|
+
rejectedCandidates.add(c);
|
|
13315
|
+
tally(c, "rejected");
|
|
13316
|
+
}
|
|
13317
|
+
}
|
|
13318
|
+
verified.sort((a, b) => a.seq - b.seq);
|
|
13319
|
+
const byLeaf = /* @__PURE__ */ new Map();
|
|
13320
|
+
for (const c of verified) {
|
|
13321
|
+
const key = `${c.mint}:${c.leaf}`;
|
|
13322
|
+
if (byLeaf.has(key)) {
|
|
13323
|
+
stats.dropped++;
|
|
13324
|
+
tally(c, "other");
|
|
13325
|
+
continue;
|
|
13326
|
+
}
|
|
13327
|
+
byLeaf.set(key, c);
|
|
13328
|
+
}
|
|
13329
|
+
const notes = [];
|
|
13330
|
+
const atRisk = [];
|
|
13331
|
+
const spentOut = new Set(knownSpent);
|
|
13332
|
+
const verifiedOut = new Set(knownVerified);
|
|
13333
|
+
const keyChecked = /* @__PURE__ */ new Map();
|
|
13334
|
+
for (const c of byLeaf.values()) {
|
|
13335
|
+
const pubOk = keyChecked.get(c.keypair.privateKey) ?? (c.keypair.privateKey !== 0n && await derivePublicKey(c.keypair.privateKey) === c.keypair.publicKey);
|
|
13336
|
+
keyChecked.set(c.keypair.privateKey, pubOk);
|
|
13337
|
+
if (!pubOk || !c.atRisk && c.keypair.publicKey !== owner.publicKey) {
|
|
13338
|
+
stats.dropped++;
|
|
13339
|
+
tally(c, "rejected");
|
|
13340
|
+
continue;
|
|
13341
|
+
}
|
|
13342
|
+
tally(c, "kept");
|
|
13343
|
+
verifiedOut.add(verifiedKey(c.mint, c.leaf, c.commitment));
|
|
13344
|
+
const utxo = {
|
|
13345
|
+
amount: c.amount,
|
|
13346
|
+
keypair: c.atRisk ? { ...c.keypair } : owner,
|
|
13347
|
+
blinding: c.blinding,
|
|
13348
|
+
mintAddress: c.mint,
|
|
13349
|
+
index: c.leaf,
|
|
13350
|
+
commitment: c.commitment
|
|
13351
|
+
};
|
|
13352
|
+
if (nullifiers.has(c.nullifier) || knownSpent.has(c.nullifier)) {
|
|
13353
|
+
stats.spent++;
|
|
13354
|
+
spentOut.add(c.nullifier);
|
|
13355
|
+
continue;
|
|
13356
|
+
}
|
|
13357
|
+
const note = {
|
|
13358
|
+
kind: c.kind,
|
|
13359
|
+
utxo,
|
|
13360
|
+
signature: bs584.encode(c.signature),
|
|
13361
|
+
legacyExposed: c.atRisk
|
|
13362
|
+
};
|
|
13363
|
+
(c.atRisk ? atRisk : notes).push(note);
|
|
13364
|
+
}
|
|
13365
|
+
const sortNotes = (list) => list.sort((a, b) => a.utxo.mintAddress === b.utxo.mintAddress ? a.utxo.index - b.utxo.index : a.utxo.mintAddress < b.utxo.mintAddress ? -1 : 1);
|
|
13366
|
+
sortNotes(notes);
|
|
13367
|
+
sortNotes(atRisk);
|
|
13368
|
+
const pendingList = Array.from(pendingByKey.values()).sort((a, b) => a.rank - b.rank || a.c.seq - b.c.seq);
|
|
13369
|
+
const carriedPending = pendingList.slice(0, MAX_CARRIED_PENDING).map((p) => p.c);
|
|
13370
|
+
const overflow = pendingList.length - carriedPending.length;
|
|
13371
|
+
if (overflow > 0) {
|
|
13372
|
+
stats.pendingDropped += overflow;
|
|
13373
|
+
ctx.warnings.push(`${overflow} unverified candidates over the carry limit were not carried to the next run`);
|
|
13374
|
+
}
|
|
13375
|
+
for (const { c } of pendingList) if (nullifiers.has(c.nullifier)) spentOut.add(c.nullifier);
|
|
13376
|
+
for (const c of carriedPending) tally(c, "kept");
|
|
13377
|
+
for (const { c } of pendingList.slice(MAX_CARRIED_PENDING)) tally(c, "other");
|
|
13378
|
+
let page = targetPage;
|
|
13379
|
+
for (const { r } of replays.values()) if (r.snapshot === null) page = startPage;
|
|
13380
|
+
const trees = {};
|
|
13381
|
+
const treeEnd = /* @__PURE__ */ new Map();
|
|
13382
|
+
for (const mint of poolMints) {
|
|
13383
|
+
const start = startTrees.get(mint);
|
|
13384
|
+
const { r, overrides } = replays.get(mint);
|
|
13385
|
+
const snap = page === startPage ? { frontier: start.frontier ?? (await MerkleFrontier.create()).toState(), pending: start.pending, nextIndex: start.nextIndex } : r.snapshot;
|
|
13386
|
+
const n = snap.nextIndex;
|
|
13387
|
+
const window2 = [];
|
|
13388
|
+
for (let leaf = n - 1; leaf >= Math.max(0, n - LEAF_WINDOW); leaf--) {
|
|
13389
|
+
const v = leaf >= start.nextIndex ? r.valueAt(leaf) : leaf >= start.windowStart ? start.window[leaf - start.windowStart] : void 0;
|
|
13390
|
+
if (v === void 0) break;
|
|
13391
|
+
window2.push(hex32(v));
|
|
13392
|
+
}
|
|
13393
|
+
window2.reverse();
|
|
13394
|
+
trees[mint] = {
|
|
13395
|
+
frontier: snap.frontier,
|
|
13396
|
+
pending: Array.from(snap.pending.entries(), ([leaf, v]) => [leaf, hex32(v)]).sort((a, b) => a[0] - b[0]),
|
|
13397
|
+
window: window2.join(""),
|
|
13398
|
+
verified: Math.min(verifiedUpTo(mint), n),
|
|
13399
|
+
overrides: Array.from(overrides.entries()).filter(([leaf]) => leaf >= n && !snap.pending.has(leaf)).sort((a, b) => a[0] - b[0]).slice(0, MAX_OVERRIDES).map(([leaf, v]) => [leaf, hex32(v)]),
|
|
13400
|
+
mismatch: r.mismatch
|
|
13401
|
+
};
|
|
13402
|
+
treeEnd.set(mint, { nextIndex: n, pending: snap.pending });
|
|
13403
|
+
}
|
|
13404
|
+
const pendingLeaves = [];
|
|
13405
|
+
const pendingLeafSeen = /* @__PURE__ */ new Set();
|
|
13406
|
+
for (const c of carriedPending) {
|
|
13407
|
+
const end = treeEnd.get(c.mint);
|
|
13408
|
+
if (!end || c.leaf >= end.nextIndex) continue;
|
|
13409
|
+
const value = streamValue(c.mint, c.leaf);
|
|
13410
|
+
const key = `${c.mint}:${c.leaf}`;
|
|
13411
|
+
if (value === void 0 || pendingLeafSeen.has(key)) continue;
|
|
13412
|
+
pendingLeafSeen.add(key);
|
|
13413
|
+
pendingLeaves.push([c.mint, c.leaf, hex32(value)]);
|
|
13414
|
+
}
|
|
13415
|
+
const keptItems = [];
|
|
13416
|
+
const keptIds = /* @__PURE__ */ new Set();
|
|
13417
|
+
for (const o of ownItems) {
|
|
13418
|
+
const t = outcomeOf.get(o.seq);
|
|
13419
|
+
if (rejectedNow.has(o.id) || t && t.total > 0 && t.rejected === t.total) {
|
|
13420
|
+
rejectedNow.add(o.id);
|
|
13421
|
+
continue;
|
|
13422
|
+
}
|
|
13423
|
+
if (o.page >= page || !t?.kept || keptIds.has(o.id)) continue;
|
|
13424
|
+
keptIds.add(o.id);
|
|
13425
|
+
keptItems.push({ seq: o.seq, item: toHex2(o.raw) });
|
|
13426
|
+
}
|
|
13427
|
+
const rejected = Array.from(/* @__PURE__ */ new Set([...cursor?.rejected ?? [], ...rejectedNow]));
|
|
13428
|
+
const nextCursor = {
|
|
13429
|
+
v: CURSOR_VERSION,
|
|
13430
|
+
epoch: head.epoch.toString(10),
|
|
13431
|
+
page,
|
|
13432
|
+
chain: chainAt.get(page) ?? startChain,
|
|
13433
|
+
watermark: Math.max(cursor?.raw.watermark ?? 0, head.watermark),
|
|
13434
|
+
fullPassSeq: cursor ? fullPassSeq : head.watermark,
|
|
13435
|
+
trees,
|
|
13436
|
+
own: {
|
|
13437
|
+
items: keptItems,
|
|
13438
|
+
verified: Array.from(verifiedOut),
|
|
13439
|
+
spent: Array.from(spentOut),
|
|
13440
|
+
pendingLeaves,
|
|
13441
|
+
rejected: rejected.slice(Math.max(0, rejected.length - MAX_REJECTED_IDS))
|
|
13442
|
+
}
|
|
13443
|
+
};
|
|
13444
|
+
return { notes, atRisk, pending: pendingByKey.size, cursor: nextCursor };
|
|
13445
|
+
} finally {
|
|
13446
|
+
params.signal?.removeEventListener("abort", onCallerAbort);
|
|
13447
|
+
}
|
|
13448
|
+
}
|
|
13449
|
+
|
|
11616
13450
|
// src/wallet/utxo-wallet.ts
|
|
11617
13451
|
var UtxoWallet = class _UtxoWallet {
|
|
11618
13452
|
constructor(viewingKey) {
|
|
@@ -11967,7 +13801,7 @@ async function loadWeb3() {
|
|
|
11967
13801
|
|
|
11968
13802
|
// src/bridge/rail-verify.ts
|
|
11969
13803
|
import nacl6 from "tweetnacl";
|
|
11970
|
-
import { sha256 as
|
|
13804
|
+
import { sha256 as sha2567 } from "@noble/hashes/sha256";
|
|
11971
13805
|
var ONECLICK_PUBKEY_B58 = "reYaWhvwu8Jzo3WUM3zhn6VrhuMEF4eADL17qtRVifc";
|
|
11972
13806
|
var b58 = /* @__PURE__ */ (() => {
|
|
11973
13807
|
const A = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
@@ -12073,7 +13907,7 @@ function canonicalPayloadString(resp) {
|
|
|
12073
13907
|
function verifyQuoteSignature(resp) {
|
|
12074
13908
|
if (!resp?.signature) return { valid: false, reason: "no signature on the response" };
|
|
12075
13909
|
const payload = { ...signedRequest(resp), ...signedQuote(resp), timestamp: resp.timestamp };
|
|
12076
|
-
const digest =
|
|
13910
|
+
const digest = sha2567(new TextEncoder().encode(stable(payload)));
|
|
12077
13911
|
const message = new TextEncoder().encode(b58.encode(new Uint8Array(digest)));
|
|
12078
13912
|
const sig = resp.signature.replace(/^ed25519:/, "");
|
|
12079
13913
|
try {
|
|
@@ -12823,13 +14657,13 @@ var DoNotRetry = class extends Error {
|
|
|
12823
14657
|
};
|
|
12824
14658
|
async function withShieldRetries(attempt, hooks = {}) {
|
|
12825
14659
|
const attempts = hooks.attempts ?? 3;
|
|
12826
|
-
const
|
|
14660
|
+
const sleep5 = hooks.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
12827
14661
|
let last = "";
|
|
12828
14662
|
for (let n = 1; n <= attempts; n++) {
|
|
12829
14663
|
if (n > 1) {
|
|
12830
14664
|
const delay = retryDelayMs(n);
|
|
12831
14665
|
hooks.onRetry?.(n, delay, last);
|
|
12832
|
-
await
|
|
14666
|
+
await sleep5(delay);
|
|
12833
14667
|
}
|
|
12834
14668
|
try {
|
|
12835
14669
|
return await attempt(n);
|
|
@@ -12877,6 +14711,10 @@ export {
|
|
|
12877
14711
|
MemoryStorageAdapter,
|
|
12878
14712
|
MerkleTree,
|
|
12879
14713
|
NATIVE_SOL_MINT,
|
|
14714
|
+
NOTE_INDEX_NO_LEAF,
|
|
14715
|
+
NOTE_INDEX_PAGE_SIZE,
|
|
14716
|
+
NoteIndexFormatError,
|
|
14717
|
+
NoteIndexHeadBehindError,
|
|
12880
14718
|
ONECLICK_PUBKEY_B58,
|
|
12881
14719
|
RECIPIENT_DELIVERY_CIPHERTEXT_LEN,
|
|
12882
14720
|
RECIPIENT_DELIVERY_EPHEMERAL_PK_LEN,
|
|
@@ -12953,6 +14791,7 @@ export {
|
|
|
12953
14791
|
computeChainNoteHash,
|
|
12954
14792
|
computeExtDataHash,
|
|
12955
14793
|
computeMerkleRoot,
|
|
14794
|
+
computeNoteIndexChain,
|
|
12956
14795
|
computeProofForLatestDeposit,
|
|
12957
14796
|
computeProofFromChain,
|
|
12958
14797
|
computeSignature,
|
|
@@ -13001,6 +14840,8 @@ export {
|
|
|
13001
14840
|
discoverSwapRefunds,
|
|
13002
14841
|
downloadNote,
|
|
13003
14842
|
encodeDeliveryCarrierMemo,
|
|
14843
|
+
encodeNoteIndexItem,
|
|
14844
|
+
encodeNoteIndexPage,
|
|
13004
14845
|
encodeNoteSimple,
|
|
13005
14846
|
encodeRecipientDeliveryNote,
|
|
13006
14847
|
encryptCompactChainNote,
|
|
@@ -13016,6 +14857,8 @@ export {
|
|
|
13016
14857
|
fetchCommitments,
|
|
13017
14858
|
fetchLatestBlockhash,
|
|
13018
14859
|
fetchLookupTables,
|
|
14860
|
+
fetchNoteIndexHead,
|
|
14861
|
+
fetchNoteIndexPage,
|
|
13019
14862
|
fetchRiskQuoteInstruction,
|
|
13020
14863
|
fetchRiskQuoteIx,
|
|
13021
14864
|
fetchSignaturesForAddress,
|
|
@@ -13088,6 +14931,8 @@ export {
|
|
|
13088
14931
|
parseDeliveryCarrierMemo,
|
|
13089
14932
|
parseError,
|
|
13090
14933
|
parseNote2 as parseNote,
|
|
14934
|
+
parseNoteIndexItem,
|
|
14935
|
+
parseNoteIndexPage,
|
|
13091
14936
|
parseRelayErrorResponse,
|
|
13092
14937
|
parseRelayErrorSignature,
|
|
13093
14938
|
parseTransactionError,
|
|
@@ -13109,6 +14954,7 @@ export {
|
|
|
13109
14954
|
readMerkleTreeState,
|
|
13110
14955
|
readRent,
|
|
13111
14956
|
recipientDeliveryNoteToBase64,
|
|
14957
|
+
recoverNotesFromIndex,
|
|
13112
14958
|
registerViewingKey,
|
|
13113
14959
|
relayRequestDigestHex,
|
|
13114
14960
|
removePendingDeposit,
|