@unicitylabs/sphere-sdk 0.3.6 → 0.3.8
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/core/index.cjs +96 -2528
- 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 +92 -2524
- package/dist/core/index.js.map +1 -1
- 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/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 +238 -2539
- 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 +234 -2532
- package/dist/index.js.map +1 -1
- package/package.json +1 -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) {
|
|
@@ -9132,26 +9177,27 @@ var GroupChatModule = class {
|
|
|
9132
9177
|
oneshotSubscription(filter, opts) {
|
|
9133
9178
|
return new Promise((resolve) => {
|
|
9134
9179
|
let done = false;
|
|
9135
|
-
|
|
9180
|
+
const state = {};
|
|
9136
9181
|
const finish = () => {
|
|
9137
9182
|
if (done) return;
|
|
9138
9183
|
done = true;
|
|
9139
|
-
if (subId) {
|
|
9184
|
+
if (state.subId) {
|
|
9140
9185
|
try {
|
|
9141
|
-
this.client.unsubscribe(subId);
|
|
9186
|
+
this.client.unsubscribe(state.subId);
|
|
9142
9187
|
} catch {
|
|
9143
9188
|
}
|
|
9144
|
-
const idx = this.subscriptionIds.indexOf(subId);
|
|
9189
|
+
const idx = this.subscriptionIds.indexOf(state.subId);
|
|
9145
9190
|
if (idx >= 0) this.subscriptionIds.splice(idx, 1);
|
|
9146
9191
|
}
|
|
9147
9192
|
resolve(opts.onComplete());
|
|
9148
9193
|
};
|
|
9149
|
-
subId = this.client.subscribe(filter, {
|
|
9194
|
+
const subId = this.client.subscribe(filter, {
|
|
9150
9195
|
onEvent: (event) => {
|
|
9151
9196
|
if (!done) opts.onEvent(event);
|
|
9152
9197
|
},
|
|
9153
9198
|
onEndOfStoredEvents: finish
|
|
9154
9199
|
});
|
|
9200
|
+
state.subId = subId;
|
|
9155
9201
|
this.subscriptionIds.push(subId);
|
|
9156
9202
|
setTimeout(finish, opts.timeoutMs ?? 5e3);
|
|
9157
9203
|
});
|
|
@@ -9182,2426 +9228,6 @@ function createGroupChatModule(config) {
|
|
|
9182
9228
|
return new GroupChatModule(config);
|
|
9183
9229
|
}
|
|
9184
9230
|
|
|
9185
|
-
// node_modules/@noble/hashes/utils.js
|
|
9186
|
-
function isBytes(a) {
|
|
9187
|
-
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
|
|
9188
|
-
}
|
|
9189
|
-
function anumber(n, title = "") {
|
|
9190
|
-
if (!Number.isSafeInteger(n) || n < 0) {
|
|
9191
|
-
const prefix = title && `"${title}" `;
|
|
9192
|
-
throw new Error(`${prefix}expected integer >= 0, got ${n}`);
|
|
9193
|
-
}
|
|
9194
|
-
}
|
|
9195
|
-
function abytes(value, length, title = "") {
|
|
9196
|
-
const bytes = isBytes(value);
|
|
9197
|
-
const len = value?.length;
|
|
9198
|
-
const needsLen = length !== void 0;
|
|
9199
|
-
if (!bytes || needsLen && len !== length) {
|
|
9200
|
-
const prefix = title && `"${title}" `;
|
|
9201
|
-
const ofLen = needsLen ? ` of length ${length}` : "";
|
|
9202
|
-
const got = bytes ? `length=${len}` : `type=${typeof value}`;
|
|
9203
|
-
throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
|
|
9204
|
-
}
|
|
9205
|
-
return value;
|
|
9206
|
-
}
|
|
9207
|
-
function ahash(h) {
|
|
9208
|
-
if (typeof h !== "function" || typeof h.create !== "function")
|
|
9209
|
-
throw new Error("Hash must wrapped by utils.createHasher");
|
|
9210
|
-
anumber(h.outputLen);
|
|
9211
|
-
anumber(h.blockLen);
|
|
9212
|
-
}
|
|
9213
|
-
function aexists(instance, checkFinished = true) {
|
|
9214
|
-
if (instance.destroyed)
|
|
9215
|
-
throw new Error("Hash instance has been destroyed");
|
|
9216
|
-
if (checkFinished && instance.finished)
|
|
9217
|
-
throw new Error("Hash#digest() has already been called");
|
|
9218
|
-
}
|
|
9219
|
-
function aoutput(out, instance) {
|
|
9220
|
-
abytes(out, void 0, "digestInto() output");
|
|
9221
|
-
const min = instance.outputLen;
|
|
9222
|
-
if (out.length < min) {
|
|
9223
|
-
throw new Error('"digestInto() output" expected to be of length >=' + min);
|
|
9224
|
-
}
|
|
9225
|
-
}
|
|
9226
|
-
function clean(...arrays) {
|
|
9227
|
-
for (let i = 0; i < arrays.length; i++) {
|
|
9228
|
-
arrays[i].fill(0);
|
|
9229
|
-
}
|
|
9230
|
-
}
|
|
9231
|
-
function createView(arr) {
|
|
9232
|
-
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
9233
|
-
}
|
|
9234
|
-
function rotr(word, shift) {
|
|
9235
|
-
return word << 32 - shift | word >>> shift;
|
|
9236
|
-
}
|
|
9237
|
-
var hasHexBuiltin = /* @__PURE__ */ (() => (
|
|
9238
|
-
// @ts-ignore
|
|
9239
|
-
typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
|
|
9240
|
-
))();
|
|
9241
|
-
var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
|
|
9242
|
-
function bytesToHex4(bytes) {
|
|
9243
|
-
abytes(bytes);
|
|
9244
|
-
if (hasHexBuiltin)
|
|
9245
|
-
return bytes.toHex();
|
|
9246
|
-
let hex = "";
|
|
9247
|
-
for (let i = 0; i < bytes.length; i++) {
|
|
9248
|
-
hex += hexes[bytes[i]];
|
|
9249
|
-
}
|
|
9250
|
-
return hex;
|
|
9251
|
-
}
|
|
9252
|
-
var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
|
|
9253
|
-
function asciiToBase16(ch) {
|
|
9254
|
-
if (ch >= asciis._0 && ch <= asciis._9)
|
|
9255
|
-
return ch - asciis._0;
|
|
9256
|
-
if (ch >= asciis.A && ch <= asciis.F)
|
|
9257
|
-
return ch - (asciis.A - 10);
|
|
9258
|
-
if (ch >= asciis.a && ch <= asciis.f)
|
|
9259
|
-
return ch - (asciis.a - 10);
|
|
9260
|
-
return;
|
|
9261
|
-
}
|
|
9262
|
-
function hexToBytes2(hex) {
|
|
9263
|
-
if (typeof hex !== "string")
|
|
9264
|
-
throw new Error("hex string expected, got " + typeof hex);
|
|
9265
|
-
if (hasHexBuiltin)
|
|
9266
|
-
return Uint8Array.fromHex(hex);
|
|
9267
|
-
const hl = hex.length;
|
|
9268
|
-
const al = hl / 2;
|
|
9269
|
-
if (hl % 2)
|
|
9270
|
-
throw new Error("hex string expected, got unpadded hex of length " + hl);
|
|
9271
|
-
const array = new Uint8Array(al);
|
|
9272
|
-
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
9273
|
-
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
|
9274
|
-
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
|
9275
|
-
if (n1 === void 0 || n2 === void 0) {
|
|
9276
|
-
const char = hex[hi] + hex[hi + 1];
|
|
9277
|
-
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
9278
|
-
}
|
|
9279
|
-
array[ai] = n1 * 16 + n2;
|
|
9280
|
-
}
|
|
9281
|
-
return array;
|
|
9282
|
-
}
|
|
9283
|
-
function concatBytes(...arrays) {
|
|
9284
|
-
let sum = 0;
|
|
9285
|
-
for (let i = 0; i < arrays.length; i++) {
|
|
9286
|
-
const a = arrays[i];
|
|
9287
|
-
abytes(a);
|
|
9288
|
-
sum += a.length;
|
|
9289
|
-
}
|
|
9290
|
-
const res = new Uint8Array(sum);
|
|
9291
|
-
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
9292
|
-
const a = arrays[i];
|
|
9293
|
-
res.set(a, pad);
|
|
9294
|
-
pad += a.length;
|
|
9295
|
-
}
|
|
9296
|
-
return res;
|
|
9297
|
-
}
|
|
9298
|
-
function createHasher(hashCons, info = {}) {
|
|
9299
|
-
const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
|
|
9300
|
-
const tmp = hashCons(void 0);
|
|
9301
|
-
hashC.outputLen = tmp.outputLen;
|
|
9302
|
-
hashC.blockLen = tmp.blockLen;
|
|
9303
|
-
hashC.create = (opts) => hashCons(opts);
|
|
9304
|
-
Object.assign(hashC, info);
|
|
9305
|
-
return Object.freeze(hashC);
|
|
9306
|
-
}
|
|
9307
|
-
function randomBytes2(bytesLength = 32) {
|
|
9308
|
-
const cr = typeof globalThis === "object" ? globalThis.crypto : null;
|
|
9309
|
-
if (typeof cr?.getRandomValues !== "function")
|
|
9310
|
-
throw new Error("crypto.getRandomValues must be defined");
|
|
9311
|
-
return cr.getRandomValues(new Uint8Array(bytesLength));
|
|
9312
|
-
}
|
|
9313
|
-
var oidNist = (suffix) => ({
|
|
9314
|
-
oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
|
|
9315
|
-
});
|
|
9316
|
-
|
|
9317
|
-
// node_modules/@noble/hashes/_md.js
|
|
9318
|
-
function Chi(a, b, c) {
|
|
9319
|
-
return a & b ^ ~a & c;
|
|
9320
|
-
}
|
|
9321
|
-
function Maj(a, b, c) {
|
|
9322
|
-
return a & b ^ a & c ^ b & c;
|
|
9323
|
-
}
|
|
9324
|
-
var HashMD = class {
|
|
9325
|
-
blockLen;
|
|
9326
|
-
outputLen;
|
|
9327
|
-
padOffset;
|
|
9328
|
-
isLE;
|
|
9329
|
-
// For partial updates less than block size
|
|
9330
|
-
buffer;
|
|
9331
|
-
view;
|
|
9332
|
-
finished = false;
|
|
9333
|
-
length = 0;
|
|
9334
|
-
pos = 0;
|
|
9335
|
-
destroyed = false;
|
|
9336
|
-
constructor(blockLen, outputLen, padOffset, isLE) {
|
|
9337
|
-
this.blockLen = blockLen;
|
|
9338
|
-
this.outputLen = outputLen;
|
|
9339
|
-
this.padOffset = padOffset;
|
|
9340
|
-
this.isLE = isLE;
|
|
9341
|
-
this.buffer = new Uint8Array(blockLen);
|
|
9342
|
-
this.view = createView(this.buffer);
|
|
9343
|
-
}
|
|
9344
|
-
update(data) {
|
|
9345
|
-
aexists(this);
|
|
9346
|
-
abytes(data);
|
|
9347
|
-
const { view, buffer, blockLen } = this;
|
|
9348
|
-
const len = data.length;
|
|
9349
|
-
for (let pos = 0; pos < len; ) {
|
|
9350
|
-
const take = Math.min(blockLen - this.pos, len - pos);
|
|
9351
|
-
if (take === blockLen) {
|
|
9352
|
-
const dataView = createView(data);
|
|
9353
|
-
for (; blockLen <= len - pos; pos += blockLen)
|
|
9354
|
-
this.process(dataView, pos);
|
|
9355
|
-
continue;
|
|
9356
|
-
}
|
|
9357
|
-
buffer.set(data.subarray(pos, pos + take), this.pos);
|
|
9358
|
-
this.pos += take;
|
|
9359
|
-
pos += take;
|
|
9360
|
-
if (this.pos === blockLen) {
|
|
9361
|
-
this.process(view, 0);
|
|
9362
|
-
this.pos = 0;
|
|
9363
|
-
}
|
|
9364
|
-
}
|
|
9365
|
-
this.length += data.length;
|
|
9366
|
-
this.roundClean();
|
|
9367
|
-
return this;
|
|
9368
|
-
}
|
|
9369
|
-
digestInto(out) {
|
|
9370
|
-
aexists(this);
|
|
9371
|
-
aoutput(out, this);
|
|
9372
|
-
this.finished = true;
|
|
9373
|
-
const { buffer, view, blockLen, isLE } = this;
|
|
9374
|
-
let { pos } = this;
|
|
9375
|
-
buffer[pos++] = 128;
|
|
9376
|
-
clean(this.buffer.subarray(pos));
|
|
9377
|
-
if (this.padOffset > blockLen - pos) {
|
|
9378
|
-
this.process(view, 0);
|
|
9379
|
-
pos = 0;
|
|
9380
|
-
}
|
|
9381
|
-
for (let i = pos; i < blockLen; i++)
|
|
9382
|
-
buffer[i] = 0;
|
|
9383
|
-
view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
|
|
9384
|
-
this.process(view, 0);
|
|
9385
|
-
const oview = createView(out);
|
|
9386
|
-
const len = this.outputLen;
|
|
9387
|
-
if (len % 4)
|
|
9388
|
-
throw new Error("_sha2: outputLen must be aligned to 32bit");
|
|
9389
|
-
const outLen = len / 4;
|
|
9390
|
-
const state = this.get();
|
|
9391
|
-
if (outLen > state.length)
|
|
9392
|
-
throw new Error("_sha2: outputLen bigger than state");
|
|
9393
|
-
for (let i = 0; i < outLen; i++)
|
|
9394
|
-
oview.setUint32(4 * i, state[i], isLE);
|
|
9395
|
-
}
|
|
9396
|
-
digest() {
|
|
9397
|
-
const { buffer, outputLen } = this;
|
|
9398
|
-
this.digestInto(buffer);
|
|
9399
|
-
const res = buffer.slice(0, outputLen);
|
|
9400
|
-
this.destroy();
|
|
9401
|
-
return res;
|
|
9402
|
-
}
|
|
9403
|
-
_cloneInto(to) {
|
|
9404
|
-
to ||= new this.constructor();
|
|
9405
|
-
to.set(...this.get());
|
|
9406
|
-
const { blockLen, buffer, length, finished, destroyed, pos } = this;
|
|
9407
|
-
to.destroyed = destroyed;
|
|
9408
|
-
to.finished = finished;
|
|
9409
|
-
to.length = length;
|
|
9410
|
-
to.pos = pos;
|
|
9411
|
-
if (length % blockLen)
|
|
9412
|
-
to.buffer.set(buffer);
|
|
9413
|
-
return to;
|
|
9414
|
-
}
|
|
9415
|
-
clone() {
|
|
9416
|
-
return this._cloneInto();
|
|
9417
|
-
}
|
|
9418
|
-
};
|
|
9419
|
-
var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
|
|
9420
|
-
1779033703,
|
|
9421
|
-
3144134277,
|
|
9422
|
-
1013904242,
|
|
9423
|
-
2773480762,
|
|
9424
|
-
1359893119,
|
|
9425
|
-
2600822924,
|
|
9426
|
-
528734635,
|
|
9427
|
-
1541459225
|
|
9428
|
-
]);
|
|
9429
|
-
|
|
9430
|
-
// node_modules/@noble/hashes/sha2.js
|
|
9431
|
-
var SHA256_K = /* @__PURE__ */ Uint32Array.from([
|
|
9432
|
-
1116352408,
|
|
9433
|
-
1899447441,
|
|
9434
|
-
3049323471,
|
|
9435
|
-
3921009573,
|
|
9436
|
-
961987163,
|
|
9437
|
-
1508970993,
|
|
9438
|
-
2453635748,
|
|
9439
|
-
2870763221,
|
|
9440
|
-
3624381080,
|
|
9441
|
-
310598401,
|
|
9442
|
-
607225278,
|
|
9443
|
-
1426881987,
|
|
9444
|
-
1925078388,
|
|
9445
|
-
2162078206,
|
|
9446
|
-
2614888103,
|
|
9447
|
-
3248222580,
|
|
9448
|
-
3835390401,
|
|
9449
|
-
4022224774,
|
|
9450
|
-
264347078,
|
|
9451
|
-
604807628,
|
|
9452
|
-
770255983,
|
|
9453
|
-
1249150122,
|
|
9454
|
-
1555081692,
|
|
9455
|
-
1996064986,
|
|
9456
|
-
2554220882,
|
|
9457
|
-
2821834349,
|
|
9458
|
-
2952996808,
|
|
9459
|
-
3210313671,
|
|
9460
|
-
3336571891,
|
|
9461
|
-
3584528711,
|
|
9462
|
-
113926993,
|
|
9463
|
-
338241895,
|
|
9464
|
-
666307205,
|
|
9465
|
-
773529912,
|
|
9466
|
-
1294757372,
|
|
9467
|
-
1396182291,
|
|
9468
|
-
1695183700,
|
|
9469
|
-
1986661051,
|
|
9470
|
-
2177026350,
|
|
9471
|
-
2456956037,
|
|
9472
|
-
2730485921,
|
|
9473
|
-
2820302411,
|
|
9474
|
-
3259730800,
|
|
9475
|
-
3345764771,
|
|
9476
|
-
3516065817,
|
|
9477
|
-
3600352804,
|
|
9478
|
-
4094571909,
|
|
9479
|
-
275423344,
|
|
9480
|
-
430227734,
|
|
9481
|
-
506948616,
|
|
9482
|
-
659060556,
|
|
9483
|
-
883997877,
|
|
9484
|
-
958139571,
|
|
9485
|
-
1322822218,
|
|
9486
|
-
1537002063,
|
|
9487
|
-
1747873779,
|
|
9488
|
-
1955562222,
|
|
9489
|
-
2024104815,
|
|
9490
|
-
2227730452,
|
|
9491
|
-
2361852424,
|
|
9492
|
-
2428436474,
|
|
9493
|
-
2756734187,
|
|
9494
|
-
3204031479,
|
|
9495
|
-
3329325298
|
|
9496
|
-
]);
|
|
9497
|
-
var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
|
|
9498
|
-
var SHA2_32B = class extends HashMD {
|
|
9499
|
-
constructor(outputLen) {
|
|
9500
|
-
super(64, outputLen, 8, false);
|
|
9501
|
-
}
|
|
9502
|
-
get() {
|
|
9503
|
-
const { A, B, C, D, E, F, G, H } = this;
|
|
9504
|
-
return [A, B, C, D, E, F, G, H];
|
|
9505
|
-
}
|
|
9506
|
-
// prettier-ignore
|
|
9507
|
-
set(A, B, C, D, E, F, G, H) {
|
|
9508
|
-
this.A = A | 0;
|
|
9509
|
-
this.B = B | 0;
|
|
9510
|
-
this.C = C | 0;
|
|
9511
|
-
this.D = D | 0;
|
|
9512
|
-
this.E = E | 0;
|
|
9513
|
-
this.F = F | 0;
|
|
9514
|
-
this.G = G | 0;
|
|
9515
|
-
this.H = H | 0;
|
|
9516
|
-
}
|
|
9517
|
-
process(view, offset) {
|
|
9518
|
-
for (let i = 0; i < 16; i++, offset += 4)
|
|
9519
|
-
SHA256_W[i] = view.getUint32(offset, false);
|
|
9520
|
-
for (let i = 16; i < 64; i++) {
|
|
9521
|
-
const W15 = SHA256_W[i - 15];
|
|
9522
|
-
const W2 = SHA256_W[i - 2];
|
|
9523
|
-
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
|
|
9524
|
-
const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
|
|
9525
|
-
SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
|
|
9526
|
-
}
|
|
9527
|
-
let { A, B, C, D, E, F, G, H } = this;
|
|
9528
|
-
for (let i = 0; i < 64; i++) {
|
|
9529
|
-
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
|
|
9530
|
-
const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
|
|
9531
|
-
const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
|
|
9532
|
-
const T2 = sigma0 + Maj(A, B, C) | 0;
|
|
9533
|
-
H = G;
|
|
9534
|
-
G = F;
|
|
9535
|
-
F = E;
|
|
9536
|
-
E = D + T1 | 0;
|
|
9537
|
-
D = C;
|
|
9538
|
-
C = B;
|
|
9539
|
-
B = A;
|
|
9540
|
-
A = T1 + T2 | 0;
|
|
9541
|
-
}
|
|
9542
|
-
A = A + this.A | 0;
|
|
9543
|
-
B = B + this.B | 0;
|
|
9544
|
-
C = C + this.C | 0;
|
|
9545
|
-
D = D + this.D | 0;
|
|
9546
|
-
E = E + this.E | 0;
|
|
9547
|
-
F = F + this.F | 0;
|
|
9548
|
-
G = G + this.G | 0;
|
|
9549
|
-
H = H + this.H | 0;
|
|
9550
|
-
this.set(A, B, C, D, E, F, G, H);
|
|
9551
|
-
}
|
|
9552
|
-
roundClean() {
|
|
9553
|
-
clean(SHA256_W);
|
|
9554
|
-
}
|
|
9555
|
-
destroy() {
|
|
9556
|
-
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
|
9557
|
-
clean(this.buffer);
|
|
9558
|
-
}
|
|
9559
|
-
};
|
|
9560
|
-
var _SHA256 = class extends SHA2_32B {
|
|
9561
|
-
// We cannot use array here since array allows indexing by variable
|
|
9562
|
-
// which means optimizer/compiler cannot use registers.
|
|
9563
|
-
A = SHA256_IV[0] | 0;
|
|
9564
|
-
B = SHA256_IV[1] | 0;
|
|
9565
|
-
C = SHA256_IV[2] | 0;
|
|
9566
|
-
D = SHA256_IV[3] | 0;
|
|
9567
|
-
E = SHA256_IV[4] | 0;
|
|
9568
|
-
F = SHA256_IV[5] | 0;
|
|
9569
|
-
G = SHA256_IV[6] | 0;
|
|
9570
|
-
H = SHA256_IV[7] | 0;
|
|
9571
|
-
constructor() {
|
|
9572
|
-
super(32);
|
|
9573
|
-
}
|
|
9574
|
-
};
|
|
9575
|
-
var sha2564 = /* @__PURE__ */ createHasher(
|
|
9576
|
-
() => new _SHA256(),
|
|
9577
|
-
/* @__PURE__ */ oidNist(1)
|
|
9578
|
-
);
|
|
9579
|
-
|
|
9580
|
-
// node_modules/@noble/curves/utils.js
|
|
9581
|
-
var _0n = /* @__PURE__ */ BigInt(0);
|
|
9582
|
-
var _1n = /* @__PURE__ */ BigInt(1);
|
|
9583
|
-
function abool(value, title = "") {
|
|
9584
|
-
if (typeof value !== "boolean") {
|
|
9585
|
-
const prefix = title && `"${title}" `;
|
|
9586
|
-
throw new Error(prefix + "expected boolean, got type=" + typeof value);
|
|
9587
|
-
}
|
|
9588
|
-
return value;
|
|
9589
|
-
}
|
|
9590
|
-
function abignumber(n) {
|
|
9591
|
-
if (typeof n === "bigint") {
|
|
9592
|
-
if (!isPosBig(n))
|
|
9593
|
-
throw new Error("positive bigint expected, got " + n);
|
|
9594
|
-
} else
|
|
9595
|
-
anumber(n);
|
|
9596
|
-
return n;
|
|
9597
|
-
}
|
|
9598
|
-
function numberToHexUnpadded(num) {
|
|
9599
|
-
const hex = abignumber(num).toString(16);
|
|
9600
|
-
return hex.length & 1 ? "0" + hex : hex;
|
|
9601
|
-
}
|
|
9602
|
-
function hexToNumber(hex) {
|
|
9603
|
-
if (typeof hex !== "string")
|
|
9604
|
-
throw new Error("hex string expected, got " + typeof hex);
|
|
9605
|
-
return hex === "" ? _0n : BigInt("0x" + hex);
|
|
9606
|
-
}
|
|
9607
|
-
function bytesToNumberBE(bytes) {
|
|
9608
|
-
return hexToNumber(bytesToHex4(bytes));
|
|
9609
|
-
}
|
|
9610
|
-
function bytesToNumberLE(bytes) {
|
|
9611
|
-
return hexToNumber(bytesToHex4(copyBytes(abytes(bytes)).reverse()));
|
|
9612
|
-
}
|
|
9613
|
-
function numberToBytesBE(n, len) {
|
|
9614
|
-
anumber(len);
|
|
9615
|
-
n = abignumber(n);
|
|
9616
|
-
const res = hexToBytes2(n.toString(16).padStart(len * 2, "0"));
|
|
9617
|
-
if (res.length !== len)
|
|
9618
|
-
throw new Error("number too large");
|
|
9619
|
-
return res;
|
|
9620
|
-
}
|
|
9621
|
-
function numberToBytesLE(n, len) {
|
|
9622
|
-
return numberToBytesBE(n, len).reverse();
|
|
9623
|
-
}
|
|
9624
|
-
function copyBytes(bytes) {
|
|
9625
|
-
return Uint8Array.from(bytes);
|
|
9626
|
-
}
|
|
9627
|
-
var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
|
|
9628
|
-
function inRange(n, min, max) {
|
|
9629
|
-
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
|
|
9630
|
-
}
|
|
9631
|
-
function aInRange(title, n, min, max) {
|
|
9632
|
-
if (!inRange(n, min, max))
|
|
9633
|
-
throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
|
|
9634
|
-
}
|
|
9635
|
-
function bitLen(n) {
|
|
9636
|
-
let len;
|
|
9637
|
-
for (len = 0; n > _0n; n >>= _1n, len += 1)
|
|
9638
|
-
;
|
|
9639
|
-
return len;
|
|
9640
|
-
}
|
|
9641
|
-
var bitMask = (n) => (_1n << BigInt(n)) - _1n;
|
|
9642
|
-
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
9643
|
-
anumber(hashLen, "hashLen");
|
|
9644
|
-
anumber(qByteLen, "qByteLen");
|
|
9645
|
-
if (typeof hmacFn !== "function")
|
|
9646
|
-
throw new Error("hmacFn must be a function");
|
|
9647
|
-
const u8n = (len) => new Uint8Array(len);
|
|
9648
|
-
const NULL = Uint8Array.of();
|
|
9649
|
-
const byte0 = Uint8Array.of(0);
|
|
9650
|
-
const byte1 = Uint8Array.of(1);
|
|
9651
|
-
const _maxDrbgIters = 1e3;
|
|
9652
|
-
let v = u8n(hashLen);
|
|
9653
|
-
let k = u8n(hashLen);
|
|
9654
|
-
let i = 0;
|
|
9655
|
-
const reset = () => {
|
|
9656
|
-
v.fill(1);
|
|
9657
|
-
k.fill(0);
|
|
9658
|
-
i = 0;
|
|
9659
|
-
};
|
|
9660
|
-
const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));
|
|
9661
|
-
const reseed = (seed = NULL) => {
|
|
9662
|
-
k = h(byte0, seed);
|
|
9663
|
-
v = h();
|
|
9664
|
-
if (seed.length === 0)
|
|
9665
|
-
return;
|
|
9666
|
-
k = h(byte1, seed);
|
|
9667
|
-
v = h();
|
|
9668
|
-
};
|
|
9669
|
-
const gen = () => {
|
|
9670
|
-
if (i++ >= _maxDrbgIters)
|
|
9671
|
-
throw new Error("drbg: tried max amount of iterations");
|
|
9672
|
-
let len = 0;
|
|
9673
|
-
const out = [];
|
|
9674
|
-
while (len < qByteLen) {
|
|
9675
|
-
v = h();
|
|
9676
|
-
const sl = v.slice();
|
|
9677
|
-
out.push(sl);
|
|
9678
|
-
len += v.length;
|
|
9679
|
-
}
|
|
9680
|
-
return concatBytes(...out);
|
|
9681
|
-
};
|
|
9682
|
-
const genUntil = (seed, pred) => {
|
|
9683
|
-
reset();
|
|
9684
|
-
reseed(seed);
|
|
9685
|
-
let res = void 0;
|
|
9686
|
-
while (!(res = pred(gen())))
|
|
9687
|
-
reseed();
|
|
9688
|
-
reset();
|
|
9689
|
-
return res;
|
|
9690
|
-
};
|
|
9691
|
-
return genUntil;
|
|
9692
|
-
}
|
|
9693
|
-
function validateObject(object, fields = {}, optFields = {}) {
|
|
9694
|
-
if (!object || typeof object !== "object")
|
|
9695
|
-
throw new Error("expected valid options object");
|
|
9696
|
-
function checkField(fieldName, expectedType, isOpt) {
|
|
9697
|
-
const val = object[fieldName];
|
|
9698
|
-
if (isOpt && val === void 0)
|
|
9699
|
-
return;
|
|
9700
|
-
const current = typeof val;
|
|
9701
|
-
if (current !== expectedType || val === null)
|
|
9702
|
-
throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
|
|
9703
|
-
}
|
|
9704
|
-
const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
|
|
9705
|
-
iter(fields, false);
|
|
9706
|
-
iter(optFields, true);
|
|
9707
|
-
}
|
|
9708
|
-
function memoized(fn) {
|
|
9709
|
-
const map = /* @__PURE__ */ new WeakMap();
|
|
9710
|
-
return (arg, ...args) => {
|
|
9711
|
-
const val = map.get(arg);
|
|
9712
|
-
if (val !== void 0)
|
|
9713
|
-
return val;
|
|
9714
|
-
const computed = fn(arg, ...args);
|
|
9715
|
-
map.set(arg, computed);
|
|
9716
|
-
return computed;
|
|
9717
|
-
};
|
|
9718
|
-
}
|
|
9719
|
-
|
|
9720
|
-
// node_modules/@noble/curves/abstract/modular.js
|
|
9721
|
-
var _0n2 = /* @__PURE__ */ BigInt(0);
|
|
9722
|
-
var _1n2 = /* @__PURE__ */ BigInt(1);
|
|
9723
|
-
var _2n = /* @__PURE__ */ BigInt(2);
|
|
9724
|
-
var _3n = /* @__PURE__ */ BigInt(3);
|
|
9725
|
-
var _4n = /* @__PURE__ */ BigInt(4);
|
|
9726
|
-
var _5n = /* @__PURE__ */ BigInt(5);
|
|
9727
|
-
var _7n = /* @__PURE__ */ BigInt(7);
|
|
9728
|
-
var _8n = /* @__PURE__ */ BigInt(8);
|
|
9729
|
-
var _9n = /* @__PURE__ */ BigInt(9);
|
|
9730
|
-
var _16n = /* @__PURE__ */ BigInt(16);
|
|
9731
|
-
function mod(a, b) {
|
|
9732
|
-
const result = a % b;
|
|
9733
|
-
return result >= _0n2 ? result : b + result;
|
|
9734
|
-
}
|
|
9735
|
-
function pow2(x, power, modulo) {
|
|
9736
|
-
let res = x;
|
|
9737
|
-
while (power-- > _0n2) {
|
|
9738
|
-
res *= res;
|
|
9739
|
-
res %= modulo;
|
|
9740
|
-
}
|
|
9741
|
-
return res;
|
|
9742
|
-
}
|
|
9743
|
-
function invert(number, modulo) {
|
|
9744
|
-
if (number === _0n2)
|
|
9745
|
-
throw new Error("invert: expected non-zero number");
|
|
9746
|
-
if (modulo <= _0n2)
|
|
9747
|
-
throw new Error("invert: expected positive modulus, got " + modulo);
|
|
9748
|
-
let a = mod(number, modulo);
|
|
9749
|
-
let b = modulo;
|
|
9750
|
-
let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
|
|
9751
|
-
while (a !== _0n2) {
|
|
9752
|
-
const q = b / a;
|
|
9753
|
-
const r = b % a;
|
|
9754
|
-
const m = x - u * q;
|
|
9755
|
-
const n = y - v * q;
|
|
9756
|
-
b = a, a = r, x = u, y = v, u = m, v = n;
|
|
9757
|
-
}
|
|
9758
|
-
const gcd = b;
|
|
9759
|
-
if (gcd !== _1n2)
|
|
9760
|
-
throw new Error("invert: does not exist");
|
|
9761
|
-
return mod(x, modulo);
|
|
9762
|
-
}
|
|
9763
|
-
function assertIsSquare(Fp, root, n) {
|
|
9764
|
-
if (!Fp.eql(Fp.sqr(root), n))
|
|
9765
|
-
throw new Error("Cannot find square root");
|
|
9766
|
-
}
|
|
9767
|
-
function sqrt3mod4(Fp, n) {
|
|
9768
|
-
const p1div4 = (Fp.ORDER + _1n2) / _4n;
|
|
9769
|
-
const root = Fp.pow(n, p1div4);
|
|
9770
|
-
assertIsSquare(Fp, root, n);
|
|
9771
|
-
return root;
|
|
9772
|
-
}
|
|
9773
|
-
function sqrt5mod8(Fp, n) {
|
|
9774
|
-
const p5div8 = (Fp.ORDER - _5n) / _8n;
|
|
9775
|
-
const n2 = Fp.mul(n, _2n);
|
|
9776
|
-
const v = Fp.pow(n2, p5div8);
|
|
9777
|
-
const nv = Fp.mul(n, v);
|
|
9778
|
-
const i = Fp.mul(Fp.mul(nv, _2n), v);
|
|
9779
|
-
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
|
|
9780
|
-
assertIsSquare(Fp, root, n);
|
|
9781
|
-
return root;
|
|
9782
|
-
}
|
|
9783
|
-
function sqrt9mod16(P) {
|
|
9784
|
-
const Fp_ = Field(P);
|
|
9785
|
-
const tn = tonelliShanks(P);
|
|
9786
|
-
const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
|
|
9787
|
-
const c2 = tn(Fp_, c1);
|
|
9788
|
-
const c3 = tn(Fp_, Fp_.neg(c1));
|
|
9789
|
-
const c4 = (P + _7n) / _16n;
|
|
9790
|
-
return (Fp, n) => {
|
|
9791
|
-
let tv1 = Fp.pow(n, c4);
|
|
9792
|
-
let tv2 = Fp.mul(tv1, c1);
|
|
9793
|
-
const tv3 = Fp.mul(tv1, c2);
|
|
9794
|
-
const tv4 = Fp.mul(tv1, c3);
|
|
9795
|
-
const e1 = Fp.eql(Fp.sqr(tv2), n);
|
|
9796
|
-
const e2 = Fp.eql(Fp.sqr(tv3), n);
|
|
9797
|
-
tv1 = Fp.cmov(tv1, tv2, e1);
|
|
9798
|
-
tv2 = Fp.cmov(tv4, tv3, e2);
|
|
9799
|
-
const e3 = Fp.eql(Fp.sqr(tv2), n);
|
|
9800
|
-
const root = Fp.cmov(tv1, tv2, e3);
|
|
9801
|
-
assertIsSquare(Fp, root, n);
|
|
9802
|
-
return root;
|
|
9803
|
-
};
|
|
9804
|
-
}
|
|
9805
|
-
function tonelliShanks(P) {
|
|
9806
|
-
if (P < _3n)
|
|
9807
|
-
throw new Error("sqrt is not defined for small field");
|
|
9808
|
-
let Q = P - _1n2;
|
|
9809
|
-
let S = 0;
|
|
9810
|
-
while (Q % _2n === _0n2) {
|
|
9811
|
-
Q /= _2n;
|
|
9812
|
-
S++;
|
|
9813
|
-
}
|
|
9814
|
-
let Z = _2n;
|
|
9815
|
-
const _Fp = Field(P);
|
|
9816
|
-
while (FpLegendre(_Fp, Z) === 1) {
|
|
9817
|
-
if (Z++ > 1e3)
|
|
9818
|
-
throw new Error("Cannot find square root: probably non-prime P");
|
|
9819
|
-
}
|
|
9820
|
-
if (S === 1)
|
|
9821
|
-
return sqrt3mod4;
|
|
9822
|
-
let cc = _Fp.pow(Z, Q);
|
|
9823
|
-
const Q1div2 = (Q + _1n2) / _2n;
|
|
9824
|
-
return function tonelliSlow(Fp, n) {
|
|
9825
|
-
if (Fp.is0(n))
|
|
9826
|
-
return n;
|
|
9827
|
-
if (FpLegendre(Fp, n) !== 1)
|
|
9828
|
-
throw new Error("Cannot find square root");
|
|
9829
|
-
let M = S;
|
|
9830
|
-
let c = Fp.mul(Fp.ONE, cc);
|
|
9831
|
-
let t = Fp.pow(n, Q);
|
|
9832
|
-
let R = Fp.pow(n, Q1div2);
|
|
9833
|
-
while (!Fp.eql(t, Fp.ONE)) {
|
|
9834
|
-
if (Fp.is0(t))
|
|
9835
|
-
return Fp.ZERO;
|
|
9836
|
-
let i = 1;
|
|
9837
|
-
let t_tmp = Fp.sqr(t);
|
|
9838
|
-
while (!Fp.eql(t_tmp, Fp.ONE)) {
|
|
9839
|
-
i++;
|
|
9840
|
-
t_tmp = Fp.sqr(t_tmp);
|
|
9841
|
-
if (i === M)
|
|
9842
|
-
throw new Error("Cannot find square root");
|
|
9843
|
-
}
|
|
9844
|
-
const exponent = _1n2 << BigInt(M - i - 1);
|
|
9845
|
-
const b = Fp.pow(c, exponent);
|
|
9846
|
-
M = i;
|
|
9847
|
-
c = Fp.sqr(b);
|
|
9848
|
-
t = Fp.mul(t, c);
|
|
9849
|
-
R = Fp.mul(R, b);
|
|
9850
|
-
}
|
|
9851
|
-
return R;
|
|
9852
|
-
};
|
|
9853
|
-
}
|
|
9854
|
-
function FpSqrt(P) {
|
|
9855
|
-
if (P % _4n === _3n)
|
|
9856
|
-
return sqrt3mod4;
|
|
9857
|
-
if (P % _8n === _5n)
|
|
9858
|
-
return sqrt5mod8;
|
|
9859
|
-
if (P % _16n === _9n)
|
|
9860
|
-
return sqrt9mod16(P);
|
|
9861
|
-
return tonelliShanks(P);
|
|
9862
|
-
}
|
|
9863
|
-
var FIELD_FIELDS = [
|
|
9864
|
-
"create",
|
|
9865
|
-
"isValid",
|
|
9866
|
-
"is0",
|
|
9867
|
-
"neg",
|
|
9868
|
-
"inv",
|
|
9869
|
-
"sqrt",
|
|
9870
|
-
"sqr",
|
|
9871
|
-
"eql",
|
|
9872
|
-
"add",
|
|
9873
|
-
"sub",
|
|
9874
|
-
"mul",
|
|
9875
|
-
"pow",
|
|
9876
|
-
"div",
|
|
9877
|
-
"addN",
|
|
9878
|
-
"subN",
|
|
9879
|
-
"mulN",
|
|
9880
|
-
"sqrN"
|
|
9881
|
-
];
|
|
9882
|
-
function validateField(field) {
|
|
9883
|
-
const initial = {
|
|
9884
|
-
ORDER: "bigint",
|
|
9885
|
-
BYTES: "number",
|
|
9886
|
-
BITS: "number"
|
|
9887
|
-
};
|
|
9888
|
-
const opts = FIELD_FIELDS.reduce((map, val) => {
|
|
9889
|
-
map[val] = "function";
|
|
9890
|
-
return map;
|
|
9891
|
-
}, initial);
|
|
9892
|
-
validateObject(field, opts);
|
|
9893
|
-
return field;
|
|
9894
|
-
}
|
|
9895
|
-
function FpPow(Fp, num, power) {
|
|
9896
|
-
if (power < _0n2)
|
|
9897
|
-
throw new Error("invalid exponent, negatives unsupported");
|
|
9898
|
-
if (power === _0n2)
|
|
9899
|
-
return Fp.ONE;
|
|
9900
|
-
if (power === _1n2)
|
|
9901
|
-
return num;
|
|
9902
|
-
let p = Fp.ONE;
|
|
9903
|
-
let d = num;
|
|
9904
|
-
while (power > _0n2) {
|
|
9905
|
-
if (power & _1n2)
|
|
9906
|
-
p = Fp.mul(p, d);
|
|
9907
|
-
d = Fp.sqr(d);
|
|
9908
|
-
power >>= _1n2;
|
|
9909
|
-
}
|
|
9910
|
-
return p;
|
|
9911
|
-
}
|
|
9912
|
-
function FpInvertBatch(Fp, nums, passZero = false) {
|
|
9913
|
-
const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
|
|
9914
|
-
const multipliedAcc = nums.reduce((acc, num, i) => {
|
|
9915
|
-
if (Fp.is0(num))
|
|
9916
|
-
return acc;
|
|
9917
|
-
inverted[i] = acc;
|
|
9918
|
-
return Fp.mul(acc, num);
|
|
9919
|
-
}, Fp.ONE);
|
|
9920
|
-
const invertedAcc = Fp.inv(multipliedAcc);
|
|
9921
|
-
nums.reduceRight((acc, num, i) => {
|
|
9922
|
-
if (Fp.is0(num))
|
|
9923
|
-
return acc;
|
|
9924
|
-
inverted[i] = Fp.mul(acc, inverted[i]);
|
|
9925
|
-
return Fp.mul(acc, num);
|
|
9926
|
-
}, invertedAcc);
|
|
9927
|
-
return inverted;
|
|
9928
|
-
}
|
|
9929
|
-
function FpLegendre(Fp, n) {
|
|
9930
|
-
const p1mod2 = (Fp.ORDER - _1n2) / _2n;
|
|
9931
|
-
const powered = Fp.pow(n, p1mod2);
|
|
9932
|
-
const yes = Fp.eql(powered, Fp.ONE);
|
|
9933
|
-
const zero = Fp.eql(powered, Fp.ZERO);
|
|
9934
|
-
const no = Fp.eql(powered, Fp.neg(Fp.ONE));
|
|
9935
|
-
if (!yes && !zero && !no)
|
|
9936
|
-
throw new Error("invalid Legendre symbol result");
|
|
9937
|
-
return yes ? 1 : zero ? 0 : -1;
|
|
9938
|
-
}
|
|
9939
|
-
function nLength(n, nBitLength) {
|
|
9940
|
-
if (nBitLength !== void 0)
|
|
9941
|
-
anumber(nBitLength);
|
|
9942
|
-
const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
|
|
9943
|
-
const nByteLength = Math.ceil(_nBitLength / 8);
|
|
9944
|
-
return { nBitLength: _nBitLength, nByteLength };
|
|
9945
|
-
}
|
|
9946
|
-
var _Field = class {
|
|
9947
|
-
ORDER;
|
|
9948
|
-
BITS;
|
|
9949
|
-
BYTES;
|
|
9950
|
-
isLE;
|
|
9951
|
-
ZERO = _0n2;
|
|
9952
|
-
ONE = _1n2;
|
|
9953
|
-
_lengths;
|
|
9954
|
-
_sqrt;
|
|
9955
|
-
// cached sqrt
|
|
9956
|
-
_mod;
|
|
9957
|
-
constructor(ORDER, opts = {}) {
|
|
9958
|
-
if (ORDER <= _0n2)
|
|
9959
|
-
throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
|
|
9960
|
-
let _nbitLength = void 0;
|
|
9961
|
-
this.isLE = false;
|
|
9962
|
-
if (opts != null && typeof opts === "object") {
|
|
9963
|
-
if (typeof opts.BITS === "number")
|
|
9964
|
-
_nbitLength = opts.BITS;
|
|
9965
|
-
if (typeof opts.sqrt === "function")
|
|
9966
|
-
this.sqrt = opts.sqrt;
|
|
9967
|
-
if (typeof opts.isLE === "boolean")
|
|
9968
|
-
this.isLE = opts.isLE;
|
|
9969
|
-
if (opts.allowedLengths)
|
|
9970
|
-
this._lengths = opts.allowedLengths?.slice();
|
|
9971
|
-
if (typeof opts.modFromBytes === "boolean")
|
|
9972
|
-
this._mod = opts.modFromBytes;
|
|
9973
|
-
}
|
|
9974
|
-
const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
|
|
9975
|
-
if (nByteLength > 2048)
|
|
9976
|
-
throw new Error("invalid field: expected ORDER of <= 2048 bytes");
|
|
9977
|
-
this.ORDER = ORDER;
|
|
9978
|
-
this.BITS = nBitLength;
|
|
9979
|
-
this.BYTES = nByteLength;
|
|
9980
|
-
this._sqrt = void 0;
|
|
9981
|
-
Object.preventExtensions(this);
|
|
9982
|
-
}
|
|
9983
|
-
create(num) {
|
|
9984
|
-
return mod(num, this.ORDER);
|
|
9985
|
-
}
|
|
9986
|
-
isValid(num) {
|
|
9987
|
-
if (typeof num !== "bigint")
|
|
9988
|
-
throw new Error("invalid field element: expected bigint, got " + typeof num);
|
|
9989
|
-
return _0n2 <= num && num < this.ORDER;
|
|
9990
|
-
}
|
|
9991
|
-
is0(num) {
|
|
9992
|
-
return num === _0n2;
|
|
9993
|
-
}
|
|
9994
|
-
// is valid and invertible
|
|
9995
|
-
isValidNot0(num) {
|
|
9996
|
-
return !this.is0(num) && this.isValid(num);
|
|
9997
|
-
}
|
|
9998
|
-
isOdd(num) {
|
|
9999
|
-
return (num & _1n2) === _1n2;
|
|
10000
|
-
}
|
|
10001
|
-
neg(num) {
|
|
10002
|
-
return mod(-num, this.ORDER);
|
|
10003
|
-
}
|
|
10004
|
-
eql(lhs, rhs) {
|
|
10005
|
-
return lhs === rhs;
|
|
10006
|
-
}
|
|
10007
|
-
sqr(num) {
|
|
10008
|
-
return mod(num * num, this.ORDER);
|
|
10009
|
-
}
|
|
10010
|
-
add(lhs, rhs) {
|
|
10011
|
-
return mod(lhs + rhs, this.ORDER);
|
|
10012
|
-
}
|
|
10013
|
-
sub(lhs, rhs) {
|
|
10014
|
-
return mod(lhs - rhs, this.ORDER);
|
|
10015
|
-
}
|
|
10016
|
-
mul(lhs, rhs) {
|
|
10017
|
-
return mod(lhs * rhs, this.ORDER);
|
|
10018
|
-
}
|
|
10019
|
-
pow(num, power) {
|
|
10020
|
-
return FpPow(this, num, power);
|
|
10021
|
-
}
|
|
10022
|
-
div(lhs, rhs) {
|
|
10023
|
-
return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
|
|
10024
|
-
}
|
|
10025
|
-
// Same as above, but doesn't normalize
|
|
10026
|
-
sqrN(num) {
|
|
10027
|
-
return num * num;
|
|
10028
|
-
}
|
|
10029
|
-
addN(lhs, rhs) {
|
|
10030
|
-
return lhs + rhs;
|
|
10031
|
-
}
|
|
10032
|
-
subN(lhs, rhs) {
|
|
10033
|
-
return lhs - rhs;
|
|
10034
|
-
}
|
|
10035
|
-
mulN(lhs, rhs) {
|
|
10036
|
-
return lhs * rhs;
|
|
10037
|
-
}
|
|
10038
|
-
inv(num) {
|
|
10039
|
-
return invert(num, this.ORDER);
|
|
10040
|
-
}
|
|
10041
|
-
sqrt(num) {
|
|
10042
|
-
if (!this._sqrt)
|
|
10043
|
-
this._sqrt = FpSqrt(this.ORDER);
|
|
10044
|
-
return this._sqrt(this, num);
|
|
10045
|
-
}
|
|
10046
|
-
toBytes(num) {
|
|
10047
|
-
return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
|
|
10048
|
-
}
|
|
10049
|
-
fromBytes(bytes, skipValidation = false) {
|
|
10050
|
-
abytes(bytes);
|
|
10051
|
-
const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
|
|
10052
|
-
if (allowedLengths) {
|
|
10053
|
-
if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
|
|
10054
|
-
throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
|
|
10055
|
-
}
|
|
10056
|
-
const padded = new Uint8Array(BYTES);
|
|
10057
|
-
padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
|
|
10058
|
-
bytes = padded;
|
|
10059
|
-
}
|
|
10060
|
-
if (bytes.length !== BYTES)
|
|
10061
|
-
throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
|
|
10062
|
-
let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
|
|
10063
|
-
if (modFromBytes)
|
|
10064
|
-
scalar = mod(scalar, ORDER);
|
|
10065
|
-
if (!skipValidation) {
|
|
10066
|
-
if (!this.isValid(scalar))
|
|
10067
|
-
throw new Error("invalid field element: outside of range 0..ORDER");
|
|
10068
|
-
}
|
|
10069
|
-
return scalar;
|
|
10070
|
-
}
|
|
10071
|
-
// TODO: we don't need it here, move out to separate fn
|
|
10072
|
-
invertBatch(lst) {
|
|
10073
|
-
return FpInvertBatch(this, lst);
|
|
10074
|
-
}
|
|
10075
|
-
// We can't move this out because Fp6, Fp12 implement it
|
|
10076
|
-
// and it's unclear what to return in there.
|
|
10077
|
-
cmov(a, b, condition) {
|
|
10078
|
-
return condition ? b : a;
|
|
10079
|
-
}
|
|
10080
|
-
};
|
|
10081
|
-
function Field(ORDER, opts = {}) {
|
|
10082
|
-
return new _Field(ORDER, opts);
|
|
10083
|
-
}
|
|
10084
|
-
function getFieldBytesLength(fieldOrder) {
|
|
10085
|
-
if (typeof fieldOrder !== "bigint")
|
|
10086
|
-
throw new Error("field order must be bigint");
|
|
10087
|
-
const bitLength = fieldOrder.toString(2).length;
|
|
10088
|
-
return Math.ceil(bitLength / 8);
|
|
10089
|
-
}
|
|
10090
|
-
function getMinHashLength(fieldOrder) {
|
|
10091
|
-
const length = getFieldBytesLength(fieldOrder);
|
|
10092
|
-
return length + Math.ceil(length / 2);
|
|
10093
|
-
}
|
|
10094
|
-
function mapHashToField(key, fieldOrder, isLE = false) {
|
|
10095
|
-
abytes(key);
|
|
10096
|
-
const len = key.length;
|
|
10097
|
-
const fieldLen = getFieldBytesLength(fieldOrder);
|
|
10098
|
-
const minLen = getMinHashLength(fieldOrder);
|
|
10099
|
-
if (len < 16 || len < minLen || len > 1024)
|
|
10100
|
-
throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
|
|
10101
|
-
const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
|
|
10102
|
-
const reduced = mod(num, fieldOrder - _1n2) + _1n2;
|
|
10103
|
-
return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
|
|
10104
|
-
}
|
|
10105
|
-
|
|
10106
|
-
// node_modules/@noble/curves/abstract/curve.js
|
|
10107
|
-
var _0n3 = /* @__PURE__ */ BigInt(0);
|
|
10108
|
-
var _1n3 = /* @__PURE__ */ BigInt(1);
|
|
10109
|
-
function negateCt(condition, item) {
|
|
10110
|
-
const neg = item.negate();
|
|
10111
|
-
return condition ? neg : item;
|
|
10112
|
-
}
|
|
10113
|
-
function normalizeZ(c, points) {
|
|
10114
|
-
const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
|
|
10115
|
-
return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
|
|
10116
|
-
}
|
|
10117
|
-
function validateW(W, bits) {
|
|
10118
|
-
if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
|
|
10119
|
-
throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
|
|
10120
|
-
}
|
|
10121
|
-
function calcWOpts(W, scalarBits) {
|
|
10122
|
-
validateW(W, scalarBits);
|
|
10123
|
-
const windows = Math.ceil(scalarBits / W) + 1;
|
|
10124
|
-
const windowSize = 2 ** (W - 1);
|
|
10125
|
-
const maxNumber = 2 ** W;
|
|
10126
|
-
const mask = bitMask(W);
|
|
10127
|
-
const shiftBy = BigInt(W);
|
|
10128
|
-
return { windows, windowSize, mask, maxNumber, shiftBy };
|
|
10129
|
-
}
|
|
10130
|
-
function calcOffsets(n, window, wOpts) {
|
|
10131
|
-
const { windowSize, mask, maxNumber, shiftBy } = wOpts;
|
|
10132
|
-
let wbits = Number(n & mask);
|
|
10133
|
-
let nextN = n >> shiftBy;
|
|
10134
|
-
if (wbits > windowSize) {
|
|
10135
|
-
wbits -= maxNumber;
|
|
10136
|
-
nextN += _1n3;
|
|
10137
|
-
}
|
|
10138
|
-
const offsetStart = window * windowSize;
|
|
10139
|
-
const offset = offsetStart + Math.abs(wbits) - 1;
|
|
10140
|
-
const isZero = wbits === 0;
|
|
10141
|
-
const isNeg = wbits < 0;
|
|
10142
|
-
const isNegF = window % 2 !== 0;
|
|
10143
|
-
const offsetF = offsetStart;
|
|
10144
|
-
return { nextN, offset, isZero, isNeg, isNegF, offsetF };
|
|
10145
|
-
}
|
|
10146
|
-
var pointPrecomputes = /* @__PURE__ */ new WeakMap();
|
|
10147
|
-
var pointWindowSizes = /* @__PURE__ */ new WeakMap();
|
|
10148
|
-
function getW(P) {
|
|
10149
|
-
return pointWindowSizes.get(P) || 1;
|
|
10150
|
-
}
|
|
10151
|
-
function assert0(n) {
|
|
10152
|
-
if (n !== _0n3)
|
|
10153
|
-
throw new Error("invalid wNAF");
|
|
10154
|
-
}
|
|
10155
|
-
var wNAF = class {
|
|
10156
|
-
BASE;
|
|
10157
|
-
ZERO;
|
|
10158
|
-
Fn;
|
|
10159
|
-
bits;
|
|
10160
|
-
// Parametrized with a given Point class (not individual point)
|
|
10161
|
-
constructor(Point, bits) {
|
|
10162
|
-
this.BASE = Point.BASE;
|
|
10163
|
-
this.ZERO = Point.ZERO;
|
|
10164
|
-
this.Fn = Point.Fn;
|
|
10165
|
-
this.bits = bits;
|
|
10166
|
-
}
|
|
10167
|
-
// non-const time multiplication ladder
|
|
10168
|
-
_unsafeLadder(elm, n, p = this.ZERO) {
|
|
10169
|
-
let d = elm;
|
|
10170
|
-
while (n > _0n3) {
|
|
10171
|
-
if (n & _1n3)
|
|
10172
|
-
p = p.add(d);
|
|
10173
|
-
d = d.double();
|
|
10174
|
-
n >>= _1n3;
|
|
10175
|
-
}
|
|
10176
|
-
return p;
|
|
10177
|
-
}
|
|
10178
|
-
/**
|
|
10179
|
-
* Creates a wNAF precomputation window. Used for caching.
|
|
10180
|
-
* Default window size is set by `utils.precompute()` and is equal to 8.
|
|
10181
|
-
* Number of precomputed points depends on the curve size:
|
|
10182
|
-
* 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
|
|
10183
|
-
* - 𝑊 is the window size
|
|
10184
|
-
* - 𝑛 is the bitlength of the curve order.
|
|
10185
|
-
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
|
|
10186
|
-
* @param point Point instance
|
|
10187
|
-
* @param W window size
|
|
10188
|
-
* @returns precomputed point tables flattened to a single array
|
|
10189
|
-
*/
|
|
10190
|
-
precomputeWindow(point, W) {
|
|
10191
|
-
const { windows, windowSize } = calcWOpts(W, this.bits);
|
|
10192
|
-
const points = [];
|
|
10193
|
-
let p = point;
|
|
10194
|
-
let base = p;
|
|
10195
|
-
for (let window = 0; window < windows; window++) {
|
|
10196
|
-
base = p;
|
|
10197
|
-
points.push(base);
|
|
10198
|
-
for (let i = 1; i < windowSize; i++) {
|
|
10199
|
-
base = base.add(p);
|
|
10200
|
-
points.push(base);
|
|
10201
|
-
}
|
|
10202
|
-
p = base.double();
|
|
10203
|
-
}
|
|
10204
|
-
return points;
|
|
10205
|
-
}
|
|
10206
|
-
/**
|
|
10207
|
-
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
|
|
10208
|
-
* More compact implementation:
|
|
10209
|
-
* https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
|
|
10210
|
-
* @returns real and fake (for const-time) points
|
|
10211
|
-
*/
|
|
10212
|
-
wNAF(W, precomputes, n) {
|
|
10213
|
-
if (!this.Fn.isValid(n))
|
|
10214
|
-
throw new Error("invalid scalar");
|
|
10215
|
-
let p = this.ZERO;
|
|
10216
|
-
let f = this.BASE;
|
|
10217
|
-
const wo = calcWOpts(W, this.bits);
|
|
10218
|
-
for (let window = 0; window < wo.windows; window++) {
|
|
10219
|
-
const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
|
|
10220
|
-
n = nextN;
|
|
10221
|
-
if (isZero) {
|
|
10222
|
-
f = f.add(negateCt(isNegF, precomputes[offsetF]));
|
|
10223
|
-
} else {
|
|
10224
|
-
p = p.add(negateCt(isNeg, precomputes[offset]));
|
|
10225
|
-
}
|
|
10226
|
-
}
|
|
10227
|
-
assert0(n);
|
|
10228
|
-
return { p, f };
|
|
10229
|
-
}
|
|
10230
|
-
/**
|
|
10231
|
-
* Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
|
|
10232
|
-
* @param acc accumulator point to add result of multiplication
|
|
10233
|
-
* @returns point
|
|
10234
|
-
*/
|
|
10235
|
-
wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
|
|
10236
|
-
const wo = calcWOpts(W, this.bits);
|
|
10237
|
-
for (let window = 0; window < wo.windows; window++) {
|
|
10238
|
-
if (n === _0n3)
|
|
10239
|
-
break;
|
|
10240
|
-
const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
|
|
10241
|
-
n = nextN;
|
|
10242
|
-
if (isZero) {
|
|
10243
|
-
continue;
|
|
10244
|
-
} else {
|
|
10245
|
-
const item = precomputes[offset];
|
|
10246
|
-
acc = acc.add(isNeg ? item.negate() : item);
|
|
10247
|
-
}
|
|
10248
|
-
}
|
|
10249
|
-
assert0(n);
|
|
10250
|
-
return acc;
|
|
10251
|
-
}
|
|
10252
|
-
getPrecomputes(W, point, transform) {
|
|
10253
|
-
let comp = pointPrecomputes.get(point);
|
|
10254
|
-
if (!comp) {
|
|
10255
|
-
comp = this.precomputeWindow(point, W);
|
|
10256
|
-
if (W !== 1) {
|
|
10257
|
-
if (typeof transform === "function")
|
|
10258
|
-
comp = transform(comp);
|
|
10259
|
-
pointPrecomputes.set(point, comp);
|
|
10260
|
-
}
|
|
10261
|
-
}
|
|
10262
|
-
return comp;
|
|
10263
|
-
}
|
|
10264
|
-
cached(point, scalar, transform) {
|
|
10265
|
-
const W = getW(point);
|
|
10266
|
-
return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
|
|
10267
|
-
}
|
|
10268
|
-
unsafe(point, scalar, transform, prev) {
|
|
10269
|
-
const W = getW(point);
|
|
10270
|
-
if (W === 1)
|
|
10271
|
-
return this._unsafeLadder(point, scalar, prev);
|
|
10272
|
-
return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
|
|
10273
|
-
}
|
|
10274
|
-
// We calculate precomputes for elliptic curve point multiplication
|
|
10275
|
-
// using windowed method. This specifies window size and
|
|
10276
|
-
// stores precomputed values. Usually only base point would be precomputed.
|
|
10277
|
-
createCache(P, W) {
|
|
10278
|
-
validateW(W, this.bits);
|
|
10279
|
-
pointWindowSizes.set(P, W);
|
|
10280
|
-
pointPrecomputes.delete(P);
|
|
10281
|
-
}
|
|
10282
|
-
hasCache(elm) {
|
|
10283
|
-
return getW(elm) !== 1;
|
|
10284
|
-
}
|
|
10285
|
-
};
|
|
10286
|
-
function mulEndoUnsafe(Point, point, k1, k2) {
|
|
10287
|
-
let acc = point;
|
|
10288
|
-
let p1 = Point.ZERO;
|
|
10289
|
-
let p2 = Point.ZERO;
|
|
10290
|
-
while (k1 > _0n3 || k2 > _0n3) {
|
|
10291
|
-
if (k1 & _1n3)
|
|
10292
|
-
p1 = p1.add(acc);
|
|
10293
|
-
if (k2 & _1n3)
|
|
10294
|
-
p2 = p2.add(acc);
|
|
10295
|
-
acc = acc.double();
|
|
10296
|
-
k1 >>= _1n3;
|
|
10297
|
-
k2 >>= _1n3;
|
|
10298
|
-
}
|
|
10299
|
-
return { p1, p2 };
|
|
10300
|
-
}
|
|
10301
|
-
function createField(order, field, isLE) {
|
|
10302
|
-
if (field) {
|
|
10303
|
-
if (field.ORDER !== order)
|
|
10304
|
-
throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
|
|
10305
|
-
validateField(field);
|
|
10306
|
-
return field;
|
|
10307
|
-
} else {
|
|
10308
|
-
return Field(order, { isLE });
|
|
10309
|
-
}
|
|
10310
|
-
}
|
|
10311
|
-
function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
|
|
10312
|
-
if (FpFnLE === void 0)
|
|
10313
|
-
FpFnLE = type === "edwards";
|
|
10314
|
-
if (!CURVE || typeof CURVE !== "object")
|
|
10315
|
-
throw new Error(`expected valid ${type} CURVE object`);
|
|
10316
|
-
for (const p of ["p", "n", "h"]) {
|
|
10317
|
-
const val = CURVE[p];
|
|
10318
|
-
if (!(typeof val === "bigint" && val > _0n3))
|
|
10319
|
-
throw new Error(`CURVE.${p} must be positive bigint`);
|
|
10320
|
-
}
|
|
10321
|
-
const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
|
|
10322
|
-
const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
|
|
10323
|
-
const _b = type === "weierstrass" ? "b" : "d";
|
|
10324
|
-
const params = ["Gx", "Gy", "a", _b];
|
|
10325
|
-
for (const p of params) {
|
|
10326
|
-
if (!Fp.isValid(CURVE[p]))
|
|
10327
|
-
throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
|
|
10328
|
-
}
|
|
10329
|
-
CURVE = Object.freeze(Object.assign({}, CURVE));
|
|
10330
|
-
return { CURVE, Fp, Fn };
|
|
10331
|
-
}
|
|
10332
|
-
function createKeygen(randomSecretKey, getPublicKey2) {
|
|
10333
|
-
return function keygen(seed) {
|
|
10334
|
-
const secretKey = randomSecretKey(seed);
|
|
10335
|
-
return { secretKey, publicKey: getPublicKey2(secretKey) };
|
|
10336
|
-
};
|
|
10337
|
-
}
|
|
10338
|
-
|
|
10339
|
-
// node_modules/@noble/hashes/hmac.js
|
|
10340
|
-
var _HMAC = class {
|
|
10341
|
-
oHash;
|
|
10342
|
-
iHash;
|
|
10343
|
-
blockLen;
|
|
10344
|
-
outputLen;
|
|
10345
|
-
finished = false;
|
|
10346
|
-
destroyed = false;
|
|
10347
|
-
constructor(hash, key) {
|
|
10348
|
-
ahash(hash);
|
|
10349
|
-
abytes(key, void 0, "key");
|
|
10350
|
-
this.iHash = hash.create();
|
|
10351
|
-
if (typeof this.iHash.update !== "function")
|
|
10352
|
-
throw new Error("Expected instance of class which extends utils.Hash");
|
|
10353
|
-
this.blockLen = this.iHash.blockLen;
|
|
10354
|
-
this.outputLen = this.iHash.outputLen;
|
|
10355
|
-
const blockLen = this.blockLen;
|
|
10356
|
-
const pad = new Uint8Array(blockLen);
|
|
10357
|
-
pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
|
|
10358
|
-
for (let i = 0; i < pad.length; i++)
|
|
10359
|
-
pad[i] ^= 54;
|
|
10360
|
-
this.iHash.update(pad);
|
|
10361
|
-
this.oHash = hash.create();
|
|
10362
|
-
for (let i = 0; i < pad.length; i++)
|
|
10363
|
-
pad[i] ^= 54 ^ 92;
|
|
10364
|
-
this.oHash.update(pad);
|
|
10365
|
-
clean(pad);
|
|
10366
|
-
}
|
|
10367
|
-
update(buf) {
|
|
10368
|
-
aexists(this);
|
|
10369
|
-
this.iHash.update(buf);
|
|
10370
|
-
return this;
|
|
10371
|
-
}
|
|
10372
|
-
digestInto(out) {
|
|
10373
|
-
aexists(this);
|
|
10374
|
-
abytes(out, this.outputLen, "output");
|
|
10375
|
-
this.finished = true;
|
|
10376
|
-
this.iHash.digestInto(out);
|
|
10377
|
-
this.oHash.update(out);
|
|
10378
|
-
this.oHash.digestInto(out);
|
|
10379
|
-
this.destroy();
|
|
10380
|
-
}
|
|
10381
|
-
digest() {
|
|
10382
|
-
const out = new Uint8Array(this.oHash.outputLen);
|
|
10383
|
-
this.digestInto(out);
|
|
10384
|
-
return out;
|
|
10385
|
-
}
|
|
10386
|
-
_cloneInto(to) {
|
|
10387
|
-
to ||= Object.create(Object.getPrototypeOf(this), {});
|
|
10388
|
-
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
|
|
10389
|
-
to = to;
|
|
10390
|
-
to.finished = finished;
|
|
10391
|
-
to.destroyed = destroyed;
|
|
10392
|
-
to.blockLen = blockLen;
|
|
10393
|
-
to.outputLen = outputLen;
|
|
10394
|
-
to.oHash = oHash._cloneInto(to.oHash);
|
|
10395
|
-
to.iHash = iHash._cloneInto(to.iHash);
|
|
10396
|
-
return to;
|
|
10397
|
-
}
|
|
10398
|
-
clone() {
|
|
10399
|
-
return this._cloneInto();
|
|
10400
|
-
}
|
|
10401
|
-
destroy() {
|
|
10402
|
-
this.destroyed = true;
|
|
10403
|
-
this.oHash.destroy();
|
|
10404
|
-
this.iHash.destroy();
|
|
10405
|
-
}
|
|
10406
|
-
};
|
|
10407
|
-
var hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();
|
|
10408
|
-
hmac.create = (hash, key) => new _HMAC(hash, key);
|
|
10409
|
-
|
|
10410
|
-
// node_modules/@noble/curves/abstract/weierstrass.js
|
|
10411
|
-
var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den;
|
|
10412
|
-
function _splitEndoScalar(k, basis, n) {
|
|
10413
|
-
const [[a1, b1], [a2, b2]] = basis;
|
|
10414
|
-
const c1 = divNearest(b2 * k, n);
|
|
10415
|
-
const c2 = divNearest(-b1 * k, n);
|
|
10416
|
-
let k1 = k - c1 * a1 - c2 * a2;
|
|
10417
|
-
let k2 = -c1 * b1 - c2 * b2;
|
|
10418
|
-
const k1neg = k1 < _0n4;
|
|
10419
|
-
const k2neg = k2 < _0n4;
|
|
10420
|
-
if (k1neg)
|
|
10421
|
-
k1 = -k1;
|
|
10422
|
-
if (k2neg)
|
|
10423
|
-
k2 = -k2;
|
|
10424
|
-
const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
|
|
10425
|
-
if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) {
|
|
10426
|
-
throw new Error("splitScalar (endomorphism): failed, k=" + k);
|
|
10427
|
-
}
|
|
10428
|
-
return { k1neg, k1, k2neg, k2 };
|
|
10429
|
-
}
|
|
10430
|
-
function validateSigFormat(format) {
|
|
10431
|
-
if (!["compact", "recovered", "der"].includes(format))
|
|
10432
|
-
throw new Error('Signature format must be "compact", "recovered", or "der"');
|
|
10433
|
-
return format;
|
|
10434
|
-
}
|
|
10435
|
-
function validateSigOpts(opts, def) {
|
|
10436
|
-
const optsn = {};
|
|
10437
|
-
for (let optName of Object.keys(def)) {
|
|
10438
|
-
optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
|
|
10439
|
-
}
|
|
10440
|
-
abool(optsn.lowS, "lowS");
|
|
10441
|
-
abool(optsn.prehash, "prehash");
|
|
10442
|
-
if (optsn.format !== void 0)
|
|
10443
|
-
validateSigFormat(optsn.format);
|
|
10444
|
-
return optsn;
|
|
10445
|
-
}
|
|
10446
|
-
var DERErr = class extends Error {
|
|
10447
|
-
constructor(m = "") {
|
|
10448
|
-
super(m);
|
|
10449
|
-
}
|
|
10450
|
-
};
|
|
10451
|
-
var DER = {
|
|
10452
|
-
// asn.1 DER encoding utils
|
|
10453
|
-
Err: DERErr,
|
|
10454
|
-
// Basic building block is TLV (Tag-Length-Value)
|
|
10455
|
-
_tlv: {
|
|
10456
|
-
encode: (tag, data) => {
|
|
10457
|
-
const { Err: E } = DER;
|
|
10458
|
-
if (tag < 0 || tag > 256)
|
|
10459
|
-
throw new E("tlv.encode: wrong tag");
|
|
10460
|
-
if (data.length & 1)
|
|
10461
|
-
throw new E("tlv.encode: unpadded data");
|
|
10462
|
-
const dataLen = data.length / 2;
|
|
10463
|
-
const len = numberToHexUnpadded(dataLen);
|
|
10464
|
-
if (len.length / 2 & 128)
|
|
10465
|
-
throw new E("tlv.encode: long form length too big");
|
|
10466
|
-
const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
|
|
10467
|
-
const t = numberToHexUnpadded(tag);
|
|
10468
|
-
return t + lenLen + len + data;
|
|
10469
|
-
},
|
|
10470
|
-
// v - value, l - left bytes (unparsed)
|
|
10471
|
-
decode(tag, data) {
|
|
10472
|
-
const { Err: E } = DER;
|
|
10473
|
-
let pos = 0;
|
|
10474
|
-
if (tag < 0 || tag > 256)
|
|
10475
|
-
throw new E("tlv.encode: wrong tag");
|
|
10476
|
-
if (data.length < 2 || data[pos++] !== tag)
|
|
10477
|
-
throw new E("tlv.decode: wrong tlv");
|
|
10478
|
-
const first = data[pos++];
|
|
10479
|
-
const isLong = !!(first & 128);
|
|
10480
|
-
let length = 0;
|
|
10481
|
-
if (!isLong)
|
|
10482
|
-
length = first;
|
|
10483
|
-
else {
|
|
10484
|
-
const lenLen = first & 127;
|
|
10485
|
-
if (!lenLen)
|
|
10486
|
-
throw new E("tlv.decode(long): indefinite length not supported");
|
|
10487
|
-
if (lenLen > 4)
|
|
10488
|
-
throw new E("tlv.decode(long): byte length is too big");
|
|
10489
|
-
const lengthBytes = data.subarray(pos, pos + lenLen);
|
|
10490
|
-
if (lengthBytes.length !== lenLen)
|
|
10491
|
-
throw new E("tlv.decode: length bytes not complete");
|
|
10492
|
-
if (lengthBytes[0] === 0)
|
|
10493
|
-
throw new E("tlv.decode(long): zero leftmost byte");
|
|
10494
|
-
for (const b of lengthBytes)
|
|
10495
|
-
length = length << 8 | b;
|
|
10496
|
-
pos += lenLen;
|
|
10497
|
-
if (length < 128)
|
|
10498
|
-
throw new E("tlv.decode(long): not minimal encoding");
|
|
10499
|
-
}
|
|
10500
|
-
const v = data.subarray(pos, pos + length);
|
|
10501
|
-
if (v.length !== length)
|
|
10502
|
-
throw new E("tlv.decode: wrong value length");
|
|
10503
|
-
return { v, l: data.subarray(pos + length) };
|
|
10504
|
-
}
|
|
10505
|
-
},
|
|
10506
|
-
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
|
|
10507
|
-
// since we always use positive integers here. It must always be empty:
|
|
10508
|
-
// - add zero byte if exists
|
|
10509
|
-
// - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
|
|
10510
|
-
_int: {
|
|
10511
|
-
encode(num) {
|
|
10512
|
-
const { Err: E } = DER;
|
|
10513
|
-
if (num < _0n4)
|
|
10514
|
-
throw new E("integer: negative integers are not allowed");
|
|
10515
|
-
let hex = numberToHexUnpadded(num);
|
|
10516
|
-
if (Number.parseInt(hex[0], 16) & 8)
|
|
10517
|
-
hex = "00" + hex;
|
|
10518
|
-
if (hex.length & 1)
|
|
10519
|
-
throw new E("unexpected DER parsing assertion: unpadded hex");
|
|
10520
|
-
return hex;
|
|
10521
|
-
},
|
|
10522
|
-
decode(data) {
|
|
10523
|
-
const { Err: E } = DER;
|
|
10524
|
-
if (data[0] & 128)
|
|
10525
|
-
throw new E("invalid signature integer: negative");
|
|
10526
|
-
if (data[0] === 0 && !(data[1] & 128))
|
|
10527
|
-
throw new E("invalid signature integer: unnecessary leading zero");
|
|
10528
|
-
return bytesToNumberBE(data);
|
|
10529
|
-
}
|
|
10530
|
-
},
|
|
10531
|
-
toSig(bytes) {
|
|
10532
|
-
const { Err: E, _int: int, _tlv: tlv } = DER;
|
|
10533
|
-
const data = abytes(bytes, void 0, "signature");
|
|
10534
|
-
const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
|
|
10535
|
-
if (seqLeftBytes.length)
|
|
10536
|
-
throw new E("invalid signature: left bytes after parsing");
|
|
10537
|
-
const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
|
|
10538
|
-
const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
|
|
10539
|
-
if (sLeftBytes.length)
|
|
10540
|
-
throw new E("invalid signature: left bytes after parsing");
|
|
10541
|
-
return { r: int.decode(rBytes), s: int.decode(sBytes) };
|
|
10542
|
-
},
|
|
10543
|
-
hexFromSig(sig) {
|
|
10544
|
-
const { _tlv: tlv, _int: int } = DER;
|
|
10545
|
-
const rs = tlv.encode(2, int.encode(sig.r));
|
|
10546
|
-
const ss = tlv.encode(2, int.encode(sig.s));
|
|
10547
|
-
const seq = rs + ss;
|
|
10548
|
-
return tlv.encode(48, seq);
|
|
10549
|
-
}
|
|
10550
|
-
};
|
|
10551
|
-
var _0n4 = BigInt(0);
|
|
10552
|
-
var _1n4 = BigInt(1);
|
|
10553
|
-
var _2n2 = BigInt(2);
|
|
10554
|
-
var _3n2 = BigInt(3);
|
|
10555
|
-
var _4n2 = BigInt(4);
|
|
10556
|
-
function weierstrass(params, extraOpts = {}) {
|
|
10557
|
-
const validated = createCurveFields("weierstrass", params, extraOpts);
|
|
10558
|
-
const { Fp, Fn } = validated;
|
|
10559
|
-
let CURVE = validated.CURVE;
|
|
10560
|
-
const { h: cofactor, n: CURVE_ORDER2 } = CURVE;
|
|
10561
|
-
validateObject(extraOpts, {}, {
|
|
10562
|
-
allowInfinityPoint: "boolean",
|
|
10563
|
-
clearCofactor: "function",
|
|
10564
|
-
isTorsionFree: "function",
|
|
10565
|
-
fromBytes: "function",
|
|
10566
|
-
toBytes: "function",
|
|
10567
|
-
endo: "object"
|
|
10568
|
-
});
|
|
10569
|
-
const { endo } = extraOpts;
|
|
10570
|
-
if (endo) {
|
|
10571
|
-
if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
|
|
10572
|
-
throw new Error('invalid endo: expected "beta": bigint and "basises": array');
|
|
10573
|
-
}
|
|
10574
|
-
}
|
|
10575
|
-
const lengths = getWLengths(Fp, Fn);
|
|
10576
|
-
function assertCompressionIsSupported() {
|
|
10577
|
-
if (!Fp.isOdd)
|
|
10578
|
-
throw new Error("compression is not supported: Field does not have .isOdd()");
|
|
10579
|
-
}
|
|
10580
|
-
function pointToBytes(_c, point, isCompressed) {
|
|
10581
|
-
const { x, y } = point.toAffine();
|
|
10582
|
-
const bx = Fp.toBytes(x);
|
|
10583
|
-
abool(isCompressed, "isCompressed");
|
|
10584
|
-
if (isCompressed) {
|
|
10585
|
-
assertCompressionIsSupported();
|
|
10586
|
-
const hasEvenY = !Fp.isOdd(y);
|
|
10587
|
-
return concatBytes(pprefix(hasEvenY), bx);
|
|
10588
|
-
} else {
|
|
10589
|
-
return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
|
|
10590
|
-
}
|
|
10591
|
-
}
|
|
10592
|
-
function pointFromBytes(bytes) {
|
|
10593
|
-
abytes(bytes, void 0, "Point");
|
|
10594
|
-
const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
|
|
10595
|
-
const length = bytes.length;
|
|
10596
|
-
const head = bytes[0];
|
|
10597
|
-
const tail = bytes.subarray(1);
|
|
10598
|
-
if (length === comp && (head === 2 || head === 3)) {
|
|
10599
|
-
const x = Fp.fromBytes(tail);
|
|
10600
|
-
if (!Fp.isValid(x))
|
|
10601
|
-
throw new Error("bad point: is not on curve, wrong x");
|
|
10602
|
-
const y2 = weierstrassEquation(x);
|
|
10603
|
-
let y;
|
|
10604
|
-
try {
|
|
10605
|
-
y = Fp.sqrt(y2);
|
|
10606
|
-
} catch (sqrtError) {
|
|
10607
|
-
const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
|
|
10608
|
-
throw new Error("bad point: is not on curve, sqrt error" + err);
|
|
10609
|
-
}
|
|
10610
|
-
assertCompressionIsSupported();
|
|
10611
|
-
const evenY = Fp.isOdd(y);
|
|
10612
|
-
const evenH = (head & 1) === 1;
|
|
10613
|
-
if (evenH !== evenY)
|
|
10614
|
-
y = Fp.neg(y);
|
|
10615
|
-
return { x, y };
|
|
10616
|
-
} else if (length === uncomp && head === 4) {
|
|
10617
|
-
const L = Fp.BYTES;
|
|
10618
|
-
const x = Fp.fromBytes(tail.subarray(0, L));
|
|
10619
|
-
const y = Fp.fromBytes(tail.subarray(L, L * 2));
|
|
10620
|
-
if (!isValidXY(x, y))
|
|
10621
|
-
throw new Error("bad point: is not on curve");
|
|
10622
|
-
return { x, y };
|
|
10623
|
-
} else {
|
|
10624
|
-
throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
|
|
10625
|
-
}
|
|
10626
|
-
}
|
|
10627
|
-
const encodePoint = extraOpts.toBytes || pointToBytes;
|
|
10628
|
-
const decodePoint = extraOpts.fromBytes || pointFromBytes;
|
|
10629
|
-
function weierstrassEquation(x) {
|
|
10630
|
-
const x2 = Fp.sqr(x);
|
|
10631
|
-
const x3 = Fp.mul(x2, x);
|
|
10632
|
-
return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
|
|
10633
|
-
}
|
|
10634
|
-
function isValidXY(x, y) {
|
|
10635
|
-
const left = Fp.sqr(y);
|
|
10636
|
-
const right = weierstrassEquation(x);
|
|
10637
|
-
return Fp.eql(left, right);
|
|
10638
|
-
}
|
|
10639
|
-
if (!isValidXY(CURVE.Gx, CURVE.Gy))
|
|
10640
|
-
throw new Error("bad curve params: generator point");
|
|
10641
|
-
const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
|
|
10642
|
-
const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
|
|
10643
|
-
if (Fp.is0(Fp.add(_4a3, _27b2)))
|
|
10644
|
-
throw new Error("bad curve params: a or b");
|
|
10645
|
-
function acoord(title, n, banZero = false) {
|
|
10646
|
-
if (!Fp.isValid(n) || banZero && Fp.is0(n))
|
|
10647
|
-
throw new Error(`bad point coordinate ${title}`);
|
|
10648
|
-
return n;
|
|
10649
|
-
}
|
|
10650
|
-
function aprjpoint(other) {
|
|
10651
|
-
if (!(other instanceof Point))
|
|
10652
|
-
throw new Error("Weierstrass Point expected");
|
|
10653
|
-
}
|
|
10654
|
-
function splitEndoScalarN(k) {
|
|
10655
|
-
if (!endo || !endo.basises)
|
|
10656
|
-
throw new Error("no endo");
|
|
10657
|
-
return _splitEndoScalar(k, endo.basises, Fn.ORDER);
|
|
10658
|
-
}
|
|
10659
|
-
const toAffineMemo = memoized((p, iz) => {
|
|
10660
|
-
const { X, Y, Z } = p;
|
|
10661
|
-
if (Fp.eql(Z, Fp.ONE))
|
|
10662
|
-
return { x: X, y: Y };
|
|
10663
|
-
const is0 = p.is0();
|
|
10664
|
-
if (iz == null)
|
|
10665
|
-
iz = is0 ? Fp.ONE : Fp.inv(Z);
|
|
10666
|
-
const x = Fp.mul(X, iz);
|
|
10667
|
-
const y = Fp.mul(Y, iz);
|
|
10668
|
-
const zz = Fp.mul(Z, iz);
|
|
10669
|
-
if (is0)
|
|
10670
|
-
return { x: Fp.ZERO, y: Fp.ZERO };
|
|
10671
|
-
if (!Fp.eql(zz, Fp.ONE))
|
|
10672
|
-
throw new Error("invZ was invalid");
|
|
10673
|
-
return { x, y };
|
|
10674
|
-
});
|
|
10675
|
-
const assertValidMemo = memoized((p) => {
|
|
10676
|
-
if (p.is0()) {
|
|
10677
|
-
if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
|
|
10678
|
-
return;
|
|
10679
|
-
throw new Error("bad point: ZERO");
|
|
10680
|
-
}
|
|
10681
|
-
const { x, y } = p.toAffine();
|
|
10682
|
-
if (!Fp.isValid(x) || !Fp.isValid(y))
|
|
10683
|
-
throw new Error("bad point: x or y not field elements");
|
|
10684
|
-
if (!isValidXY(x, y))
|
|
10685
|
-
throw new Error("bad point: equation left != right");
|
|
10686
|
-
if (!p.isTorsionFree())
|
|
10687
|
-
throw new Error("bad point: not in prime-order subgroup");
|
|
10688
|
-
return true;
|
|
10689
|
-
});
|
|
10690
|
-
function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
|
|
10691
|
-
k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
|
|
10692
|
-
k1p = negateCt(k1neg, k1p);
|
|
10693
|
-
k2p = negateCt(k2neg, k2p);
|
|
10694
|
-
return k1p.add(k2p);
|
|
10695
|
-
}
|
|
10696
|
-
class Point {
|
|
10697
|
-
// base / generator point
|
|
10698
|
-
static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
|
|
10699
|
-
// zero / infinity / identity point
|
|
10700
|
-
static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
|
|
10701
|
-
// 0, 1, 0
|
|
10702
|
-
// math field
|
|
10703
|
-
static Fp = Fp;
|
|
10704
|
-
// scalar field
|
|
10705
|
-
static Fn = Fn;
|
|
10706
|
-
X;
|
|
10707
|
-
Y;
|
|
10708
|
-
Z;
|
|
10709
|
-
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
10710
|
-
constructor(X, Y, Z) {
|
|
10711
|
-
this.X = acoord("x", X);
|
|
10712
|
-
this.Y = acoord("y", Y, true);
|
|
10713
|
-
this.Z = acoord("z", Z);
|
|
10714
|
-
Object.freeze(this);
|
|
10715
|
-
}
|
|
10716
|
-
static CURVE() {
|
|
10717
|
-
return CURVE;
|
|
10718
|
-
}
|
|
10719
|
-
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
10720
|
-
static fromAffine(p) {
|
|
10721
|
-
const { x, y } = p || {};
|
|
10722
|
-
if (!p || !Fp.isValid(x) || !Fp.isValid(y))
|
|
10723
|
-
throw new Error("invalid affine point");
|
|
10724
|
-
if (p instanceof Point)
|
|
10725
|
-
throw new Error("projective point not allowed");
|
|
10726
|
-
if (Fp.is0(x) && Fp.is0(y))
|
|
10727
|
-
return Point.ZERO;
|
|
10728
|
-
return new Point(x, y, Fp.ONE);
|
|
10729
|
-
}
|
|
10730
|
-
static fromBytes(bytes) {
|
|
10731
|
-
const P = Point.fromAffine(decodePoint(abytes(bytes, void 0, "point")));
|
|
10732
|
-
P.assertValidity();
|
|
10733
|
-
return P;
|
|
10734
|
-
}
|
|
10735
|
-
static fromHex(hex) {
|
|
10736
|
-
return Point.fromBytes(hexToBytes2(hex));
|
|
10737
|
-
}
|
|
10738
|
-
get x() {
|
|
10739
|
-
return this.toAffine().x;
|
|
10740
|
-
}
|
|
10741
|
-
get y() {
|
|
10742
|
-
return this.toAffine().y;
|
|
10743
|
-
}
|
|
10744
|
-
/**
|
|
10745
|
-
*
|
|
10746
|
-
* @param windowSize
|
|
10747
|
-
* @param isLazy true will defer table computation until the first multiplication
|
|
10748
|
-
* @returns
|
|
10749
|
-
*/
|
|
10750
|
-
precompute(windowSize = 8, isLazy = true) {
|
|
10751
|
-
wnaf.createCache(this, windowSize);
|
|
10752
|
-
if (!isLazy)
|
|
10753
|
-
this.multiply(_3n2);
|
|
10754
|
-
return this;
|
|
10755
|
-
}
|
|
10756
|
-
// TODO: return `this`
|
|
10757
|
-
/** A point on curve is valid if it conforms to equation. */
|
|
10758
|
-
assertValidity() {
|
|
10759
|
-
assertValidMemo(this);
|
|
10760
|
-
}
|
|
10761
|
-
hasEvenY() {
|
|
10762
|
-
const { y } = this.toAffine();
|
|
10763
|
-
if (!Fp.isOdd)
|
|
10764
|
-
throw new Error("Field doesn't support isOdd");
|
|
10765
|
-
return !Fp.isOdd(y);
|
|
10766
|
-
}
|
|
10767
|
-
/** Compare one point to another. */
|
|
10768
|
-
equals(other) {
|
|
10769
|
-
aprjpoint(other);
|
|
10770
|
-
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
10771
|
-
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
10772
|
-
const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
|
|
10773
|
-
const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
|
|
10774
|
-
return U1 && U2;
|
|
10775
|
-
}
|
|
10776
|
-
/** Flips point to one corresponding to (x, -y) in Affine coordinates. */
|
|
10777
|
-
negate() {
|
|
10778
|
-
return new Point(this.X, Fp.neg(this.Y), this.Z);
|
|
10779
|
-
}
|
|
10780
|
-
// Renes-Costello-Batina exception-free doubling formula.
|
|
10781
|
-
// There is 30% faster Jacobian formula, but it is not complete.
|
|
10782
|
-
// https://eprint.iacr.org/2015/1060, algorithm 3
|
|
10783
|
-
// Cost: 8M + 3S + 3*a + 2*b3 + 15add.
|
|
10784
|
-
double() {
|
|
10785
|
-
const { a, b } = CURVE;
|
|
10786
|
-
const b3 = Fp.mul(b, _3n2);
|
|
10787
|
-
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
10788
|
-
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
|
|
10789
|
-
let t0 = Fp.mul(X1, X1);
|
|
10790
|
-
let t1 = Fp.mul(Y1, Y1);
|
|
10791
|
-
let t2 = Fp.mul(Z1, Z1);
|
|
10792
|
-
let t3 = Fp.mul(X1, Y1);
|
|
10793
|
-
t3 = Fp.add(t3, t3);
|
|
10794
|
-
Z3 = Fp.mul(X1, Z1);
|
|
10795
|
-
Z3 = Fp.add(Z3, Z3);
|
|
10796
|
-
X3 = Fp.mul(a, Z3);
|
|
10797
|
-
Y3 = Fp.mul(b3, t2);
|
|
10798
|
-
Y3 = Fp.add(X3, Y3);
|
|
10799
|
-
X3 = Fp.sub(t1, Y3);
|
|
10800
|
-
Y3 = Fp.add(t1, Y3);
|
|
10801
|
-
Y3 = Fp.mul(X3, Y3);
|
|
10802
|
-
X3 = Fp.mul(t3, X3);
|
|
10803
|
-
Z3 = Fp.mul(b3, Z3);
|
|
10804
|
-
t2 = Fp.mul(a, t2);
|
|
10805
|
-
t3 = Fp.sub(t0, t2);
|
|
10806
|
-
t3 = Fp.mul(a, t3);
|
|
10807
|
-
t3 = Fp.add(t3, Z3);
|
|
10808
|
-
Z3 = Fp.add(t0, t0);
|
|
10809
|
-
t0 = Fp.add(Z3, t0);
|
|
10810
|
-
t0 = Fp.add(t0, t2);
|
|
10811
|
-
t0 = Fp.mul(t0, t3);
|
|
10812
|
-
Y3 = Fp.add(Y3, t0);
|
|
10813
|
-
t2 = Fp.mul(Y1, Z1);
|
|
10814
|
-
t2 = Fp.add(t2, t2);
|
|
10815
|
-
t0 = Fp.mul(t2, t3);
|
|
10816
|
-
X3 = Fp.sub(X3, t0);
|
|
10817
|
-
Z3 = Fp.mul(t2, t1);
|
|
10818
|
-
Z3 = Fp.add(Z3, Z3);
|
|
10819
|
-
Z3 = Fp.add(Z3, Z3);
|
|
10820
|
-
return new Point(X3, Y3, Z3);
|
|
10821
|
-
}
|
|
10822
|
-
// Renes-Costello-Batina exception-free addition formula.
|
|
10823
|
-
// There is 30% faster Jacobian formula, but it is not complete.
|
|
10824
|
-
// https://eprint.iacr.org/2015/1060, algorithm 1
|
|
10825
|
-
// Cost: 12M + 0S + 3*a + 3*b3 + 23add.
|
|
10826
|
-
add(other) {
|
|
10827
|
-
aprjpoint(other);
|
|
10828
|
-
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
10829
|
-
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
10830
|
-
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
|
|
10831
|
-
const a = CURVE.a;
|
|
10832
|
-
const b3 = Fp.mul(CURVE.b, _3n2);
|
|
10833
|
-
let t0 = Fp.mul(X1, X2);
|
|
10834
|
-
let t1 = Fp.mul(Y1, Y2);
|
|
10835
|
-
let t2 = Fp.mul(Z1, Z2);
|
|
10836
|
-
let t3 = Fp.add(X1, Y1);
|
|
10837
|
-
let t4 = Fp.add(X2, Y2);
|
|
10838
|
-
t3 = Fp.mul(t3, t4);
|
|
10839
|
-
t4 = Fp.add(t0, t1);
|
|
10840
|
-
t3 = Fp.sub(t3, t4);
|
|
10841
|
-
t4 = Fp.add(X1, Z1);
|
|
10842
|
-
let t5 = Fp.add(X2, Z2);
|
|
10843
|
-
t4 = Fp.mul(t4, t5);
|
|
10844
|
-
t5 = Fp.add(t0, t2);
|
|
10845
|
-
t4 = Fp.sub(t4, t5);
|
|
10846
|
-
t5 = Fp.add(Y1, Z1);
|
|
10847
|
-
X3 = Fp.add(Y2, Z2);
|
|
10848
|
-
t5 = Fp.mul(t5, X3);
|
|
10849
|
-
X3 = Fp.add(t1, t2);
|
|
10850
|
-
t5 = Fp.sub(t5, X3);
|
|
10851
|
-
Z3 = Fp.mul(a, t4);
|
|
10852
|
-
X3 = Fp.mul(b3, t2);
|
|
10853
|
-
Z3 = Fp.add(X3, Z3);
|
|
10854
|
-
X3 = Fp.sub(t1, Z3);
|
|
10855
|
-
Z3 = Fp.add(t1, Z3);
|
|
10856
|
-
Y3 = Fp.mul(X3, Z3);
|
|
10857
|
-
t1 = Fp.add(t0, t0);
|
|
10858
|
-
t1 = Fp.add(t1, t0);
|
|
10859
|
-
t2 = Fp.mul(a, t2);
|
|
10860
|
-
t4 = Fp.mul(b3, t4);
|
|
10861
|
-
t1 = Fp.add(t1, t2);
|
|
10862
|
-
t2 = Fp.sub(t0, t2);
|
|
10863
|
-
t2 = Fp.mul(a, t2);
|
|
10864
|
-
t4 = Fp.add(t4, t2);
|
|
10865
|
-
t0 = Fp.mul(t1, t4);
|
|
10866
|
-
Y3 = Fp.add(Y3, t0);
|
|
10867
|
-
t0 = Fp.mul(t5, t4);
|
|
10868
|
-
X3 = Fp.mul(t3, X3);
|
|
10869
|
-
X3 = Fp.sub(X3, t0);
|
|
10870
|
-
t0 = Fp.mul(t3, t1);
|
|
10871
|
-
Z3 = Fp.mul(t5, Z3);
|
|
10872
|
-
Z3 = Fp.add(Z3, t0);
|
|
10873
|
-
return new Point(X3, Y3, Z3);
|
|
10874
|
-
}
|
|
10875
|
-
subtract(other) {
|
|
10876
|
-
return this.add(other.negate());
|
|
10877
|
-
}
|
|
10878
|
-
is0() {
|
|
10879
|
-
return this.equals(Point.ZERO);
|
|
10880
|
-
}
|
|
10881
|
-
/**
|
|
10882
|
-
* Constant time multiplication.
|
|
10883
|
-
* Uses wNAF method. Windowed method may be 10% faster,
|
|
10884
|
-
* but takes 2x longer to generate and consumes 2x memory.
|
|
10885
|
-
* Uses precomputes when available.
|
|
10886
|
-
* Uses endomorphism for Koblitz curves.
|
|
10887
|
-
* @param scalar by which the point would be multiplied
|
|
10888
|
-
* @returns New point
|
|
10889
|
-
*/
|
|
10890
|
-
multiply(scalar) {
|
|
10891
|
-
const { endo: endo2 } = extraOpts;
|
|
10892
|
-
if (!Fn.isValidNot0(scalar))
|
|
10893
|
-
throw new Error("invalid scalar: out of range");
|
|
10894
|
-
let point, fake;
|
|
10895
|
-
const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
|
|
10896
|
-
if (endo2) {
|
|
10897
|
-
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
|
|
10898
|
-
const { p: k1p, f: k1f } = mul(k1);
|
|
10899
|
-
const { p: k2p, f: k2f } = mul(k2);
|
|
10900
|
-
fake = k1f.add(k2f);
|
|
10901
|
-
point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
|
|
10902
|
-
} else {
|
|
10903
|
-
const { p, f } = mul(scalar);
|
|
10904
|
-
point = p;
|
|
10905
|
-
fake = f;
|
|
10906
|
-
}
|
|
10907
|
-
return normalizeZ(Point, [point, fake])[0];
|
|
10908
|
-
}
|
|
10909
|
-
/**
|
|
10910
|
-
* Non-constant-time multiplication. Uses double-and-add algorithm.
|
|
10911
|
-
* It's faster, but should only be used when you don't care about
|
|
10912
|
-
* an exposed secret key e.g. sig verification, which works over *public* keys.
|
|
10913
|
-
*/
|
|
10914
|
-
multiplyUnsafe(sc) {
|
|
10915
|
-
const { endo: endo2 } = extraOpts;
|
|
10916
|
-
const p = this;
|
|
10917
|
-
if (!Fn.isValid(sc))
|
|
10918
|
-
throw new Error("invalid scalar: out of range");
|
|
10919
|
-
if (sc === _0n4 || p.is0())
|
|
10920
|
-
return Point.ZERO;
|
|
10921
|
-
if (sc === _1n4)
|
|
10922
|
-
return p;
|
|
10923
|
-
if (wnaf.hasCache(this))
|
|
10924
|
-
return this.multiply(sc);
|
|
10925
|
-
if (endo2) {
|
|
10926
|
-
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
|
|
10927
|
-
const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
|
|
10928
|
-
return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
|
|
10929
|
-
} else {
|
|
10930
|
-
return wnaf.unsafe(p, sc);
|
|
10931
|
-
}
|
|
10932
|
-
}
|
|
10933
|
-
/**
|
|
10934
|
-
* Converts Projective point to affine (x, y) coordinates.
|
|
10935
|
-
* @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
|
|
10936
|
-
*/
|
|
10937
|
-
toAffine(invertedZ) {
|
|
10938
|
-
return toAffineMemo(this, invertedZ);
|
|
10939
|
-
}
|
|
10940
|
-
/**
|
|
10941
|
-
* Checks whether Point is free of torsion elements (is in prime subgroup).
|
|
10942
|
-
* Always torsion-free for cofactor=1 curves.
|
|
10943
|
-
*/
|
|
10944
|
-
isTorsionFree() {
|
|
10945
|
-
const { isTorsionFree } = extraOpts;
|
|
10946
|
-
if (cofactor === _1n4)
|
|
10947
|
-
return true;
|
|
10948
|
-
if (isTorsionFree)
|
|
10949
|
-
return isTorsionFree(Point, this);
|
|
10950
|
-
return wnaf.unsafe(this, CURVE_ORDER2).is0();
|
|
10951
|
-
}
|
|
10952
|
-
clearCofactor() {
|
|
10953
|
-
const { clearCofactor } = extraOpts;
|
|
10954
|
-
if (cofactor === _1n4)
|
|
10955
|
-
return this;
|
|
10956
|
-
if (clearCofactor)
|
|
10957
|
-
return clearCofactor(Point, this);
|
|
10958
|
-
return this.multiplyUnsafe(cofactor);
|
|
10959
|
-
}
|
|
10960
|
-
isSmallOrder() {
|
|
10961
|
-
return this.multiplyUnsafe(cofactor).is0();
|
|
10962
|
-
}
|
|
10963
|
-
toBytes(isCompressed = true) {
|
|
10964
|
-
abool(isCompressed, "isCompressed");
|
|
10965
|
-
this.assertValidity();
|
|
10966
|
-
return encodePoint(Point, this, isCompressed);
|
|
10967
|
-
}
|
|
10968
|
-
toHex(isCompressed = true) {
|
|
10969
|
-
return bytesToHex4(this.toBytes(isCompressed));
|
|
10970
|
-
}
|
|
10971
|
-
toString() {
|
|
10972
|
-
return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
|
|
10973
|
-
}
|
|
10974
|
-
}
|
|
10975
|
-
const bits = Fn.BITS;
|
|
10976
|
-
const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
|
|
10977
|
-
Point.BASE.precompute(8);
|
|
10978
|
-
return Point;
|
|
10979
|
-
}
|
|
10980
|
-
function pprefix(hasEvenY) {
|
|
10981
|
-
return Uint8Array.of(hasEvenY ? 2 : 3);
|
|
10982
|
-
}
|
|
10983
|
-
function getWLengths(Fp, Fn) {
|
|
10984
|
-
return {
|
|
10985
|
-
secretKey: Fn.BYTES,
|
|
10986
|
-
publicKey: 1 + Fp.BYTES,
|
|
10987
|
-
publicKeyUncompressed: 1 + 2 * Fp.BYTES,
|
|
10988
|
-
publicKeyHasPrefix: true,
|
|
10989
|
-
signature: 2 * Fn.BYTES
|
|
10990
|
-
};
|
|
10991
|
-
}
|
|
10992
|
-
function ecdh(Point, ecdhOpts = {}) {
|
|
10993
|
-
const { Fn } = Point;
|
|
10994
|
-
const randomBytes_ = ecdhOpts.randomBytes || randomBytes2;
|
|
10995
|
-
const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
|
|
10996
|
-
function isValidSecretKey(secretKey) {
|
|
10997
|
-
try {
|
|
10998
|
-
const num = Fn.fromBytes(secretKey);
|
|
10999
|
-
return Fn.isValidNot0(num);
|
|
11000
|
-
} catch (error) {
|
|
11001
|
-
return false;
|
|
11002
|
-
}
|
|
11003
|
-
}
|
|
11004
|
-
function isValidPublicKey(publicKey, isCompressed) {
|
|
11005
|
-
const { publicKey: comp, publicKeyUncompressed } = lengths;
|
|
11006
|
-
try {
|
|
11007
|
-
const l = publicKey.length;
|
|
11008
|
-
if (isCompressed === true && l !== comp)
|
|
11009
|
-
return false;
|
|
11010
|
-
if (isCompressed === false && l !== publicKeyUncompressed)
|
|
11011
|
-
return false;
|
|
11012
|
-
return !!Point.fromBytes(publicKey);
|
|
11013
|
-
} catch (error) {
|
|
11014
|
-
return false;
|
|
11015
|
-
}
|
|
11016
|
-
}
|
|
11017
|
-
function randomSecretKey(seed = randomBytes_(lengths.seed)) {
|
|
11018
|
-
return mapHashToField(abytes(seed, lengths.seed, "seed"), Fn.ORDER);
|
|
11019
|
-
}
|
|
11020
|
-
function getPublicKey2(secretKey, isCompressed = true) {
|
|
11021
|
-
return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
|
|
11022
|
-
}
|
|
11023
|
-
function isProbPub(item) {
|
|
11024
|
-
const { secretKey, publicKey, publicKeyUncompressed } = lengths;
|
|
11025
|
-
if (!isBytes(item))
|
|
11026
|
-
return void 0;
|
|
11027
|
-
if ("_lengths" in Fn && Fn._lengths || secretKey === publicKey)
|
|
11028
|
-
return void 0;
|
|
11029
|
-
const l = abytes(item, void 0, "key").length;
|
|
11030
|
-
return l === publicKey || l === publicKeyUncompressed;
|
|
11031
|
-
}
|
|
11032
|
-
function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
|
|
11033
|
-
if (isProbPub(secretKeyA) === true)
|
|
11034
|
-
throw new Error("first arg must be private key");
|
|
11035
|
-
if (isProbPub(publicKeyB) === false)
|
|
11036
|
-
throw new Error("second arg must be public key");
|
|
11037
|
-
const s = Fn.fromBytes(secretKeyA);
|
|
11038
|
-
const b = Point.fromBytes(publicKeyB);
|
|
11039
|
-
return b.multiply(s).toBytes(isCompressed);
|
|
11040
|
-
}
|
|
11041
|
-
const utils = {
|
|
11042
|
-
isValidSecretKey,
|
|
11043
|
-
isValidPublicKey,
|
|
11044
|
-
randomSecretKey
|
|
11045
|
-
};
|
|
11046
|
-
const keygen = createKeygen(randomSecretKey, getPublicKey2);
|
|
11047
|
-
return Object.freeze({ getPublicKey: getPublicKey2, getSharedSecret, keygen, Point, utils, lengths });
|
|
11048
|
-
}
|
|
11049
|
-
function ecdsa(Point, hash, ecdsaOpts = {}) {
|
|
11050
|
-
ahash(hash);
|
|
11051
|
-
validateObject(ecdsaOpts, {}, {
|
|
11052
|
-
hmac: "function",
|
|
11053
|
-
lowS: "boolean",
|
|
11054
|
-
randomBytes: "function",
|
|
11055
|
-
bits2int: "function",
|
|
11056
|
-
bits2int_modN: "function"
|
|
11057
|
-
});
|
|
11058
|
-
ecdsaOpts = Object.assign({}, ecdsaOpts);
|
|
11059
|
-
const randomBytes3 = ecdsaOpts.randomBytes || randomBytes2;
|
|
11060
|
-
const hmac2 = ecdsaOpts.hmac || ((key, msg) => hmac(hash, key, msg));
|
|
11061
|
-
const { Fp, Fn } = Point;
|
|
11062
|
-
const { ORDER: CURVE_ORDER2, BITS: fnBits } = Fn;
|
|
11063
|
-
const { keygen, getPublicKey: getPublicKey2, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
|
|
11064
|
-
const defaultSigOpts = {
|
|
11065
|
-
prehash: true,
|
|
11066
|
-
lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
|
|
11067
|
-
format: "compact",
|
|
11068
|
-
extraEntropy: false
|
|
11069
|
-
};
|
|
11070
|
-
const hasLargeCofactor = CURVE_ORDER2 * _2n2 < Fp.ORDER;
|
|
11071
|
-
function isBiggerThanHalfOrder(number) {
|
|
11072
|
-
const HALF = CURVE_ORDER2 >> _1n4;
|
|
11073
|
-
return number > HALF;
|
|
11074
|
-
}
|
|
11075
|
-
function validateRS(title, num) {
|
|
11076
|
-
if (!Fn.isValidNot0(num))
|
|
11077
|
-
throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
|
|
11078
|
-
return num;
|
|
11079
|
-
}
|
|
11080
|
-
function assertSmallCofactor() {
|
|
11081
|
-
if (hasLargeCofactor)
|
|
11082
|
-
throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
|
|
11083
|
-
}
|
|
11084
|
-
function validateSigLength(bytes, format) {
|
|
11085
|
-
validateSigFormat(format);
|
|
11086
|
-
const size = lengths.signature;
|
|
11087
|
-
const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
|
|
11088
|
-
return abytes(bytes, sizer);
|
|
11089
|
-
}
|
|
11090
|
-
class Signature {
|
|
11091
|
-
r;
|
|
11092
|
-
s;
|
|
11093
|
-
recovery;
|
|
11094
|
-
constructor(r, s, recovery) {
|
|
11095
|
-
this.r = validateRS("r", r);
|
|
11096
|
-
this.s = validateRS("s", s);
|
|
11097
|
-
if (recovery != null) {
|
|
11098
|
-
assertSmallCofactor();
|
|
11099
|
-
if (![0, 1, 2, 3].includes(recovery))
|
|
11100
|
-
throw new Error("invalid recovery id");
|
|
11101
|
-
this.recovery = recovery;
|
|
11102
|
-
}
|
|
11103
|
-
Object.freeze(this);
|
|
11104
|
-
}
|
|
11105
|
-
static fromBytes(bytes, format = defaultSigOpts.format) {
|
|
11106
|
-
validateSigLength(bytes, format);
|
|
11107
|
-
let recid;
|
|
11108
|
-
if (format === "der") {
|
|
11109
|
-
const { r: r2, s: s2 } = DER.toSig(abytes(bytes));
|
|
11110
|
-
return new Signature(r2, s2);
|
|
11111
|
-
}
|
|
11112
|
-
if (format === "recovered") {
|
|
11113
|
-
recid = bytes[0];
|
|
11114
|
-
format = "compact";
|
|
11115
|
-
bytes = bytes.subarray(1);
|
|
11116
|
-
}
|
|
11117
|
-
const L = lengths.signature / 2;
|
|
11118
|
-
const r = bytes.subarray(0, L);
|
|
11119
|
-
const s = bytes.subarray(L, L * 2);
|
|
11120
|
-
return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
|
|
11121
|
-
}
|
|
11122
|
-
static fromHex(hex, format) {
|
|
11123
|
-
return this.fromBytes(hexToBytes2(hex), format);
|
|
11124
|
-
}
|
|
11125
|
-
assertRecovery() {
|
|
11126
|
-
const { recovery } = this;
|
|
11127
|
-
if (recovery == null)
|
|
11128
|
-
throw new Error("invalid recovery id: must be present");
|
|
11129
|
-
return recovery;
|
|
11130
|
-
}
|
|
11131
|
-
addRecoveryBit(recovery) {
|
|
11132
|
-
return new Signature(this.r, this.s, recovery);
|
|
11133
|
-
}
|
|
11134
|
-
recoverPublicKey(messageHash) {
|
|
11135
|
-
const { r, s } = this;
|
|
11136
|
-
const recovery = this.assertRecovery();
|
|
11137
|
-
const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER2 : r;
|
|
11138
|
-
if (!Fp.isValid(radj))
|
|
11139
|
-
throw new Error("invalid recovery id: sig.r+curve.n != R.x");
|
|
11140
|
-
const x = Fp.toBytes(radj);
|
|
11141
|
-
const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));
|
|
11142
|
-
const ir = Fn.inv(radj);
|
|
11143
|
-
const h = bits2int_modN(abytes(messageHash, void 0, "msgHash"));
|
|
11144
|
-
const u1 = Fn.create(-h * ir);
|
|
11145
|
-
const u2 = Fn.create(s * ir);
|
|
11146
|
-
const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
|
|
11147
|
-
if (Q.is0())
|
|
11148
|
-
throw new Error("invalid recovery: point at infinify");
|
|
11149
|
-
Q.assertValidity();
|
|
11150
|
-
return Q;
|
|
11151
|
-
}
|
|
11152
|
-
// Signatures should be low-s, to prevent malleability.
|
|
11153
|
-
hasHighS() {
|
|
11154
|
-
return isBiggerThanHalfOrder(this.s);
|
|
11155
|
-
}
|
|
11156
|
-
toBytes(format = defaultSigOpts.format) {
|
|
11157
|
-
validateSigFormat(format);
|
|
11158
|
-
if (format === "der")
|
|
11159
|
-
return hexToBytes2(DER.hexFromSig(this));
|
|
11160
|
-
const { r, s } = this;
|
|
11161
|
-
const rb = Fn.toBytes(r);
|
|
11162
|
-
const sb = Fn.toBytes(s);
|
|
11163
|
-
if (format === "recovered") {
|
|
11164
|
-
assertSmallCofactor();
|
|
11165
|
-
return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);
|
|
11166
|
-
}
|
|
11167
|
-
return concatBytes(rb, sb);
|
|
11168
|
-
}
|
|
11169
|
-
toHex(format) {
|
|
11170
|
-
return bytesToHex4(this.toBytes(format));
|
|
11171
|
-
}
|
|
11172
|
-
}
|
|
11173
|
-
const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
|
|
11174
|
-
if (bytes.length > 8192)
|
|
11175
|
-
throw new Error("input is too large");
|
|
11176
|
-
const num = bytesToNumberBE(bytes);
|
|
11177
|
-
const delta = bytes.length * 8 - fnBits;
|
|
11178
|
-
return delta > 0 ? num >> BigInt(delta) : num;
|
|
11179
|
-
};
|
|
11180
|
-
const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
|
|
11181
|
-
return Fn.create(bits2int(bytes));
|
|
11182
|
-
};
|
|
11183
|
-
const ORDER_MASK = bitMask(fnBits);
|
|
11184
|
-
function int2octets(num) {
|
|
11185
|
-
aInRange("num < 2^" + fnBits, num, _0n4, ORDER_MASK);
|
|
11186
|
-
return Fn.toBytes(num);
|
|
11187
|
-
}
|
|
11188
|
-
function validateMsgAndHash(message, prehash) {
|
|
11189
|
-
abytes(message, void 0, "message");
|
|
11190
|
-
return prehash ? abytes(hash(message), void 0, "prehashed message") : message;
|
|
11191
|
-
}
|
|
11192
|
-
function prepSig(message, secretKey, opts) {
|
|
11193
|
-
const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
|
|
11194
|
-
message = validateMsgAndHash(message, prehash);
|
|
11195
|
-
const h1int = bits2int_modN(message);
|
|
11196
|
-
const d = Fn.fromBytes(secretKey);
|
|
11197
|
-
if (!Fn.isValidNot0(d))
|
|
11198
|
-
throw new Error("invalid private key");
|
|
11199
|
-
const seedArgs = [int2octets(d), int2octets(h1int)];
|
|
11200
|
-
if (extraEntropy != null && extraEntropy !== false) {
|
|
11201
|
-
const e = extraEntropy === true ? randomBytes3(lengths.secretKey) : extraEntropy;
|
|
11202
|
-
seedArgs.push(abytes(e, void 0, "extraEntropy"));
|
|
11203
|
-
}
|
|
11204
|
-
const seed = concatBytes(...seedArgs);
|
|
11205
|
-
const m = h1int;
|
|
11206
|
-
function k2sig(kBytes) {
|
|
11207
|
-
const k = bits2int(kBytes);
|
|
11208
|
-
if (!Fn.isValidNot0(k))
|
|
11209
|
-
return;
|
|
11210
|
-
const ik = Fn.inv(k);
|
|
11211
|
-
const q = Point.BASE.multiply(k).toAffine();
|
|
11212
|
-
const r = Fn.create(q.x);
|
|
11213
|
-
if (r === _0n4)
|
|
11214
|
-
return;
|
|
11215
|
-
const s = Fn.create(ik * Fn.create(m + r * d));
|
|
11216
|
-
if (s === _0n4)
|
|
11217
|
-
return;
|
|
11218
|
-
let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
|
|
11219
|
-
let normS = s;
|
|
11220
|
-
if (lowS && isBiggerThanHalfOrder(s)) {
|
|
11221
|
-
normS = Fn.neg(s);
|
|
11222
|
-
recovery ^= 1;
|
|
11223
|
-
}
|
|
11224
|
-
return new Signature(r, normS, hasLargeCofactor ? void 0 : recovery);
|
|
11225
|
-
}
|
|
11226
|
-
return { seed, k2sig };
|
|
11227
|
-
}
|
|
11228
|
-
function sign(message, secretKey, opts = {}) {
|
|
11229
|
-
const { seed, k2sig } = prepSig(message, secretKey, opts);
|
|
11230
|
-
const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac2);
|
|
11231
|
-
const sig = drbg(seed, k2sig);
|
|
11232
|
-
return sig.toBytes(opts.format);
|
|
11233
|
-
}
|
|
11234
|
-
function verify(signature, message, publicKey, opts = {}) {
|
|
11235
|
-
const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
|
|
11236
|
-
publicKey = abytes(publicKey, void 0, "publicKey");
|
|
11237
|
-
message = validateMsgAndHash(message, prehash);
|
|
11238
|
-
if (!isBytes(signature)) {
|
|
11239
|
-
const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
|
|
11240
|
-
throw new Error("verify expects Uint8Array signature" + end);
|
|
11241
|
-
}
|
|
11242
|
-
validateSigLength(signature, format);
|
|
11243
|
-
try {
|
|
11244
|
-
const sig = Signature.fromBytes(signature, format);
|
|
11245
|
-
const P = Point.fromBytes(publicKey);
|
|
11246
|
-
if (lowS && sig.hasHighS())
|
|
11247
|
-
return false;
|
|
11248
|
-
const { r, s } = sig;
|
|
11249
|
-
const h = bits2int_modN(message);
|
|
11250
|
-
const is = Fn.inv(s);
|
|
11251
|
-
const u1 = Fn.create(h * is);
|
|
11252
|
-
const u2 = Fn.create(r * is);
|
|
11253
|
-
const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
|
|
11254
|
-
if (R.is0())
|
|
11255
|
-
return false;
|
|
11256
|
-
const v = Fn.create(R.x);
|
|
11257
|
-
return v === r;
|
|
11258
|
-
} catch (e) {
|
|
11259
|
-
return false;
|
|
11260
|
-
}
|
|
11261
|
-
}
|
|
11262
|
-
function recoverPublicKey(signature, message, opts = {}) {
|
|
11263
|
-
const { prehash } = validateSigOpts(opts, defaultSigOpts);
|
|
11264
|
-
message = validateMsgAndHash(message, prehash);
|
|
11265
|
-
return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
|
|
11266
|
-
}
|
|
11267
|
-
return Object.freeze({
|
|
11268
|
-
keygen,
|
|
11269
|
-
getPublicKey: getPublicKey2,
|
|
11270
|
-
getSharedSecret,
|
|
11271
|
-
utils,
|
|
11272
|
-
lengths,
|
|
11273
|
-
Point,
|
|
11274
|
-
sign,
|
|
11275
|
-
verify,
|
|
11276
|
-
recoverPublicKey,
|
|
11277
|
-
Signature,
|
|
11278
|
-
hash
|
|
11279
|
-
});
|
|
11280
|
-
}
|
|
11281
|
-
|
|
11282
|
-
// node_modules/@noble/curves/secp256k1.js
|
|
11283
|
-
var secp256k1_CURVE = {
|
|
11284
|
-
p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
|
|
11285
|
-
n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
|
|
11286
|
-
h: BigInt(1),
|
|
11287
|
-
a: BigInt(0),
|
|
11288
|
-
b: BigInt(7),
|
|
11289
|
-
Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
|
|
11290
|
-
Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
|
|
11291
|
-
};
|
|
11292
|
-
var secp256k1_ENDO = {
|
|
11293
|
-
beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
|
|
11294
|
-
basises: [
|
|
11295
|
-
[BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
|
|
11296
|
-
[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
|
|
11297
|
-
]
|
|
11298
|
-
};
|
|
11299
|
-
var _2n3 = /* @__PURE__ */ BigInt(2);
|
|
11300
|
-
function sqrtMod(y) {
|
|
11301
|
-
const P = secp256k1_CURVE.p;
|
|
11302
|
-
const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
|
|
11303
|
-
const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
|
|
11304
|
-
const b2 = y * y * y % P;
|
|
11305
|
-
const b3 = b2 * b2 * y % P;
|
|
11306
|
-
const b6 = pow2(b3, _3n3, P) * b3 % P;
|
|
11307
|
-
const b9 = pow2(b6, _3n3, P) * b3 % P;
|
|
11308
|
-
const b11 = pow2(b9, _2n3, P) * b2 % P;
|
|
11309
|
-
const b22 = pow2(b11, _11n, P) * b11 % P;
|
|
11310
|
-
const b44 = pow2(b22, _22n, P) * b22 % P;
|
|
11311
|
-
const b88 = pow2(b44, _44n, P) * b44 % P;
|
|
11312
|
-
const b176 = pow2(b88, _88n, P) * b88 % P;
|
|
11313
|
-
const b220 = pow2(b176, _44n, P) * b44 % P;
|
|
11314
|
-
const b223 = pow2(b220, _3n3, P) * b3 % P;
|
|
11315
|
-
const t1 = pow2(b223, _23n, P) * b22 % P;
|
|
11316
|
-
const t2 = pow2(t1, _6n, P) * b2 % P;
|
|
11317
|
-
const root = pow2(t2, _2n3, P);
|
|
11318
|
-
if (!Fpk1.eql(Fpk1.sqr(root), y))
|
|
11319
|
-
throw new Error("Cannot find square root");
|
|
11320
|
-
return root;
|
|
11321
|
-
}
|
|
11322
|
-
var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
|
|
11323
|
-
var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
|
|
11324
|
-
Fp: Fpk1,
|
|
11325
|
-
endo: secp256k1_ENDO
|
|
11326
|
-
});
|
|
11327
|
-
var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha2564);
|
|
11328
|
-
|
|
11329
|
-
// modules/market/MarketModule.ts
|
|
11330
|
-
function hexToBytes3(hex) {
|
|
11331
|
-
const len = hex.length >> 1;
|
|
11332
|
-
const bytes = new Uint8Array(len);
|
|
11333
|
-
for (let i = 0; i < len; i++) {
|
|
11334
|
-
bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
11335
|
-
}
|
|
11336
|
-
return bytes;
|
|
11337
|
-
}
|
|
11338
|
-
function signRequest(body, privateKeyHex) {
|
|
11339
|
-
const timestamp = Date.now();
|
|
11340
|
-
const payload = JSON.stringify({ body, timestamp });
|
|
11341
|
-
const messageHash = sha2564(new TextEncoder().encode(payload));
|
|
11342
|
-
const privateKeyBytes = hexToBytes3(privateKeyHex);
|
|
11343
|
-
const signature = secp256k1.sign(messageHash, privateKeyBytes);
|
|
11344
|
-
const publicKey = bytesToHex4(secp256k1.getPublicKey(privateKeyBytes, true));
|
|
11345
|
-
return {
|
|
11346
|
-
body: JSON.stringify(body),
|
|
11347
|
-
headers: {
|
|
11348
|
-
"x-signature": bytesToHex4(signature),
|
|
11349
|
-
"x-public-key": publicKey,
|
|
11350
|
-
"x-timestamp": String(timestamp),
|
|
11351
|
-
"content-type": "application/json"
|
|
11352
|
-
}
|
|
11353
|
-
};
|
|
11354
|
-
}
|
|
11355
|
-
function toSnakeCaseIntent(req) {
|
|
11356
|
-
const result = {
|
|
11357
|
-
description: req.description,
|
|
11358
|
-
intent_type: req.intentType
|
|
11359
|
-
};
|
|
11360
|
-
if (req.category !== void 0) result.category = req.category;
|
|
11361
|
-
if (req.price !== void 0) result.price = req.price;
|
|
11362
|
-
if (req.currency !== void 0) result.currency = req.currency;
|
|
11363
|
-
if (req.location !== void 0) result.location = req.location;
|
|
11364
|
-
if (req.contactHandle !== void 0) result.contact_handle = req.contactHandle;
|
|
11365
|
-
if (req.expiresInDays !== void 0) result.expires_in_days = req.expiresInDays;
|
|
11366
|
-
return result;
|
|
11367
|
-
}
|
|
11368
|
-
function toSnakeCaseFilters(opts) {
|
|
11369
|
-
const result = {};
|
|
11370
|
-
if (opts?.filters) {
|
|
11371
|
-
const f = opts.filters;
|
|
11372
|
-
if (f.intentType !== void 0) result.intent_type = f.intentType;
|
|
11373
|
-
if (f.category !== void 0) result.category = f.category;
|
|
11374
|
-
if (f.minPrice !== void 0) result.min_price = f.minPrice;
|
|
11375
|
-
if (f.maxPrice !== void 0) result.max_price = f.maxPrice;
|
|
11376
|
-
if (f.location !== void 0) result.location = f.location;
|
|
11377
|
-
}
|
|
11378
|
-
if (opts?.limit !== void 0) result.limit = opts.limit;
|
|
11379
|
-
return result;
|
|
11380
|
-
}
|
|
11381
|
-
function mapSearchResult(raw) {
|
|
11382
|
-
return {
|
|
11383
|
-
id: raw.id,
|
|
11384
|
-
score: raw.score,
|
|
11385
|
-
agentNametag: raw.agent_nametag ?? void 0,
|
|
11386
|
-
agentPublicKey: raw.agent_public_key,
|
|
11387
|
-
description: raw.description,
|
|
11388
|
-
intentType: raw.intent_type,
|
|
11389
|
-
category: raw.category ?? void 0,
|
|
11390
|
-
price: raw.price ?? void 0,
|
|
11391
|
-
currency: raw.currency,
|
|
11392
|
-
location: raw.location ?? void 0,
|
|
11393
|
-
contactMethod: raw.contact_method,
|
|
11394
|
-
contactHandle: raw.contact_handle ?? void 0,
|
|
11395
|
-
createdAt: raw.created_at,
|
|
11396
|
-
expiresAt: raw.expires_at
|
|
11397
|
-
};
|
|
11398
|
-
}
|
|
11399
|
-
function mapMyIntent(raw) {
|
|
11400
|
-
return {
|
|
11401
|
-
id: raw.id,
|
|
11402
|
-
intentType: raw.intent_type,
|
|
11403
|
-
category: raw.category ?? void 0,
|
|
11404
|
-
price: raw.price ?? void 0,
|
|
11405
|
-
currency: raw.currency,
|
|
11406
|
-
location: raw.location ?? void 0,
|
|
11407
|
-
status: raw.status,
|
|
11408
|
-
createdAt: raw.created_at,
|
|
11409
|
-
expiresAt: raw.expires_at
|
|
11410
|
-
};
|
|
11411
|
-
}
|
|
11412
|
-
function mapFeedListing(raw) {
|
|
11413
|
-
return {
|
|
11414
|
-
id: raw.id,
|
|
11415
|
-
title: raw.title,
|
|
11416
|
-
descriptionPreview: raw.description_preview,
|
|
11417
|
-
agentName: raw.agent_name,
|
|
11418
|
-
agentId: raw.agent_id,
|
|
11419
|
-
type: raw.type,
|
|
11420
|
-
createdAt: raw.created_at
|
|
11421
|
-
};
|
|
11422
|
-
}
|
|
11423
|
-
function mapFeedMessage(raw) {
|
|
11424
|
-
if (raw.type === "initial") {
|
|
11425
|
-
return { type: "initial", listings: (raw.listings ?? []).map(mapFeedListing) };
|
|
11426
|
-
}
|
|
11427
|
-
return { type: "new", listing: mapFeedListing(raw.listing) };
|
|
11428
|
-
}
|
|
11429
|
-
var MarketModule = class {
|
|
11430
|
-
apiUrl;
|
|
11431
|
-
timeout;
|
|
11432
|
-
identity = null;
|
|
11433
|
-
registered = false;
|
|
11434
|
-
constructor(config) {
|
|
11435
|
-
this.apiUrl = (config?.apiUrl ?? DEFAULT_MARKET_API_URL).replace(/\/+$/, "");
|
|
11436
|
-
this.timeout = config?.timeout ?? 3e4;
|
|
11437
|
-
}
|
|
11438
|
-
/** Called by Sphere after construction */
|
|
11439
|
-
initialize(deps) {
|
|
11440
|
-
this.identity = deps.identity;
|
|
11441
|
-
}
|
|
11442
|
-
/** No-op — stateless module */
|
|
11443
|
-
async load() {
|
|
11444
|
-
}
|
|
11445
|
-
/** No-op — stateless module */
|
|
11446
|
-
destroy() {
|
|
11447
|
-
}
|
|
11448
|
-
// ---------------------------------------------------------------------------
|
|
11449
|
-
// Public API
|
|
11450
|
-
// ---------------------------------------------------------------------------
|
|
11451
|
-
/** Post a new intent (agent is auto-registered on first post) */
|
|
11452
|
-
async postIntent(intent) {
|
|
11453
|
-
const body = toSnakeCaseIntent(intent);
|
|
11454
|
-
const data = await this.apiPost("/api/intents", body);
|
|
11455
|
-
return {
|
|
11456
|
-
intentId: data.intent_id ?? data.intentId,
|
|
11457
|
-
message: data.message,
|
|
11458
|
-
expiresAt: data.expires_at ?? data.expiresAt
|
|
11459
|
-
};
|
|
11460
|
-
}
|
|
11461
|
-
/** Semantic search for intents (public — no auth required) */
|
|
11462
|
-
async search(query, opts) {
|
|
11463
|
-
const body = {
|
|
11464
|
-
query,
|
|
11465
|
-
...toSnakeCaseFilters(opts)
|
|
11466
|
-
};
|
|
11467
|
-
const data = await this.apiPublicPost("/api/search", body);
|
|
11468
|
-
let results = (data.intents ?? []).map(mapSearchResult);
|
|
11469
|
-
const minScore = opts?.filters?.minScore;
|
|
11470
|
-
if (minScore != null) {
|
|
11471
|
-
results = results.filter((r) => Math.round(r.score * 100) >= Math.round(minScore * 100));
|
|
11472
|
-
}
|
|
11473
|
-
return { intents: results, count: results.length };
|
|
11474
|
-
}
|
|
11475
|
-
/** List own intents (authenticated) */
|
|
11476
|
-
async getMyIntents() {
|
|
11477
|
-
const data = await this.apiGet("/api/intents");
|
|
11478
|
-
return (data.intents ?? []).map(mapMyIntent);
|
|
11479
|
-
}
|
|
11480
|
-
/** Close (delete) an intent */
|
|
11481
|
-
async closeIntent(intentId) {
|
|
11482
|
-
await this.apiDelete(`/api/intents/${encodeURIComponent(intentId)}`);
|
|
11483
|
-
}
|
|
11484
|
-
/** Fetch the most recent listings via REST (public — no auth required) */
|
|
11485
|
-
async getRecentListings() {
|
|
11486
|
-
const res = await fetch(`${this.apiUrl}/api/feed/recent`, {
|
|
11487
|
-
signal: AbortSignal.timeout(this.timeout)
|
|
11488
|
-
});
|
|
11489
|
-
const data = await this.parseResponse(res);
|
|
11490
|
-
return (data.listings ?? []).map(mapFeedListing);
|
|
11491
|
-
}
|
|
11492
|
-
/**
|
|
11493
|
-
* Subscribe to the live listing feed via WebSocket.
|
|
11494
|
-
* Returns an unsubscribe function that closes the connection.
|
|
11495
|
-
*
|
|
11496
|
-
* Requires a WebSocket implementation — works natively in browsers
|
|
11497
|
-
* and in Node.js 21+ (or with the `ws` package).
|
|
11498
|
-
*/
|
|
11499
|
-
subscribeFeed(listener) {
|
|
11500
|
-
const wsUrl = this.apiUrl.replace(/^http/, "ws") + "/ws/feed";
|
|
11501
|
-
const ws2 = new WebSocket(wsUrl);
|
|
11502
|
-
ws2.onmessage = (event) => {
|
|
11503
|
-
try {
|
|
11504
|
-
const raw = JSON.parse(typeof event.data === "string" ? event.data : event.data.toString());
|
|
11505
|
-
listener(mapFeedMessage(raw));
|
|
11506
|
-
} catch {
|
|
11507
|
-
}
|
|
11508
|
-
};
|
|
11509
|
-
return () => {
|
|
11510
|
-
ws2.close();
|
|
11511
|
-
};
|
|
11512
|
-
}
|
|
11513
|
-
// ---------------------------------------------------------------------------
|
|
11514
|
-
// Private: HTTP helpers
|
|
11515
|
-
// ---------------------------------------------------------------------------
|
|
11516
|
-
ensureIdentity() {
|
|
11517
|
-
if (!this.identity) {
|
|
11518
|
-
throw new Error("MarketModule not initialized \u2014 call initialize() first");
|
|
11519
|
-
}
|
|
11520
|
-
}
|
|
11521
|
-
/** Register the agent's public key with the server (idempotent) */
|
|
11522
|
-
async ensureRegistered() {
|
|
11523
|
-
if (this.registered) return;
|
|
11524
|
-
this.ensureIdentity();
|
|
11525
|
-
const publicKey = bytesToHex4(secp256k1.getPublicKey(hexToBytes3(this.identity.privateKey), true));
|
|
11526
|
-
const body = { public_key: publicKey };
|
|
11527
|
-
if (this.identity.nametag) body.nametag = this.identity.nametag;
|
|
11528
|
-
const res = await fetch(`${this.apiUrl}/api/agent/register`, {
|
|
11529
|
-
method: "POST",
|
|
11530
|
-
headers: { "content-type": "application/json" },
|
|
11531
|
-
body: JSON.stringify(body),
|
|
11532
|
-
signal: AbortSignal.timeout(this.timeout)
|
|
11533
|
-
});
|
|
11534
|
-
if (res.ok || res.status === 409) {
|
|
11535
|
-
this.registered = true;
|
|
11536
|
-
return;
|
|
11537
|
-
}
|
|
11538
|
-
const text = await res.text();
|
|
11539
|
-
let data;
|
|
11540
|
-
try {
|
|
11541
|
-
data = JSON.parse(text);
|
|
11542
|
-
} catch {
|
|
11543
|
-
}
|
|
11544
|
-
throw new Error(data?.error ?? `Agent registration failed: HTTP ${res.status}`);
|
|
11545
|
-
}
|
|
11546
|
-
async parseResponse(res) {
|
|
11547
|
-
const text = await res.text();
|
|
11548
|
-
let data;
|
|
11549
|
-
try {
|
|
11550
|
-
data = JSON.parse(text);
|
|
11551
|
-
} catch {
|
|
11552
|
-
throw new Error(`Market API error: HTTP ${res.status} \u2014 unexpected response (not JSON)`);
|
|
11553
|
-
}
|
|
11554
|
-
if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
|
|
11555
|
-
return data;
|
|
11556
|
-
}
|
|
11557
|
-
async apiPost(path, body) {
|
|
11558
|
-
this.ensureIdentity();
|
|
11559
|
-
await this.ensureRegistered();
|
|
11560
|
-
const signed = signRequest(body, this.identity.privateKey);
|
|
11561
|
-
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11562
|
-
method: "POST",
|
|
11563
|
-
headers: signed.headers,
|
|
11564
|
-
body: signed.body,
|
|
11565
|
-
signal: AbortSignal.timeout(this.timeout)
|
|
11566
|
-
});
|
|
11567
|
-
return this.parseResponse(res);
|
|
11568
|
-
}
|
|
11569
|
-
async apiGet(path) {
|
|
11570
|
-
this.ensureIdentity();
|
|
11571
|
-
await this.ensureRegistered();
|
|
11572
|
-
const signed = signRequest({}, this.identity.privateKey);
|
|
11573
|
-
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11574
|
-
method: "GET",
|
|
11575
|
-
headers: signed.headers,
|
|
11576
|
-
signal: AbortSignal.timeout(this.timeout)
|
|
11577
|
-
});
|
|
11578
|
-
return this.parseResponse(res);
|
|
11579
|
-
}
|
|
11580
|
-
async apiDelete(path) {
|
|
11581
|
-
this.ensureIdentity();
|
|
11582
|
-
await this.ensureRegistered();
|
|
11583
|
-
const signed = signRequest({}, this.identity.privateKey);
|
|
11584
|
-
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11585
|
-
method: "DELETE",
|
|
11586
|
-
headers: signed.headers,
|
|
11587
|
-
signal: AbortSignal.timeout(this.timeout)
|
|
11588
|
-
});
|
|
11589
|
-
return this.parseResponse(res);
|
|
11590
|
-
}
|
|
11591
|
-
async apiPublicPost(path, body) {
|
|
11592
|
-
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11593
|
-
method: "POST",
|
|
11594
|
-
headers: { "content-type": "application/json" },
|
|
11595
|
-
body: JSON.stringify(body),
|
|
11596
|
-
signal: AbortSignal.timeout(this.timeout)
|
|
11597
|
-
});
|
|
11598
|
-
return this.parseResponse(res);
|
|
11599
|
-
}
|
|
11600
|
-
};
|
|
11601
|
-
function createMarketModule(config) {
|
|
11602
|
-
return new MarketModule(config);
|
|
11603
|
-
}
|
|
11604
|
-
|
|
11605
9231
|
// core/encryption.ts
|
|
11606
9232
|
import CryptoJS6 from "crypto-js";
|
|
11607
9233
|
function encryptSimple(plaintext, password) {
|
|
@@ -12437,7 +10063,6 @@ var Sphere = class _Sphere {
|
|
|
12437
10063
|
_payments;
|
|
12438
10064
|
_communications;
|
|
12439
10065
|
_groupChat = null;
|
|
12440
|
-
_market = null;
|
|
12441
10066
|
// Events
|
|
12442
10067
|
eventHandlers = /* @__PURE__ */ new Map();
|
|
12443
10068
|
// Provider management
|
|
@@ -12447,7 +10072,7 @@ var Sphere = class _Sphere {
|
|
|
12447
10072
|
// ===========================================================================
|
|
12448
10073
|
// Constructor (private)
|
|
12449
10074
|
// ===========================================================================
|
|
12450
|
-
constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig
|
|
10075
|
+
constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig) {
|
|
12451
10076
|
this._storage = storage;
|
|
12452
10077
|
this._transport = transport;
|
|
12453
10078
|
this._oracle = oracle;
|
|
@@ -12458,7 +10083,6 @@ var Sphere = class _Sphere {
|
|
|
12458
10083
|
this._payments = createPaymentsModule({ l1: l1Config });
|
|
12459
10084
|
this._communications = createCommunicationsModule();
|
|
12460
10085
|
this._groupChat = groupChatConfig ? createGroupChatModule(groupChatConfig) : null;
|
|
12461
|
-
this._market = marketConfig ? createMarketModule(marketConfig) : null;
|
|
12462
10086
|
}
|
|
12463
10087
|
// ===========================================================================
|
|
12464
10088
|
// Static Methods - Wallet Management
|
|
@@ -12506,8 +10130,8 @@ var Sphere = class _Sphere {
|
|
|
12506
10130
|
* ```
|
|
12507
10131
|
*/
|
|
12508
10132
|
static async init(options) {
|
|
10133
|
+
_Sphere.configureTokenRegistry(options.storage, options.network);
|
|
12509
10134
|
const groupChat = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
|
|
12510
|
-
const market = _Sphere.resolveMarketConfig(options.market);
|
|
12511
10135
|
const walletExists = await _Sphere.exists(options.storage);
|
|
12512
10136
|
if (walletExists) {
|
|
12513
10137
|
const sphere2 = await _Sphere.load({
|
|
@@ -12518,8 +10142,7 @@ var Sphere = class _Sphere {
|
|
|
12518
10142
|
l1: options.l1,
|
|
12519
10143
|
price: options.price,
|
|
12520
10144
|
groupChat,
|
|
12521
|
-
password: options.password
|
|
12522
|
-
market
|
|
10145
|
+
password: options.password
|
|
12523
10146
|
});
|
|
12524
10147
|
return { sphere: sphere2, created: false };
|
|
12525
10148
|
}
|
|
@@ -12546,8 +10169,7 @@ var Sphere = class _Sphere {
|
|
|
12546
10169
|
l1: options.l1,
|
|
12547
10170
|
price: options.price,
|
|
12548
10171
|
groupChat,
|
|
12549
|
-
password: options.password
|
|
12550
|
-
market
|
|
10172
|
+
password: options.password
|
|
12551
10173
|
});
|
|
12552
10174
|
return { sphere, created: true, generatedMnemonic };
|
|
12553
10175
|
}
|
|
@@ -12575,20 +10197,17 @@ var Sphere = class _Sphere {
|
|
|
12575
10197
|
return config;
|
|
12576
10198
|
}
|
|
12577
10199
|
/**
|
|
12578
|
-
*
|
|
12579
|
-
*
|
|
12580
|
-
*
|
|
12581
|
-
*
|
|
10200
|
+
* Configure TokenRegistry in the main bundle context.
|
|
10201
|
+
*
|
|
10202
|
+
* The provider factory functions (createBrowserProviders / createNodeProviders)
|
|
10203
|
+
* are compiled into separate bundles by tsup, each with their own inlined copy
|
|
10204
|
+
* of TokenRegistry. Their TokenRegistry.configure() call configures a different
|
|
10205
|
+
* singleton than the one used by PaymentsModule (which lives in the main bundle).
|
|
10206
|
+
* This method ensures the main bundle's TokenRegistry is properly configured.
|
|
12582
10207
|
*/
|
|
12583
|
-
static
|
|
12584
|
-
|
|
12585
|
-
|
|
12586
|
-
return { apiUrl: DEFAULT_MARKET_API_URL };
|
|
12587
|
-
}
|
|
12588
|
-
return {
|
|
12589
|
-
apiUrl: config.apiUrl ?? DEFAULT_MARKET_API_URL,
|
|
12590
|
-
timeout: config.timeout
|
|
12591
|
-
};
|
|
10208
|
+
static configureTokenRegistry(storage, network) {
|
|
10209
|
+
const netConfig = network ? NETWORKS[network] : NETWORKS.testnet;
|
|
10210
|
+
TokenRegistry.configure({ remoteUrl: netConfig.tokenRegistryUrl, storage });
|
|
12592
10211
|
}
|
|
12593
10212
|
/**
|
|
12594
10213
|
* Create new wallet with mnemonic
|
|
@@ -12600,8 +10219,8 @@ var Sphere = class _Sphere {
|
|
|
12600
10219
|
if (await _Sphere.exists(options.storage)) {
|
|
12601
10220
|
throw new Error("Wallet already exists. Use Sphere.load() or Sphere.clear() first.");
|
|
12602
10221
|
}
|
|
10222
|
+
_Sphere.configureTokenRegistry(options.storage, options.network);
|
|
12603
10223
|
const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
|
|
12604
|
-
const marketConfig = _Sphere.resolveMarketConfig(options.market);
|
|
12605
10224
|
const sphere = new _Sphere(
|
|
12606
10225
|
options.storage,
|
|
12607
10226
|
options.transport,
|
|
@@ -12609,8 +10228,7 @@ var Sphere = class _Sphere {
|
|
|
12609
10228
|
options.tokenStorage,
|
|
12610
10229
|
options.l1,
|
|
12611
10230
|
options.price,
|
|
12612
|
-
groupChatConfig
|
|
12613
|
-
marketConfig
|
|
10231
|
+
groupChatConfig
|
|
12614
10232
|
);
|
|
12615
10233
|
sphere._password = options.password ?? null;
|
|
12616
10234
|
await sphere.storeMnemonic(options.mnemonic, options.derivationPath);
|
|
@@ -12636,8 +10254,8 @@ var Sphere = class _Sphere {
|
|
|
12636
10254
|
if (!await _Sphere.exists(options.storage)) {
|
|
12637
10255
|
throw new Error("No wallet found. Use Sphere.create() to create a new wallet.");
|
|
12638
10256
|
}
|
|
10257
|
+
_Sphere.configureTokenRegistry(options.storage, options.network);
|
|
12639
10258
|
const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
|
|
12640
|
-
const marketConfig = _Sphere.resolveMarketConfig(options.market);
|
|
12641
10259
|
const sphere = new _Sphere(
|
|
12642
10260
|
options.storage,
|
|
12643
10261
|
options.transport,
|
|
@@ -12645,8 +10263,7 @@ var Sphere = class _Sphere {
|
|
|
12645
10263
|
options.tokenStorage,
|
|
12646
10264
|
options.l1,
|
|
12647
10265
|
options.price,
|
|
12648
|
-
groupChatConfig
|
|
12649
|
-
marketConfig
|
|
10266
|
+
groupChatConfig
|
|
12650
10267
|
);
|
|
12651
10268
|
sphere._password = options.password ?? null;
|
|
12652
10269
|
await sphere.loadIdentityFromStorage();
|
|
@@ -12692,7 +10309,6 @@ var Sphere = class _Sphere {
|
|
|
12692
10309
|
console.log("[Sphere.import] Storage reconnected");
|
|
12693
10310
|
}
|
|
12694
10311
|
const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat);
|
|
12695
|
-
const marketConfig = _Sphere.resolveMarketConfig(options.market);
|
|
12696
10312
|
const sphere = new _Sphere(
|
|
12697
10313
|
options.storage,
|
|
12698
10314
|
options.transport,
|
|
@@ -12700,8 +10316,7 @@ var Sphere = class _Sphere {
|
|
|
12700
10316
|
options.tokenStorage,
|
|
12701
10317
|
options.l1,
|
|
12702
10318
|
options.price,
|
|
12703
|
-
groupChatConfig
|
|
12704
|
-
marketConfig
|
|
10319
|
+
groupChatConfig
|
|
12705
10320
|
);
|
|
12706
10321
|
sphere._password = options.password ?? null;
|
|
12707
10322
|
if (options.mnemonic) {
|
|
@@ -12866,10 +10481,6 @@ var Sphere = class _Sphere {
|
|
|
12866
10481
|
get groupChat() {
|
|
12867
10482
|
return this._groupChat;
|
|
12868
10483
|
}
|
|
12869
|
-
/** Market module (intent bulletin board). Null if not configured. */
|
|
12870
|
-
get market() {
|
|
12871
|
-
return this._market;
|
|
12872
|
-
}
|
|
12873
10484
|
// ===========================================================================
|
|
12874
10485
|
// Public Properties - State
|
|
12875
10486
|
// ===========================================================================
|
|
@@ -13745,14 +11356,9 @@ var Sphere = class _Sphere {
|
|
|
13745
11356
|
storage: this._storage,
|
|
13746
11357
|
emitEvent
|
|
13747
11358
|
});
|
|
13748
|
-
this._market?.initialize({
|
|
13749
|
-
identity: this._identity,
|
|
13750
|
-
emitEvent
|
|
13751
|
-
});
|
|
13752
11359
|
await this._payments.load();
|
|
13753
11360
|
await this._communications.load();
|
|
13754
11361
|
await this._groupChat?.load();
|
|
13755
|
-
await this._market?.load();
|
|
13756
11362
|
}
|
|
13757
11363
|
/**
|
|
13758
11364
|
* Derive address at a specific index
|
|
@@ -14453,22 +12059,12 @@ var Sphere = class _Sphere {
|
|
|
14453
12059
|
return;
|
|
14454
12060
|
}
|
|
14455
12061
|
try {
|
|
14456
|
-
|
|
14457
|
-
if (transportPubkey && this._transport.resolve) {
|
|
12062
|
+
if (this._identity?.directAddress && this._transport.resolve) {
|
|
14458
12063
|
try {
|
|
14459
|
-
const existing = await this._transport.resolve(
|
|
12064
|
+
const existing = await this._transport.resolve(this._identity.directAddress);
|
|
14460
12065
|
if (existing) {
|
|
14461
|
-
|
|
14462
|
-
|
|
14463
|
-
if (!recoveredNametag && !this._identity?.nametag && this._transport.recoverNametag) {
|
|
14464
|
-
try {
|
|
14465
|
-
recoveredNametag = await this._transport.recoverNametag() ?? void 0;
|
|
14466
|
-
if (recoveredNametag) fromLegacy = true;
|
|
14467
|
-
} catch {
|
|
14468
|
-
}
|
|
14469
|
-
}
|
|
14470
|
-
if (recoveredNametag && !this._identity?.nametag) {
|
|
14471
|
-
this._identity.nametag = recoveredNametag;
|
|
12066
|
+
if (existing.nametag && !this._identity.nametag) {
|
|
12067
|
+
this._identity.nametag = existing.nametag;
|
|
14472
12068
|
await this._updateCachedProxyAddress();
|
|
14473
12069
|
const entry = await this.ensureAddressTracked(this._currentAddressIndex);
|
|
14474
12070
|
let nametags = this._addressNametags.get(entry.addressId);
|
|
@@ -14477,20 +12073,10 @@ var Sphere = class _Sphere {
|
|
|
14477
12073
|
this._addressNametags.set(entry.addressId, nametags);
|
|
14478
12074
|
}
|
|
14479
12075
|
if (!nametags.has(0)) {
|
|
14480
|
-
nametags.set(0,
|
|
12076
|
+
nametags.set(0, existing.nametag);
|
|
14481
12077
|
await this.persistAddressNametags();
|
|
14482
12078
|
}
|
|
14483
|
-
this.emitEvent("nametag:recovered", { nametag:
|
|
14484
|
-
if (fromLegacy) {
|
|
14485
|
-
await this._transport.publishIdentityBinding(
|
|
14486
|
-
this._identity.chainPubkey,
|
|
14487
|
-
this._identity.l1Address,
|
|
14488
|
-
this._identity.directAddress || "",
|
|
14489
|
-
recoveredNametag
|
|
14490
|
-
);
|
|
14491
|
-
console.log(`[Sphere] Migrated legacy binding with nametag @${recoveredNametag}`);
|
|
14492
|
-
return;
|
|
14493
|
-
}
|
|
12079
|
+
this.emitEvent("nametag:recovered", { nametag: existing.nametag });
|
|
14494
12080
|
}
|
|
14495
12081
|
console.log("[Sphere] Existing binding found, skipping re-publish");
|
|
14496
12082
|
return;
|
|
@@ -14577,7 +12163,6 @@ var Sphere = class _Sphere {
|
|
|
14577
12163
|
this._payments.destroy();
|
|
14578
12164
|
this._communications.destroy();
|
|
14579
12165
|
this._groupChat?.destroy();
|
|
14580
|
-
this._market?.destroy();
|
|
14581
12166
|
await this._transport.disconnect();
|
|
14582
12167
|
await this._storage.disconnect();
|
|
14583
12168
|
await this._oracle.disconnect();
|
|
@@ -14885,14 +12470,9 @@ var Sphere = class _Sphere {
|
|
|
14885
12470
|
storage: this._storage,
|
|
14886
12471
|
emitEvent
|
|
14887
12472
|
});
|
|
14888
|
-
this._market?.initialize({
|
|
14889
|
-
identity: this._identity,
|
|
14890
|
-
emitEvent
|
|
14891
|
-
});
|
|
14892
12473
|
await this._payments.load();
|
|
14893
12474
|
await this._communications.load();
|
|
14894
12475
|
await this._groupChat?.load();
|
|
14895
|
-
await this._market?.load();
|
|
14896
12476
|
}
|
|
14897
12477
|
// ===========================================================================
|
|
14898
12478
|
// Private: Helpers
|
|
@@ -15077,7 +12657,7 @@ async function checkWebSocket(url, timeoutMs) {
|
|
|
15077
12657
|
resolve({ healthy: true, url, responseTimeMs });
|
|
15078
12658
|
}
|
|
15079
12659
|
};
|
|
15080
|
-
ws2.onerror = (
|
|
12660
|
+
ws2.onerror = (_event) => {
|
|
15081
12661
|
if (!resolved) {
|
|
15082
12662
|
resolved = true;
|
|
15083
12663
|
clearTimeout(timer);
|
|
@@ -15577,26 +13157,37 @@ var CoinGeckoPriceProvider = class {
|
|
|
15577
13157
|
timeout;
|
|
15578
13158
|
debug;
|
|
15579
13159
|
baseUrl;
|
|
13160
|
+
storage;
|
|
13161
|
+
/** In-flight fetch promise for deduplication of concurrent getPrices() calls */
|
|
13162
|
+
fetchPromise = null;
|
|
13163
|
+
/** Token names being fetched in the current in-flight request */
|
|
13164
|
+
fetchNames = null;
|
|
13165
|
+
/** Whether persistent cache has been loaded into memory */
|
|
13166
|
+
persistentCacheLoaded = false;
|
|
13167
|
+
/** Promise for loading persistent cache (deduplication) */
|
|
13168
|
+
loadCachePromise = null;
|
|
15580
13169
|
constructor(config) {
|
|
15581
13170
|
this.apiKey = config?.apiKey;
|
|
15582
13171
|
this.cacheTtlMs = config?.cacheTtlMs ?? 6e4;
|
|
15583
13172
|
this.timeout = config?.timeout ?? 1e4;
|
|
15584
13173
|
this.debug = config?.debug ?? false;
|
|
13174
|
+
this.storage = config?.storage ?? null;
|
|
15585
13175
|
this.baseUrl = config?.baseUrl ?? (this.apiKey ? "https://pro-api.coingecko.com/api/v3" : "https://api.coingecko.com/api/v3");
|
|
15586
13176
|
}
|
|
15587
13177
|
async getPrices(tokenNames) {
|
|
15588
13178
|
if (tokenNames.length === 0) {
|
|
15589
13179
|
return /* @__PURE__ */ new Map();
|
|
15590
13180
|
}
|
|
13181
|
+
if (!this.persistentCacheLoaded && this.storage) {
|
|
13182
|
+
await this.loadFromStorage();
|
|
13183
|
+
}
|
|
15591
13184
|
const now = Date.now();
|
|
15592
13185
|
const result = /* @__PURE__ */ new Map();
|
|
15593
13186
|
const uncachedNames = [];
|
|
15594
13187
|
for (const name of tokenNames) {
|
|
15595
13188
|
const cached = this.cache.get(name);
|
|
15596
13189
|
if (cached && cached.expiresAt > now) {
|
|
15597
|
-
|
|
15598
|
-
result.set(name, cached.price);
|
|
15599
|
-
}
|
|
13190
|
+
result.set(name, cached.price);
|
|
15600
13191
|
} else {
|
|
15601
13192
|
uncachedNames.push(name);
|
|
15602
13193
|
}
|
|
@@ -15604,6 +13195,41 @@ var CoinGeckoPriceProvider = class {
|
|
|
15604
13195
|
if (uncachedNames.length === 0) {
|
|
15605
13196
|
return result;
|
|
15606
13197
|
}
|
|
13198
|
+
if (this.fetchPromise && this.fetchNames) {
|
|
13199
|
+
const allCovered = uncachedNames.every((n) => this.fetchNames.has(n));
|
|
13200
|
+
if (allCovered) {
|
|
13201
|
+
if (this.debug) {
|
|
13202
|
+
console.log(`[CoinGecko] Deduplicating request, reusing in-flight fetch`);
|
|
13203
|
+
}
|
|
13204
|
+
const fetched = await this.fetchPromise;
|
|
13205
|
+
for (const name of uncachedNames) {
|
|
13206
|
+
const price = fetched.get(name);
|
|
13207
|
+
if (price) {
|
|
13208
|
+
result.set(name, price);
|
|
13209
|
+
}
|
|
13210
|
+
}
|
|
13211
|
+
return result;
|
|
13212
|
+
}
|
|
13213
|
+
}
|
|
13214
|
+
const fetchPromise = this.doFetch(uncachedNames);
|
|
13215
|
+
this.fetchPromise = fetchPromise;
|
|
13216
|
+
this.fetchNames = new Set(uncachedNames);
|
|
13217
|
+
try {
|
|
13218
|
+
const fetched = await fetchPromise;
|
|
13219
|
+
for (const [name, price] of fetched) {
|
|
13220
|
+
result.set(name, price);
|
|
13221
|
+
}
|
|
13222
|
+
} finally {
|
|
13223
|
+
if (this.fetchPromise === fetchPromise) {
|
|
13224
|
+
this.fetchPromise = null;
|
|
13225
|
+
this.fetchNames = null;
|
|
13226
|
+
}
|
|
13227
|
+
}
|
|
13228
|
+
return result;
|
|
13229
|
+
}
|
|
13230
|
+
async doFetch(uncachedNames) {
|
|
13231
|
+
const result = /* @__PURE__ */ new Map();
|
|
13232
|
+
const now = Date.now();
|
|
15607
13233
|
try {
|
|
15608
13234
|
const ids = uncachedNames.join(",");
|
|
15609
13235
|
const url = `${this.baseUrl}/simple/price?ids=${encodeURIComponent(ids)}&vs_currencies=usd,eur&include_24hr_change=true`;
|
|
@@ -15619,6 +13245,9 @@ var CoinGeckoPriceProvider = class {
|
|
|
15619
13245
|
signal: AbortSignal.timeout(this.timeout)
|
|
15620
13246
|
});
|
|
15621
13247
|
if (!response.ok) {
|
|
13248
|
+
if (response.status === 429) {
|
|
13249
|
+
this.extendCacheOnRateLimit(uncachedNames);
|
|
13250
|
+
}
|
|
15622
13251
|
throw new Error(`CoinGecko API error: ${response.status} ${response.statusText}`);
|
|
15623
13252
|
}
|
|
15624
13253
|
const data = await response.json();
|
|
@@ -15637,25 +13266,113 @@ var CoinGeckoPriceProvider = class {
|
|
|
15637
13266
|
}
|
|
15638
13267
|
for (const name of uncachedNames) {
|
|
15639
13268
|
if (!result.has(name)) {
|
|
15640
|
-
|
|
13269
|
+
const zeroPrice = {
|
|
13270
|
+
tokenName: name,
|
|
13271
|
+
priceUsd: 0,
|
|
13272
|
+
priceEur: 0,
|
|
13273
|
+
change24h: 0,
|
|
13274
|
+
timestamp: now
|
|
13275
|
+
};
|
|
13276
|
+
this.cache.set(name, { price: zeroPrice, expiresAt: now + this.cacheTtlMs });
|
|
13277
|
+
result.set(name, zeroPrice);
|
|
15641
13278
|
}
|
|
15642
13279
|
}
|
|
15643
13280
|
if (this.debug) {
|
|
15644
13281
|
console.log(`[CoinGecko] Fetched ${result.size} prices`);
|
|
15645
13282
|
}
|
|
13283
|
+
this.saveToStorage();
|
|
15646
13284
|
} catch (error) {
|
|
15647
13285
|
if (this.debug) {
|
|
15648
13286
|
console.warn("[CoinGecko] Fetch failed, using stale cache:", error);
|
|
15649
13287
|
}
|
|
15650
13288
|
for (const name of uncachedNames) {
|
|
15651
13289
|
const stale = this.cache.get(name);
|
|
15652
|
-
if (stale
|
|
13290
|
+
if (stale) {
|
|
15653
13291
|
result.set(name, stale.price);
|
|
15654
13292
|
}
|
|
15655
13293
|
}
|
|
15656
13294
|
}
|
|
15657
13295
|
return result;
|
|
15658
13296
|
}
|
|
13297
|
+
// ===========================================================================
|
|
13298
|
+
// Persistent Storage
|
|
13299
|
+
// ===========================================================================
|
|
13300
|
+
/**
|
|
13301
|
+
* Load cached prices from StorageProvider into in-memory cache.
|
|
13302
|
+
* Only loads entries that are still within cacheTtlMs.
|
|
13303
|
+
*/
|
|
13304
|
+
async loadFromStorage() {
|
|
13305
|
+
if (this.loadCachePromise) {
|
|
13306
|
+
return this.loadCachePromise;
|
|
13307
|
+
}
|
|
13308
|
+
this.loadCachePromise = this.doLoadFromStorage();
|
|
13309
|
+
try {
|
|
13310
|
+
await this.loadCachePromise;
|
|
13311
|
+
} finally {
|
|
13312
|
+
this.loadCachePromise = null;
|
|
13313
|
+
}
|
|
13314
|
+
}
|
|
13315
|
+
async doLoadFromStorage() {
|
|
13316
|
+
this.persistentCacheLoaded = true;
|
|
13317
|
+
if (!this.storage) return;
|
|
13318
|
+
try {
|
|
13319
|
+
const [cached, cachedTs] = await Promise.all([
|
|
13320
|
+
this.storage.get(STORAGE_KEYS_GLOBAL.PRICE_CACHE),
|
|
13321
|
+
this.storage.get(STORAGE_KEYS_GLOBAL.PRICE_CACHE_TS)
|
|
13322
|
+
]);
|
|
13323
|
+
if (!cached || !cachedTs) return;
|
|
13324
|
+
const ts = parseInt(cachedTs, 10);
|
|
13325
|
+
if (isNaN(ts)) return;
|
|
13326
|
+
const age = Date.now() - ts;
|
|
13327
|
+
if (age > this.cacheTtlMs) return;
|
|
13328
|
+
const data = JSON.parse(cached);
|
|
13329
|
+
const expiresAt = ts + this.cacheTtlMs;
|
|
13330
|
+
for (const [name, price] of Object.entries(data)) {
|
|
13331
|
+
if (!this.cache.has(name)) {
|
|
13332
|
+
this.cache.set(name, { price, expiresAt });
|
|
13333
|
+
}
|
|
13334
|
+
}
|
|
13335
|
+
if (this.debug) {
|
|
13336
|
+
console.log(`[CoinGecko] Loaded ${Object.keys(data).length} prices from persistent cache`);
|
|
13337
|
+
}
|
|
13338
|
+
} catch {
|
|
13339
|
+
}
|
|
13340
|
+
}
|
|
13341
|
+
/**
|
|
13342
|
+
* Save current prices to StorageProvider (fire-and-forget).
|
|
13343
|
+
*/
|
|
13344
|
+
saveToStorage() {
|
|
13345
|
+
if (!this.storage) return;
|
|
13346
|
+
const data = {};
|
|
13347
|
+
for (const [name, entry] of this.cache) {
|
|
13348
|
+
data[name] = entry.price;
|
|
13349
|
+
}
|
|
13350
|
+
Promise.all([
|
|
13351
|
+
this.storage.set(STORAGE_KEYS_GLOBAL.PRICE_CACHE, JSON.stringify(data)),
|
|
13352
|
+
this.storage.set(STORAGE_KEYS_GLOBAL.PRICE_CACHE_TS, String(Date.now()))
|
|
13353
|
+
]).catch(() => {
|
|
13354
|
+
});
|
|
13355
|
+
}
|
|
13356
|
+
// ===========================================================================
|
|
13357
|
+
// Rate-limit handling
|
|
13358
|
+
// ===========================================================================
|
|
13359
|
+
/**
|
|
13360
|
+
* On 429 rate-limit, extend stale cache entries so subsequent calls
|
|
13361
|
+
* don't immediately retry and hammer the API.
|
|
13362
|
+
*/
|
|
13363
|
+
extendCacheOnRateLimit(names) {
|
|
13364
|
+
const backoffMs = 6e4;
|
|
13365
|
+
const extendedExpiry = Date.now() + backoffMs;
|
|
13366
|
+
for (const name of names) {
|
|
13367
|
+
const existing = this.cache.get(name);
|
|
13368
|
+
if (existing) {
|
|
13369
|
+
existing.expiresAt = Math.max(existing.expiresAt, extendedExpiry);
|
|
13370
|
+
}
|
|
13371
|
+
}
|
|
13372
|
+
if (this.debug) {
|
|
13373
|
+
console.warn(`[CoinGecko] Rate-limited (429), extended cache TTL by ${backoffMs / 1e3}s`);
|
|
13374
|
+
}
|
|
13375
|
+
}
|
|
15659
13376
|
async getPrice(tokenName) {
|
|
15660
13377
|
const prices = await this.getPrices([tokenName]);
|
|
15661
13378
|
return prices.get(tokenName) ?? null;
|
|
@@ -15685,7 +13402,6 @@ export {
|
|
|
15685
13402
|
DEFAULT_GROUP_RELAYS,
|
|
15686
13403
|
DEFAULT_IPFS_BOOTSTRAP_PEERS,
|
|
15687
13404
|
DEFAULT_IPFS_GATEWAYS,
|
|
15688
|
-
DEFAULT_MARKET_API_URL,
|
|
15689
13405
|
DEFAULT_NOSTR_RELAYS,
|
|
15690
13406
|
DEV_AGGREGATOR_URL,
|
|
15691
13407
|
GroupChatModule,
|
|
@@ -15694,7 +13410,6 @@ export {
|
|
|
15694
13410
|
l1_exports as L1,
|
|
15695
13411
|
L1PaymentsModule,
|
|
15696
13412
|
LIMITS,
|
|
15697
|
-
MarketModule,
|
|
15698
13413
|
NETWORKS,
|
|
15699
13414
|
NIP29_KINDS,
|
|
15700
13415
|
NOSTR_EVENT_KINDS,
|
|
@@ -15722,7 +13437,6 @@ export {
|
|
|
15722
13437
|
createGroupChatModule,
|
|
15723
13438
|
createKeyPair,
|
|
15724
13439
|
createL1PaymentsModule,
|
|
15725
|
-
createMarketModule,
|
|
15726
13440
|
createPaymentSession,
|
|
15727
13441
|
createPaymentSessionError,
|
|
15728
13442
|
createPaymentsModule,
|
|
@@ -15810,16 +13524,4 @@ export {
|
|
|
15810
13524
|
txfToToken,
|
|
15811
13525
|
validateMnemonic2 as validateMnemonic
|
|
15812
13526
|
};
|
|
15813
|
-
/*! Bundled license information:
|
|
15814
|
-
|
|
15815
|
-
@noble/hashes/utils.js:
|
|
15816
|
-
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
15817
|
-
|
|
15818
|
-
@noble/curves/utils.js:
|
|
15819
|
-
@noble/curves/abstract/modular.js:
|
|
15820
|
-
@noble/curves/abstract/curve.js:
|
|
15821
|
-
@noble/curves/abstract/weierstrass.js:
|
|
15822
|
-
@noble/curves/secp256k1.js:
|
|
15823
|
-
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
15824
|
-
*/
|
|
15825
13527
|
//# sourceMappingURL=index.js.map
|