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