@unicitylabs/sphere-sdk 0.3.7 → 0.3.9
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/dist/connect/index.cjs +770 -0
- package/dist/connect/index.cjs.map +1 -0
- package/dist/connect/index.d.cts +312 -0
- package/dist/connect/index.d.ts +312 -0
- package/dist/connect/index.js +747 -0
- package/dist/connect/index.js.map +1 -0
- package/dist/core/index.cjs +90 -2502
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +10 -165
- package/dist/core/index.d.ts +10 -165
- package/dist/core/index.js +86 -2498
- package/dist/core/index.js.map +1 -1
- package/dist/impl/browser/connect/index.cjs +271 -0
- package/dist/impl/browser/connect/index.cjs.map +1 -0
- package/dist/impl/browser/connect/index.d.cts +137 -0
- package/dist/impl/browser/connect/index.d.ts +137 -0
- package/dist/impl/browser/connect/index.js +248 -0
- package/dist/impl/browser/connect/index.js.map +1 -0
- package/dist/impl/browser/index.cjs +201 -28
- package/dist/impl/browser/index.cjs.map +1 -1
- package/dist/impl/browser/index.js +201 -28
- package/dist/impl/browser/index.js.map +1 -1
- package/dist/impl/browser/ipfs.cjs +6 -1
- package/dist/impl/browser/ipfs.cjs.map +1 -1
- package/dist/impl/browser/ipfs.js +6 -1
- package/dist/impl/browser/ipfs.js.map +1 -1
- package/dist/impl/nodejs/connect/index.cjs +372 -0
- package/dist/impl/nodejs/connect/index.cjs.map +1 -0
- package/dist/impl/nodejs/connect/index.d.cts +178 -0
- package/dist/impl/nodejs/connect/index.d.ts +178 -0
- package/dist/impl/nodejs/connect/index.js +333 -0
- package/dist/impl/nodejs/connect/index.js.map +1 -0
- package/dist/impl/nodejs/index.cjs +201 -28
- package/dist/impl/nodejs/index.cjs.map +1 -1
- package/dist/impl/nodejs/index.d.cts +2 -21
- package/dist/impl/nodejs/index.d.ts +2 -21
- package/dist/impl/nodejs/index.js +201 -28
- package/dist/impl/nodejs/index.js.map +1 -1
- package/dist/index.cjs +232 -2513
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +59 -169
- package/dist/index.d.ts +59 -169
- package/dist/index.js +228 -2506
- package/dist/index.js.map +1 -1
- package/package.json +31 -1
package/dist/index.js
CHANGED
|
@@ -59,10 +59,10 @@ function bech32Polymod(values) {
|
|
|
59
59
|
}
|
|
60
60
|
function bech32Checksum(hrp, data) {
|
|
61
61
|
const values = hrpExpand(hrp).concat(data).concat([0, 0, 0, 0, 0, 0]);
|
|
62
|
-
const
|
|
62
|
+
const mod = bech32Polymod(values) ^ 1;
|
|
63
63
|
const ret = [];
|
|
64
64
|
for (let p = 0; p < 6; p++) {
|
|
65
|
-
ret.push(
|
|
65
|
+
ret.push(mod >> 5 * (5 - p) & 31);
|
|
66
66
|
}
|
|
67
67
|
return ret;
|
|
68
68
|
}
|
|
@@ -2494,7 +2494,11 @@ var STORAGE_KEYS_GLOBAL = {
|
|
|
2494
2494
|
/** Cached token registry JSON (fetched from remote) */
|
|
2495
2495
|
TOKEN_REGISTRY_CACHE: "token_registry_cache",
|
|
2496
2496
|
/** Timestamp of last token registry cache update (ms since epoch) */
|
|
2497
|
-
TOKEN_REGISTRY_CACHE_TS: "token_registry_cache_ts"
|
|
2497
|
+
TOKEN_REGISTRY_CACHE_TS: "token_registry_cache_ts",
|
|
2498
|
+
/** Cached price data JSON (from CoinGecko or other provider) */
|
|
2499
|
+
PRICE_CACHE: "price_cache",
|
|
2500
|
+
/** Timestamp of last price cache update (ms since epoch) */
|
|
2501
|
+
PRICE_CACHE_TS: "price_cache_ts"
|
|
2498
2502
|
};
|
|
2499
2503
|
var STORAGE_KEYS_ADDRESS = {
|
|
2500
2504
|
/** Pending transfers for this address */
|
|
@@ -2651,7 +2655,6 @@ var TIMEOUTS = {
|
|
|
2651
2655
|
/** Sync interval */
|
|
2652
2656
|
SYNC_INTERVAL: 6e4
|
|
2653
2657
|
};
|
|
2654
|
-
var DEFAULT_MARKET_API_URL = "https://market-api.unicity.network";
|
|
2655
2658
|
var LIMITS = {
|
|
2656
2659
|
/** Min nametag length */
|
|
2657
2660
|
NAMETAG_MIN_LENGTH: 3,
|
|
@@ -2719,6 +2722,7 @@ var TokenRegistry = class _TokenRegistry {
|
|
|
2719
2722
|
refreshTimer = null;
|
|
2720
2723
|
lastRefreshAt = 0;
|
|
2721
2724
|
refreshPromise = null;
|
|
2725
|
+
initialLoadPromise = null;
|
|
2722
2726
|
constructor() {
|
|
2723
2727
|
this.definitionsById = /* @__PURE__ */ new Map();
|
|
2724
2728
|
this.definitionsBySymbol = /* @__PURE__ */ new Map();
|
|
@@ -2757,13 +2761,8 @@ var TokenRegistry = class _TokenRegistry {
|
|
|
2757
2761
|
if (options.refreshIntervalMs !== void 0) {
|
|
2758
2762
|
instance.refreshIntervalMs = options.refreshIntervalMs;
|
|
2759
2763
|
}
|
|
2760
|
-
if (instance.storage) {
|
|
2761
|
-
instance.loadFromCache();
|
|
2762
|
-
}
|
|
2763
2764
|
const autoRefresh = options.autoRefresh ?? true;
|
|
2764
|
-
|
|
2765
|
-
instance.startAutoRefresh();
|
|
2766
|
-
}
|
|
2765
|
+
instance.initialLoadPromise = instance.performInitialLoad(autoRefresh);
|
|
2767
2766
|
}
|
|
2768
2767
|
/**
|
|
2769
2768
|
* Reset the singleton instance (useful for testing).
|
|
@@ -2781,6 +2780,53 @@ var TokenRegistry = class _TokenRegistry {
|
|
|
2781
2780
|
static destroy() {
|
|
2782
2781
|
_TokenRegistry.resetInstance();
|
|
2783
2782
|
}
|
|
2783
|
+
/**
|
|
2784
|
+
* Wait for the initial data load (cache or remote) to complete.
|
|
2785
|
+
* Returns true if data was loaded, false if not (timeout or no data source).
|
|
2786
|
+
*
|
|
2787
|
+
* @param timeoutMs - Maximum wait time in ms (default: 10s). Set to 0 for no timeout.
|
|
2788
|
+
*/
|
|
2789
|
+
static async waitForReady(timeoutMs = 1e4) {
|
|
2790
|
+
const instance = _TokenRegistry.getInstance();
|
|
2791
|
+
if (!instance.initialLoadPromise) {
|
|
2792
|
+
return instance.definitionsById.size > 0;
|
|
2793
|
+
}
|
|
2794
|
+
if (timeoutMs <= 0) {
|
|
2795
|
+
return instance.initialLoadPromise;
|
|
2796
|
+
}
|
|
2797
|
+
return Promise.race([
|
|
2798
|
+
instance.initialLoadPromise,
|
|
2799
|
+
new Promise((resolve) => setTimeout(() => resolve(false), timeoutMs))
|
|
2800
|
+
]);
|
|
2801
|
+
}
|
|
2802
|
+
// ===========================================================================
|
|
2803
|
+
// Initial Load
|
|
2804
|
+
// ===========================================================================
|
|
2805
|
+
/**
|
|
2806
|
+
* Perform initial data load: try cache first, fall back to remote fetch.
|
|
2807
|
+
* After initial data is available, start periodic auto-refresh if configured.
|
|
2808
|
+
*/
|
|
2809
|
+
async performInitialLoad(autoRefresh) {
|
|
2810
|
+
let loaded = false;
|
|
2811
|
+
if (this.storage) {
|
|
2812
|
+
loaded = await this.loadFromCache();
|
|
2813
|
+
}
|
|
2814
|
+
if (loaded) {
|
|
2815
|
+
if (autoRefresh && this.remoteUrl) {
|
|
2816
|
+
this.startAutoRefresh();
|
|
2817
|
+
}
|
|
2818
|
+
return true;
|
|
2819
|
+
}
|
|
2820
|
+
if (autoRefresh && this.remoteUrl) {
|
|
2821
|
+
loaded = await this.refreshFromRemote();
|
|
2822
|
+
this.stopAutoRefresh();
|
|
2823
|
+
this.refreshTimer = setInterval(() => {
|
|
2824
|
+
this.refreshFromRemote();
|
|
2825
|
+
}, this.refreshIntervalMs);
|
|
2826
|
+
return loaded;
|
|
2827
|
+
}
|
|
2828
|
+
return false;
|
|
2829
|
+
}
|
|
2784
2830
|
// ===========================================================================
|
|
2785
2831
|
// Cache (StorageProvider)
|
|
2786
2832
|
// ===========================================================================
|
|
@@ -3923,7 +3969,7 @@ var InstantSplitProcessor = class {
|
|
|
3923
3969
|
console.warn("[InstantSplitProcessor] Sender pubkey mismatch (non-fatal)");
|
|
3924
3970
|
}
|
|
3925
3971
|
const burnTxJson = JSON.parse(bundle.burnTransaction);
|
|
3926
|
-
const
|
|
3972
|
+
const _burnTransaction = await TransferTransaction.fromJSON(burnTxJson);
|
|
3927
3973
|
console.log("[InstantSplitProcessor] Burn transaction validated");
|
|
3928
3974
|
const mintDataJson = JSON.parse(bundle.recipientMintData);
|
|
3929
3975
|
const mintData = await MintTransactionData2.fromJSON(mintDataJson);
|
|
@@ -4588,6 +4634,7 @@ var PaymentsModule = class _PaymentsModule {
|
|
|
4588
4634
|
*/
|
|
4589
4635
|
async load() {
|
|
4590
4636
|
this.ensureInitialized();
|
|
4637
|
+
await TokenRegistry.waitForReady();
|
|
4591
4638
|
const providers = this.getTokenStorageProviders();
|
|
4592
4639
|
for (const [id, provider] of providers) {
|
|
4593
4640
|
try {
|
|
@@ -5929,7 +5976,6 @@ var PaymentsModule = class _PaymentsModule {
|
|
|
5929
5976
|
/**
|
|
5930
5977
|
* Non-blocking proof check with 500ms timeout.
|
|
5931
5978
|
*/
|
|
5932
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
5933
5979
|
async quickProofCheck(stClient, trustBase, commitment, timeoutMs = 500) {
|
|
5934
5980
|
try {
|
|
5935
5981
|
const proof = await Promise.race([
|
|
@@ -5945,7 +5991,6 @@ var PaymentsModule = class _PaymentsModule {
|
|
|
5945
5991
|
* Perform V5 bundle finalization from stored bundle data and proofs.
|
|
5946
5992
|
* Extracted from InstantSplitProcessor.processV5Bundle() steps 4-10.
|
|
5947
5993
|
*/
|
|
5948
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
5949
5994
|
async finalizeFromV5Bundle(bundle, pending2, signingService, stClient, trustBase) {
|
|
5950
5995
|
const mintDataJson = JSON.parse(bundle.recipientMintData);
|
|
5951
5996
|
const mintData = await MintTransactionData3.fromJSON(mintDataJson);
|
|
@@ -6108,7 +6153,7 @@ var PaymentsModule = class _PaymentsModule {
|
|
|
6108
6153
|
return false;
|
|
6109
6154
|
}
|
|
6110
6155
|
if (incomingStateKey) {
|
|
6111
|
-
for (const [
|
|
6156
|
+
for (const [_existingId, existing] of this.tokens) {
|
|
6112
6157
|
if (isSameTokenState(existing, token)) {
|
|
6113
6158
|
this.log(`Duplicate token state ignored: ${incomingTokenId?.slice(0, 8)}..._${incomingStateHash?.slice(0, 8)}...`);
|
|
6114
6159
|
return false;
|
|
@@ -7471,7 +7516,7 @@ var PaymentsModule = class _PaymentsModule {
|
|
|
7471
7516
|
}
|
|
7472
7517
|
}
|
|
7473
7518
|
clearTimeout(timeoutId);
|
|
7474
|
-
} catch (
|
|
7519
|
+
} catch (_err) {
|
|
7475
7520
|
continue;
|
|
7476
7521
|
}
|
|
7477
7522
|
if (!inclusionProof) {
|
|
@@ -9192,26 +9237,27 @@ var GroupChatModule = class {
|
|
|
9192
9237
|
oneshotSubscription(filter, opts) {
|
|
9193
9238
|
return new Promise((resolve) => {
|
|
9194
9239
|
let done = false;
|
|
9195
|
-
|
|
9240
|
+
const state = {};
|
|
9196
9241
|
const finish = () => {
|
|
9197
9242
|
if (done) return;
|
|
9198
9243
|
done = true;
|
|
9199
|
-
if (subId) {
|
|
9244
|
+
if (state.subId) {
|
|
9200
9245
|
try {
|
|
9201
|
-
this.client.unsubscribe(subId);
|
|
9246
|
+
this.client.unsubscribe(state.subId);
|
|
9202
9247
|
} catch {
|
|
9203
9248
|
}
|
|
9204
|
-
const idx = this.subscriptionIds.indexOf(subId);
|
|
9249
|
+
const idx = this.subscriptionIds.indexOf(state.subId);
|
|
9205
9250
|
if (idx >= 0) this.subscriptionIds.splice(idx, 1);
|
|
9206
9251
|
}
|
|
9207
9252
|
resolve(opts.onComplete());
|
|
9208
9253
|
};
|
|
9209
|
-
subId = this.client.subscribe(filter, {
|
|
9254
|
+
const subId = this.client.subscribe(filter, {
|
|
9210
9255
|
onEvent: (event) => {
|
|
9211
9256
|
if (!done) opts.onEvent(event);
|
|
9212
9257
|
},
|
|
9213
9258
|
onEndOfStoredEvents: finish
|
|
9214
9259
|
});
|
|
9260
|
+
state.subId = subId;
|
|
9215
9261
|
this.subscriptionIds.push(subId);
|
|
9216
9262
|
setTimeout(finish, opts.timeoutMs ?? 5e3);
|
|
9217
9263
|
});
|
|
@@ -9242,2426 +9288,6 @@ function createGroupChatModule(config) {
|
|
|
9242
9288
|
return new GroupChatModule(config);
|
|
9243
9289
|
}
|
|
9244
9290
|
|
|
9245
|
-
// node_modules/@noble/hashes/utils.js
|
|
9246
|
-
function isBytes(a) {
|
|
9247
|
-
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
|
|
9248
|
-
}
|
|
9249
|
-
function anumber(n, title = "") {
|
|
9250
|
-
if (!Number.isSafeInteger(n) || n < 0) {
|
|
9251
|
-
const prefix = title && `"${title}" `;
|
|
9252
|
-
throw new Error(`${prefix}expected integer >= 0, got ${n}`);
|
|
9253
|
-
}
|
|
9254
|
-
}
|
|
9255
|
-
function abytes(value, length, title = "") {
|
|
9256
|
-
const bytes = isBytes(value);
|
|
9257
|
-
const len = value?.length;
|
|
9258
|
-
const needsLen = length !== void 0;
|
|
9259
|
-
if (!bytes || needsLen && len !== length) {
|
|
9260
|
-
const prefix = title && `"${title}" `;
|
|
9261
|
-
const ofLen = needsLen ? ` of length ${length}` : "";
|
|
9262
|
-
const got = bytes ? `length=${len}` : `type=${typeof value}`;
|
|
9263
|
-
throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
|
|
9264
|
-
}
|
|
9265
|
-
return value;
|
|
9266
|
-
}
|
|
9267
|
-
function ahash(h) {
|
|
9268
|
-
if (typeof h !== "function" || typeof h.create !== "function")
|
|
9269
|
-
throw new Error("Hash must wrapped by utils.createHasher");
|
|
9270
|
-
anumber(h.outputLen);
|
|
9271
|
-
anumber(h.blockLen);
|
|
9272
|
-
}
|
|
9273
|
-
function aexists(instance, checkFinished = true) {
|
|
9274
|
-
if (instance.destroyed)
|
|
9275
|
-
throw new Error("Hash instance has been destroyed");
|
|
9276
|
-
if (checkFinished && instance.finished)
|
|
9277
|
-
throw new Error("Hash#digest() has already been called");
|
|
9278
|
-
}
|
|
9279
|
-
function aoutput(out, instance) {
|
|
9280
|
-
abytes(out, void 0, "digestInto() output");
|
|
9281
|
-
const min = instance.outputLen;
|
|
9282
|
-
if (out.length < min) {
|
|
9283
|
-
throw new Error('"digestInto() output" expected to be of length >=' + min);
|
|
9284
|
-
}
|
|
9285
|
-
}
|
|
9286
|
-
function clean(...arrays) {
|
|
9287
|
-
for (let i = 0; i < arrays.length; i++) {
|
|
9288
|
-
arrays[i].fill(0);
|
|
9289
|
-
}
|
|
9290
|
-
}
|
|
9291
|
-
function createView(arr) {
|
|
9292
|
-
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
9293
|
-
}
|
|
9294
|
-
function rotr(word, shift) {
|
|
9295
|
-
return word << 32 - shift | word >>> shift;
|
|
9296
|
-
}
|
|
9297
|
-
var hasHexBuiltin = /* @__PURE__ */ (() => (
|
|
9298
|
-
// @ts-ignore
|
|
9299
|
-
typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
|
|
9300
|
-
))();
|
|
9301
|
-
var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
|
|
9302
|
-
function bytesToHex4(bytes) {
|
|
9303
|
-
abytes(bytes);
|
|
9304
|
-
if (hasHexBuiltin)
|
|
9305
|
-
return bytes.toHex();
|
|
9306
|
-
let hex = "";
|
|
9307
|
-
for (let i = 0; i < bytes.length; i++) {
|
|
9308
|
-
hex += hexes[bytes[i]];
|
|
9309
|
-
}
|
|
9310
|
-
return hex;
|
|
9311
|
-
}
|
|
9312
|
-
var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
|
|
9313
|
-
function asciiToBase16(ch) {
|
|
9314
|
-
if (ch >= asciis._0 && ch <= asciis._9)
|
|
9315
|
-
return ch - asciis._0;
|
|
9316
|
-
if (ch >= asciis.A && ch <= asciis.F)
|
|
9317
|
-
return ch - (asciis.A - 10);
|
|
9318
|
-
if (ch >= asciis.a && ch <= asciis.f)
|
|
9319
|
-
return ch - (asciis.a - 10);
|
|
9320
|
-
return;
|
|
9321
|
-
}
|
|
9322
|
-
function hexToBytes2(hex) {
|
|
9323
|
-
if (typeof hex !== "string")
|
|
9324
|
-
throw new Error("hex string expected, got " + typeof hex);
|
|
9325
|
-
if (hasHexBuiltin)
|
|
9326
|
-
return Uint8Array.fromHex(hex);
|
|
9327
|
-
const hl = hex.length;
|
|
9328
|
-
const al = hl / 2;
|
|
9329
|
-
if (hl % 2)
|
|
9330
|
-
throw new Error("hex string expected, got unpadded hex of length " + hl);
|
|
9331
|
-
const array = new Uint8Array(al);
|
|
9332
|
-
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
9333
|
-
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
|
9334
|
-
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
|
9335
|
-
if (n1 === void 0 || n2 === void 0) {
|
|
9336
|
-
const char = hex[hi] + hex[hi + 1];
|
|
9337
|
-
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
9338
|
-
}
|
|
9339
|
-
array[ai] = n1 * 16 + n2;
|
|
9340
|
-
}
|
|
9341
|
-
return array;
|
|
9342
|
-
}
|
|
9343
|
-
function concatBytes(...arrays) {
|
|
9344
|
-
let sum = 0;
|
|
9345
|
-
for (let i = 0; i < arrays.length; i++) {
|
|
9346
|
-
const a = arrays[i];
|
|
9347
|
-
abytes(a);
|
|
9348
|
-
sum += a.length;
|
|
9349
|
-
}
|
|
9350
|
-
const res = new Uint8Array(sum);
|
|
9351
|
-
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
9352
|
-
const a = arrays[i];
|
|
9353
|
-
res.set(a, pad);
|
|
9354
|
-
pad += a.length;
|
|
9355
|
-
}
|
|
9356
|
-
return res;
|
|
9357
|
-
}
|
|
9358
|
-
function createHasher(hashCons, info = {}) {
|
|
9359
|
-
const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
|
|
9360
|
-
const tmp = hashCons(void 0);
|
|
9361
|
-
hashC.outputLen = tmp.outputLen;
|
|
9362
|
-
hashC.blockLen = tmp.blockLen;
|
|
9363
|
-
hashC.create = (opts) => hashCons(opts);
|
|
9364
|
-
Object.assign(hashC, info);
|
|
9365
|
-
return Object.freeze(hashC);
|
|
9366
|
-
}
|
|
9367
|
-
function randomBytes2(bytesLength = 32) {
|
|
9368
|
-
const cr = typeof globalThis === "object" ? globalThis.crypto : null;
|
|
9369
|
-
if (typeof cr?.getRandomValues !== "function")
|
|
9370
|
-
throw new Error("crypto.getRandomValues must be defined");
|
|
9371
|
-
return cr.getRandomValues(new Uint8Array(bytesLength));
|
|
9372
|
-
}
|
|
9373
|
-
var oidNist = (suffix) => ({
|
|
9374
|
-
oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
|
|
9375
|
-
});
|
|
9376
|
-
|
|
9377
|
-
// node_modules/@noble/hashes/_md.js
|
|
9378
|
-
function Chi(a, b, c) {
|
|
9379
|
-
return a & b ^ ~a & c;
|
|
9380
|
-
}
|
|
9381
|
-
function Maj(a, b, c) {
|
|
9382
|
-
return a & b ^ a & c ^ b & c;
|
|
9383
|
-
}
|
|
9384
|
-
var HashMD = class {
|
|
9385
|
-
blockLen;
|
|
9386
|
-
outputLen;
|
|
9387
|
-
padOffset;
|
|
9388
|
-
isLE;
|
|
9389
|
-
// For partial updates less than block size
|
|
9390
|
-
buffer;
|
|
9391
|
-
view;
|
|
9392
|
-
finished = false;
|
|
9393
|
-
length = 0;
|
|
9394
|
-
pos = 0;
|
|
9395
|
-
destroyed = false;
|
|
9396
|
-
constructor(blockLen, outputLen, padOffset, isLE) {
|
|
9397
|
-
this.blockLen = blockLen;
|
|
9398
|
-
this.outputLen = outputLen;
|
|
9399
|
-
this.padOffset = padOffset;
|
|
9400
|
-
this.isLE = isLE;
|
|
9401
|
-
this.buffer = new Uint8Array(blockLen);
|
|
9402
|
-
this.view = createView(this.buffer);
|
|
9403
|
-
}
|
|
9404
|
-
update(data) {
|
|
9405
|
-
aexists(this);
|
|
9406
|
-
abytes(data);
|
|
9407
|
-
const { view, buffer, blockLen } = this;
|
|
9408
|
-
const len = data.length;
|
|
9409
|
-
for (let pos = 0; pos < len; ) {
|
|
9410
|
-
const take = Math.min(blockLen - this.pos, len - pos);
|
|
9411
|
-
if (take === blockLen) {
|
|
9412
|
-
const dataView = createView(data);
|
|
9413
|
-
for (; blockLen <= len - pos; pos += blockLen)
|
|
9414
|
-
this.process(dataView, pos);
|
|
9415
|
-
continue;
|
|
9416
|
-
}
|
|
9417
|
-
buffer.set(data.subarray(pos, pos + take), this.pos);
|
|
9418
|
-
this.pos += take;
|
|
9419
|
-
pos += take;
|
|
9420
|
-
if (this.pos === blockLen) {
|
|
9421
|
-
this.process(view, 0);
|
|
9422
|
-
this.pos = 0;
|
|
9423
|
-
}
|
|
9424
|
-
}
|
|
9425
|
-
this.length += data.length;
|
|
9426
|
-
this.roundClean();
|
|
9427
|
-
return this;
|
|
9428
|
-
}
|
|
9429
|
-
digestInto(out) {
|
|
9430
|
-
aexists(this);
|
|
9431
|
-
aoutput(out, this);
|
|
9432
|
-
this.finished = true;
|
|
9433
|
-
const { buffer, view, blockLen, isLE } = this;
|
|
9434
|
-
let { pos } = this;
|
|
9435
|
-
buffer[pos++] = 128;
|
|
9436
|
-
clean(this.buffer.subarray(pos));
|
|
9437
|
-
if (this.padOffset > blockLen - pos) {
|
|
9438
|
-
this.process(view, 0);
|
|
9439
|
-
pos = 0;
|
|
9440
|
-
}
|
|
9441
|
-
for (let i = pos; i < blockLen; i++)
|
|
9442
|
-
buffer[i] = 0;
|
|
9443
|
-
view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
|
|
9444
|
-
this.process(view, 0);
|
|
9445
|
-
const oview = createView(out);
|
|
9446
|
-
const len = this.outputLen;
|
|
9447
|
-
if (len % 4)
|
|
9448
|
-
throw new Error("_sha2: outputLen must be aligned to 32bit");
|
|
9449
|
-
const outLen = len / 4;
|
|
9450
|
-
const state = this.get();
|
|
9451
|
-
if (outLen > state.length)
|
|
9452
|
-
throw new Error("_sha2: outputLen bigger than state");
|
|
9453
|
-
for (let i = 0; i < outLen; i++)
|
|
9454
|
-
oview.setUint32(4 * i, state[i], isLE);
|
|
9455
|
-
}
|
|
9456
|
-
digest() {
|
|
9457
|
-
const { buffer, outputLen } = this;
|
|
9458
|
-
this.digestInto(buffer);
|
|
9459
|
-
const res = buffer.slice(0, outputLen);
|
|
9460
|
-
this.destroy();
|
|
9461
|
-
return res;
|
|
9462
|
-
}
|
|
9463
|
-
_cloneInto(to) {
|
|
9464
|
-
to ||= new this.constructor();
|
|
9465
|
-
to.set(...this.get());
|
|
9466
|
-
const { blockLen, buffer, length, finished, destroyed, pos } = this;
|
|
9467
|
-
to.destroyed = destroyed;
|
|
9468
|
-
to.finished = finished;
|
|
9469
|
-
to.length = length;
|
|
9470
|
-
to.pos = pos;
|
|
9471
|
-
if (length % blockLen)
|
|
9472
|
-
to.buffer.set(buffer);
|
|
9473
|
-
return to;
|
|
9474
|
-
}
|
|
9475
|
-
clone() {
|
|
9476
|
-
return this._cloneInto();
|
|
9477
|
-
}
|
|
9478
|
-
};
|
|
9479
|
-
var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
|
|
9480
|
-
1779033703,
|
|
9481
|
-
3144134277,
|
|
9482
|
-
1013904242,
|
|
9483
|
-
2773480762,
|
|
9484
|
-
1359893119,
|
|
9485
|
-
2600822924,
|
|
9486
|
-
528734635,
|
|
9487
|
-
1541459225
|
|
9488
|
-
]);
|
|
9489
|
-
|
|
9490
|
-
// node_modules/@noble/hashes/sha2.js
|
|
9491
|
-
var SHA256_K = /* @__PURE__ */ Uint32Array.from([
|
|
9492
|
-
1116352408,
|
|
9493
|
-
1899447441,
|
|
9494
|
-
3049323471,
|
|
9495
|
-
3921009573,
|
|
9496
|
-
961987163,
|
|
9497
|
-
1508970993,
|
|
9498
|
-
2453635748,
|
|
9499
|
-
2870763221,
|
|
9500
|
-
3624381080,
|
|
9501
|
-
310598401,
|
|
9502
|
-
607225278,
|
|
9503
|
-
1426881987,
|
|
9504
|
-
1925078388,
|
|
9505
|
-
2162078206,
|
|
9506
|
-
2614888103,
|
|
9507
|
-
3248222580,
|
|
9508
|
-
3835390401,
|
|
9509
|
-
4022224774,
|
|
9510
|
-
264347078,
|
|
9511
|
-
604807628,
|
|
9512
|
-
770255983,
|
|
9513
|
-
1249150122,
|
|
9514
|
-
1555081692,
|
|
9515
|
-
1996064986,
|
|
9516
|
-
2554220882,
|
|
9517
|
-
2821834349,
|
|
9518
|
-
2952996808,
|
|
9519
|
-
3210313671,
|
|
9520
|
-
3336571891,
|
|
9521
|
-
3584528711,
|
|
9522
|
-
113926993,
|
|
9523
|
-
338241895,
|
|
9524
|
-
666307205,
|
|
9525
|
-
773529912,
|
|
9526
|
-
1294757372,
|
|
9527
|
-
1396182291,
|
|
9528
|
-
1695183700,
|
|
9529
|
-
1986661051,
|
|
9530
|
-
2177026350,
|
|
9531
|
-
2456956037,
|
|
9532
|
-
2730485921,
|
|
9533
|
-
2820302411,
|
|
9534
|
-
3259730800,
|
|
9535
|
-
3345764771,
|
|
9536
|
-
3516065817,
|
|
9537
|
-
3600352804,
|
|
9538
|
-
4094571909,
|
|
9539
|
-
275423344,
|
|
9540
|
-
430227734,
|
|
9541
|
-
506948616,
|
|
9542
|
-
659060556,
|
|
9543
|
-
883997877,
|
|
9544
|
-
958139571,
|
|
9545
|
-
1322822218,
|
|
9546
|
-
1537002063,
|
|
9547
|
-
1747873779,
|
|
9548
|
-
1955562222,
|
|
9549
|
-
2024104815,
|
|
9550
|
-
2227730452,
|
|
9551
|
-
2361852424,
|
|
9552
|
-
2428436474,
|
|
9553
|
-
2756734187,
|
|
9554
|
-
3204031479,
|
|
9555
|
-
3329325298
|
|
9556
|
-
]);
|
|
9557
|
-
var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
|
|
9558
|
-
var SHA2_32B = class extends HashMD {
|
|
9559
|
-
constructor(outputLen) {
|
|
9560
|
-
super(64, outputLen, 8, false);
|
|
9561
|
-
}
|
|
9562
|
-
get() {
|
|
9563
|
-
const { A, B, C, D, E, F, G, H } = this;
|
|
9564
|
-
return [A, B, C, D, E, F, G, H];
|
|
9565
|
-
}
|
|
9566
|
-
// prettier-ignore
|
|
9567
|
-
set(A, B, C, D, E, F, G, H) {
|
|
9568
|
-
this.A = A | 0;
|
|
9569
|
-
this.B = B | 0;
|
|
9570
|
-
this.C = C | 0;
|
|
9571
|
-
this.D = D | 0;
|
|
9572
|
-
this.E = E | 0;
|
|
9573
|
-
this.F = F | 0;
|
|
9574
|
-
this.G = G | 0;
|
|
9575
|
-
this.H = H | 0;
|
|
9576
|
-
}
|
|
9577
|
-
process(view, offset) {
|
|
9578
|
-
for (let i = 0; i < 16; i++, offset += 4)
|
|
9579
|
-
SHA256_W[i] = view.getUint32(offset, false);
|
|
9580
|
-
for (let i = 16; i < 64; i++) {
|
|
9581
|
-
const W15 = SHA256_W[i - 15];
|
|
9582
|
-
const W2 = SHA256_W[i - 2];
|
|
9583
|
-
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
|
|
9584
|
-
const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
|
|
9585
|
-
SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
|
|
9586
|
-
}
|
|
9587
|
-
let { A, B, C, D, E, F, G, H } = this;
|
|
9588
|
-
for (let i = 0; i < 64; i++) {
|
|
9589
|
-
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
|
|
9590
|
-
const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
|
|
9591
|
-
const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
|
|
9592
|
-
const T2 = sigma0 + Maj(A, B, C) | 0;
|
|
9593
|
-
H = G;
|
|
9594
|
-
G = F;
|
|
9595
|
-
F = E;
|
|
9596
|
-
E = D + T1 | 0;
|
|
9597
|
-
D = C;
|
|
9598
|
-
C = B;
|
|
9599
|
-
B = A;
|
|
9600
|
-
A = T1 + T2 | 0;
|
|
9601
|
-
}
|
|
9602
|
-
A = A + this.A | 0;
|
|
9603
|
-
B = B + this.B | 0;
|
|
9604
|
-
C = C + this.C | 0;
|
|
9605
|
-
D = D + this.D | 0;
|
|
9606
|
-
E = E + this.E | 0;
|
|
9607
|
-
F = F + this.F | 0;
|
|
9608
|
-
G = G + this.G | 0;
|
|
9609
|
-
H = H + this.H | 0;
|
|
9610
|
-
this.set(A, B, C, D, E, F, G, H);
|
|
9611
|
-
}
|
|
9612
|
-
roundClean() {
|
|
9613
|
-
clean(SHA256_W);
|
|
9614
|
-
}
|
|
9615
|
-
destroy() {
|
|
9616
|
-
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
|
9617
|
-
clean(this.buffer);
|
|
9618
|
-
}
|
|
9619
|
-
};
|
|
9620
|
-
var _SHA256 = class extends SHA2_32B {
|
|
9621
|
-
// We cannot use array here since array allows indexing by variable
|
|
9622
|
-
// which means optimizer/compiler cannot use registers.
|
|
9623
|
-
A = SHA256_IV[0] | 0;
|
|
9624
|
-
B = SHA256_IV[1] | 0;
|
|
9625
|
-
C = SHA256_IV[2] | 0;
|
|
9626
|
-
D = SHA256_IV[3] | 0;
|
|
9627
|
-
E = SHA256_IV[4] | 0;
|
|
9628
|
-
F = SHA256_IV[5] | 0;
|
|
9629
|
-
G = SHA256_IV[6] | 0;
|
|
9630
|
-
H = SHA256_IV[7] | 0;
|
|
9631
|
-
constructor() {
|
|
9632
|
-
super(32);
|
|
9633
|
-
}
|
|
9634
|
-
};
|
|
9635
|
-
var sha2564 = /* @__PURE__ */ createHasher(
|
|
9636
|
-
() => new _SHA256(),
|
|
9637
|
-
/* @__PURE__ */ oidNist(1)
|
|
9638
|
-
);
|
|
9639
|
-
|
|
9640
|
-
// node_modules/@noble/curves/utils.js
|
|
9641
|
-
var _0n = /* @__PURE__ */ BigInt(0);
|
|
9642
|
-
var _1n = /* @__PURE__ */ BigInt(1);
|
|
9643
|
-
function abool(value, title = "") {
|
|
9644
|
-
if (typeof value !== "boolean") {
|
|
9645
|
-
const prefix = title && `"${title}" `;
|
|
9646
|
-
throw new Error(prefix + "expected boolean, got type=" + typeof value);
|
|
9647
|
-
}
|
|
9648
|
-
return value;
|
|
9649
|
-
}
|
|
9650
|
-
function abignumber(n) {
|
|
9651
|
-
if (typeof n === "bigint") {
|
|
9652
|
-
if (!isPosBig(n))
|
|
9653
|
-
throw new Error("positive bigint expected, got " + n);
|
|
9654
|
-
} else
|
|
9655
|
-
anumber(n);
|
|
9656
|
-
return n;
|
|
9657
|
-
}
|
|
9658
|
-
function numberToHexUnpadded(num) {
|
|
9659
|
-
const hex = abignumber(num).toString(16);
|
|
9660
|
-
return hex.length & 1 ? "0" + hex : hex;
|
|
9661
|
-
}
|
|
9662
|
-
function hexToNumber(hex) {
|
|
9663
|
-
if (typeof hex !== "string")
|
|
9664
|
-
throw new Error("hex string expected, got " + typeof hex);
|
|
9665
|
-
return hex === "" ? _0n : BigInt("0x" + hex);
|
|
9666
|
-
}
|
|
9667
|
-
function bytesToNumberBE(bytes) {
|
|
9668
|
-
return hexToNumber(bytesToHex4(bytes));
|
|
9669
|
-
}
|
|
9670
|
-
function bytesToNumberLE(bytes) {
|
|
9671
|
-
return hexToNumber(bytesToHex4(copyBytes(abytes(bytes)).reverse()));
|
|
9672
|
-
}
|
|
9673
|
-
function numberToBytesBE(n, len) {
|
|
9674
|
-
anumber(len);
|
|
9675
|
-
n = abignumber(n);
|
|
9676
|
-
const res = hexToBytes2(n.toString(16).padStart(len * 2, "0"));
|
|
9677
|
-
if (res.length !== len)
|
|
9678
|
-
throw new Error("number too large");
|
|
9679
|
-
return res;
|
|
9680
|
-
}
|
|
9681
|
-
function numberToBytesLE(n, len) {
|
|
9682
|
-
return numberToBytesBE(n, len).reverse();
|
|
9683
|
-
}
|
|
9684
|
-
function copyBytes(bytes) {
|
|
9685
|
-
return Uint8Array.from(bytes);
|
|
9686
|
-
}
|
|
9687
|
-
var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
|
|
9688
|
-
function inRange(n, min, max) {
|
|
9689
|
-
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
|
|
9690
|
-
}
|
|
9691
|
-
function aInRange(title, n, min, max) {
|
|
9692
|
-
if (!inRange(n, min, max))
|
|
9693
|
-
throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
|
|
9694
|
-
}
|
|
9695
|
-
function bitLen(n) {
|
|
9696
|
-
let len;
|
|
9697
|
-
for (len = 0; n > _0n; n >>= _1n, len += 1)
|
|
9698
|
-
;
|
|
9699
|
-
return len;
|
|
9700
|
-
}
|
|
9701
|
-
var bitMask = (n) => (_1n << BigInt(n)) - _1n;
|
|
9702
|
-
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
9703
|
-
anumber(hashLen, "hashLen");
|
|
9704
|
-
anumber(qByteLen, "qByteLen");
|
|
9705
|
-
if (typeof hmacFn !== "function")
|
|
9706
|
-
throw new Error("hmacFn must be a function");
|
|
9707
|
-
const u8n = (len) => new Uint8Array(len);
|
|
9708
|
-
const NULL = Uint8Array.of();
|
|
9709
|
-
const byte0 = Uint8Array.of(0);
|
|
9710
|
-
const byte1 = Uint8Array.of(1);
|
|
9711
|
-
const _maxDrbgIters = 1e3;
|
|
9712
|
-
let v = u8n(hashLen);
|
|
9713
|
-
let k = u8n(hashLen);
|
|
9714
|
-
let i = 0;
|
|
9715
|
-
const reset = () => {
|
|
9716
|
-
v.fill(1);
|
|
9717
|
-
k.fill(0);
|
|
9718
|
-
i = 0;
|
|
9719
|
-
};
|
|
9720
|
-
const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));
|
|
9721
|
-
const reseed = (seed = NULL) => {
|
|
9722
|
-
k = h(byte0, seed);
|
|
9723
|
-
v = h();
|
|
9724
|
-
if (seed.length === 0)
|
|
9725
|
-
return;
|
|
9726
|
-
k = h(byte1, seed);
|
|
9727
|
-
v = h();
|
|
9728
|
-
};
|
|
9729
|
-
const gen = () => {
|
|
9730
|
-
if (i++ >= _maxDrbgIters)
|
|
9731
|
-
throw new Error("drbg: tried max amount of iterations");
|
|
9732
|
-
let len = 0;
|
|
9733
|
-
const out = [];
|
|
9734
|
-
while (len < qByteLen) {
|
|
9735
|
-
v = h();
|
|
9736
|
-
const sl = v.slice();
|
|
9737
|
-
out.push(sl);
|
|
9738
|
-
len += v.length;
|
|
9739
|
-
}
|
|
9740
|
-
return concatBytes(...out);
|
|
9741
|
-
};
|
|
9742
|
-
const genUntil = (seed, pred) => {
|
|
9743
|
-
reset();
|
|
9744
|
-
reseed(seed);
|
|
9745
|
-
let res = void 0;
|
|
9746
|
-
while (!(res = pred(gen())))
|
|
9747
|
-
reseed();
|
|
9748
|
-
reset();
|
|
9749
|
-
return res;
|
|
9750
|
-
};
|
|
9751
|
-
return genUntil;
|
|
9752
|
-
}
|
|
9753
|
-
function validateObject(object, fields = {}, optFields = {}) {
|
|
9754
|
-
if (!object || typeof object !== "object")
|
|
9755
|
-
throw new Error("expected valid options object");
|
|
9756
|
-
function checkField(fieldName, expectedType, isOpt) {
|
|
9757
|
-
const val = object[fieldName];
|
|
9758
|
-
if (isOpt && val === void 0)
|
|
9759
|
-
return;
|
|
9760
|
-
const current = typeof val;
|
|
9761
|
-
if (current !== expectedType || val === null)
|
|
9762
|
-
throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
|
|
9763
|
-
}
|
|
9764
|
-
const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
|
|
9765
|
-
iter(fields, false);
|
|
9766
|
-
iter(optFields, true);
|
|
9767
|
-
}
|
|
9768
|
-
function memoized(fn) {
|
|
9769
|
-
const map = /* @__PURE__ */ new WeakMap();
|
|
9770
|
-
return (arg, ...args) => {
|
|
9771
|
-
const val = map.get(arg);
|
|
9772
|
-
if (val !== void 0)
|
|
9773
|
-
return val;
|
|
9774
|
-
const computed = fn(arg, ...args);
|
|
9775
|
-
map.set(arg, computed);
|
|
9776
|
-
return computed;
|
|
9777
|
-
};
|
|
9778
|
-
}
|
|
9779
|
-
|
|
9780
|
-
// node_modules/@noble/curves/abstract/modular.js
|
|
9781
|
-
var _0n2 = /* @__PURE__ */ BigInt(0);
|
|
9782
|
-
var _1n2 = /* @__PURE__ */ BigInt(1);
|
|
9783
|
-
var _2n = /* @__PURE__ */ BigInt(2);
|
|
9784
|
-
var _3n = /* @__PURE__ */ BigInt(3);
|
|
9785
|
-
var _4n = /* @__PURE__ */ BigInt(4);
|
|
9786
|
-
var _5n = /* @__PURE__ */ BigInt(5);
|
|
9787
|
-
var _7n = /* @__PURE__ */ BigInt(7);
|
|
9788
|
-
var _8n = /* @__PURE__ */ BigInt(8);
|
|
9789
|
-
var _9n = /* @__PURE__ */ BigInt(9);
|
|
9790
|
-
var _16n = /* @__PURE__ */ BigInt(16);
|
|
9791
|
-
function mod(a, b) {
|
|
9792
|
-
const result = a % b;
|
|
9793
|
-
return result >= _0n2 ? result : b + result;
|
|
9794
|
-
}
|
|
9795
|
-
function pow2(x, power, modulo) {
|
|
9796
|
-
let res = x;
|
|
9797
|
-
while (power-- > _0n2) {
|
|
9798
|
-
res *= res;
|
|
9799
|
-
res %= modulo;
|
|
9800
|
-
}
|
|
9801
|
-
return res;
|
|
9802
|
-
}
|
|
9803
|
-
function invert(number, modulo) {
|
|
9804
|
-
if (number === _0n2)
|
|
9805
|
-
throw new Error("invert: expected non-zero number");
|
|
9806
|
-
if (modulo <= _0n2)
|
|
9807
|
-
throw new Error("invert: expected positive modulus, got " + modulo);
|
|
9808
|
-
let a = mod(number, modulo);
|
|
9809
|
-
let b = modulo;
|
|
9810
|
-
let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
|
|
9811
|
-
while (a !== _0n2) {
|
|
9812
|
-
const q = b / a;
|
|
9813
|
-
const r = b % a;
|
|
9814
|
-
const m = x - u * q;
|
|
9815
|
-
const n = y - v * q;
|
|
9816
|
-
b = a, a = r, x = u, y = v, u = m, v = n;
|
|
9817
|
-
}
|
|
9818
|
-
const gcd = b;
|
|
9819
|
-
if (gcd !== _1n2)
|
|
9820
|
-
throw new Error("invert: does not exist");
|
|
9821
|
-
return mod(x, modulo);
|
|
9822
|
-
}
|
|
9823
|
-
function assertIsSquare(Fp, root, n) {
|
|
9824
|
-
if (!Fp.eql(Fp.sqr(root), n))
|
|
9825
|
-
throw new Error("Cannot find square root");
|
|
9826
|
-
}
|
|
9827
|
-
function sqrt3mod4(Fp, n) {
|
|
9828
|
-
const p1div4 = (Fp.ORDER + _1n2) / _4n;
|
|
9829
|
-
const root = Fp.pow(n, p1div4);
|
|
9830
|
-
assertIsSquare(Fp, root, n);
|
|
9831
|
-
return root;
|
|
9832
|
-
}
|
|
9833
|
-
function sqrt5mod8(Fp, n) {
|
|
9834
|
-
const p5div8 = (Fp.ORDER - _5n) / _8n;
|
|
9835
|
-
const n2 = Fp.mul(n, _2n);
|
|
9836
|
-
const v = Fp.pow(n2, p5div8);
|
|
9837
|
-
const nv = Fp.mul(n, v);
|
|
9838
|
-
const i = Fp.mul(Fp.mul(nv, _2n), v);
|
|
9839
|
-
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
|
|
9840
|
-
assertIsSquare(Fp, root, n);
|
|
9841
|
-
return root;
|
|
9842
|
-
}
|
|
9843
|
-
function sqrt9mod16(P) {
|
|
9844
|
-
const Fp_ = Field(P);
|
|
9845
|
-
const tn = tonelliShanks(P);
|
|
9846
|
-
const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
|
|
9847
|
-
const c2 = tn(Fp_, c1);
|
|
9848
|
-
const c3 = tn(Fp_, Fp_.neg(c1));
|
|
9849
|
-
const c4 = (P + _7n) / _16n;
|
|
9850
|
-
return (Fp, n) => {
|
|
9851
|
-
let tv1 = Fp.pow(n, c4);
|
|
9852
|
-
let tv2 = Fp.mul(tv1, c1);
|
|
9853
|
-
const tv3 = Fp.mul(tv1, c2);
|
|
9854
|
-
const tv4 = Fp.mul(tv1, c3);
|
|
9855
|
-
const e1 = Fp.eql(Fp.sqr(tv2), n);
|
|
9856
|
-
const e2 = Fp.eql(Fp.sqr(tv3), n);
|
|
9857
|
-
tv1 = Fp.cmov(tv1, tv2, e1);
|
|
9858
|
-
tv2 = Fp.cmov(tv4, tv3, e2);
|
|
9859
|
-
const e3 = Fp.eql(Fp.sqr(tv2), n);
|
|
9860
|
-
const root = Fp.cmov(tv1, tv2, e3);
|
|
9861
|
-
assertIsSquare(Fp, root, n);
|
|
9862
|
-
return root;
|
|
9863
|
-
};
|
|
9864
|
-
}
|
|
9865
|
-
function tonelliShanks(P) {
|
|
9866
|
-
if (P < _3n)
|
|
9867
|
-
throw new Error("sqrt is not defined for small field");
|
|
9868
|
-
let Q = P - _1n2;
|
|
9869
|
-
let S = 0;
|
|
9870
|
-
while (Q % _2n === _0n2) {
|
|
9871
|
-
Q /= _2n;
|
|
9872
|
-
S++;
|
|
9873
|
-
}
|
|
9874
|
-
let Z = _2n;
|
|
9875
|
-
const _Fp = Field(P);
|
|
9876
|
-
while (FpLegendre(_Fp, Z) === 1) {
|
|
9877
|
-
if (Z++ > 1e3)
|
|
9878
|
-
throw new Error("Cannot find square root: probably non-prime P");
|
|
9879
|
-
}
|
|
9880
|
-
if (S === 1)
|
|
9881
|
-
return sqrt3mod4;
|
|
9882
|
-
let cc = _Fp.pow(Z, Q);
|
|
9883
|
-
const Q1div2 = (Q + _1n2) / _2n;
|
|
9884
|
-
return function tonelliSlow(Fp, n) {
|
|
9885
|
-
if (Fp.is0(n))
|
|
9886
|
-
return n;
|
|
9887
|
-
if (FpLegendre(Fp, n) !== 1)
|
|
9888
|
-
throw new Error("Cannot find square root");
|
|
9889
|
-
let M = S;
|
|
9890
|
-
let c = Fp.mul(Fp.ONE, cc);
|
|
9891
|
-
let t = Fp.pow(n, Q);
|
|
9892
|
-
let R = Fp.pow(n, Q1div2);
|
|
9893
|
-
while (!Fp.eql(t, Fp.ONE)) {
|
|
9894
|
-
if (Fp.is0(t))
|
|
9895
|
-
return Fp.ZERO;
|
|
9896
|
-
let i = 1;
|
|
9897
|
-
let t_tmp = Fp.sqr(t);
|
|
9898
|
-
while (!Fp.eql(t_tmp, Fp.ONE)) {
|
|
9899
|
-
i++;
|
|
9900
|
-
t_tmp = Fp.sqr(t_tmp);
|
|
9901
|
-
if (i === M)
|
|
9902
|
-
throw new Error("Cannot find square root");
|
|
9903
|
-
}
|
|
9904
|
-
const exponent = _1n2 << BigInt(M - i - 1);
|
|
9905
|
-
const b = Fp.pow(c, exponent);
|
|
9906
|
-
M = i;
|
|
9907
|
-
c = Fp.sqr(b);
|
|
9908
|
-
t = Fp.mul(t, c);
|
|
9909
|
-
R = Fp.mul(R, b);
|
|
9910
|
-
}
|
|
9911
|
-
return R;
|
|
9912
|
-
};
|
|
9913
|
-
}
|
|
9914
|
-
function FpSqrt(P) {
|
|
9915
|
-
if (P % _4n === _3n)
|
|
9916
|
-
return sqrt3mod4;
|
|
9917
|
-
if (P % _8n === _5n)
|
|
9918
|
-
return sqrt5mod8;
|
|
9919
|
-
if (P % _16n === _9n)
|
|
9920
|
-
return sqrt9mod16(P);
|
|
9921
|
-
return tonelliShanks(P);
|
|
9922
|
-
}
|
|
9923
|
-
var FIELD_FIELDS = [
|
|
9924
|
-
"create",
|
|
9925
|
-
"isValid",
|
|
9926
|
-
"is0",
|
|
9927
|
-
"neg",
|
|
9928
|
-
"inv",
|
|
9929
|
-
"sqrt",
|
|
9930
|
-
"sqr",
|
|
9931
|
-
"eql",
|
|
9932
|
-
"add",
|
|
9933
|
-
"sub",
|
|
9934
|
-
"mul",
|
|
9935
|
-
"pow",
|
|
9936
|
-
"div",
|
|
9937
|
-
"addN",
|
|
9938
|
-
"subN",
|
|
9939
|
-
"mulN",
|
|
9940
|
-
"sqrN"
|
|
9941
|
-
];
|
|
9942
|
-
function validateField(field) {
|
|
9943
|
-
const initial = {
|
|
9944
|
-
ORDER: "bigint",
|
|
9945
|
-
BYTES: "number",
|
|
9946
|
-
BITS: "number"
|
|
9947
|
-
};
|
|
9948
|
-
const opts = FIELD_FIELDS.reduce((map, val) => {
|
|
9949
|
-
map[val] = "function";
|
|
9950
|
-
return map;
|
|
9951
|
-
}, initial);
|
|
9952
|
-
validateObject(field, opts);
|
|
9953
|
-
return field;
|
|
9954
|
-
}
|
|
9955
|
-
function FpPow(Fp, num, power) {
|
|
9956
|
-
if (power < _0n2)
|
|
9957
|
-
throw new Error("invalid exponent, negatives unsupported");
|
|
9958
|
-
if (power === _0n2)
|
|
9959
|
-
return Fp.ONE;
|
|
9960
|
-
if (power === _1n2)
|
|
9961
|
-
return num;
|
|
9962
|
-
let p = Fp.ONE;
|
|
9963
|
-
let d = num;
|
|
9964
|
-
while (power > _0n2) {
|
|
9965
|
-
if (power & _1n2)
|
|
9966
|
-
p = Fp.mul(p, d);
|
|
9967
|
-
d = Fp.sqr(d);
|
|
9968
|
-
power >>= _1n2;
|
|
9969
|
-
}
|
|
9970
|
-
return p;
|
|
9971
|
-
}
|
|
9972
|
-
function FpInvertBatch(Fp, nums, passZero = false) {
|
|
9973
|
-
const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
|
|
9974
|
-
const multipliedAcc = nums.reduce((acc, num, i) => {
|
|
9975
|
-
if (Fp.is0(num))
|
|
9976
|
-
return acc;
|
|
9977
|
-
inverted[i] = acc;
|
|
9978
|
-
return Fp.mul(acc, num);
|
|
9979
|
-
}, Fp.ONE);
|
|
9980
|
-
const invertedAcc = Fp.inv(multipliedAcc);
|
|
9981
|
-
nums.reduceRight((acc, num, i) => {
|
|
9982
|
-
if (Fp.is0(num))
|
|
9983
|
-
return acc;
|
|
9984
|
-
inverted[i] = Fp.mul(acc, inverted[i]);
|
|
9985
|
-
return Fp.mul(acc, num);
|
|
9986
|
-
}, invertedAcc);
|
|
9987
|
-
return inverted;
|
|
9988
|
-
}
|
|
9989
|
-
function FpLegendre(Fp, n) {
|
|
9990
|
-
const p1mod2 = (Fp.ORDER - _1n2) / _2n;
|
|
9991
|
-
const powered = Fp.pow(n, p1mod2);
|
|
9992
|
-
const yes = Fp.eql(powered, Fp.ONE);
|
|
9993
|
-
const zero = Fp.eql(powered, Fp.ZERO);
|
|
9994
|
-
const no = Fp.eql(powered, Fp.neg(Fp.ONE));
|
|
9995
|
-
if (!yes && !zero && !no)
|
|
9996
|
-
throw new Error("invalid Legendre symbol result");
|
|
9997
|
-
return yes ? 1 : zero ? 0 : -1;
|
|
9998
|
-
}
|
|
9999
|
-
function nLength(n, nBitLength) {
|
|
10000
|
-
if (nBitLength !== void 0)
|
|
10001
|
-
anumber(nBitLength);
|
|
10002
|
-
const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
|
|
10003
|
-
const nByteLength = Math.ceil(_nBitLength / 8);
|
|
10004
|
-
return { nBitLength: _nBitLength, nByteLength };
|
|
10005
|
-
}
|
|
10006
|
-
var _Field = class {
|
|
10007
|
-
ORDER;
|
|
10008
|
-
BITS;
|
|
10009
|
-
BYTES;
|
|
10010
|
-
isLE;
|
|
10011
|
-
ZERO = _0n2;
|
|
10012
|
-
ONE = _1n2;
|
|
10013
|
-
_lengths;
|
|
10014
|
-
_sqrt;
|
|
10015
|
-
// cached sqrt
|
|
10016
|
-
_mod;
|
|
10017
|
-
constructor(ORDER, opts = {}) {
|
|
10018
|
-
if (ORDER <= _0n2)
|
|
10019
|
-
throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
|
|
10020
|
-
let _nbitLength = void 0;
|
|
10021
|
-
this.isLE = false;
|
|
10022
|
-
if (opts != null && typeof opts === "object") {
|
|
10023
|
-
if (typeof opts.BITS === "number")
|
|
10024
|
-
_nbitLength = opts.BITS;
|
|
10025
|
-
if (typeof opts.sqrt === "function")
|
|
10026
|
-
this.sqrt = opts.sqrt;
|
|
10027
|
-
if (typeof opts.isLE === "boolean")
|
|
10028
|
-
this.isLE = opts.isLE;
|
|
10029
|
-
if (opts.allowedLengths)
|
|
10030
|
-
this._lengths = opts.allowedLengths?.slice();
|
|
10031
|
-
if (typeof opts.modFromBytes === "boolean")
|
|
10032
|
-
this._mod = opts.modFromBytes;
|
|
10033
|
-
}
|
|
10034
|
-
const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
|
|
10035
|
-
if (nByteLength > 2048)
|
|
10036
|
-
throw new Error("invalid field: expected ORDER of <= 2048 bytes");
|
|
10037
|
-
this.ORDER = ORDER;
|
|
10038
|
-
this.BITS = nBitLength;
|
|
10039
|
-
this.BYTES = nByteLength;
|
|
10040
|
-
this._sqrt = void 0;
|
|
10041
|
-
Object.preventExtensions(this);
|
|
10042
|
-
}
|
|
10043
|
-
create(num) {
|
|
10044
|
-
return mod(num, this.ORDER);
|
|
10045
|
-
}
|
|
10046
|
-
isValid(num) {
|
|
10047
|
-
if (typeof num !== "bigint")
|
|
10048
|
-
throw new Error("invalid field element: expected bigint, got " + typeof num);
|
|
10049
|
-
return _0n2 <= num && num < this.ORDER;
|
|
10050
|
-
}
|
|
10051
|
-
is0(num) {
|
|
10052
|
-
return num === _0n2;
|
|
10053
|
-
}
|
|
10054
|
-
// is valid and invertible
|
|
10055
|
-
isValidNot0(num) {
|
|
10056
|
-
return !this.is0(num) && this.isValid(num);
|
|
10057
|
-
}
|
|
10058
|
-
isOdd(num) {
|
|
10059
|
-
return (num & _1n2) === _1n2;
|
|
10060
|
-
}
|
|
10061
|
-
neg(num) {
|
|
10062
|
-
return mod(-num, this.ORDER);
|
|
10063
|
-
}
|
|
10064
|
-
eql(lhs, rhs) {
|
|
10065
|
-
return lhs === rhs;
|
|
10066
|
-
}
|
|
10067
|
-
sqr(num) {
|
|
10068
|
-
return mod(num * num, this.ORDER);
|
|
10069
|
-
}
|
|
10070
|
-
add(lhs, rhs) {
|
|
10071
|
-
return mod(lhs + rhs, this.ORDER);
|
|
10072
|
-
}
|
|
10073
|
-
sub(lhs, rhs) {
|
|
10074
|
-
return mod(lhs - rhs, this.ORDER);
|
|
10075
|
-
}
|
|
10076
|
-
mul(lhs, rhs) {
|
|
10077
|
-
return mod(lhs * rhs, this.ORDER);
|
|
10078
|
-
}
|
|
10079
|
-
pow(num, power) {
|
|
10080
|
-
return FpPow(this, num, power);
|
|
10081
|
-
}
|
|
10082
|
-
div(lhs, rhs) {
|
|
10083
|
-
return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
|
|
10084
|
-
}
|
|
10085
|
-
// Same as above, but doesn't normalize
|
|
10086
|
-
sqrN(num) {
|
|
10087
|
-
return num * num;
|
|
10088
|
-
}
|
|
10089
|
-
addN(lhs, rhs) {
|
|
10090
|
-
return lhs + rhs;
|
|
10091
|
-
}
|
|
10092
|
-
subN(lhs, rhs) {
|
|
10093
|
-
return lhs - rhs;
|
|
10094
|
-
}
|
|
10095
|
-
mulN(lhs, rhs) {
|
|
10096
|
-
return lhs * rhs;
|
|
10097
|
-
}
|
|
10098
|
-
inv(num) {
|
|
10099
|
-
return invert(num, this.ORDER);
|
|
10100
|
-
}
|
|
10101
|
-
sqrt(num) {
|
|
10102
|
-
if (!this._sqrt)
|
|
10103
|
-
this._sqrt = FpSqrt(this.ORDER);
|
|
10104
|
-
return this._sqrt(this, num);
|
|
10105
|
-
}
|
|
10106
|
-
toBytes(num) {
|
|
10107
|
-
return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
|
|
10108
|
-
}
|
|
10109
|
-
fromBytes(bytes, skipValidation = false) {
|
|
10110
|
-
abytes(bytes);
|
|
10111
|
-
const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
|
|
10112
|
-
if (allowedLengths) {
|
|
10113
|
-
if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
|
|
10114
|
-
throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
|
|
10115
|
-
}
|
|
10116
|
-
const padded = new Uint8Array(BYTES);
|
|
10117
|
-
padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
|
|
10118
|
-
bytes = padded;
|
|
10119
|
-
}
|
|
10120
|
-
if (bytes.length !== BYTES)
|
|
10121
|
-
throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
|
|
10122
|
-
let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
|
|
10123
|
-
if (modFromBytes)
|
|
10124
|
-
scalar = mod(scalar, ORDER);
|
|
10125
|
-
if (!skipValidation) {
|
|
10126
|
-
if (!this.isValid(scalar))
|
|
10127
|
-
throw new Error("invalid field element: outside of range 0..ORDER");
|
|
10128
|
-
}
|
|
10129
|
-
return scalar;
|
|
10130
|
-
}
|
|
10131
|
-
// TODO: we don't need it here, move out to separate fn
|
|
10132
|
-
invertBatch(lst) {
|
|
10133
|
-
return FpInvertBatch(this, lst);
|
|
10134
|
-
}
|
|
10135
|
-
// We can't move this out because Fp6, Fp12 implement it
|
|
10136
|
-
// and it's unclear what to return in there.
|
|
10137
|
-
cmov(a, b, condition) {
|
|
10138
|
-
return condition ? b : a;
|
|
10139
|
-
}
|
|
10140
|
-
};
|
|
10141
|
-
function Field(ORDER, opts = {}) {
|
|
10142
|
-
return new _Field(ORDER, opts);
|
|
10143
|
-
}
|
|
10144
|
-
function getFieldBytesLength(fieldOrder) {
|
|
10145
|
-
if (typeof fieldOrder !== "bigint")
|
|
10146
|
-
throw new Error("field order must be bigint");
|
|
10147
|
-
const bitLength = fieldOrder.toString(2).length;
|
|
10148
|
-
return Math.ceil(bitLength / 8);
|
|
10149
|
-
}
|
|
10150
|
-
function getMinHashLength(fieldOrder) {
|
|
10151
|
-
const length = getFieldBytesLength(fieldOrder);
|
|
10152
|
-
return length + Math.ceil(length / 2);
|
|
10153
|
-
}
|
|
10154
|
-
function mapHashToField(key, fieldOrder, isLE = false) {
|
|
10155
|
-
abytes(key);
|
|
10156
|
-
const len = key.length;
|
|
10157
|
-
const fieldLen = getFieldBytesLength(fieldOrder);
|
|
10158
|
-
const minLen = getMinHashLength(fieldOrder);
|
|
10159
|
-
if (len < 16 || len < minLen || len > 1024)
|
|
10160
|
-
throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
|
|
10161
|
-
const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
|
|
10162
|
-
const reduced = mod(num, fieldOrder - _1n2) + _1n2;
|
|
10163
|
-
return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
|
|
10164
|
-
}
|
|
10165
|
-
|
|
10166
|
-
// node_modules/@noble/curves/abstract/curve.js
|
|
10167
|
-
var _0n3 = /* @__PURE__ */ BigInt(0);
|
|
10168
|
-
var _1n3 = /* @__PURE__ */ BigInt(1);
|
|
10169
|
-
function negateCt(condition, item) {
|
|
10170
|
-
const neg = item.negate();
|
|
10171
|
-
return condition ? neg : item;
|
|
10172
|
-
}
|
|
10173
|
-
function normalizeZ(c, points) {
|
|
10174
|
-
const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
|
|
10175
|
-
return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
|
|
10176
|
-
}
|
|
10177
|
-
function validateW(W, bits) {
|
|
10178
|
-
if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
|
|
10179
|
-
throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
|
|
10180
|
-
}
|
|
10181
|
-
function calcWOpts(W, scalarBits) {
|
|
10182
|
-
validateW(W, scalarBits);
|
|
10183
|
-
const windows = Math.ceil(scalarBits / W) + 1;
|
|
10184
|
-
const windowSize = 2 ** (W - 1);
|
|
10185
|
-
const maxNumber = 2 ** W;
|
|
10186
|
-
const mask = bitMask(W);
|
|
10187
|
-
const shiftBy = BigInt(W);
|
|
10188
|
-
return { windows, windowSize, mask, maxNumber, shiftBy };
|
|
10189
|
-
}
|
|
10190
|
-
function calcOffsets(n, window, wOpts) {
|
|
10191
|
-
const { windowSize, mask, maxNumber, shiftBy } = wOpts;
|
|
10192
|
-
let wbits = Number(n & mask);
|
|
10193
|
-
let nextN = n >> shiftBy;
|
|
10194
|
-
if (wbits > windowSize) {
|
|
10195
|
-
wbits -= maxNumber;
|
|
10196
|
-
nextN += _1n3;
|
|
10197
|
-
}
|
|
10198
|
-
const offsetStart = window * windowSize;
|
|
10199
|
-
const offset = offsetStart + Math.abs(wbits) - 1;
|
|
10200
|
-
const isZero = wbits === 0;
|
|
10201
|
-
const isNeg = wbits < 0;
|
|
10202
|
-
const isNegF = window % 2 !== 0;
|
|
10203
|
-
const offsetF = offsetStart;
|
|
10204
|
-
return { nextN, offset, isZero, isNeg, isNegF, offsetF };
|
|
10205
|
-
}
|
|
10206
|
-
var pointPrecomputes = /* @__PURE__ */ new WeakMap();
|
|
10207
|
-
var pointWindowSizes = /* @__PURE__ */ new WeakMap();
|
|
10208
|
-
function getW(P) {
|
|
10209
|
-
return pointWindowSizes.get(P) || 1;
|
|
10210
|
-
}
|
|
10211
|
-
function assert0(n) {
|
|
10212
|
-
if (n !== _0n3)
|
|
10213
|
-
throw new Error("invalid wNAF");
|
|
10214
|
-
}
|
|
10215
|
-
var wNAF = class {
|
|
10216
|
-
BASE;
|
|
10217
|
-
ZERO;
|
|
10218
|
-
Fn;
|
|
10219
|
-
bits;
|
|
10220
|
-
// Parametrized with a given Point class (not individual point)
|
|
10221
|
-
constructor(Point, bits) {
|
|
10222
|
-
this.BASE = Point.BASE;
|
|
10223
|
-
this.ZERO = Point.ZERO;
|
|
10224
|
-
this.Fn = Point.Fn;
|
|
10225
|
-
this.bits = bits;
|
|
10226
|
-
}
|
|
10227
|
-
// non-const time multiplication ladder
|
|
10228
|
-
_unsafeLadder(elm, n, p = this.ZERO) {
|
|
10229
|
-
let d = elm;
|
|
10230
|
-
while (n > _0n3) {
|
|
10231
|
-
if (n & _1n3)
|
|
10232
|
-
p = p.add(d);
|
|
10233
|
-
d = d.double();
|
|
10234
|
-
n >>= _1n3;
|
|
10235
|
-
}
|
|
10236
|
-
return p;
|
|
10237
|
-
}
|
|
10238
|
-
/**
|
|
10239
|
-
* Creates a wNAF precomputation window. Used for caching.
|
|
10240
|
-
* Default window size is set by `utils.precompute()` and is equal to 8.
|
|
10241
|
-
* Number of precomputed points depends on the curve size:
|
|
10242
|
-
* 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
|
|
10243
|
-
* - 𝑊 is the window size
|
|
10244
|
-
* - 𝑛 is the bitlength of the curve order.
|
|
10245
|
-
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
|
|
10246
|
-
* @param point Point instance
|
|
10247
|
-
* @param W window size
|
|
10248
|
-
* @returns precomputed point tables flattened to a single array
|
|
10249
|
-
*/
|
|
10250
|
-
precomputeWindow(point, W) {
|
|
10251
|
-
const { windows, windowSize } = calcWOpts(W, this.bits);
|
|
10252
|
-
const points = [];
|
|
10253
|
-
let p = point;
|
|
10254
|
-
let base = p;
|
|
10255
|
-
for (let window = 0; window < windows; window++) {
|
|
10256
|
-
base = p;
|
|
10257
|
-
points.push(base);
|
|
10258
|
-
for (let i = 1; i < windowSize; i++) {
|
|
10259
|
-
base = base.add(p);
|
|
10260
|
-
points.push(base);
|
|
10261
|
-
}
|
|
10262
|
-
p = base.double();
|
|
10263
|
-
}
|
|
10264
|
-
return points;
|
|
10265
|
-
}
|
|
10266
|
-
/**
|
|
10267
|
-
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
|
|
10268
|
-
* More compact implementation:
|
|
10269
|
-
* https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
|
|
10270
|
-
* @returns real and fake (for const-time) points
|
|
10271
|
-
*/
|
|
10272
|
-
wNAF(W, precomputes, n) {
|
|
10273
|
-
if (!this.Fn.isValid(n))
|
|
10274
|
-
throw new Error("invalid scalar");
|
|
10275
|
-
let p = this.ZERO;
|
|
10276
|
-
let f = this.BASE;
|
|
10277
|
-
const wo = calcWOpts(W, this.bits);
|
|
10278
|
-
for (let window = 0; window < wo.windows; window++) {
|
|
10279
|
-
const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
|
|
10280
|
-
n = nextN;
|
|
10281
|
-
if (isZero) {
|
|
10282
|
-
f = f.add(negateCt(isNegF, precomputes[offsetF]));
|
|
10283
|
-
} else {
|
|
10284
|
-
p = p.add(negateCt(isNeg, precomputes[offset]));
|
|
10285
|
-
}
|
|
10286
|
-
}
|
|
10287
|
-
assert0(n);
|
|
10288
|
-
return { p, f };
|
|
10289
|
-
}
|
|
10290
|
-
/**
|
|
10291
|
-
* Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
|
|
10292
|
-
* @param acc accumulator point to add result of multiplication
|
|
10293
|
-
* @returns point
|
|
10294
|
-
*/
|
|
10295
|
-
wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
|
|
10296
|
-
const wo = calcWOpts(W, this.bits);
|
|
10297
|
-
for (let window = 0; window < wo.windows; window++) {
|
|
10298
|
-
if (n === _0n3)
|
|
10299
|
-
break;
|
|
10300
|
-
const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
|
|
10301
|
-
n = nextN;
|
|
10302
|
-
if (isZero) {
|
|
10303
|
-
continue;
|
|
10304
|
-
} else {
|
|
10305
|
-
const item = precomputes[offset];
|
|
10306
|
-
acc = acc.add(isNeg ? item.negate() : item);
|
|
10307
|
-
}
|
|
10308
|
-
}
|
|
10309
|
-
assert0(n);
|
|
10310
|
-
return acc;
|
|
10311
|
-
}
|
|
10312
|
-
getPrecomputes(W, point, transform) {
|
|
10313
|
-
let comp = pointPrecomputes.get(point);
|
|
10314
|
-
if (!comp) {
|
|
10315
|
-
comp = this.precomputeWindow(point, W);
|
|
10316
|
-
if (W !== 1) {
|
|
10317
|
-
if (typeof transform === "function")
|
|
10318
|
-
comp = transform(comp);
|
|
10319
|
-
pointPrecomputes.set(point, comp);
|
|
10320
|
-
}
|
|
10321
|
-
}
|
|
10322
|
-
return comp;
|
|
10323
|
-
}
|
|
10324
|
-
cached(point, scalar, transform) {
|
|
10325
|
-
const W = getW(point);
|
|
10326
|
-
return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
|
|
10327
|
-
}
|
|
10328
|
-
unsafe(point, scalar, transform, prev) {
|
|
10329
|
-
const W = getW(point);
|
|
10330
|
-
if (W === 1)
|
|
10331
|
-
return this._unsafeLadder(point, scalar, prev);
|
|
10332
|
-
return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
|
|
10333
|
-
}
|
|
10334
|
-
// We calculate precomputes for elliptic curve point multiplication
|
|
10335
|
-
// using windowed method. This specifies window size and
|
|
10336
|
-
// stores precomputed values. Usually only base point would be precomputed.
|
|
10337
|
-
createCache(P, W) {
|
|
10338
|
-
validateW(W, this.bits);
|
|
10339
|
-
pointWindowSizes.set(P, W);
|
|
10340
|
-
pointPrecomputes.delete(P);
|
|
10341
|
-
}
|
|
10342
|
-
hasCache(elm) {
|
|
10343
|
-
return getW(elm) !== 1;
|
|
10344
|
-
}
|
|
10345
|
-
};
|
|
10346
|
-
function mulEndoUnsafe(Point, point, k1, k2) {
|
|
10347
|
-
let acc = point;
|
|
10348
|
-
let p1 = Point.ZERO;
|
|
10349
|
-
let p2 = Point.ZERO;
|
|
10350
|
-
while (k1 > _0n3 || k2 > _0n3) {
|
|
10351
|
-
if (k1 & _1n3)
|
|
10352
|
-
p1 = p1.add(acc);
|
|
10353
|
-
if (k2 & _1n3)
|
|
10354
|
-
p2 = p2.add(acc);
|
|
10355
|
-
acc = acc.double();
|
|
10356
|
-
k1 >>= _1n3;
|
|
10357
|
-
k2 >>= _1n3;
|
|
10358
|
-
}
|
|
10359
|
-
return { p1, p2 };
|
|
10360
|
-
}
|
|
10361
|
-
function createField(order, field, isLE) {
|
|
10362
|
-
if (field) {
|
|
10363
|
-
if (field.ORDER !== order)
|
|
10364
|
-
throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
|
|
10365
|
-
validateField(field);
|
|
10366
|
-
return field;
|
|
10367
|
-
} else {
|
|
10368
|
-
return Field(order, { isLE });
|
|
10369
|
-
}
|
|
10370
|
-
}
|
|
10371
|
-
function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
|
|
10372
|
-
if (FpFnLE === void 0)
|
|
10373
|
-
FpFnLE = type === "edwards";
|
|
10374
|
-
if (!CURVE || typeof CURVE !== "object")
|
|
10375
|
-
throw new Error(`expected valid ${type} CURVE object`);
|
|
10376
|
-
for (const p of ["p", "n", "h"]) {
|
|
10377
|
-
const val = CURVE[p];
|
|
10378
|
-
if (!(typeof val === "bigint" && val > _0n3))
|
|
10379
|
-
throw new Error(`CURVE.${p} must be positive bigint`);
|
|
10380
|
-
}
|
|
10381
|
-
const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
|
|
10382
|
-
const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
|
|
10383
|
-
const _b = type === "weierstrass" ? "b" : "d";
|
|
10384
|
-
const params = ["Gx", "Gy", "a", _b];
|
|
10385
|
-
for (const p of params) {
|
|
10386
|
-
if (!Fp.isValid(CURVE[p]))
|
|
10387
|
-
throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
|
|
10388
|
-
}
|
|
10389
|
-
CURVE = Object.freeze(Object.assign({}, CURVE));
|
|
10390
|
-
return { CURVE, Fp, Fn };
|
|
10391
|
-
}
|
|
10392
|
-
function createKeygen(randomSecretKey, getPublicKey2) {
|
|
10393
|
-
return function keygen(seed) {
|
|
10394
|
-
const secretKey = randomSecretKey(seed);
|
|
10395
|
-
return { secretKey, publicKey: getPublicKey2(secretKey) };
|
|
10396
|
-
};
|
|
10397
|
-
}
|
|
10398
|
-
|
|
10399
|
-
// node_modules/@noble/hashes/hmac.js
|
|
10400
|
-
var _HMAC = class {
|
|
10401
|
-
oHash;
|
|
10402
|
-
iHash;
|
|
10403
|
-
blockLen;
|
|
10404
|
-
outputLen;
|
|
10405
|
-
finished = false;
|
|
10406
|
-
destroyed = false;
|
|
10407
|
-
constructor(hash, key) {
|
|
10408
|
-
ahash(hash);
|
|
10409
|
-
abytes(key, void 0, "key");
|
|
10410
|
-
this.iHash = hash.create();
|
|
10411
|
-
if (typeof this.iHash.update !== "function")
|
|
10412
|
-
throw new Error("Expected instance of class which extends utils.Hash");
|
|
10413
|
-
this.blockLen = this.iHash.blockLen;
|
|
10414
|
-
this.outputLen = this.iHash.outputLen;
|
|
10415
|
-
const blockLen = this.blockLen;
|
|
10416
|
-
const pad = new Uint8Array(blockLen);
|
|
10417
|
-
pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
|
|
10418
|
-
for (let i = 0; i < pad.length; i++)
|
|
10419
|
-
pad[i] ^= 54;
|
|
10420
|
-
this.iHash.update(pad);
|
|
10421
|
-
this.oHash = hash.create();
|
|
10422
|
-
for (let i = 0; i < pad.length; i++)
|
|
10423
|
-
pad[i] ^= 54 ^ 92;
|
|
10424
|
-
this.oHash.update(pad);
|
|
10425
|
-
clean(pad);
|
|
10426
|
-
}
|
|
10427
|
-
update(buf) {
|
|
10428
|
-
aexists(this);
|
|
10429
|
-
this.iHash.update(buf);
|
|
10430
|
-
return this;
|
|
10431
|
-
}
|
|
10432
|
-
digestInto(out) {
|
|
10433
|
-
aexists(this);
|
|
10434
|
-
abytes(out, this.outputLen, "output");
|
|
10435
|
-
this.finished = true;
|
|
10436
|
-
this.iHash.digestInto(out);
|
|
10437
|
-
this.oHash.update(out);
|
|
10438
|
-
this.oHash.digestInto(out);
|
|
10439
|
-
this.destroy();
|
|
10440
|
-
}
|
|
10441
|
-
digest() {
|
|
10442
|
-
const out = new Uint8Array(this.oHash.outputLen);
|
|
10443
|
-
this.digestInto(out);
|
|
10444
|
-
return out;
|
|
10445
|
-
}
|
|
10446
|
-
_cloneInto(to) {
|
|
10447
|
-
to ||= Object.create(Object.getPrototypeOf(this), {});
|
|
10448
|
-
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
|
|
10449
|
-
to = to;
|
|
10450
|
-
to.finished = finished;
|
|
10451
|
-
to.destroyed = destroyed;
|
|
10452
|
-
to.blockLen = blockLen;
|
|
10453
|
-
to.outputLen = outputLen;
|
|
10454
|
-
to.oHash = oHash._cloneInto(to.oHash);
|
|
10455
|
-
to.iHash = iHash._cloneInto(to.iHash);
|
|
10456
|
-
return to;
|
|
10457
|
-
}
|
|
10458
|
-
clone() {
|
|
10459
|
-
return this._cloneInto();
|
|
10460
|
-
}
|
|
10461
|
-
destroy() {
|
|
10462
|
-
this.destroyed = true;
|
|
10463
|
-
this.oHash.destroy();
|
|
10464
|
-
this.iHash.destroy();
|
|
10465
|
-
}
|
|
10466
|
-
};
|
|
10467
|
-
var hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();
|
|
10468
|
-
hmac.create = (hash, key) => new _HMAC(hash, key);
|
|
10469
|
-
|
|
10470
|
-
// node_modules/@noble/curves/abstract/weierstrass.js
|
|
10471
|
-
var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den;
|
|
10472
|
-
function _splitEndoScalar(k, basis, n) {
|
|
10473
|
-
const [[a1, b1], [a2, b2]] = basis;
|
|
10474
|
-
const c1 = divNearest(b2 * k, n);
|
|
10475
|
-
const c2 = divNearest(-b1 * k, n);
|
|
10476
|
-
let k1 = k - c1 * a1 - c2 * a2;
|
|
10477
|
-
let k2 = -c1 * b1 - c2 * b2;
|
|
10478
|
-
const k1neg = k1 < _0n4;
|
|
10479
|
-
const k2neg = k2 < _0n4;
|
|
10480
|
-
if (k1neg)
|
|
10481
|
-
k1 = -k1;
|
|
10482
|
-
if (k2neg)
|
|
10483
|
-
k2 = -k2;
|
|
10484
|
-
const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
|
|
10485
|
-
if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) {
|
|
10486
|
-
throw new Error("splitScalar (endomorphism): failed, k=" + k);
|
|
10487
|
-
}
|
|
10488
|
-
return { k1neg, k1, k2neg, k2 };
|
|
10489
|
-
}
|
|
10490
|
-
function validateSigFormat(format) {
|
|
10491
|
-
if (!["compact", "recovered", "der"].includes(format))
|
|
10492
|
-
throw new Error('Signature format must be "compact", "recovered", or "der"');
|
|
10493
|
-
return format;
|
|
10494
|
-
}
|
|
10495
|
-
function validateSigOpts(opts, def) {
|
|
10496
|
-
const optsn = {};
|
|
10497
|
-
for (let optName of Object.keys(def)) {
|
|
10498
|
-
optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
|
|
10499
|
-
}
|
|
10500
|
-
abool(optsn.lowS, "lowS");
|
|
10501
|
-
abool(optsn.prehash, "prehash");
|
|
10502
|
-
if (optsn.format !== void 0)
|
|
10503
|
-
validateSigFormat(optsn.format);
|
|
10504
|
-
return optsn;
|
|
10505
|
-
}
|
|
10506
|
-
var DERErr = class extends Error {
|
|
10507
|
-
constructor(m = "") {
|
|
10508
|
-
super(m);
|
|
10509
|
-
}
|
|
10510
|
-
};
|
|
10511
|
-
var DER = {
|
|
10512
|
-
// asn.1 DER encoding utils
|
|
10513
|
-
Err: DERErr,
|
|
10514
|
-
// Basic building block is TLV (Tag-Length-Value)
|
|
10515
|
-
_tlv: {
|
|
10516
|
-
encode: (tag, data) => {
|
|
10517
|
-
const { Err: E } = DER;
|
|
10518
|
-
if (tag < 0 || tag > 256)
|
|
10519
|
-
throw new E("tlv.encode: wrong tag");
|
|
10520
|
-
if (data.length & 1)
|
|
10521
|
-
throw new E("tlv.encode: unpadded data");
|
|
10522
|
-
const dataLen = data.length / 2;
|
|
10523
|
-
const len = numberToHexUnpadded(dataLen);
|
|
10524
|
-
if (len.length / 2 & 128)
|
|
10525
|
-
throw new E("tlv.encode: long form length too big");
|
|
10526
|
-
const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
|
|
10527
|
-
const t = numberToHexUnpadded(tag);
|
|
10528
|
-
return t + lenLen + len + data;
|
|
10529
|
-
},
|
|
10530
|
-
// v - value, l - left bytes (unparsed)
|
|
10531
|
-
decode(tag, data) {
|
|
10532
|
-
const { Err: E } = DER;
|
|
10533
|
-
let pos = 0;
|
|
10534
|
-
if (tag < 0 || tag > 256)
|
|
10535
|
-
throw new E("tlv.encode: wrong tag");
|
|
10536
|
-
if (data.length < 2 || data[pos++] !== tag)
|
|
10537
|
-
throw new E("tlv.decode: wrong tlv");
|
|
10538
|
-
const first = data[pos++];
|
|
10539
|
-
const isLong = !!(first & 128);
|
|
10540
|
-
let length = 0;
|
|
10541
|
-
if (!isLong)
|
|
10542
|
-
length = first;
|
|
10543
|
-
else {
|
|
10544
|
-
const lenLen = first & 127;
|
|
10545
|
-
if (!lenLen)
|
|
10546
|
-
throw new E("tlv.decode(long): indefinite length not supported");
|
|
10547
|
-
if (lenLen > 4)
|
|
10548
|
-
throw new E("tlv.decode(long): byte length is too big");
|
|
10549
|
-
const lengthBytes = data.subarray(pos, pos + lenLen);
|
|
10550
|
-
if (lengthBytes.length !== lenLen)
|
|
10551
|
-
throw new E("tlv.decode: length bytes not complete");
|
|
10552
|
-
if (lengthBytes[0] === 0)
|
|
10553
|
-
throw new E("tlv.decode(long): zero leftmost byte");
|
|
10554
|
-
for (const b of lengthBytes)
|
|
10555
|
-
length = length << 8 | b;
|
|
10556
|
-
pos += lenLen;
|
|
10557
|
-
if (length < 128)
|
|
10558
|
-
throw new E("tlv.decode(long): not minimal encoding");
|
|
10559
|
-
}
|
|
10560
|
-
const v = data.subarray(pos, pos + length);
|
|
10561
|
-
if (v.length !== length)
|
|
10562
|
-
throw new E("tlv.decode: wrong value length");
|
|
10563
|
-
return { v, l: data.subarray(pos + length) };
|
|
10564
|
-
}
|
|
10565
|
-
},
|
|
10566
|
-
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
|
|
10567
|
-
// since we always use positive integers here. It must always be empty:
|
|
10568
|
-
// - add zero byte if exists
|
|
10569
|
-
// - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
|
|
10570
|
-
_int: {
|
|
10571
|
-
encode(num) {
|
|
10572
|
-
const { Err: E } = DER;
|
|
10573
|
-
if (num < _0n4)
|
|
10574
|
-
throw new E("integer: negative integers are not allowed");
|
|
10575
|
-
let hex = numberToHexUnpadded(num);
|
|
10576
|
-
if (Number.parseInt(hex[0], 16) & 8)
|
|
10577
|
-
hex = "00" + hex;
|
|
10578
|
-
if (hex.length & 1)
|
|
10579
|
-
throw new E("unexpected DER parsing assertion: unpadded hex");
|
|
10580
|
-
return hex;
|
|
10581
|
-
},
|
|
10582
|
-
decode(data) {
|
|
10583
|
-
const { Err: E } = DER;
|
|
10584
|
-
if (data[0] & 128)
|
|
10585
|
-
throw new E("invalid signature integer: negative");
|
|
10586
|
-
if (data[0] === 0 && !(data[1] & 128))
|
|
10587
|
-
throw new E("invalid signature integer: unnecessary leading zero");
|
|
10588
|
-
return bytesToNumberBE(data);
|
|
10589
|
-
}
|
|
10590
|
-
},
|
|
10591
|
-
toSig(bytes) {
|
|
10592
|
-
const { Err: E, _int: int, _tlv: tlv } = DER;
|
|
10593
|
-
const data = abytes(bytes, void 0, "signature");
|
|
10594
|
-
const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
|
|
10595
|
-
if (seqLeftBytes.length)
|
|
10596
|
-
throw new E("invalid signature: left bytes after parsing");
|
|
10597
|
-
const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
|
|
10598
|
-
const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
|
|
10599
|
-
if (sLeftBytes.length)
|
|
10600
|
-
throw new E("invalid signature: left bytes after parsing");
|
|
10601
|
-
return { r: int.decode(rBytes), s: int.decode(sBytes) };
|
|
10602
|
-
},
|
|
10603
|
-
hexFromSig(sig) {
|
|
10604
|
-
const { _tlv: tlv, _int: int } = DER;
|
|
10605
|
-
const rs = tlv.encode(2, int.encode(sig.r));
|
|
10606
|
-
const ss = tlv.encode(2, int.encode(sig.s));
|
|
10607
|
-
const seq = rs + ss;
|
|
10608
|
-
return tlv.encode(48, seq);
|
|
10609
|
-
}
|
|
10610
|
-
};
|
|
10611
|
-
var _0n4 = BigInt(0);
|
|
10612
|
-
var _1n4 = BigInt(1);
|
|
10613
|
-
var _2n2 = BigInt(2);
|
|
10614
|
-
var _3n2 = BigInt(3);
|
|
10615
|
-
var _4n2 = BigInt(4);
|
|
10616
|
-
function weierstrass(params, extraOpts = {}) {
|
|
10617
|
-
const validated = createCurveFields("weierstrass", params, extraOpts);
|
|
10618
|
-
const { Fp, Fn } = validated;
|
|
10619
|
-
let CURVE = validated.CURVE;
|
|
10620
|
-
const { h: cofactor, n: CURVE_ORDER2 } = CURVE;
|
|
10621
|
-
validateObject(extraOpts, {}, {
|
|
10622
|
-
allowInfinityPoint: "boolean",
|
|
10623
|
-
clearCofactor: "function",
|
|
10624
|
-
isTorsionFree: "function",
|
|
10625
|
-
fromBytes: "function",
|
|
10626
|
-
toBytes: "function",
|
|
10627
|
-
endo: "object"
|
|
10628
|
-
});
|
|
10629
|
-
const { endo } = extraOpts;
|
|
10630
|
-
if (endo) {
|
|
10631
|
-
if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
|
|
10632
|
-
throw new Error('invalid endo: expected "beta": bigint and "basises": array');
|
|
10633
|
-
}
|
|
10634
|
-
}
|
|
10635
|
-
const lengths = getWLengths(Fp, Fn);
|
|
10636
|
-
function assertCompressionIsSupported() {
|
|
10637
|
-
if (!Fp.isOdd)
|
|
10638
|
-
throw new Error("compression is not supported: Field does not have .isOdd()");
|
|
10639
|
-
}
|
|
10640
|
-
function pointToBytes(_c, point, isCompressed) {
|
|
10641
|
-
const { x, y } = point.toAffine();
|
|
10642
|
-
const bx = Fp.toBytes(x);
|
|
10643
|
-
abool(isCompressed, "isCompressed");
|
|
10644
|
-
if (isCompressed) {
|
|
10645
|
-
assertCompressionIsSupported();
|
|
10646
|
-
const hasEvenY = !Fp.isOdd(y);
|
|
10647
|
-
return concatBytes(pprefix(hasEvenY), bx);
|
|
10648
|
-
} else {
|
|
10649
|
-
return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
|
|
10650
|
-
}
|
|
10651
|
-
}
|
|
10652
|
-
function pointFromBytes(bytes) {
|
|
10653
|
-
abytes(bytes, void 0, "Point");
|
|
10654
|
-
const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
|
|
10655
|
-
const length = bytes.length;
|
|
10656
|
-
const head = bytes[0];
|
|
10657
|
-
const tail = bytes.subarray(1);
|
|
10658
|
-
if (length === comp && (head === 2 || head === 3)) {
|
|
10659
|
-
const x = Fp.fromBytes(tail);
|
|
10660
|
-
if (!Fp.isValid(x))
|
|
10661
|
-
throw new Error("bad point: is not on curve, wrong x");
|
|
10662
|
-
const y2 = weierstrassEquation(x);
|
|
10663
|
-
let y;
|
|
10664
|
-
try {
|
|
10665
|
-
y = Fp.sqrt(y2);
|
|
10666
|
-
} catch (sqrtError) {
|
|
10667
|
-
const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
|
|
10668
|
-
throw new Error("bad point: is not on curve, sqrt error" + err);
|
|
10669
|
-
}
|
|
10670
|
-
assertCompressionIsSupported();
|
|
10671
|
-
const evenY = Fp.isOdd(y);
|
|
10672
|
-
const evenH = (head & 1) === 1;
|
|
10673
|
-
if (evenH !== evenY)
|
|
10674
|
-
y = Fp.neg(y);
|
|
10675
|
-
return { x, y };
|
|
10676
|
-
} else if (length === uncomp && head === 4) {
|
|
10677
|
-
const L = Fp.BYTES;
|
|
10678
|
-
const x = Fp.fromBytes(tail.subarray(0, L));
|
|
10679
|
-
const y = Fp.fromBytes(tail.subarray(L, L * 2));
|
|
10680
|
-
if (!isValidXY(x, y))
|
|
10681
|
-
throw new Error("bad point: is not on curve");
|
|
10682
|
-
return { x, y };
|
|
10683
|
-
} else {
|
|
10684
|
-
throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
|
|
10685
|
-
}
|
|
10686
|
-
}
|
|
10687
|
-
const encodePoint = extraOpts.toBytes || pointToBytes;
|
|
10688
|
-
const decodePoint = extraOpts.fromBytes || pointFromBytes;
|
|
10689
|
-
function weierstrassEquation(x) {
|
|
10690
|
-
const x2 = Fp.sqr(x);
|
|
10691
|
-
const x3 = Fp.mul(x2, x);
|
|
10692
|
-
return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
|
|
10693
|
-
}
|
|
10694
|
-
function isValidXY(x, y) {
|
|
10695
|
-
const left = Fp.sqr(y);
|
|
10696
|
-
const right = weierstrassEquation(x);
|
|
10697
|
-
return Fp.eql(left, right);
|
|
10698
|
-
}
|
|
10699
|
-
if (!isValidXY(CURVE.Gx, CURVE.Gy))
|
|
10700
|
-
throw new Error("bad curve params: generator point");
|
|
10701
|
-
const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
|
|
10702
|
-
const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
|
|
10703
|
-
if (Fp.is0(Fp.add(_4a3, _27b2)))
|
|
10704
|
-
throw new Error("bad curve params: a or b");
|
|
10705
|
-
function acoord(title, n, banZero = false) {
|
|
10706
|
-
if (!Fp.isValid(n) || banZero && Fp.is0(n))
|
|
10707
|
-
throw new Error(`bad point coordinate ${title}`);
|
|
10708
|
-
return n;
|
|
10709
|
-
}
|
|
10710
|
-
function aprjpoint(other) {
|
|
10711
|
-
if (!(other instanceof Point))
|
|
10712
|
-
throw new Error("Weierstrass Point expected");
|
|
10713
|
-
}
|
|
10714
|
-
function splitEndoScalarN(k) {
|
|
10715
|
-
if (!endo || !endo.basises)
|
|
10716
|
-
throw new Error("no endo");
|
|
10717
|
-
return _splitEndoScalar(k, endo.basises, Fn.ORDER);
|
|
10718
|
-
}
|
|
10719
|
-
const toAffineMemo = memoized((p, iz) => {
|
|
10720
|
-
const { X, Y, Z } = p;
|
|
10721
|
-
if (Fp.eql(Z, Fp.ONE))
|
|
10722
|
-
return { x: X, y: Y };
|
|
10723
|
-
const is0 = p.is0();
|
|
10724
|
-
if (iz == null)
|
|
10725
|
-
iz = is0 ? Fp.ONE : Fp.inv(Z);
|
|
10726
|
-
const x = Fp.mul(X, iz);
|
|
10727
|
-
const y = Fp.mul(Y, iz);
|
|
10728
|
-
const zz = Fp.mul(Z, iz);
|
|
10729
|
-
if (is0)
|
|
10730
|
-
return { x: Fp.ZERO, y: Fp.ZERO };
|
|
10731
|
-
if (!Fp.eql(zz, Fp.ONE))
|
|
10732
|
-
throw new Error("invZ was invalid");
|
|
10733
|
-
return { x, y };
|
|
10734
|
-
});
|
|
10735
|
-
const assertValidMemo = memoized((p) => {
|
|
10736
|
-
if (p.is0()) {
|
|
10737
|
-
if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
|
|
10738
|
-
return;
|
|
10739
|
-
throw new Error("bad point: ZERO");
|
|
10740
|
-
}
|
|
10741
|
-
const { x, y } = p.toAffine();
|
|
10742
|
-
if (!Fp.isValid(x) || !Fp.isValid(y))
|
|
10743
|
-
throw new Error("bad point: x or y not field elements");
|
|
10744
|
-
if (!isValidXY(x, y))
|
|
10745
|
-
throw new Error("bad point: equation left != right");
|
|
10746
|
-
if (!p.isTorsionFree())
|
|
10747
|
-
throw new Error("bad point: not in prime-order subgroup");
|
|
10748
|
-
return true;
|
|
10749
|
-
});
|
|
10750
|
-
function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
|
|
10751
|
-
k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
|
|
10752
|
-
k1p = negateCt(k1neg, k1p);
|
|
10753
|
-
k2p = negateCt(k2neg, k2p);
|
|
10754
|
-
return k1p.add(k2p);
|
|
10755
|
-
}
|
|
10756
|
-
class Point {
|
|
10757
|
-
// base / generator point
|
|
10758
|
-
static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
|
|
10759
|
-
// zero / infinity / identity point
|
|
10760
|
-
static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
|
|
10761
|
-
// 0, 1, 0
|
|
10762
|
-
// math field
|
|
10763
|
-
static Fp = Fp;
|
|
10764
|
-
// scalar field
|
|
10765
|
-
static Fn = Fn;
|
|
10766
|
-
X;
|
|
10767
|
-
Y;
|
|
10768
|
-
Z;
|
|
10769
|
-
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
10770
|
-
constructor(X, Y, Z) {
|
|
10771
|
-
this.X = acoord("x", X);
|
|
10772
|
-
this.Y = acoord("y", Y, true);
|
|
10773
|
-
this.Z = acoord("z", Z);
|
|
10774
|
-
Object.freeze(this);
|
|
10775
|
-
}
|
|
10776
|
-
static CURVE() {
|
|
10777
|
-
return CURVE;
|
|
10778
|
-
}
|
|
10779
|
-
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
10780
|
-
static fromAffine(p) {
|
|
10781
|
-
const { x, y } = p || {};
|
|
10782
|
-
if (!p || !Fp.isValid(x) || !Fp.isValid(y))
|
|
10783
|
-
throw new Error("invalid affine point");
|
|
10784
|
-
if (p instanceof Point)
|
|
10785
|
-
throw new Error("projective point not allowed");
|
|
10786
|
-
if (Fp.is0(x) && Fp.is0(y))
|
|
10787
|
-
return Point.ZERO;
|
|
10788
|
-
return new Point(x, y, Fp.ONE);
|
|
10789
|
-
}
|
|
10790
|
-
static fromBytes(bytes) {
|
|
10791
|
-
const P = Point.fromAffine(decodePoint(abytes(bytes, void 0, "point")));
|
|
10792
|
-
P.assertValidity();
|
|
10793
|
-
return P;
|
|
10794
|
-
}
|
|
10795
|
-
static fromHex(hex) {
|
|
10796
|
-
return Point.fromBytes(hexToBytes2(hex));
|
|
10797
|
-
}
|
|
10798
|
-
get x() {
|
|
10799
|
-
return this.toAffine().x;
|
|
10800
|
-
}
|
|
10801
|
-
get y() {
|
|
10802
|
-
return this.toAffine().y;
|
|
10803
|
-
}
|
|
10804
|
-
/**
|
|
10805
|
-
*
|
|
10806
|
-
* @param windowSize
|
|
10807
|
-
* @param isLazy true will defer table computation until the first multiplication
|
|
10808
|
-
* @returns
|
|
10809
|
-
*/
|
|
10810
|
-
precompute(windowSize = 8, isLazy = true) {
|
|
10811
|
-
wnaf.createCache(this, windowSize);
|
|
10812
|
-
if (!isLazy)
|
|
10813
|
-
this.multiply(_3n2);
|
|
10814
|
-
return this;
|
|
10815
|
-
}
|
|
10816
|
-
// TODO: return `this`
|
|
10817
|
-
/** A point on curve is valid if it conforms to equation. */
|
|
10818
|
-
assertValidity() {
|
|
10819
|
-
assertValidMemo(this);
|
|
10820
|
-
}
|
|
10821
|
-
hasEvenY() {
|
|
10822
|
-
const { y } = this.toAffine();
|
|
10823
|
-
if (!Fp.isOdd)
|
|
10824
|
-
throw new Error("Field doesn't support isOdd");
|
|
10825
|
-
return !Fp.isOdd(y);
|
|
10826
|
-
}
|
|
10827
|
-
/** Compare one point to another. */
|
|
10828
|
-
equals(other) {
|
|
10829
|
-
aprjpoint(other);
|
|
10830
|
-
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
10831
|
-
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
10832
|
-
const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
|
|
10833
|
-
const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
|
|
10834
|
-
return U1 && U2;
|
|
10835
|
-
}
|
|
10836
|
-
/** Flips point to one corresponding to (x, -y) in Affine coordinates. */
|
|
10837
|
-
negate() {
|
|
10838
|
-
return new Point(this.X, Fp.neg(this.Y), this.Z);
|
|
10839
|
-
}
|
|
10840
|
-
// Renes-Costello-Batina exception-free doubling formula.
|
|
10841
|
-
// There is 30% faster Jacobian formula, but it is not complete.
|
|
10842
|
-
// https://eprint.iacr.org/2015/1060, algorithm 3
|
|
10843
|
-
// Cost: 8M + 3S + 3*a + 2*b3 + 15add.
|
|
10844
|
-
double() {
|
|
10845
|
-
const { a, b } = CURVE;
|
|
10846
|
-
const b3 = Fp.mul(b, _3n2);
|
|
10847
|
-
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
10848
|
-
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
|
|
10849
|
-
let t0 = Fp.mul(X1, X1);
|
|
10850
|
-
let t1 = Fp.mul(Y1, Y1);
|
|
10851
|
-
let t2 = Fp.mul(Z1, Z1);
|
|
10852
|
-
let t3 = Fp.mul(X1, Y1);
|
|
10853
|
-
t3 = Fp.add(t3, t3);
|
|
10854
|
-
Z3 = Fp.mul(X1, Z1);
|
|
10855
|
-
Z3 = Fp.add(Z3, Z3);
|
|
10856
|
-
X3 = Fp.mul(a, Z3);
|
|
10857
|
-
Y3 = Fp.mul(b3, t2);
|
|
10858
|
-
Y3 = Fp.add(X3, Y3);
|
|
10859
|
-
X3 = Fp.sub(t1, Y3);
|
|
10860
|
-
Y3 = Fp.add(t1, Y3);
|
|
10861
|
-
Y3 = Fp.mul(X3, Y3);
|
|
10862
|
-
X3 = Fp.mul(t3, X3);
|
|
10863
|
-
Z3 = Fp.mul(b3, Z3);
|
|
10864
|
-
t2 = Fp.mul(a, t2);
|
|
10865
|
-
t3 = Fp.sub(t0, t2);
|
|
10866
|
-
t3 = Fp.mul(a, t3);
|
|
10867
|
-
t3 = Fp.add(t3, Z3);
|
|
10868
|
-
Z3 = Fp.add(t0, t0);
|
|
10869
|
-
t0 = Fp.add(Z3, t0);
|
|
10870
|
-
t0 = Fp.add(t0, t2);
|
|
10871
|
-
t0 = Fp.mul(t0, t3);
|
|
10872
|
-
Y3 = Fp.add(Y3, t0);
|
|
10873
|
-
t2 = Fp.mul(Y1, Z1);
|
|
10874
|
-
t2 = Fp.add(t2, t2);
|
|
10875
|
-
t0 = Fp.mul(t2, t3);
|
|
10876
|
-
X3 = Fp.sub(X3, t0);
|
|
10877
|
-
Z3 = Fp.mul(t2, t1);
|
|
10878
|
-
Z3 = Fp.add(Z3, Z3);
|
|
10879
|
-
Z3 = Fp.add(Z3, Z3);
|
|
10880
|
-
return new Point(X3, Y3, Z3);
|
|
10881
|
-
}
|
|
10882
|
-
// Renes-Costello-Batina exception-free addition formula.
|
|
10883
|
-
// There is 30% faster Jacobian formula, but it is not complete.
|
|
10884
|
-
// https://eprint.iacr.org/2015/1060, algorithm 1
|
|
10885
|
-
// Cost: 12M + 0S + 3*a + 3*b3 + 23add.
|
|
10886
|
-
add(other) {
|
|
10887
|
-
aprjpoint(other);
|
|
10888
|
-
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
10889
|
-
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
10890
|
-
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
|
|
10891
|
-
const a = CURVE.a;
|
|
10892
|
-
const b3 = Fp.mul(CURVE.b, _3n2);
|
|
10893
|
-
let t0 = Fp.mul(X1, X2);
|
|
10894
|
-
let t1 = Fp.mul(Y1, Y2);
|
|
10895
|
-
let t2 = Fp.mul(Z1, Z2);
|
|
10896
|
-
let t3 = Fp.add(X1, Y1);
|
|
10897
|
-
let t4 = Fp.add(X2, Y2);
|
|
10898
|
-
t3 = Fp.mul(t3, t4);
|
|
10899
|
-
t4 = Fp.add(t0, t1);
|
|
10900
|
-
t3 = Fp.sub(t3, t4);
|
|
10901
|
-
t4 = Fp.add(X1, Z1);
|
|
10902
|
-
let t5 = Fp.add(X2, Z2);
|
|
10903
|
-
t4 = Fp.mul(t4, t5);
|
|
10904
|
-
t5 = Fp.add(t0, t2);
|
|
10905
|
-
t4 = Fp.sub(t4, t5);
|
|
10906
|
-
t5 = Fp.add(Y1, Z1);
|
|
10907
|
-
X3 = Fp.add(Y2, Z2);
|
|
10908
|
-
t5 = Fp.mul(t5, X3);
|
|
10909
|
-
X3 = Fp.add(t1, t2);
|
|
10910
|
-
t5 = Fp.sub(t5, X3);
|
|
10911
|
-
Z3 = Fp.mul(a, t4);
|
|
10912
|
-
X3 = Fp.mul(b3, t2);
|
|
10913
|
-
Z3 = Fp.add(X3, Z3);
|
|
10914
|
-
X3 = Fp.sub(t1, Z3);
|
|
10915
|
-
Z3 = Fp.add(t1, Z3);
|
|
10916
|
-
Y3 = Fp.mul(X3, Z3);
|
|
10917
|
-
t1 = Fp.add(t0, t0);
|
|
10918
|
-
t1 = Fp.add(t1, t0);
|
|
10919
|
-
t2 = Fp.mul(a, t2);
|
|
10920
|
-
t4 = Fp.mul(b3, t4);
|
|
10921
|
-
t1 = Fp.add(t1, t2);
|
|
10922
|
-
t2 = Fp.sub(t0, t2);
|
|
10923
|
-
t2 = Fp.mul(a, t2);
|
|
10924
|
-
t4 = Fp.add(t4, t2);
|
|
10925
|
-
t0 = Fp.mul(t1, t4);
|
|
10926
|
-
Y3 = Fp.add(Y3, t0);
|
|
10927
|
-
t0 = Fp.mul(t5, t4);
|
|
10928
|
-
X3 = Fp.mul(t3, X3);
|
|
10929
|
-
X3 = Fp.sub(X3, t0);
|
|
10930
|
-
t0 = Fp.mul(t3, t1);
|
|
10931
|
-
Z3 = Fp.mul(t5, Z3);
|
|
10932
|
-
Z3 = Fp.add(Z3, t0);
|
|
10933
|
-
return new Point(X3, Y3, Z3);
|
|
10934
|
-
}
|
|
10935
|
-
subtract(other) {
|
|
10936
|
-
return this.add(other.negate());
|
|
10937
|
-
}
|
|
10938
|
-
is0() {
|
|
10939
|
-
return this.equals(Point.ZERO);
|
|
10940
|
-
}
|
|
10941
|
-
/**
|
|
10942
|
-
* Constant time multiplication.
|
|
10943
|
-
* Uses wNAF method. Windowed method may be 10% faster,
|
|
10944
|
-
* but takes 2x longer to generate and consumes 2x memory.
|
|
10945
|
-
* Uses precomputes when available.
|
|
10946
|
-
* Uses endomorphism for Koblitz curves.
|
|
10947
|
-
* @param scalar by which the point would be multiplied
|
|
10948
|
-
* @returns New point
|
|
10949
|
-
*/
|
|
10950
|
-
multiply(scalar) {
|
|
10951
|
-
const { endo: endo2 } = extraOpts;
|
|
10952
|
-
if (!Fn.isValidNot0(scalar))
|
|
10953
|
-
throw new Error("invalid scalar: out of range");
|
|
10954
|
-
let point, fake;
|
|
10955
|
-
const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
|
|
10956
|
-
if (endo2) {
|
|
10957
|
-
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
|
|
10958
|
-
const { p: k1p, f: k1f } = mul(k1);
|
|
10959
|
-
const { p: k2p, f: k2f } = mul(k2);
|
|
10960
|
-
fake = k1f.add(k2f);
|
|
10961
|
-
point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
|
|
10962
|
-
} else {
|
|
10963
|
-
const { p, f } = mul(scalar);
|
|
10964
|
-
point = p;
|
|
10965
|
-
fake = f;
|
|
10966
|
-
}
|
|
10967
|
-
return normalizeZ(Point, [point, fake])[0];
|
|
10968
|
-
}
|
|
10969
|
-
/**
|
|
10970
|
-
* Non-constant-time multiplication. Uses double-and-add algorithm.
|
|
10971
|
-
* It's faster, but should only be used when you don't care about
|
|
10972
|
-
* an exposed secret key e.g. sig verification, which works over *public* keys.
|
|
10973
|
-
*/
|
|
10974
|
-
multiplyUnsafe(sc) {
|
|
10975
|
-
const { endo: endo2 } = extraOpts;
|
|
10976
|
-
const p = this;
|
|
10977
|
-
if (!Fn.isValid(sc))
|
|
10978
|
-
throw new Error("invalid scalar: out of range");
|
|
10979
|
-
if (sc === _0n4 || p.is0())
|
|
10980
|
-
return Point.ZERO;
|
|
10981
|
-
if (sc === _1n4)
|
|
10982
|
-
return p;
|
|
10983
|
-
if (wnaf.hasCache(this))
|
|
10984
|
-
return this.multiply(sc);
|
|
10985
|
-
if (endo2) {
|
|
10986
|
-
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
|
|
10987
|
-
const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
|
|
10988
|
-
return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
|
|
10989
|
-
} else {
|
|
10990
|
-
return wnaf.unsafe(p, sc);
|
|
10991
|
-
}
|
|
10992
|
-
}
|
|
10993
|
-
/**
|
|
10994
|
-
* Converts Projective point to affine (x, y) coordinates.
|
|
10995
|
-
* @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
|
|
10996
|
-
*/
|
|
10997
|
-
toAffine(invertedZ) {
|
|
10998
|
-
return toAffineMemo(this, invertedZ);
|
|
10999
|
-
}
|
|
11000
|
-
/**
|
|
11001
|
-
* Checks whether Point is free of torsion elements (is in prime subgroup).
|
|
11002
|
-
* Always torsion-free for cofactor=1 curves.
|
|
11003
|
-
*/
|
|
11004
|
-
isTorsionFree() {
|
|
11005
|
-
const { isTorsionFree } = extraOpts;
|
|
11006
|
-
if (cofactor === _1n4)
|
|
11007
|
-
return true;
|
|
11008
|
-
if (isTorsionFree)
|
|
11009
|
-
return isTorsionFree(Point, this);
|
|
11010
|
-
return wnaf.unsafe(this, CURVE_ORDER2).is0();
|
|
11011
|
-
}
|
|
11012
|
-
clearCofactor() {
|
|
11013
|
-
const { clearCofactor } = extraOpts;
|
|
11014
|
-
if (cofactor === _1n4)
|
|
11015
|
-
return this;
|
|
11016
|
-
if (clearCofactor)
|
|
11017
|
-
return clearCofactor(Point, this);
|
|
11018
|
-
return this.multiplyUnsafe(cofactor);
|
|
11019
|
-
}
|
|
11020
|
-
isSmallOrder() {
|
|
11021
|
-
return this.multiplyUnsafe(cofactor).is0();
|
|
11022
|
-
}
|
|
11023
|
-
toBytes(isCompressed = true) {
|
|
11024
|
-
abool(isCompressed, "isCompressed");
|
|
11025
|
-
this.assertValidity();
|
|
11026
|
-
return encodePoint(Point, this, isCompressed);
|
|
11027
|
-
}
|
|
11028
|
-
toHex(isCompressed = true) {
|
|
11029
|
-
return bytesToHex4(this.toBytes(isCompressed));
|
|
11030
|
-
}
|
|
11031
|
-
toString() {
|
|
11032
|
-
return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
|
|
11033
|
-
}
|
|
11034
|
-
}
|
|
11035
|
-
const bits = Fn.BITS;
|
|
11036
|
-
const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
|
|
11037
|
-
Point.BASE.precompute(8);
|
|
11038
|
-
return Point;
|
|
11039
|
-
}
|
|
11040
|
-
function pprefix(hasEvenY) {
|
|
11041
|
-
return Uint8Array.of(hasEvenY ? 2 : 3);
|
|
11042
|
-
}
|
|
11043
|
-
function getWLengths(Fp, Fn) {
|
|
11044
|
-
return {
|
|
11045
|
-
secretKey: Fn.BYTES,
|
|
11046
|
-
publicKey: 1 + Fp.BYTES,
|
|
11047
|
-
publicKeyUncompressed: 1 + 2 * Fp.BYTES,
|
|
11048
|
-
publicKeyHasPrefix: true,
|
|
11049
|
-
signature: 2 * Fn.BYTES
|
|
11050
|
-
};
|
|
11051
|
-
}
|
|
11052
|
-
function ecdh(Point, ecdhOpts = {}) {
|
|
11053
|
-
const { Fn } = Point;
|
|
11054
|
-
const randomBytes_ = ecdhOpts.randomBytes || randomBytes2;
|
|
11055
|
-
const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
|
|
11056
|
-
function isValidSecretKey(secretKey) {
|
|
11057
|
-
try {
|
|
11058
|
-
const num = Fn.fromBytes(secretKey);
|
|
11059
|
-
return Fn.isValidNot0(num);
|
|
11060
|
-
} catch (error) {
|
|
11061
|
-
return false;
|
|
11062
|
-
}
|
|
11063
|
-
}
|
|
11064
|
-
function isValidPublicKey(publicKey, isCompressed) {
|
|
11065
|
-
const { publicKey: comp, publicKeyUncompressed } = lengths;
|
|
11066
|
-
try {
|
|
11067
|
-
const l = publicKey.length;
|
|
11068
|
-
if (isCompressed === true && l !== comp)
|
|
11069
|
-
return false;
|
|
11070
|
-
if (isCompressed === false && l !== publicKeyUncompressed)
|
|
11071
|
-
return false;
|
|
11072
|
-
return !!Point.fromBytes(publicKey);
|
|
11073
|
-
} catch (error) {
|
|
11074
|
-
return false;
|
|
11075
|
-
}
|
|
11076
|
-
}
|
|
11077
|
-
function randomSecretKey(seed = randomBytes_(lengths.seed)) {
|
|
11078
|
-
return mapHashToField(abytes(seed, lengths.seed, "seed"), Fn.ORDER);
|
|
11079
|
-
}
|
|
11080
|
-
function getPublicKey2(secretKey, isCompressed = true) {
|
|
11081
|
-
return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
|
|
11082
|
-
}
|
|
11083
|
-
function isProbPub(item) {
|
|
11084
|
-
const { secretKey, publicKey, publicKeyUncompressed } = lengths;
|
|
11085
|
-
if (!isBytes(item))
|
|
11086
|
-
return void 0;
|
|
11087
|
-
if ("_lengths" in Fn && Fn._lengths || secretKey === publicKey)
|
|
11088
|
-
return void 0;
|
|
11089
|
-
const l = abytes(item, void 0, "key").length;
|
|
11090
|
-
return l === publicKey || l === publicKeyUncompressed;
|
|
11091
|
-
}
|
|
11092
|
-
function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
|
|
11093
|
-
if (isProbPub(secretKeyA) === true)
|
|
11094
|
-
throw new Error("first arg must be private key");
|
|
11095
|
-
if (isProbPub(publicKeyB) === false)
|
|
11096
|
-
throw new Error("second arg must be public key");
|
|
11097
|
-
const s = Fn.fromBytes(secretKeyA);
|
|
11098
|
-
const b = Point.fromBytes(publicKeyB);
|
|
11099
|
-
return b.multiply(s).toBytes(isCompressed);
|
|
11100
|
-
}
|
|
11101
|
-
const utils = {
|
|
11102
|
-
isValidSecretKey,
|
|
11103
|
-
isValidPublicKey,
|
|
11104
|
-
randomSecretKey
|
|
11105
|
-
};
|
|
11106
|
-
const keygen = createKeygen(randomSecretKey, getPublicKey2);
|
|
11107
|
-
return Object.freeze({ getPublicKey: getPublicKey2, getSharedSecret, keygen, Point, utils, lengths });
|
|
11108
|
-
}
|
|
11109
|
-
function ecdsa(Point, hash, ecdsaOpts = {}) {
|
|
11110
|
-
ahash(hash);
|
|
11111
|
-
validateObject(ecdsaOpts, {}, {
|
|
11112
|
-
hmac: "function",
|
|
11113
|
-
lowS: "boolean",
|
|
11114
|
-
randomBytes: "function",
|
|
11115
|
-
bits2int: "function",
|
|
11116
|
-
bits2int_modN: "function"
|
|
11117
|
-
});
|
|
11118
|
-
ecdsaOpts = Object.assign({}, ecdsaOpts);
|
|
11119
|
-
const randomBytes3 = ecdsaOpts.randomBytes || randomBytes2;
|
|
11120
|
-
const hmac2 = ecdsaOpts.hmac || ((key, msg) => hmac(hash, key, msg));
|
|
11121
|
-
const { Fp, Fn } = Point;
|
|
11122
|
-
const { ORDER: CURVE_ORDER2, BITS: fnBits } = Fn;
|
|
11123
|
-
const { keygen, getPublicKey: getPublicKey2, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
|
|
11124
|
-
const defaultSigOpts = {
|
|
11125
|
-
prehash: true,
|
|
11126
|
-
lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
|
|
11127
|
-
format: "compact",
|
|
11128
|
-
extraEntropy: false
|
|
11129
|
-
};
|
|
11130
|
-
const hasLargeCofactor = CURVE_ORDER2 * _2n2 < Fp.ORDER;
|
|
11131
|
-
function isBiggerThanHalfOrder(number) {
|
|
11132
|
-
const HALF = CURVE_ORDER2 >> _1n4;
|
|
11133
|
-
return number > HALF;
|
|
11134
|
-
}
|
|
11135
|
-
function validateRS(title, num) {
|
|
11136
|
-
if (!Fn.isValidNot0(num))
|
|
11137
|
-
throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
|
|
11138
|
-
return num;
|
|
11139
|
-
}
|
|
11140
|
-
function assertSmallCofactor() {
|
|
11141
|
-
if (hasLargeCofactor)
|
|
11142
|
-
throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
|
|
11143
|
-
}
|
|
11144
|
-
function validateSigLength(bytes, format) {
|
|
11145
|
-
validateSigFormat(format);
|
|
11146
|
-
const size = lengths.signature;
|
|
11147
|
-
const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
|
|
11148
|
-
return abytes(bytes, sizer);
|
|
11149
|
-
}
|
|
11150
|
-
class Signature {
|
|
11151
|
-
r;
|
|
11152
|
-
s;
|
|
11153
|
-
recovery;
|
|
11154
|
-
constructor(r, s, recovery) {
|
|
11155
|
-
this.r = validateRS("r", r);
|
|
11156
|
-
this.s = validateRS("s", s);
|
|
11157
|
-
if (recovery != null) {
|
|
11158
|
-
assertSmallCofactor();
|
|
11159
|
-
if (![0, 1, 2, 3].includes(recovery))
|
|
11160
|
-
throw new Error("invalid recovery id");
|
|
11161
|
-
this.recovery = recovery;
|
|
11162
|
-
}
|
|
11163
|
-
Object.freeze(this);
|
|
11164
|
-
}
|
|
11165
|
-
static fromBytes(bytes, format = defaultSigOpts.format) {
|
|
11166
|
-
validateSigLength(bytes, format);
|
|
11167
|
-
let recid;
|
|
11168
|
-
if (format === "der") {
|
|
11169
|
-
const { r: r2, s: s2 } = DER.toSig(abytes(bytes));
|
|
11170
|
-
return new Signature(r2, s2);
|
|
11171
|
-
}
|
|
11172
|
-
if (format === "recovered") {
|
|
11173
|
-
recid = bytes[0];
|
|
11174
|
-
format = "compact";
|
|
11175
|
-
bytes = bytes.subarray(1);
|
|
11176
|
-
}
|
|
11177
|
-
const L = lengths.signature / 2;
|
|
11178
|
-
const r = bytes.subarray(0, L);
|
|
11179
|
-
const s = bytes.subarray(L, L * 2);
|
|
11180
|
-
return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
|
|
11181
|
-
}
|
|
11182
|
-
static fromHex(hex, format) {
|
|
11183
|
-
return this.fromBytes(hexToBytes2(hex), format);
|
|
11184
|
-
}
|
|
11185
|
-
assertRecovery() {
|
|
11186
|
-
const { recovery } = this;
|
|
11187
|
-
if (recovery == null)
|
|
11188
|
-
throw new Error("invalid recovery id: must be present");
|
|
11189
|
-
return recovery;
|
|
11190
|
-
}
|
|
11191
|
-
addRecoveryBit(recovery) {
|
|
11192
|
-
return new Signature(this.r, this.s, recovery);
|
|
11193
|
-
}
|
|
11194
|
-
recoverPublicKey(messageHash) {
|
|
11195
|
-
const { r, s } = this;
|
|
11196
|
-
const recovery = this.assertRecovery();
|
|
11197
|
-
const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER2 : r;
|
|
11198
|
-
if (!Fp.isValid(radj))
|
|
11199
|
-
throw new Error("invalid recovery id: sig.r+curve.n != R.x");
|
|
11200
|
-
const x = Fp.toBytes(radj);
|
|
11201
|
-
const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));
|
|
11202
|
-
const ir = Fn.inv(radj);
|
|
11203
|
-
const h = bits2int_modN(abytes(messageHash, void 0, "msgHash"));
|
|
11204
|
-
const u1 = Fn.create(-h * ir);
|
|
11205
|
-
const u2 = Fn.create(s * ir);
|
|
11206
|
-
const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
|
|
11207
|
-
if (Q.is0())
|
|
11208
|
-
throw new Error("invalid recovery: point at infinify");
|
|
11209
|
-
Q.assertValidity();
|
|
11210
|
-
return Q;
|
|
11211
|
-
}
|
|
11212
|
-
// Signatures should be low-s, to prevent malleability.
|
|
11213
|
-
hasHighS() {
|
|
11214
|
-
return isBiggerThanHalfOrder(this.s);
|
|
11215
|
-
}
|
|
11216
|
-
toBytes(format = defaultSigOpts.format) {
|
|
11217
|
-
validateSigFormat(format);
|
|
11218
|
-
if (format === "der")
|
|
11219
|
-
return hexToBytes2(DER.hexFromSig(this));
|
|
11220
|
-
const { r, s } = this;
|
|
11221
|
-
const rb = Fn.toBytes(r);
|
|
11222
|
-
const sb = Fn.toBytes(s);
|
|
11223
|
-
if (format === "recovered") {
|
|
11224
|
-
assertSmallCofactor();
|
|
11225
|
-
return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);
|
|
11226
|
-
}
|
|
11227
|
-
return concatBytes(rb, sb);
|
|
11228
|
-
}
|
|
11229
|
-
toHex(format) {
|
|
11230
|
-
return bytesToHex4(this.toBytes(format));
|
|
11231
|
-
}
|
|
11232
|
-
}
|
|
11233
|
-
const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
|
|
11234
|
-
if (bytes.length > 8192)
|
|
11235
|
-
throw new Error("input is too large");
|
|
11236
|
-
const num = bytesToNumberBE(bytes);
|
|
11237
|
-
const delta = bytes.length * 8 - fnBits;
|
|
11238
|
-
return delta > 0 ? num >> BigInt(delta) : num;
|
|
11239
|
-
};
|
|
11240
|
-
const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
|
|
11241
|
-
return Fn.create(bits2int(bytes));
|
|
11242
|
-
};
|
|
11243
|
-
const ORDER_MASK = bitMask(fnBits);
|
|
11244
|
-
function int2octets(num) {
|
|
11245
|
-
aInRange("num < 2^" + fnBits, num, _0n4, ORDER_MASK);
|
|
11246
|
-
return Fn.toBytes(num);
|
|
11247
|
-
}
|
|
11248
|
-
function validateMsgAndHash(message, prehash) {
|
|
11249
|
-
abytes(message, void 0, "message");
|
|
11250
|
-
return prehash ? abytes(hash(message), void 0, "prehashed message") : message;
|
|
11251
|
-
}
|
|
11252
|
-
function prepSig(message, secretKey, opts) {
|
|
11253
|
-
const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
|
|
11254
|
-
message = validateMsgAndHash(message, prehash);
|
|
11255
|
-
const h1int = bits2int_modN(message);
|
|
11256
|
-
const d = Fn.fromBytes(secretKey);
|
|
11257
|
-
if (!Fn.isValidNot0(d))
|
|
11258
|
-
throw new Error("invalid private key");
|
|
11259
|
-
const seedArgs = [int2octets(d), int2octets(h1int)];
|
|
11260
|
-
if (extraEntropy != null && extraEntropy !== false) {
|
|
11261
|
-
const e = extraEntropy === true ? randomBytes3(lengths.secretKey) : extraEntropy;
|
|
11262
|
-
seedArgs.push(abytes(e, void 0, "extraEntropy"));
|
|
11263
|
-
}
|
|
11264
|
-
const seed = concatBytes(...seedArgs);
|
|
11265
|
-
const m = h1int;
|
|
11266
|
-
function k2sig(kBytes) {
|
|
11267
|
-
const k = bits2int(kBytes);
|
|
11268
|
-
if (!Fn.isValidNot0(k))
|
|
11269
|
-
return;
|
|
11270
|
-
const ik = Fn.inv(k);
|
|
11271
|
-
const q = Point.BASE.multiply(k).toAffine();
|
|
11272
|
-
const r = Fn.create(q.x);
|
|
11273
|
-
if (r === _0n4)
|
|
11274
|
-
return;
|
|
11275
|
-
const s = Fn.create(ik * Fn.create(m + r * d));
|
|
11276
|
-
if (s === _0n4)
|
|
11277
|
-
return;
|
|
11278
|
-
let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
|
|
11279
|
-
let normS = s;
|
|
11280
|
-
if (lowS && isBiggerThanHalfOrder(s)) {
|
|
11281
|
-
normS = Fn.neg(s);
|
|
11282
|
-
recovery ^= 1;
|
|
11283
|
-
}
|
|
11284
|
-
return new Signature(r, normS, hasLargeCofactor ? void 0 : recovery);
|
|
11285
|
-
}
|
|
11286
|
-
return { seed, k2sig };
|
|
11287
|
-
}
|
|
11288
|
-
function sign(message, secretKey, opts = {}) {
|
|
11289
|
-
const { seed, k2sig } = prepSig(message, secretKey, opts);
|
|
11290
|
-
const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac2);
|
|
11291
|
-
const sig = drbg(seed, k2sig);
|
|
11292
|
-
return sig.toBytes(opts.format);
|
|
11293
|
-
}
|
|
11294
|
-
function verify(signature, message, publicKey, opts = {}) {
|
|
11295
|
-
const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
|
|
11296
|
-
publicKey = abytes(publicKey, void 0, "publicKey");
|
|
11297
|
-
message = validateMsgAndHash(message, prehash);
|
|
11298
|
-
if (!isBytes(signature)) {
|
|
11299
|
-
const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
|
|
11300
|
-
throw new Error("verify expects Uint8Array signature" + end);
|
|
11301
|
-
}
|
|
11302
|
-
validateSigLength(signature, format);
|
|
11303
|
-
try {
|
|
11304
|
-
const sig = Signature.fromBytes(signature, format);
|
|
11305
|
-
const P = Point.fromBytes(publicKey);
|
|
11306
|
-
if (lowS && sig.hasHighS())
|
|
11307
|
-
return false;
|
|
11308
|
-
const { r, s } = sig;
|
|
11309
|
-
const h = bits2int_modN(message);
|
|
11310
|
-
const is = Fn.inv(s);
|
|
11311
|
-
const u1 = Fn.create(h * is);
|
|
11312
|
-
const u2 = Fn.create(r * is);
|
|
11313
|
-
const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
|
|
11314
|
-
if (R.is0())
|
|
11315
|
-
return false;
|
|
11316
|
-
const v = Fn.create(R.x);
|
|
11317
|
-
return v === r;
|
|
11318
|
-
} catch (e) {
|
|
11319
|
-
return false;
|
|
11320
|
-
}
|
|
11321
|
-
}
|
|
11322
|
-
function recoverPublicKey(signature, message, opts = {}) {
|
|
11323
|
-
const { prehash } = validateSigOpts(opts, defaultSigOpts);
|
|
11324
|
-
message = validateMsgAndHash(message, prehash);
|
|
11325
|
-
return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
|
|
11326
|
-
}
|
|
11327
|
-
return Object.freeze({
|
|
11328
|
-
keygen,
|
|
11329
|
-
getPublicKey: getPublicKey2,
|
|
11330
|
-
getSharedSecret,
|
|
11331
|
-
utils,
|
|
11332
|
-
lengths,
|
|
11333
|
-
Point,
|
|
11334
|
-
sign,
|
|
11335
|
-
verify,
|
|
11336
|
-
recoverPublicKey,
|
|
11337
|
-
Signature,
|
|
11338
|
-
hash
|
|
11339
|
-
});
|
|
11340
|
-
}
|
|
11341
|
-
|
|
11342
|
-
// node_modules/@noble/curves/secp256k1.js
|
|
11343
|
-
var secp256k1_CURVE = {
|
|
11344
|
-
p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
|
|
11345
|
-
n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
|
|
11346
|
-
h: BigInt(1),
|
|
11347
|
-
a: BigInt(0),
|
|
11348
|
-
b: BigInt(7),
|
|
11349
|
-
Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
|
|
11350
|
-
Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
|
|
11351
|
-
};
|
|
11352
|
-
var secp256k1_ENDO = {
|
|
11353
|
-
beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
|
|
11354
|
-
basises: [
|
|
11355
|
-
[BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
|
|
11356
|
-
[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
|
|
11357
|
-
]
|
|
11358
|
-
};
|
|
11359
|
-
var _2n3 = /* @__PURE__ */ BigInt(2);
|
|
11360
|
-
function sqrtMod(y) {
|
|
11361
|
-
const P = secp256k1_CURVE.p;
|
|
11362
|
-
const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
|
|
11363
|
-
const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
|
|
11364
|
-
const b2 = y * y * y % P;
|
|
11365
|
-
const b3 = b2 * b2 * y % P;
|
|
11366
|
-
const b6 = pow2(b3, _3n3, P) * b3 % P;
|
|
11367
|
-
const b9 = pow2(b6, _3n3, P) * b3 % P;
|
|
11368
|
-
const b11 = pow2(b9, _2n3, P) * b2 % P;
|
|
11369
|
-
const b22 = pow2(b11, _11n, P) * b11 % P;
|
|
11370
|
-
const b44 = pow2(b22, _22n, P) * b22 % P;
|
|
11371
|
-
const b88 = pow2(b44, _44n, P) * b44 % P;
|
|
11372
|
-
const b176 = pow2(b88, _88n, P) * b88 % P;
|
|
11373
|
-
const b220 = pow2(b176, _44n, P) * b44 % P;
|
|
11374
|
-
const b223 = pow2(b220, _3n3, P) * b3 % P;
|
|
11375
|
-
const t1 = pow2(b223, _23n, P) * b22 % P;
|
|
11376
|
-
const t2 = pow2(t1, _6n, P) * b2 % P;
|
|
11377
|
-
const root = pow2(t2, _2n3, P);
|
|
11378
|
-
if (!Fpk1.eql(Fpk1.sqr(root), y))
|
|
11379
|
-
throw new Error("Cannot find square root");
|
|
11380
|
-
return root;
|
|
11381
|
-
}
|
|
11382
|
-
var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
|
|
11383
|
-
var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
|
|
11384
|
-
Fp: Fpk1,
|
|
11385
|
-
endo: secp256k1_ENDO
|
|
11386
|
-
});
|
|
11387
|
-
var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha2564);
|
|
11388
|
-
|
|
11389
|
-
// modules/market/MarketModule.ts
|
|
11390
|
-
function hexToBytes3(hex) {
|
|
11391
|
-
const len = hex.length >> 1;
|
|
11392
|
-
const bytes = new Uint8Array(len);
|
|
11393
|
-
for (let i = 0; i < len; i++) {
|
|
11394
|
-
bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
11395
|
-
}
|
|
11396
|
-
return bytes;
|
|
11397
|
-
}
|
|
11398
|
-
function signRequest(body, privateKeyHex) {
|
|
11399
|
-
const timestamp = Date.now();
|
|
11400
|
-
const payload = JSON.stringify({ body, timestamp });
|
|
11401
|
-
const messageHash = sha2564(new TextEncoder().encode(payload));
|
|
11402
|
-
const privateKeyBytes = hexToBytes3(privateKeyHex);
|
|
11403
|
-
const signature = secp256k1.sign(messageHash, privateKeyBytes);
|
|
11404
|
-
const publicKey = bytesToHex4(secp256k1.getPublicKey(privateKeyBytes, true));
|
|
11405
|
-
return {
|
|
11406
|
-
body: JSON.stringify(body),
|
|
11407
|
-
headers: {
|
|
11408
|
-
"x-signature": bytesToHex4(signature),
|
|
11409
|
-
"x-public-key": publicKey,
|
|
11410
|
-
"x-timestamp": String(timestamp),
|
|
11411
|
-
"content-type": "application/json"
|
|
11412
|
-
}
|
|
11413
|
-
};
|
|
11414
|
-
}
|
|
11415
|
-
function toSnakeCaseIntent(req) {
|
|
11416
|
-
const result = {
|
|
11417
|
-
description: req.description,
|
|
11418
|
-
intent_type: req.intentType
|
|
11419
|
-
};
|
|
11420
|
-
if (req.category !== void 0) result.category = req.category;
|
|
11421
|
-
if (req.price !== void 0) result.price = req.price;
|
|
11422
|
-
if (req.currency !== void 0) result.currency = req.currency;
|
|
11423
|
-
if (req.location !== void 0) result.location = req.location;
|
|
11424
|
-
if (req.contactHandle !== void 0) result.contact_handle = req.contactHandle;
|
|
11425
|
-
if (req.expiresInDays !== void 0) result.expires_in_days = req.expiresInDays;
|
|
11426
|
-
return result;
|
|
11427
|
-
}
|
|
11428
|
-
function toSnakeCaseFilters(opts) {
|
|
11429
|
-
const result = {};
|
|
11430
|
-
if (opts?.filters) {
|
|
11431
|
-
const f = opts.filters;
|
|
11432
|
-
if (f.intentType !== void 0) result.intent_type = f.intentType;
|
|
11433
|
-
if (f.category !== void 0) result.category = f.category;
|
|
11434
|
-
if (f.minPrice !== void 0) result.min_price = f.minPrice;
|
|
11435
|
-
if (f.maxPrice !== void 0) result.max_price = f.maxPrice;
|
|
11436
|
-
if (f.location !== void 0) result.location = f.location;
|
|
11437
|
-
}
|
|
11438
|
-
if (opts?.limit !== void 0) result.limit = opts.limit;
|
|
11439
|
-
return result;
|
|
11440
|
-
}
|
|
11441
|
-
function mapSearchResult(raw) {
|
|
11442
|
-
return {
|
|
11443
|
-
id: raw.id,
|
|
11444
|
-
score: raw.score,
|
|
11445
|
-
agentNametag: raw.agent_nametag ?? void 0,
|
|
11446
|
-
agentPublicKey: raw.agent_public_key,
|
|
11447
|
-
description: raw.description,
|
|
11448
|
-
intentType: raw.intent_type,
|
|
11449
|
-
category: raw.category ?? void 0,
|
|
11450
|
-
price: raw.price ?? void 0,
|
|
11451
|
-
currency: raw.currency,
|
|
11452
|
-
location: raw.location ?? void 0,
|
|
11453
|
-
contactMethod: raw.contact_method,
|
|
11454
|
-
contactHandle: raw.contact_handle ?? void 0,
|
|
11455
|
-
createdAt: raw.created_at,
|
|
11456
|
-
expiresAt: raw.expires_at
|
|
11457
|
-
};
|
|
11458
|
-
}
|
|
11459
|
-
function mapMyIntent(raw) {
|
|
11460
|
-
return {
|
|
11461
|
-
id: raw.id,
|
|
11462
|
-
intentType: raw.intent_type,
|
|
11463
|
-
category: raw.category ?? void 0,
|
|
11464
|
-
price: raw.price ?? void 0,
|
|
11465
|
-
currency: raw.currency,
|
|
11466
|
-
location: raw.location ?? void 0,
|
|
11467
|
-
status: raw.status,
|
|
11468
|
-
createdAt: raw.created_at,
|
|
11469
|
-
expiresAt: raw.expires_at
|
|
11470
|
-
};
|
|
11471
|
-
}
|
|
11472
|
-
function mapFeedListing(raw) {
|
|
11473
|
-
return {
|
|
11474
|
-
id: raw.id,
|
|
11475
|
-
title: raw.title,
|
|
11476
|
-
descriptionPreview: raw.description_preview,
|
|
11477
|
-
agentName: raw.agent_name,
|
|
11478
|
-
agentId: raw.agent_id,
|
|
11479
|
-
type: raw.type,
|
|
11480
|
-
createdAt: raw.created_at
|
|
11481
|
-
};
|
|
11482
|
-
}
|
|
11483
|
-
function mapFeedMessage(raw) {
|
|
11484
|
-
if (raw.type === "initial") {
|
|
11485
|
-
return { type: "initial", listings: (raw.listings ?? []).map(mapFeedListing) };
|
|
11486
|
-
}
|
|
11487
|
-
return { type: "new", listing: mapFeedListing(raw.listing) };
|
|
11488
|
-
}
|
|
11489
|
-
var MarketModule = class {
|
|
11490
|
-
apiUrl;
|
|
11491
|
-
timeout;
|
|
11492
|
-
identity = null;
|
|
11493
|
-
registered = false;
|
|
11494
|
-
constructor(config) {
|
|
11495
|
-
this.apiUrl = (config?.apiUrl ?? DEFAULT_MARKET_API_URL).replace(/\/+$/, "");
|
|
11496
|
-
this.timeout = config?.timeout ?? 3e4;
|
|
11497
|
-
}
|
|
11498
|
-
/** Called by Sphere after construction */
|
|
11499
|
-
initialize(deps) {
|
|
11500
|
-
this.identity = deps.identity;
|
|
11501
|
-
}
|
|
11502
|
-
/** No-op — stateless module */
|
|
11503
|
-
async load() {
|
|
11504
|
-
}
|
|
11505
|
-
/** No-op — stateless module */
|
|
11506
|
-
destroy() {
|
|
11507
|
-
}
|
|
11508
|
-
// ---------------------------------------------------------------------------
|
|
11509
|
-
// Public API
|
|
11510
|
-
// ---------------------------------------------------------------------------
|
|
11511
|
-
/** Post a new intent (agent is auto-registered on first post) */
|
|
11512
|
-
async postIntent(intent) {
|
|
11513
|
-
const body = toSnakeCaseIntent(intent);
|
|
11514
|
-
const data = await this.apiPost("/api/intents", body);
|
|
11515
|
-
return {
|
|
11516
|
-
intentId: data.intent_id ?? data.intentId,
|
|
11517
|
-
message: data.message,
|
|
11518
|
-
expiresAt: data.expires_at ?? data.expiresAt
|
|
11519
|
-
};
|
|
11520
|
-
}
|
|
11521
|
-
/** Semantic search for intents (public — no auth required) */
|
|
11522
|
-
async search(query, opts) {
|
|
11523
|
-
const body = {
|
|
11524
|
-
query,
|
|
11525
|
-
...toSnakeCaseFilters(opts)
|
|
11526
|
-
};
|
|
11527
|
-
const data = await this.apiPublicPost("/api/search", body);
|
|
11528
|
-
let results = (data.intents ?? []).map(mapSearchResult);
|
|
11529
|
-
const minScore = opts?.filters?.minScore;
|
|
11530
|
-
if (minScore != null) {
|
|
11531
|
-
results = results.filter((r) => Math.round(r.score * 100) >= Math.round(minScore * 100));
|
|
11532
|
-
}
|
|
11533
|
-
return { intents: results, count: results.length };
|
|
11534
|
-
}
|
|
11535
|
-
/** List own intents (authenticated) */
|
|
11536
|
-
async getMyIntents() {
|
|
11537
|
-
const data = await this.apiGet("/api/intents");
|
|
11538
|
-
return (data.intents ?? []).map(mapMyIntent);
|
|
11539
|
-
}
|
|
11540
|
-
/** Close (delete) an intent */
|
|
11541
|
-
async closeIntent(intentId) {
|
|
11542
|
-
await this.apiDelete(`/api/intents/${encodeURIComponent(intentId)}`);
|
|
11543
|
-
}
|
|
11544
|
-
/** Fetch the most recent listings via REST (public — no auth required) */
|
|
11545
|
-
async getRecentListings() {
|
|
11546
|
-
const res = await fetch(`${this.apiUrl}/api/feed/recent`, {
|
|
11547
|
-
signal: AbortSignal.timeout(this.timeout)
|
|
11548
|
-
});
|
|
11549
|
-
const data = await this.parseResponse(res);
|
|
11550
|
-
return (data.listings ?? []).map(mapFeedListing);
|
|
11551
|
-
}
|
|
11552
|
-
/**
|
|
11553
|
-
* Subscribe to the live listing feed via WebSocket.
|
|
11554
|
-
* Returns an unsubscribe function that closes the connection.
|
|
11555
|
-
*
|
|
11556
|
-
* Requires a WebSocket implementation — works natively in browsers
|
|
11557
|
-
* and in Node.js 21+ (or with the `ws` package).
|
|
11558
|
-
*/
|
|
11559
|
-
subscribeFeed(listener) {
|
|
11560
|
-
const wsUrl = this.apiUrl.replace(/^http/, "ws") + "/ws/feed";
|
|
11561
|
-
const ws2 = new WebSocket(wsUrl);
|
|
11562
|
-
ws2.onmessage = (event) => {
|
|
11563
|
-
try {
|
|
11564
|
-
const raw = JSON.parse(typeof event.data === "string" ? event.data : event.data.toString());
|
|
11565
|
-
listener(mapFeedMessage(raw));
|
|
11566
|
-
} catch {
|
|
11567
|
-
}
|
|
11568
|
-
};
|
|
11569
|
-
return () => {
|
|
11570
|
-
ws2.close();
|
|
11571
|
-
};
|
|
11572
|
-
}
|
|
11573
|
-
// ---------------------------------------------------------------------------
|
|
11574
|
-
// Private: HTTP helpers
|
|
11575
|
-
// ---------------------------------------------------------------------------
|
|
11576
|
-
ensureIdentity() {
|
|
11577
|
-
if (!this.identity) {
|
|
11578
|
-
throw new Error("MarketModule not initialized \u2014 call initialize() first");
|
|
11579
|
-
}
|
|
11580
|
-
}
|
|
11581
|
-
/** Register the agent's public key with the server (idempotent) */
|
|
11582
|
-
async ensureRegistered() {
|
|
11583
|
-
if (this.registered) return;
|
|
11584
|
-
this.ensureIdentity();
|
|
11585
|
-
const publicKey = bytesToHex4(secp256k1.getPublicKey(hexToBytes3(this.identity.privateKey), true));
|
|
11586
|
-
const body = { public_key: publicKey };
|
|
11587
|
-
if (this.identity.nametag) body.nametag = this.identity.nametag;
|
|
11588
|
-
const res = await fetch(`${this.apiUrl}/api/agent/register`, {
|
|
11589
|
-
method: "POST",
|
|
11590
|
-
headers: { "content-type": "application/json" },
|
|
11591
|
-
body: JSON.stringify(body),
|
|
11592
|
-
signal: AbortSignal.timeout(this.timeout)
|
|
11593
|
-
});
|
|
11594
|
-
if (res.ok || res.status === 409) {
|
|
11595
|
-
this.registered = true;
|
|
11596
|
-
return;
|
|
11597
|
-
}
|
|
11598
|
-
const text = await res.text();
|
|
11599
|
-
let data;
|
|
11600
|
-
try {
|
|
11601
|
-
data = JSON.parse(text);
|
|
11602
|
-
} catch {
|
|
11603
|
-
}
|
|
11604
|
-
throw new Error(data?.error ?? `Agent registration failed: HTTP ${res.status}`);
|
|
11605
|
-
}
|
|
11606
|
-
async parseResponse(res) {
|
|
11607
|
-
const text = await res.text();
|
|
11608
|
-
let data;
|
|
11609
|
-
try {
|
|
11610
|
-
data = JSON.parse(text);
|
|
11611
|
-
} catch {
|
|
11612
|
-
throw new Error(`Market API error: HTTP ${res.status} \u2014 unexpected response (not JSON)`);
|
|
11613
|
-
}
|
|
11614
|
-
if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
|
|
11615
|
-
return data;
|
|
11616
|
-
}
|
|
11617
|
-
async apiPost(path, body) {
|
|
11618
|
-
this.ensureIdentity();
|
|
11619
|
-
await this.ensureRegistered();
|
|
11620
|
-
const signed = signRequest(body, this.identity.privateKey);
|
|
11621
|
-
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11622
|
-
method: "POST",
|
|
11623
|
-
headers: signed.headers,
|
|
11624
|
-
body: signed.body,
|
|
11625
|
-
signal: AbortSignal.timeout(this.timeout)
|
|
11626
|
-
});
|
|
11627
|
-
return this.parseResponse(res);
|
|
11628
|
-
}
|
|
11629
|
-
async apiGet(path) {
|
|
11630
|
-
this.ensureIdentity();
|
|
11631
|
-
await this.ensureRegistered();
|
|
11632
|
-
const signed = signRequest({}, this.identity.privateKey);
|
|
11633
|
-
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11634
|
-
method: "GET",
|
|
11635
|
-
headers: signed.headers,
|
|
11636
|
-
signal: AbortSignal.timeout(this.timeout)
|
|
11637
|
-
});
|
|
11638
|
-
return this.parseResponse(res);
|
|
11639
|
-
}
|
|
11640
|
-
async apiDelete(path) {
|
|
11641
|
-
this.ensureIdentity();
|
|
11642
|
-
await this.ensureRegistered();
|
|
11643
|
-
const signed = signRequest({}, this.identity.privateKey);
|
|
11644
|
-
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11645
|
-
method: "DELETE",
|
|
11646
|
-
headers: signed.headers,
|
|
11647
|
-
signal: AbortSignal.timeout(this.timeout)
|
|
11648
|
-
});
|
|
11649
|
-
return this.parseResponse(res);
|
|
11650
|
-
}
|
|
11651
|
-
async apiPublicPost(path, body) {
|
|
11652
|
-
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11653
|
-
method: "POST",
|
|
11654
|
-
headers: { "content-type": "application/json" },
|
|
11655
|
-
body: JSON.stringify(body),
|
|
11656
|
-
signal: AbortSignal.timeout(this.timeout)
|
|
11657
|
-
});
|
|
11658
|
-
return this.parseResponse(res);
|
|
11659
|
-
}
|
|
11660
|
-
};
|
|
11661
|
-
function createMarketModule(config) {
|
|
11662
|
-
return new MarketModule(config);
|
|
11663
|
-
}
|
|
11664
|
-
|
|
11665
9291
|
// core/encryption.ts
|
|
11666
9292
|
import CryptoJS6 from "crypto-js";
|
|
11667
9293
|
function encryptSimple(plaintext, password) {
|
|
@@ -12497,7 +10123,6 @@ var Sphere = class _Sphere {
|
|
|
12497
10123
|
_payments;
|
|
12498
10124
|
_communications;
|
|
12499
10125
|
_groupChat = null;
|
|
12500
|
-
_market = null;
|
|
12501
10126
|
// Events
|
|
12502
10127
|
eventHandlers = /* @__PURE__ */ new Map();
|
|
12503
10128
|
// Provider management
|
|
@@ -12507,7 +10132,7 @@ var Sphere = class _Sphere {
|
|
|
12507
10132
|
// ===========================================================================
|
|
12508
10133
|
// Constructor (private)
|
|
12509
10134
|
// ===========================================================================
|
|
12510
|
-
constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig
|
|
10135
|
+
constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig) {
|
|
12511
10136
|
this._storage = storage;
|
|
12512
10137
|
this._transport = transport;
|
|
12513
10138
|
this._oracle = oracle;
|
|
@@ -12518,7 +10143,6 @@ var Sphere = class _Sphere {
|
|
|
12518
10143
|
this._payments = createPaymentsModule({ l1: l1Config });
|
|
12519
10144
|
this._communications = createCommunicationsModule();
|
|
12520
10145
|
this._groupChat = groupChatConfig ? createGroupChatModule(groupChatConfig) : null;
|
|
12521
|
-
this._market = marketConfig ? createMarketModule(marketConfig) : null;
|
|
12522
10146
|
}
|
|
12523
10147
|
// ===========================================================================
|
|
12524
10148
|
// Static Methods - Wallet Management
|
|
@@ -12566,8 +10190,8 @@ var Sphere = class _Sphere {
|
|
|
12566
10190
|
* ```
|
|
12567
10191
|
*/
|
|
12568
10192
|
static async init(options) {
|
|
10193
|
+
_Sphere.configureTokenRegistry(options.storage, options.network);
|
|
12569
10194
|
const groupChat = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
|
|
12570
|
-
const market = _Sphere.resolveMarketConfig(options.market);
|
|
12571
10195
|
const walletExists = await _Sphere.exists(options.storage);
|
|
12572
10196
|
if (walletExists) {
|
|
12573
10197
|
const sphere2 = await _Sphere.load({
|
|
@@ -12578,8 +10202,7 @@ var Sphere = class _Sphere {
|
|
|
12578
10202
|
l1: options.l1,
|
|
12579
10203
|
price: options.price,
|
|
12580
10204
|
groupChat,
|
|
12581
|
-
password: options.password
|
|
12582
|
-
market
|
|
10205
|
+
password: options.password
|
|
12583
10206
|
});
|
|
12584
10207
|
return { sphere: sphere2, created: false };
|
|
12585
10208
|
}
|
|
@@ -12606,8 +10229,7 @@ var Sphere = class _Sphere {
|
|
|
12606
10229
|
l1: options.l1,
|
|
12607
10230
|
price: options.price,
|
|
12608
10231
|
groupChat,
|
|
12609
|
-
password: options.password
|
|
12610
|
-
market
|
|
10232
|
+
password: options.password
|
|
12611
10233
|
});
|
|
12612
10234
|
return { sphere, created: true, generatedMnemonic };
|
|
12613
10235
|
}
|
|
@@ -12635,20 +10257,17 @@ var Sphere = class _Sphere {
|
|
|
12635
10257
|
return config;
|
|
12636
10258
|
}
|
|
12637
10259
|
/**
|
|
12638
|
-
*
|
|
12639
|
-
*
|
|
12640
|
-
*
|
|
12641
|
-
*
|
|
10260
|
+
* Configure TokenRegistry in the main bundle context.
|
|
10261
|
+
*
|
|
10262
|
+
* The provider factory functions (createBrowserProviders / createNodeProviders)
|
|
10263
|
+
* are compiled into separate bundles by tsup, each with their own inlined copy
|
|
10264
|
+
* of TokenRegistry. Their TokenRegistry.configure() call configures a different
|
|
10265
|
+
* singleton than the one used by PaymentsModule (which lives in the main bundle).
|
|
10266
|
+
* This method ensures the main bundle's TokenRegistry is properly configured.
|
|
12642
10267
|
*/
|
|
12643
|
-
static
|
|
12644
|
-
|
|
12645
|
-
|
|
12646
|
-
return { apiUrl: DEFAULT_MARKET_API_URL };
|
|
12647
|
-
}
|
|
12648
|
-
return {
|
|
12649
|
-
apiUrl: config.apiUrl ?? DEFAULT_MARKET_API_URL,
|
|
12650
|
-
timeout: config.timeout
|
|
12651
|
-
};
|
|
10268
|
+
static configureTokenRegistry(storage, network) {
|
|
10269
|
+
const netConfig = network ? NETWORKS[network] : NETWORKS.testnet;
|
|
10270
|
+
TokenRegistry.configure({ remoteUrl: netConfig.tokenRegistryUrl, storage });
|
|
12652
10271
|
}
|
|
12653
10272
|
/**
|
|
12654
10273
|
* Create new wallet with mnemonic
|
|
@@ -12660,8 +10279,8 @@ var Sphere = class _Sphere {
|
|
|
12660
10279
|
if (await _Sphere.exists(options.storage)) {
|
|
12661
10280
|
throw new Error("Wallet already exists. Use Sphere.load() or Sphere.clear() first.");
|
|
12662
10281
|
}
|
|
10282
|
+
_Sphere.configureTokenRegistry(options.storage, options.network);
|
|
12663
10283
|
const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
|
|
12664
|
-
const marketConfig = _Sphere.resolveMarketConfig(options.market);
|
|
12665
10284
|
const sphere = new _Sphere(
|
|
12666
10285
|
options.storage,
|
|
12667
10286
|
options.transport,
|
|
@@ -12669,8 +10288,7 @@ var Sphere = class _Sphere {
|
|
|
12669
10288
|
options.tokenStorage,
|
|
12670
10289
|
options.l1,
|
|
12671
10290
|
options.price,
|
|
12672
|
-
groupChatConfig
|
|
12673
|
-
marketConfig
|
|
10291
|
+
groupChatConfig
|
|
12674
10292
|
);
|
|
12675
10293
|
sphere._password = options.password ?? null;
|
|
12676
10294
|
await sphere.storeMnemonic(options.mnemonic, options.derivationPath);
|
|
@@ -12696,8 +10314,8 @@ var Sphere = class _Sphere {
|
|
|
12696
10314
|
if (!await _Sphere.exists(options.storage)) {
|
|
12697
10315
|
throw new Error("No wallet found. Use Sphere.create() to create a new wallet.");
|
|
12698
10316
|
}
|
|
10317
|
+
_Sphere.configureTokenRegistry(options.storage, options.network);
|
|
12699
10318
|
const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
|
|
12700
|
-
const marketConfig = _Sphere.resolveMarketConfig(options.market);
|
|
12701
10319
|
const sphere = new _Sphere(
|
|
12702
10320
|
options.storage,
|
|
12703
10321
|
options.transport,
|
|
@@ -12705,8 +10323,7 @@ var Sphere = class _Sphere {
|
|
|
12705
10323
|
options.tokenStorage,
|
|
12706
10324
|
options.l1,
|
|
12707
10325
|
options.price,
|
|
12708
|
-
groupChatConfig
|
|
12709
|
-
marketConfig
|
|
10326
|
+
groupChatConfig
|
|
12710
10327
|
);
|
|
12711
10328
|
sphere._password = options.password ?? null;
|
|
12712
10329
|
await sphere.loadIdentityFromStorage();
|
|
@@ -12752,7 +10369,6 @@ var Sphere = class _Sphere {
|
|
|
12752
10369
|
console.log("[Sphere.import] Storage reconnected");
|
|
12753
10370
|
}
|
|
12754
10371
|
const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat);
|
|
12755
|
-
const marketConfig = _Sphere.resolveMarketConfig(options.market);
|
|
12756
10372
|
const sphere = new _Sphere(
|
|
12757
10373
|
options.storage,
|
|
12758
10374
|
options.transport,
|
|
@@ -12760,8 +10376,7 @@ var Sphere = class _Sphere {
|
|
|
12760
10376
|
options.tokenStorage,
|
|
12761
10377
|
options.l1,
|
|
12762
10378
|
options.price,
|
|
12763
|
-
groupChatConfig
|
|
12764
|
-
marketConfig
|
|
10379
|
+
groupChatConfig
|
|
12765
10380
|
);
|
|
12766
10381
|
sphere._password = options.password ?? null;
|
|
12767
10382
|
if (options.mnemonic) {
|
|
@@ -12926,10 +10541,6 @@ var Sphere = class _Sphere {
|
|
|
12926
10541
|
get groupChat() {
|
|
12927
10542
|
return this._groupChat;
|
|
12928
10543
|
}
|
|
12929
|
-
/** Market module (intent bulletin board). Null if not configured. */
|
|
12930
|
-
get market() {
|
|
12931
|
-
return this._market;
|
|
12932
|
-
}
|
|
12933
10544
|
// ===========================================================================
|
|
12934
10545
|
// Public Properties - State
|
|
12935
10546
|
// ===========================================================================
|
|
@@ -13805,14 +11416,9 @@ var Sphere = class _Sphere {
|
|
|
13805
11416
|
storage: this._storage,
|
|
13806
11417
|
emitEvent
|
|
13807
11418
|
});
|
|
13808
|
-
this._market?.initialize({
|
|
13809
|
-
identity: this._identity,
|
|
13810
|
-
emitEvent
|
|
13811
|
-
});
|
|
13812
11419
|
await this._payments.load();
|
|
13813
11420
|
await this._communications.load();
|
|
13814
11421
|
await this._groupChat?.load();
|
|
13815
|
-
await this._market?.load();
|
|
13816
11422
|
}
|
|
13817
11423
|
/**
|
|
13818
11424
|
* Derive address at a specific index
|
|
@@ -14637,7 +12243,6 @@ var Sphere = class _Sphere {
|
|
|
14637
12243
|
this._payments.destroy();
|
|
14638
12244
|
this._communications.destroy();
|
|
14639
12245
|
this._groupChat?.destroy();
|
|
14640
|
-
this._market?.destroy();
|
|
14641
12246
|
await this._transport.disconnect();
|
|
14642
12247
|
await this._storage.disconnect();
|
|
14643
12248
|
await this._oracle.disconnect();
|
|
@@ -14945,14 +12550,9 @@ var Sphere = class _Sphere {
|
|
|
14945
12550
|
storage: this._storage,
|
|
14946
12551
|
emitEvent
|
|
14947
12552
|
});
|
|
14948
|
-
this._market?.initialize({
|
|
14949
|
-
identity: this._identity,
|
|
14950
|
-
emitEvent
|
|
14951
|
-
});
|
|
14952
12553
|
await this._payments.load();
|
|
14953
12554
|
await this._communications.load();
|
|
14954
12555
|
await this._groupChat?.load();
|
|
14955
|
-
await this._market?.load();
|
|
14956
12556
|
}
|
|
14957
12557
|
// ===========================================================================
|
|
14958
12558
|
// Private: Helpers
|
|
@@ -15137,7 +12737,7 @@ async function checkWebSocket(url, timeoutMs) {
|
|
|
15137
12737
|
resolve({ healthy: true, url, responseTimeMs });
|
|
15138
12738
|
}
|
|
15139
12739
|
};
|
|
15140
|
-
ws2.onerror = (
|
|
12740
|
+
ws2.onerror = (_event) => {
|
|
15141
12741
|
if (!resolved) {
|
|
15142
12742
|
resolved = true;
|
|
15143
12743
|
clearTimeout(timer);
|
|
@@ -15637,26 +13237,37 @@ var CoinGeckoPriceProvider = class {
|
|
|
15637
13237
|
timeout;
|
|
15638
13238
|
debug;
|
|
15639
13239
|
baseUrl;
|
|
13240
|
+
storage;
|
|
13241
|
+
/** In-flight fetch promise for deduplication of concurrent getPrices() calls */
|
|
13242
|
+
fetchPromise = null;
|
|
13243
|
+
/** Token names being fetched in the current in-flight request */
|
|
13244
|
+
fetchNames = null;
|
|
13245
|
+
/** Whether persistent cache has been loaded into memory */
|
|
13246
|
+
persistentCacheLoaded = false;
|
|
13247
|
+
/** Promise for loading persistent cache (deduplication) */
|
|
13248
|
+
loadCachePromise = null;
|
|
15640
13249
|
constructor(config) {
|
|
15641
13250
|
this.apiKey = config?.apiKey;
|
|
15642
13251
|
this.cacheTtlMs = config?.cacheTtlMs ?? 6e4;
|
|
15643
13252
|
this.timeout = config?.timeout ?? 1e4;
|
|
15644
13253
|
this.debug = config?.debug ?? false;
|
|
13254
|
+
this.storage = config?.storage ?? null;
|
|
15645
13255
|
this.baseUrl = config?.baseUrl ?? (this.apiKey ? "https://pro-api.coingecko.com/api/v3" : "https://api.coingecko.com/api/v3");
|
|
15646
13256
|
}
|
|
15647
13257
|
async getPrices(tokenNames) {
|
|
15648
13258
|
if (tokenNames.length === 0) {
|
|
15649
13259
|
return /* @__PURE__ */ new Map();
|
|
15650
13260
|
}
|
|
13261
|
+
if (!this.persistentCacheLoaded && this.storage) {
|
|
13262
|
+
await this.loadFromStorage();
|
|
13263
|
+
}
|
|
15651
13264
|
const now = Date.now();
|
|
15652
13265
|
const result = /* @__PURE__ */ new Map();
|
|
15653
13266
|
const uncachedNames = [];
|
|
15654
13267
|
for (const name of tokenNames) {
|
|
15655
13268
|
const cached = this.cache.get(name);
|
|
15656
13269
|
if (cached && cached.expiresAt > now) {
|
|
15657
|
-
|
|
15658
|
-
result.set(name, cached.price);
|
|
15659
|
-
}
|
|
13270
|
+
result.set(name, cached.price);
|
|
15660
13271
|
} else {
|
|
15661
13272
|
uncachedNames.push(name);
|
|
15662
13273
|
}
|
|
@@ -15664,6 +13275,41 @@ var CoinGeckoPriceProvider = class {
|
|
|
15664
13275
|
if (uncachedNames.length === 0) {
|
|
15665
13276
|
return result;
|
|
15666
13277
|
}
|
|
13278
|
+
if (this.fetchPromise && this.fetchNames) {
|
|
13279
|
+
const allCovered = uncachedNames.every((n) => this.fetchNames.has(n));
|
|
13280
|
+
if (allCovered) {
|
|
13281
|
+
if (this.debug) {
|
|
13282
|
+
console.log(`[CoinGecko] Deduplicating request, reusing in-flight fetch`);
|
|
13283
|
+
}
|
|
13284
|
+
const fetched = await this.fetchPromise;
|
|
13285
|
+
for (const name of uncachedNames) {
|
|
13286
|
+
const price = fetched.get(name);
|
|
13287
|
+
if (price) {
|
|
13288
|
+
result.set(name, price);
|
|
13289
|
+
}
|
|
13290
|
+
}
|
|
13291
|
+
return result;
|
|
13292
|
+
}
|
|
13293
|
+
}
|
|
13294
|
+
const fetchPromise = this.doFetch(uncachedNames);
|
|
13295
|
+
this.fetchPromise = fetchPromise;
|
|
13296
|
+
this.fetchNames = new Set(uncachedNames);
|
|
13297
|
+
try {
|
|
13298
|
+
const fetched = await fetchPromise;
|
|
13299
|
+
for (const [name, price] of fetched) {
|
|
13300
|
+
result.set(name, price);
|
|
13301
|
+
}
|
|
13302
|
+
} finally {
|
|
13303
|
+
if (this.fetchPromise === fetchPromise) {
|
|
13304
|
+
this.fetchPromise = null;
|
|
13305
|
+
this.fetchNames = null;
|
|
13306
|
+
}
|
|
13307
|
+
}
|
|
13308
|
+
return result;
|
|
13309
|
+
}
|
|
13310
|
+
async doFetch(uncachedNames) {
|
|
13311
|
+
const result = /* @__PURE__ */ new Map();
|
|
13312
|
+
const now = Date.now();
|
|
15667
13313
|
try {
|
|
15668
13314
|
const ids = uncachedNames.join(",");
|
|
15669
13315
|
const url = `${this.baseUrl}/simple/price?ids=${encodeURIComponent(ids)}&vs_currencies=usd,eur&include_24hr_change=true`;
|
|
@@ -15679,6 +13325,9 @@ var CoinGeckoPriceProvider = class {
|
|
|
15679
13325
|
signal: AbortSignal.timeout(this.timeout)
|
|
15680
13326
|
});
|
|
15681
13327
|
if (!response.ok) {
|
|
13328
|
+
if (response.status === 429) {
|
|
13329
|
+
this.extendCacheOnRateLimit(uncachedNames);
|
|
13330
|
+
}
|
|
15682
13331
|
throw new Error(`CoinGecko API error: ${response.status} ${response.statusText}`);
|
|
15683
13332
|
}
|
|
15684
13333
|
const data = await response.json();
|
|
@@ -15697,25 +13346,113 @@ var CoinGeckoPriceProvider = class {
|
|
|
15697
13346
|
}
|
|
15698
13347
|
for (const name of uncachedNames) {
|
|
15699
13348
|
if (!result.has(name)) {
|
|
15700
|
-
|
|
13349
|
+
const zeroPrice = {
|
|
13350
|
+
tokenName: name,
|
|
13351
|
+
priceUsd: 0,
|
|
13352
|
+
priceEur: 0,
|
|
13353
|
+
change24h: 0,
|
|
13354
|
+
timestamp: now
|
|
13355
|
+
};
|
|
13356
|
+
this.cache.set(name, { price: zeroPrice, expiresAt: now + this.cacheTtlMs });
|
|
13357
|
+
result.set(name, zeroPrice);
|
|
15701
13358
|
}
|
|
15702
13359
|
}
|
|
15703
13360
|
if (this.debug) {
|
|
15704
13361
|
console.log(`[CoinGecko] Fetched ${result.size} prices`);
|
|
15705
13362
|
}
|
|
13363
|
+
this.saveToStorage();
|
|
15706
13364
|
} catch (error) {
|
|
15707
13365
|
if (this.debug) {
|
|
15708
13366
|
console.warn("[CoinGecko] Fetch failed, using stale cache:", error);
|
|
15709
13367
|
}
|
|
15710
13368
|
for (const name of uncachedNames) {
|
|
15711
13369
|
const stale = this.cache.get(name);
|
|
15712
|
-
if (stale
|
|
13370
|
+
if (stale) {
|
|
15713
13371
|
result.set(name, stale.price);
|
|
15714
13372
|
}
|
|
15715
13373
|
}
|
|
15716
13374
|
}
|
|
15717
13375
|
return result;
|
|
15718
13376
|
}
|
|
13377
|
+
// ===========================================================================
|
|
13378
|
+
// Persistent Storage
|
|
13379
|
+
// ===========================================================================
|
|
13380
|
+
/**
|
|
13381
|
+
* Load cached prices from StorageProvider into in-memory cache.
|
|
13382
|
+
* Only loads entries that are still within cacheTtlMs.
|
|
13383
|
+
*/
|
|
13384
|
+
async loadFromStorage() {
|
|
13385
|
+
if (this.loadCachePromise) {
|
|
13386
|
+
return this.loadCachePromise;
|
|
13387
|
+
}
|
|
13388
|
+
this.loadCachePromise = this.doLoadFromStorage();
|
|
13389
|
+
try {
|
|
13390
|
+
await this.loadCachePromise;
|
|
13391
|
+
} finally {
|
|
13392
|
+
this.loadCachePromise = null;
|
|
13393
|
+
}
|
|
13394
|
+
}
|
|
13395
|
+
async doLoadFromStorage() {
|
|
13396
|
+
this.persistentCacheLoaded = true;
|
|
13397
|
+
if (!this.storage) return;
|
|
13398
|
+
try {
|
|
13399
|
+
const [cached, cachedTs] = await Promise.all([
|
|
13400
|
+
this.storage.get(STORAGE_KEYS_GLOBAL.PRICE_CACHE),
|
|
13401
|
+
this.storage.get(STORAGE_KEYS_GLOBAL.PRICE_CACHE_TS)
|
|
13402
|
+
]);
|
|
13403
|
+
if (!cached || !cachedTs) return;
|
|
13404
|
+
const ts = parseInt(cachedTs, 10);
|
|
13405
|
+
if (isNaN(ts)) return;
|
|
13406
|
+
const age = Date.now() - ts;
|
|
13407
|
+
if (age > this.cacheTtlMs) return;
|
|
13408
|
+
const data = JSON.parse(cached);
|
|
13409
|
+
const expiresAt = ts + this.cacheTtlMs;
|
|
13410
|
+
for (const [name, price] of Object.entries(data)) {
|
|
13411
|
+
if (!this.cache.has(name)) {
|
|
13412
|
+
this.cache.set(name, { price, expiresAt });
|
|
13413
|
+
}
|
|
13414
|
+
}
|
|
13415
|
+
if (this.debug) {
|
|
13416
|
+
console.log(`[CoinGecko] Loaded ${Object.keys(data).length} prices from persistent cache`);
|
|
13417
|
+
}
|
|
13418
|
+
} catch {
|
|
13419
|
+
}
|
|
13420
|
+
}
|
|
13421
|
+
/**
|
|
13422
|
+
* Save current prices to StorageProvider (fire-and-forget).
|
|
13423
|
+
*/
|
|
13424
|
+
saveToStorage() {
|
|
13425
|
+
if (!this.storage) return;
|
|
13426
|
+
const data = {};
|
|
13427
|
+
for (const [name, entry] of this.cache) {
|
|
13428
|
+
data[name] = entry.price;
|
|
13429
|
+
}
|
|
13430
|
+
Promise.all([
|
|
13431
|
+
this.storage.set(STORAGE_KEYS_GLOBAL.PRICE_CACHE, JSON.stringify(data)),
|
|
13432
|
+
this.storage.set(STORAGE_KEYS_GLOBAL.PRICE_CACHE_TS, String(Date.now()))
|
|
13433
|
+
]).catch(() => {
|
|
13434
|
+
});
|
|
13435
|
+
}
|
|
13436
|
+
// ===========================================================================
|
|
13437
|
+
// Rate-limit handling
|
|
13438
|
+
// ===========================================================================
|
|
13439
|
+
/**
|
|
13440
|
+
* On 429 rate-limit, extend stale cache entries so subsequent calls
|
|
13441
|
+
* don't immediately retry and hammer the API.
|
|
13442
|
+
*/
|
|
13443
|
+
extendCacheOnRateLimit(names) {
|
|
13444
|
+
const backoffMs = 6e4;
|
|
13445
|
+
const extendedExpiry = Date.now() + backoffMs;
|
|
13446
|
+
for (const name of names) {
|
|
13447
|
+
const existing = this.cache.get(name);
|
|
13448
|
+
if (existing) {
|
|
13449
|
+
existing.expiresAt = Math.max(existing.expiresAt, extendedExpiry);
|
|
13450
|
+
}
|
|
13451
|
+
}
|
|
13452
|
+
if (this.debug) {
|
|
13453
|
+
console.warn(`[CoinGecko] Rate-limited (429), extended cache TTL by ${backoffMs / 1e3}s`);
|
|
13454
|
+
}
|
|
13455
|
+
}
|
|
15719
13456
|
async getPrice(tokenName) {
|
|
15720
13457
|
const prices = await this.getPrices([tokenName]);
|
|
15721
13458
|
return prices.get(tokenName) ?? null;
|
|
@@ -15745,7 +13482,6 @@ export {
|
|
|
15745
13482
|
DEFAULT_GROUP_RELAYS,
|
|
15746
13483
|
DEFAULT_IPFS_BOOTSTRAP_PEERS,
|
|
15747
13484
|
DEFAULT_IPFS_GATEWAYS,
|
|
15748
|
-
DEFAULT_MARKET_API_URL,
|
|
15749
13485
|
DEFAULT_NOSTR_RELAYS,
|
|
15750
13486
|
DEV_AGGREGATOR_URL,
|
|
15751
13487
|
GroupChatModule,
|
|
@@ -15754,7 +13490,6 @@ export {
|
|
|
15754
13490
|
l1_exports as L1,
|
|
15755
13491
|
L1PaymentsModule,
|
|
15756
13492
|
LIMITS,
|
|
15757
|
-
MarketModule,
|
|
15758
13493
|
NETWORKS,
|
|
15759
13494
|
NIP29_KINDS,
|
|
15760
13495
|
NOSTR_EVENT_KINDS,
|
|
@@ -15782,7 +13517,6 @@ export {
|
|
|
15782
13517
|
createGroupChatModule,
|
|
15783
13518
|
createKeyPair,
|
|
15784
13519
|
createL1PaymentsModule,
|
|
15785
|
-
createMarketModule,
|
|
15786
13520
|
createPaymentSession,
|
|
15787
13521
|
createPaymentSessionError,
|
|
15788
13522
|
createPaymentsModule,
|
|
@@ -15870,16 +13604,4 @@ export {
|
|
|
15870
13604
|
txfToToken,
|
|
15871
13605
|
validateMnemonic2 as validateMnemonic
|
|
15872
13606
|
};
|
|
15873
|
-
/*! Bundled license information:
|
|
15874
|
-
|
|
15875
|
-
@noble/hashes/utils.js:
|
|
15876
|
-
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
15877
|
-
|
|
15878
|
-
@noble/curves/utils.js:
|
|
15879
|
-
@noble/curves/abstract/modular.js:
|
|
15880
|
-
@noble/curves/abstract/curve.js:
|
|
15881
|
-
@noble/curves/abstract/weierstrass.js:
|
|
15882
|
-
@noble/curves/secp256k1.js:
|
|
15883
|
-
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
15884
|
-
*/
|
|
15885
13607
|
//# sourceMappingURL=index.js.map
|