@unicitylabs/sphere-sdk 0.3.7 → 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 +97 -2589
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +11 -222
- package/dist/core/index.d.ts +11 -222
- package/dist/core/index.js +93 -2585
- package/dist/core/index.js.map +1 -1
- package/dist/impl/browser/index.cjs +233 -195
- package/dist/impl/browser/index.cjs.map +1 -1
- package/dist/impl/browser/index.js +234 -198
- 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 +205 -142
- package/dist/impl/nodejs/index.cjs.map +1 -1
- package/dist/impl/nodejs/index.d.cts +2 -70
- package/dist/impl/nodejs/index.d.ts +2 -70
- package/dist/impl/nodejs/index.js +206 -145
- package/dist/impl/nodejs/index.js.map +1 -1
- package/dist/index.cjs +239 -2600
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +60 -226
- package/dist/index.d.ts +60 -226
- package/dist/index.js +235 -2593
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/core/index.cjs
CHANGED
|
@@ -20,15 +20,15 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
20
20
|
}
|
|
21
21
|
return to;
|
|
22
22
|
};
|
|
23
|
-
var __toESM = (
|
|
23
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
24
24
|
// If the importer is in node compatibility mode or this is not an ESM
|
|
25
25
|
// file that has been converted to a CommonJS file using a Babel-
|
|
26
26
|
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
27
27
|
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
28
|
-
isNodeMode || !
|
|
29
|
-
|
|
28
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
29
|
+
mod
|
|
30
30
|
));
|
|
31
|
-
var __toCommonJS = (
|
|
31
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
32
32
|
|
|
33
33
|
// core/bech32.ts
|
|
34
34
|
function convertBits(data, fromBits, toBits, pad) {
|
|
@@ -75,10 +75,10 @@ function bech32Polymod(values) {
|
|
|
75
75
|
}
|
|
76
76
|
function bech32Checksum(hrp, data) {
|
|
77
77
|
const values = hrpExpand(hrp).concat(data).concat([0, 0, 0, 0, 0, 0]);
|
|
78
|
-
const
|
|
78
|
+
const mod = bech32Polymod(values) ^ 1;
|
|
79
79
|
const ret = [];
|
|
80
80
|
for (let p = 0; p < 6; p++) {
|
|
81
|
-
ret.push(
|
|
81
|
+
ret.push(mod >> 5 * (5 - p) & 31);
|
|
82
82
|
}
|
|
83
83
|
return ret;
|
|
84
84
|
}
|
|
@@ -2433,7 +2433,11 @@ var STORAGE_KEYS_GLOBAL = {
|
|
|
2433
2433
|
/** Cached token registry JSON (fetched from remote) */
|
|
2434
2434
|
TOKEN_REGISTRY_CACHE: "token_registry_cache",
|
|
2435
2435
|
/** Timestamp of last token registry cache update (ms since epoch) */
|
|
2436
|
-
TOKEN_REGISTRY_CACHE_TS: "token_registry_cache_ts"
|
|
2436
|
+
TOKEN_REGISTRY_CACHE_TS: "token_registry_cache_ts",
|
|
2437
|
+
/** Cached price data JSON (from CoinGecko or other provider) */
|
|
2438
|
+
PRICE_CACHE: "price_cache",
|
|
2439
|
+
/** Timestamp of last price cache update (ms since epoch) */
|
|
2440
|
+
PRICE_CACHE_TS: "price_cache_ts"
|
|
2437
2441
|
};
|
|
2438
2442
|
var STORAGE_KEYS_ADDRESS = {
|
|
2439
2443
|
/** Pending transfers for this address */
|
|
@@ -2551,7 +2555,6 @@ var NETWORKS = {
|
|
|
2551
2555
|
tokenRegistryUrl: TOKEN_REGISTRY_URL
|
|
2552
2556
|
}
|
|
2553
2557
|
};
|
|
2554
|
-
var DEFAULT_MARKET_API_URL = "https://market-api.unicity.network";
|
|
2555
2558
|
|
|
2556
2559
|
// types/txf.ts
|
|
2557
2560
|
var ARCHIVED_PREFIX = "archived-";
|
|
@@ -2606,6 +2609,7 @@ var TokenRegistry = class _TokenRegistry {
|
|
|
2606
2609
|
refreshTimer = null;
|
|
2607
2610
|
lastRefreshAt = 0;
|
|
2608
2611
|
refreshPromise = null;
|
|
2612
|
+
initialLoadPromise = null;
|
|
2609
2613
|
constructor() {
|
|
2610
2614
|
this.definitionsById = /* @__PURE__ */ new Map();
|
|
2611
2615
|
this.definitionsBySymbol = /* @__PURE__ */ new Map();
|
|
@@ -2644,13 +2648,8 @@ var TokenRegistry = class _TokenRegistry {
|
|
|
2644
2648
|
if (options.refreshIntervalMs !== void 0) {
|
|
2645
2649
|
instance.refreshIntervalMs = options.refreshIntervalMs;
|
|
2646
2650
|
}
|
|
2647
|
-
if (instance.storage) {
|
|
2648
|
-
instance.loadFromCache();
|
|
2649
|
-
}
|
|
2650
2651
|
const autoRefresh = options.autoRefresh ?? true;
|
|
2651
|
-
|
|
2652
|
-
instance.startAutoRefresh();
|
|
2653
|
-
}
|
|
2652
|
+
instance.initialLoadPromise = instance.performInitialLoad(autoRefresh);
|
|
2654
2653
|
}
|
|
2655
2654
|
/**
|
|
2656
2655
|
* Reset the singleton instance (useful for testing).
|
|
@@ -2668,6 +2667,53 @@ var TokenRegistry = class _TokenRegistry {
|
|
|
2668
2667
|
static destroy() {
|
|
2669
2668
|
_TokenRegistry.resetInstance();
|
|
2670
2669
|
}
|
|
2670
|
+
/**
|
|
2671
|
+
* Wait for the initial data load (cache or remote) to complete.
|
|
2672
|
+
* Returns true if data was loaded, false if not (timeout or no data source).
|
|
2673
|
+
*
|
|
2674
|
+
* @param timeoutMs - Maximum wait time in ms (default: 10s). Set to 0 for no timeout.
|
|
2675
|
+
*/
|
|
2676
|
+
static async waitForReady(timeoutMs = 1e4) {
|
|
2677
|
+
const instance = _TokenRegistry.getInstance();
|
|
2678
|
+
if (!instance.initialLoadPromise) {
|
|
2679
|
+
return instance.definitionsById.size > 0;
|
|
2680
|
+
}
|
|
2681
|
+
if (timeoutMs <= 0) {
|
|
2682
|
+
return instance.initialLoadPromise;
|
|
2683
|
+
}
|
|
2684
|
+
return Promise.race([
|
|
2685
|
+
instance.initialLoadPromise,
|
|
2686
|
+
new Promise((resolve) => setTimeout(() => resolve(false), timeoutMs))
|
|
2687
|
+
]);
|
|
2688
|
+
}
|
|
2689
|
+
// ===========================================================================
|
|
2690
|
+
// Initial Load
|
|
2691
|
+
// ===========================================================================
|
|
2692
|
+
/**
|
|
2693
|
+
* Perform initial data load: try cache first, fall back to remote fetch.
|
|
2694
|
+
* After initial data is available, start periodic auto-refresh if configured.
|
|
2695
|
+
*/
|
|
2696
|
+
async performInitialLoad(autoRefresh) {
|
|
2697
|
+
let loaded = false;
|
|
2698
|
+
if (this.storage) {
|
|
2699
|
+
loaded = await this.loadFromCache();
|
|
2700
|
+
}
|
|
2701
|
+
if (loaded) {
|
|
2702
|
+
if (autoRefresh && this.remoteUrl) {
|
|
2703
|
+
this.startAutoRefresh();
|
|
2704
|
+
}
|
|
2705
|
+
return true;
|
|
2706
|
+
}
|
|
2707
|
+
if (autoRefresh && this.remoteUrl) {
|
|
2708
|
+
loaded = await this.refreshFromRemote();
|
|
2709
|
+
this.stopAutoRefresh();
|
|
2710
|
+
this.refreshTimer = setInterval(() => {
|
|
2711
|
+
this.refreshFromRemote();
|
|
2712
|
+
}, this.refreshIntervalMs);
|
|
2713
|
+
return loaded;
|
|
2714
|
+
}
|
|
2715
|
+
return false;
|
|
2716
|
+
}
|
|
2671
2717
|
// ===========================================================================
|
|
2672
2718
|
// Cache (StorageProvider)
|
|
2673
2719
|
// ===========================================================================
|
|
@@ -3725,7 +3771,7 @@ var InstantSplitProcessor = class {
|
|
|
3725
3771
|
console.warn("[InstantSplitProcessor] Sender pubkey mismatch (non-fatal)");
|
|
3726
3772
|
}
|
|
3727
3773
|
const burnTxJson = JSON.parse(bundle.burnTransaction);
|
|
3728
|
-
const
|
|
3774
|
+
const _burnTransaction = await import_TransferTransaction.TransferTransaction.fromJSON(burnTxJson);
|
|
3729
3775
|
console.log("[InstantSplitProcessor] Burn transaction validated");
|
|
3730
3776
|
const mintDataJson = JSON.parse(bundle.recipientMintData);
|
|
3731
3777
|
const mintData = await import_MintTransactionData2.MintTransactionData.fromJSON(mintDataJson);
|
|
@@ -4390,6 +4436,7 @@ var PaymentsModule = class _PaymentsModule {
|
|
|
4390
4436
|
*/
|
|
4391
4437
|
async load() {
|
|
4392
4438
|
this.ensureInitialized();
|
|
4439
|
+
await TokenRegistry.waitForReady();
|
|
4393
4440
|
const providers = this.getTokenStorageProviders();
|
|
4394
4441
|
for (const [id, provider] of providers) {
|
|
4395
4442
|
try {
|
|
@@ -5731,7 +5778,6 @@ var PaymentsModule = class _PaymentsModule {
|
|
|
5731
5778
|
/**
|
|
5732
5779
|
* Non-blocking proof check with 500ms timeout.
|
|
5733
5780
|
*/
|
|
5734
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
5735
5781
|
async quickProofCheck(stClient, trustBase, commitment, timeoutMs = 500) {
|
|
5736
5782
|
try {
|
|
5737
5783
|
const proof = await Promise.race([
|
|
@@ -5747,7 +5793,6 @@ var PaymentsModule = class _PaymentsModule {
|
|
|
5747
5793
|
* Perform V5 bundle finalization from stored bundle data and proofs.
|
|
5748
5794
|
* Extracted from InstantSplitProcessor.processV5Bundle() steps 4-10.
|
|
5749
5795
|
*/
|
|
5750
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
5751
5796
|
async finalizeFromV5Bundle(bundle, pending2, signingService, stClient, trustBase) {
|
|
5752
5797
|
const mintDataJson = JSON.parse(bundle.recipientMintData);
|
|
5753
5798
|
const mintData = await import_MintTransactionData3.MintTransactionData.fromJSON(mintDataJson);
|
|
@@ -5910,7 +5955,7 @@ var PaymentsModule = class _PaymentsModule {
|
|
|
5910
5955
|
return false;
|
|
5911
5956
|
}
|
|
5912
5957
|
if (incomingStateKey) {
|
|
5913
|
-
for (const [
|
|
5958
|
+
for (const [_existingId, existing] of this.tokens) {
|
|
5914
5959
|
if (isSameTokenState(existing, token)) {
|
|
5915
5960
|
this.log(`Duplicate token state ignored: ${incomingTokenId?.slice(0, 8)}..._${incomingStateHash?.slice(0, 8)}...`);
|
|
5916
5961
|
return false;
|
|
@@ -7273,7 +7318,7 @@ var PaymentsModule = class _PaymentsModule {
|
|
|
7273
7318
|
}
|
|
7274
7319
|
}
|
|
7275
7320
|
clearTimeout(timeoutId);
|
|
7276
|
-
} catch (
|
|
7321
|
+
} catch (_err) {
|
|
7277
7322
|
continue;
|
|
7278
7323
|
}
|
|
7279
7324
|
if (!inclusionProof) {
|
|
@@ -7352,28 +7397,6 @@ var CommunicationsModule = class {
|
|
|
7352
7397
|
this.unsubscribeMessages = deps.transport.onMessage((msg) => {
|
|
7353
7398
|
this.handleIncomingMessage(msg);
|
|
7354
7399
|
});
|
|
7355
|
-
if (deps.transport.onReadReceipt) {
|
|
7356
|
-
deps.transport.onReadReceipt((receipt) => {
|
|
7357
|
-
const msg = this.messages.get(receipt.messageEventId);
|
|
7358
|
-
if (msg && msg.senderPubkey === this.deps.identity.chainPubkey) {
|
|
7359
|
-
msg.isRead = true;
|
|
7360
|
-
this.save();
|
|
7361
|
-
this.deps.emitEvent("message:read", {
|
|
7362
|
-
messageIds: [receipt.messageEventId],
|
|
7363
|
-
peerPubkey: receipt.senderTransportPubkey
|
|
7364
|
-
});
|
|
7365
|
-
}
|
|
7366
|
-
});
|
|
7367
|
-
}
|
|
7368
|
-
if (deps.transport.onTypingIndicator) {
|
|
7369
|
-
deps.transport.onTypingIndicator((indicator) => {
|
|
7370
|
-
this.deps.emitEvent("message:typing", {
|
|
7371
|
-
senderPubkey: indicator.senderTransportPubkey,
|
|
7372
|
-
senderNametag: indicator.senderNametag,
|
|
7373
|
-
timestamp: indicator.timestamp
|
|
7374
|
-
});
|
|
7375
|
-
});
|
|
7376
|
-
}
|
|
7377
7400
|
}
|
|
7378
7401
|
/**
|
|
7379
7402
|
* Load messages from storage
|
|
@@ -7417,7 +7440,7 @@ var CommunicationsModule = class {
|
|
|
7417
7440
|
recipientPubkey,
|
|
7418
7441
|
content,
|
|
7419
7442
|
timestamp: Date.now(),
|
|
7420
|
-
isRead:
|
|
7443
|
+
isRead: true
|
|
7421
7444
|
};
|
|
7422
7445
|
this.messages.set(message.id, message);
|
|
7423
7446
|
if (this.config.autoSave) {
|
|
@@ -7463,16 +7486,6 @@ var CommunicationsModule = class {
|
|
|
7463
7486
|
if (this.config.autoSave) {
|
|
7464
7487
|
await this.save();
|
|
7465
7488
|
}
|
|
7466
|
-
if (this.config.readReceipts && this.deps?.transport.sendReadReceipt) {
|
|
7467
|
-
for (const id of messageIds) {
|
|
7468
|
-
const msg = this.messages.get(id);
|
|
7469
|
-
if (msg && msg.senderPubkey !== this.deps.identity.chainPubkey) {
|
|
7470
|
-
this.deps.transport.sendReadReceipt(msg.senderPubkey, id).catch((err) => {
|
|
7471
|
-
console.warn("[Communications] Failed to send read receipt:", err);
|
|
7472
|
-
});
|
|
7473
|
-
}
|
|
7474
|
-
}
|
|
7475
|
-
}
|
|
7476
7489
|
}
|
|
7477
7490
|
/**
|
|
7478
7491
|
* Get unread count
|
|
@@ -7486,15 +7499,6 @@ var CommunicationsModule = class {
|
|
|
7486
7499
|
}
|
|
7487
7500
|
return messages.length;
|
|
7488
7501
|
}
|
|
7489
|
-
/**
|
|
7490
|
-
* Send typing indicator to a peer
|
|
7491
|
-
*/
|
|
7492
|
-
async sendTypingIndicator(peerPubkey) {
|
|
7493
|
-
this.ensureInitialized();
|
|
7494
|
-
if (this.deps.transport.sendTypingIndicator) {
|
|
7495
|
-
await this.deps.transport.sendTypingIndicator(peerPubkey);
|
|
7496
|
-
}
|
|
7497
|
-
}
|
|
7498
7502
|
/**
|
|
7499
7503
|
* Subscribe to incoming DMs
|
|
7500
7504
|
*/
|
|
@@ -7564,26 +7568,7 @@ var CommunicationsModule = class {
|
|
|
7564
7568
|
// Private: Message Handling
|
|
7565
7569
|
// ===========================================================================
|
|
7566
7570
|
handleIncomingMessage(msg) {
|
|
7567
|
-
if (msg.isSelfWrap && msg.recipientTransportPubkey) {
|
|
7568
|
-
if (this.messages.has(msg.id)) return;
|
|
7569
|
-
const message2 = {
|
|
7570
|
-
id: msg.id,
|
|
7571
|
-
senderPubkey: this.deps.identity.chainPubkey,
|
|
7572
|
-
senderNametag: msg.senderNametag,
|
|
7573
|
-
recipientPubkey: msg.recipientTransportPubkey,
|
|
7574
|
-
content: msg.content,
|
|
7575
|
-
timestamp: msg.timestamp,
|
|
7576
|
-
isRead: false
|
|
7577
|
-
};
|
|
7578
|
-
this.messages.set(message2.id, message2);
|
|
7579
|
-
this.deps.emitEvent("message:dm", message2);
|
|
7580
|
-
if (this.config.autoSave) {
|
|
7581
|
-
this.save();
|
|
7582
|
-
}
|
|
7583
|
-
return;
|
|
7584
|
-
}
|
|
7585
7571
|
if (msg.senderTransportPubkey === this.deps?.identity.chainPubkey) return;
|
|
7586
|
-
if (this.messages.has(msg.id)) return;
|
|
7587
7572
|
const message = {
|
|
7588
7573
|
id: msg.id,
|
|
7589
7574
|
senderPubkey: msg.senderTransportPubkey,
|
|
@@ -8990,26 +8975,27 @@ var GroupChatModule = class {
|
|
|
8990
8975
|
oneshotSubscription(filter, opts) {
|
|
8991
8976
|
return new Promise((resolve) => {
|
|
8992
8977
|
let done = false;
|
|
8993
|
-
|
|
8978
|
+
const state = {};
|
|
8994
8979
|
const finish = () => {
|
|
8995
8980
|
if (done) return;
|
|
8996
8981
|
done = true;
|
|
8997
|
-
if (subId) {
|
|
8982
|
+
if (state.subId) {
|
|
8998
8983
|
try {
|
|
8999
|
-
this.client.unsubscribe(subId);
|
|
8984
|
+
this.client.unsubscribe(state.subId);
|
|
9000
8985
|
} catch {
|
|
9001
8986
|
}
|
|
9002
|
-
const idx = this.subscriptionIds.indexOf(subId);
|
|
8987
|
+
const idx = this.subscriptionIds.indexOf(state.subId);
|
|
9003
8988
|
if (idx >= 0) this.subscriptionIds.splice(idx, 1);
|
|
9004
8989
|
}
|
|
9005
8990
|
resolve(opts.onComplete());
|
|
9006
8991
|
};
|
|
9007
|
-
subId = this.client.subscribe(filter, {
|
|
8992
|
+
const subId = this.client.subscribe(filter, {
|
|
9008
8993
|
onEvent: (event) => {
|
|
9009
8994
|
if (!done) opts.onEvent(event);
|
|
9010
8995
|
},
|
|
9011
8996
|
onEndOfStoredEvents: finish
|
|
9012
8997
|
});
|
|
8998
|
+
state.subId = subId;
|
|
9013
8999
|
this.subscriptionIds.push(subId);
|
|
9014
9000
|
setTimeout(finish, opts.timeoutMs ?? 5e3);
|
|
9015
9001
|
});
|
|
@@ -9040,2426 +9026,6 @@ function createGroupChatModule(config) {
|
|
|
9040
9026
|
return new GroupChatModule(config);
|
|
9041
9027
|
}
|
|
9042
9028
|
|
|
9043
|
-
// node_modules/@noble/hashes/utils.js
|
|
9044
|
-
function isBytes(a) {
|
|
9045
|
-
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
|
|
9046
|
-
}
|
|
9047
|
-
function anumber(n, title = "") {
|
|
9048
|
-
if (!Number.isSafeInteger(n) || n < 0) {
|
|
9049
|
-
const prefix = title && `"${title}" `;
|
|
9050
|
-
throw new Error(`${prefix}expected integer >= 0, got ${n}`);
|
|
9051
|
-
}
|
|
9052
|
-
}
|
|
9053
|
-
function abytes(value, length, title = "") {
|
|
9054
|
-
const bytes = isBytes(value);
|
|
9055
|
-
const len = value?.length;
|
|
9056
|
-
const needsLen = length !== void 0;
|
|
9057
|
-
if (!bytes || needsLen && len !== length) {
|
|
9058
|
-
const prefix = title && `"${title}" `;
|
|
9059
|
-
const ofLen = needsLen ? ` of length ${length}` : "";
|
|
9060
|
-
const got = bytes ? `length=${len}` : `type=${typeof value}`;
|
|
9061
|
-
throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
|
|
9062
|
-
}
|
|
9063
|
-
return value;
|
|
9064
|
-
}
|
|
9065
|
-
function ahash(h) {
|
|
9066
|
-
if (typeof h !== "function" || typeof h.create !== "function")
|
|
9067
|
-
throw new Error("Hash must wrapped by utils.createHasher");
|
|
9068
|
-
anumber(h.outputLen);
|
|
9069
|
-
anumber(h.blockLen);
|
|
9070
|
-
}
|
|
9071
|
-
function aexists(instance, checkFinished = true) {
|
|
9072
|
-
if (instance.destroyed)
|
|
9073
|
-
throw new Error("Hash instance has been destroyed");
|
|
9074
|
-
if (checkFinished && instance.finished)
|
|
9075
|
-
throw new Error("Hash#digest() has already been called");
|
|
9076
|
-
}
|
|
9077
|
-
function aoutput(out, instance) {
|
|
9078
|
-
abytes(out, void 0, "digestInto() output");
|
|
9079
|
-
const min = instance.outputLen;
|
|
9080
|
-
if (out.length < min) {
|
|
9081
|
-
throw new Error('"digestInto() output" expected to be of length >=' + min);
|
|
9082
|
-
}
|
|
9083
|
-
}
|
|
9084
|
-
function clean(...arrays) {
|
|
9085
|
-
for (let i = 0; i < arrays.length; i++) {
|
|
9086
|
-
arrays[i].fill(0);
|
|
9087
|
-
}
|
|
9088
|
-
}
|
|
9089
|
-
function createView(arr) {
|
|
9090
|
-
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
9091
|
-
}
|
|
9092
|
-
function rotr(word, shift) {
|
|
9093
|
-
return word << 32 - shift | word >>> shift;
|
|
9094
|
-
}
|
|
9095
|
-
var hasHexBuiltin = /* @__PURE__ */ (() => (
|
|
9096
|
-
// @ts-ignore
|
|
9097
|
-
typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
|
|
9098
|
-
))();
|
|
9099
|
-
var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
|
|
9100
|
-
function bytesToHex4(bytes) {
|
|
9101
|
-
abytes(bytes);
|
|
9102
|
-
if (hasHexBuiltin)
|
|
9103
|
-
return bytes.toHex();
|
|
9104
|
-
let hex = "";
|
|
9105
|
-
for (let i = 0; i < bytes.length; i++) {
|
|
9106
|
-
hex += hexes[bytes[i]];
|
|
9107
|
-
}
|
|
9108
|
-
return hex;
|
|
9109
|
-
}
|
|
9110
|
-
var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
|
|
9111
|
-
function asciiToBase16(ch) {
|
|
9112
|
-
if (ch >= asciis._0 && ch <= asciis._9)
|
|
9113
|
-
return ch - asciis._0;
|
|
9114
|
-
if (ch >= asciis.A && ch <= asciis.F)
|
|
9115
|
-
return ch - (asciis.A - 10);
|
|
9116
|
-
if (ch >= asciis.a && ch <= asciis.f)
|
|
9117
|
-
return ch - (asciis.a - 10);
|
|
9118
|
-
return;
|
|
9119
|
-
}
|
|
9120
|
-
function hexToBytes2(hex) {
|
|
9121
|
-
if (typeof hex !== "string")
|
|
9122
|
-
throw new Error("hex string expected, got " + typeof hex);
|
|
9123
|
-
if (hasHexBuiltin)
|
|
9124
|
-
return Uint8Array.fromHex(hex);
|
|
9125
|
-
const hl = hex.length;
|
|
9126
|
-
const al = hl / 2;
|
|
9127
|
-
if (hl % 2)
|
|
9128
|
-
throw new Error("hex string expected, got unpadded hex of length " + hl);
|
|
9129
|
-
const array = new Uint8Array(al);
|
|
9130
|
-
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
9131
|
-
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
|
9132
|
-
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
|
9133
|
-
if (n1 === void 0 || n2 === void 0) {
|
|
9134
|
-
const char = hex[hi] + hex[hi + 1];
|
|
9135
|
-
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
9136
|
-
}
|
|
9137
|
-
array[ai] = n1 * 16 + n2;
|
|
9138
|
-
}
|
|
9139
|
-
return array;
|
|
9140
|
-
}
|
|
9141
|
-
function concatBytes(...arrays) {
|
|
9142
|
-
let sum = 0;
|
|
9143
|
-
for (let i = 0; i < arrays.length; i++) {
|
|
9144
|
-
const a = arrays[i];
|
|
9145
|
-
abytes(a);
|
|
9146
|
-
sum += a.length;
|
|
9147
|
-
}
|
|
9148
|
-
const res = new Uint8Array(sum);
|
|
9149
|
-
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
9150
|
-
const a = arrays[i];
|
|
9151
|
-
res.set(a, pad);
|
|
9152
|
-
pad += a.length;
|
|
9153
|
-
}
|
|
9154
|
-
return res;
|
|
9155
|
-
}
|
|
9156
|
-
function createHasher(hashCons, info = {}) {
|
|
9157
|
-
const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
|
|
9158
|
-
const tmp = hashCons(void 0);
|
|
9159
|
-
hashC.outputLen = tmp.outputLen;
|
|
9160
|
-
hashC.blockLen = tmp.blockLen;
|
|
9161
|
-
hashC.create = (opts) => hashCons(opts);
|
|
9162
|
-
Object.assign(hashC, info);
|
|
9163
|
-
return Object.freeze(hashC);
|
|
9164
|
-
}
|
|
9165
|
-
function randomBytes2(bytesLength = 32) {
|
|
9166
|
-
const cr = typeof globalThis === "object" ? globalThis.crypto : null;
|
|
9167
|
-
if (typeof cr?.getRandomValues !== "function")
|
|
9168
|
-
throw new Error("crypto.getRandomValues must be defined");
|
|
9169
|
-
return cr.getRandomValues(new Uint8Array(bytesLength));
|
|
9170
|
-
}
|
|
9171
|
-
var oidNist = (suffix) => ({
|
|
9172
|
-
oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
|
|
9173
|
-
});
|
|
9174
|
-
|
|
9175
|
-
// node_modules/@noble/hashes/_md.js
|
|
9176
|
-
function Chi(a, b, c) {
|
|
9177
|
-
return a & b ^ ~a & c;
|
|
9178
|
-
}
|
|
9179
|
-
function Maj(a, b, c) {
|
|
9180
|
-
return a & b ^ a & c ^ b & c;
|
|
9181
|
-
}
|
|
9182
|
-
var HashMD = class {
|
|
9183
|
-
blockLen;
|
|
9184
|
-
outputLen;
|
|
9185
|
-
padOffset;
|
|
9186
|
-
isLE;
|
|
9187
|
-
// For partial updates less than block size
|
|
9188
|
-
buffer;
|
|
9189
|
-
view;
|
|
9190
|
-
finished = false;
|
|
9191
|
-
length = 0;
|
|
9192
|
-
pos = 0;
|
|
9193
|
-
destroyed = false;
|
|
9194
|
-
constructor(blockLen, outputLen, padOffset, isLE) {
|
|
9195
|
-
this.blockLen = blockLen;
|
|
9196
|
-
this.outputLen = outputLen;
|
|
9197
|
-
this.padOffset = padOffset;
|
|
9198
|
-
this.isLE = isLE;
|
|
9199
|
-
this.buffer = new Uint8Array(blockLen);
|
|
9200
|
-
this.view = createView(this.buffer);
|
|
9201
|
-
}
|
|
9202
|
-
update(data) {
|
|
9203
|
-
aexists(this);
|
|
9204
|
-
abytes(data);
|
|
9205
|
-
const { view, buffer, blockLen } = this;
|
|
9206
|
-
const len = data.length;
|
|
9207
|
-
for (let pos = 0; pos < len; ) {
|
|
9208
|
-
const take = Math.min(blockLen - this.pos, len - pos);
|
|
9209
|
-
if (take === blockLen) {
|
|
9210
|
-
const dataView = createView(data);
|
|
9211
|
-
for (; blockLen <= len - pos; pos += blockLen)
|
|
9212
|
-
this.process(dataView, pos);
|
|
9213
|
-
continue;
|
|
9214
|
-
}
|
|
9215
|
-
buffer.set(data.subarray(pos, pos + take), this.pos);
|
|
9216
|
-
this.pos += take;
|
|
9217
|
-
pos += take;
|
|
9218
|
-
if (this.pos === blockLen) {
|
|
9219
|
-
this.process(view, 0);
|
|
9220
|
-
this.pos = 0;
|
|
9221
|
-
}
|
|
9222
|
-
}
|
|
9223
|
-
this.length += data.length;
|
|
9224
|
-
this.roundClean();
|
|
9225
|
-
return this;
|
|
9226
|
-
}
|
|
9227
|
-
digestInto(out) {
|
|
9228
|
-
aexists(this);
|
|
9229
|
-
aoutput(out, this);
|
|
9230
|
-
this.finished = true;
|
|
9231
|
-
const { buffer, view, blockLen, isLE } = this;
|
|
9232
|
-
let { pos } = this;
|
|
9233
|
-
buffer[pos++] = 128;
|
|
9234
|
-
clean(this.buffer.subarray(pos));
|
|
9235
|
-
if (this.padOffset > blockLen - pos) {
|
|
9236
|
-
this.process(view, 0);
|
|
9237
|
-
pos = 0;
|
|
9238
|
-
}
|
|
9239
|
-
for (let i = pos; i < blockLen; i++)
|
|
9240
|
-
buffer[i] = 0;
|
|
9241
|
-
view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
|
|
9242
|
-
this.process(view, 0);
|
|
9243
|
-
const oview = createView(out);
|
|
9244
|
-
const len = this.outputLen;
|
|
9245
|
-
if (len % 4)
|
|
9246
|
-
throw new Error("_sha2: outputLen must be aligned to 32bit");
|
|
9247
|
-
const outLen = len / 4;
|
|
9248
|
-
const state = this.get();
|
|
9249
|
-
if (outLen > state.length)
|
|
9250
|
-
throw new Error("_sha2: outputLen bigger than state");
|
|
9251
|
-
for (let i = 0; i < outLen; i++)
|
|
9252
|
-
oview.setUint32(4 * i, state[i], isLE);
|
|
9253
|
-
}
|
|
9254
|
-
digest() {
|
|
9255
|
-
const { buffer, outputLen } = this;
|
|
9256
|
-
this.digestInto(buffer);
|
|
9257
|
-
const res = buffer.slice(0, outputLen);
|
|
9258
|
-
this.destroy();
|
|
9259
|
-
return res;
|
|
9260
|
-
}
|
|
9261
|
-
_cloneInto(to) {
|
|
9262
|
-
to ||= new this.constructor();
|
|
9263
|
-
to.set(...this.get());
|
|
9264
|
-
const { blockLen, buffer, length, finished, destroyed, pos } = this;
|
|
9265
|
-
to.destroyed = destroyed;
|
|
9266
|
-
to.finished = finished;
|
|
9267
|
-
to.length = length;
|
|
9268
|
-
to.pos = pos;
|
|
9269
|
-
if (length % blockLen)
|
|
9270
|
-
to.buffer.set(buffer);
|
|
9271
|
-
return to;
|
|
9272
|
-
}
|
|
9273
|
-
clone() {
|
|
9274
|
-
return this._cloneInto();
|
|
9275
|
-
}
|
|
9276
|
-
};
|
|
9277
|
-
var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
|
|
9278
|
-
1779033703,
|
|
9279
|
-
3144134277,
|
|
9280
|
-
1013904242,
|
|
9281
|
-
2773480762,
|
|
9282
|
-
1359893119,
|
|
9283
|
-
2600822924,
|
|
9284
|
-
528734635,
|
|
9285
|
-
1541459225
|
|
9286
|
-
]);
|
|
9287
|
-
|
|
9288
|
-
// node_modules/@noble/hashes/sha2.js
|
|
9289
|
-
var SHA256_K = /* @__PURE__ */ Uint32Array.from([
|
|
9290
|
-
1116352408,
|
|
9291
|
-
1899447441,
|
|
9292
|
-
3049323471,
|
|
9293
|
-
3921009573,
|
|
9294
|
-
961987163,
|
|
9295
|
-
1508970993,
|
|
9296
|
-
2453635748,
|
|
9297
|
-
2870763221,
|
|
9298
|
-
3624381080,
|
|
9299
|
-
310598401,
|
|
9300
|
-
607225278,
|
|
9301
|
-
1426881987,
|
|
9302
|
-
1925078388,
|
|
9303
|
-
2162078206,
|
|
9304
|
-
2614888103,
|
|
9305
|
-
3248222580,
|
|
9306
|
-
3835390401,
|
|
9307
|
-
4022224774,
|
|
9308
|
-
264347078,
|
|
9309
|
-
604807628,
|
|
9310
|
-
770255983,
|
|
9311
|
-
1249150122,
|
|
9312
|
-
1555081692,
|
|
9313
|
-
1996064986,
|
|
9314
|
-
2554220882,
|
|
9315
|
-
2821834349,
|
|
9316
|
-
2952996808,
|
|
9317
|
-
3210313671,
|
|
9318
|
-
3336571891,
|
|
9319
|
-
3584528711,
|
|
9320
|
-
113926993,
|
|
9321
|
-
338241895,
|
|
9322
|
-
666307205,
|
|
9323
|
-
773529912,
|
|
9324
|
-
1294757372,
|
|
9325
|
-
1396182291,
|
|
9326
|
-
1695183700,
|
|
9327
|
-
1986661051,
|
|
9328
|
-
2177026350,
|
|
9329
|
-
2456956037,
|
|
9330
|
-
2730485921,
|
|
9331
|
-
2820302411,
|
|
9332
|
-
3259730800,
|
|
9333
|
-
3345764771,
|
|
9334
|
-
3516065817,
|
|
9335
|
-
3600352804,
|
|
9336
|
-
4094571909,
|
|
9337
|
-
275423344,
|
|
9338
|
-
430227734,
|
|
9339
|
-
506948616,
|
|
9340
|
-
659060556,
|
|
9341
|
-
883997877,
|
|
9342
|
-
958139571,
|
|
9343
|
-
1322822218,
|
|
9344
|
-
1537002063,
|
|
9345
|
-
1747873779,
|
|
9346
|
-
1955562222,
|
|
9347
|
-
2024104815,
|
|
9348
|
-
2227730452,
|
|
9349
|
-
2361852424,
|
|
9350
|
-
2428436474,
|
|
9351
|
-
2756734187,
|
|
9352
|
-
3204031479,
|
|
9353
|
-
3329325298
|
|
9354
|
-
]);
|
|
9355
|
-
var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
|
|
9356
|
-
var SHA2_32B = class extends HashMD {
|
|
9357
|
-
constructor(outputLen) {
|
|
9358
|
-
super(64, outputLen, 8, false);
|
|
9359
|
-
}
|
|
9360
|
-
get() {
|
|
9361
|
-
const { A, B, C, D, E, F, G, H } = this;
|
|
9362
|
-
return [A, B, C, D, E, F, G, H];
|
|
9363
|
-
}
|
|
9364
|
-
// prettier-ignore
|
|
9365
|
-
set(A, B, C, D, E, F, G, H) {
|
|
9366
|
-
this.A = A | 0;
|
|
9367
|
-
this.B = B | 0;
|
|
9368
|
-
this.C = C | 0;
|
|
9369
|
-
this.D = D | 0;
|
|
9370
|
-
this.E = E | 0;
|
|
9371
|
-
this.F = F | 0;
|
|
9372
|
-
this.G = G | 0;
|
|
9373
|
-
this.H = H | 0;
|
|
9374
|
-
}
|
|
9375
|
-
process(view, offset) {
|
|
9376
|
-
for (let i = 0; i < 16; i++, offset += 4)
|
|
9377
|
-
SHA256_W[i] = view.getUint32(offset, false);
|
|
9378
|
-
for (let i = 16; i < 64; i++) {
|
|
9379
|
-
const W15 = SHA256_W[i - 15];
|
|
9380
|
-
const W2 = SHA256_W[i - 2];
|
|
9381
|
-
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
|
|
9382
|
-
const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
|
|
9383
|
-
SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
|
|
9384
|
-
}
|
|
9385
|
-
let { A, B, C, D, E, F, G, H } = this;
|
|
9386
|
-
for (let i = 0; i < 64; i++) {
|
|
9387
|
-
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
|
|
9388
|
-
const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
|
|
9389
|
-
const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
|
|
9390
|
-
const T2 = sigma0 + Maj(A, B, C) | 0;
|
|
9391
|
-
H = G;
|
|
9392
|
-
G = F;
|
|
9393
|
-
F = E;
|
|
9394
|
-
E = D + T1 | 0;
|
|
9395
|
-
D = C;
|
|
9396
|
-
C = B;
|
|
9397
|
-
B = A;
|
|
9398
|
-
A = T1 + T2 | 0;
|
|
9399
|
-
}
|
|
9400
|
-
A = A + this.A | 0;
|
|
9401
|
-
B = B + this.B | 0;
|
|
9402
|
-
C = C + this.C | 0;
|
|
9403
|
-
D = D + this.D | 0;
|
|
9404
|
-
E = E + this.E | 0;
|
|
9405
|
-
F = F + this.F | 0;
|
|
9406
|
-
G = G + this.G | 0;
|
|
9407
|
-
H = H + this.H | 0;
|
|
9408
|
-
this.set(A, B, C, D, E, F, G, H);
|
|
9409
|
-
}
|
|
9410
|
-
roundClean() {
|
|
9411
|
-
clean(SHA256_W);
|
|
9412
|
-
}
|
|
9413
|
-
destroy() {
|
|
9414
|
-
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
|
9415
|
-
clean(this.buffer);
|
|
9416
|
-
}
|
|
9417
|
-
};
|
|
9418
|
-
var _SHA256 = class extends SHA2_32B {
|
|
9419
|
-
// We cannot use array here since array allows indexing by variable
|
|
9420
|
-
// which means optimizer/compiler cannot use registers.
|
|
9421
|
-
A = SHA256_IV[0] | 0;
|
|
9422
|
-
B = SHA256_IV[1] | 0;
|
|
9423
|
-
C = SHA256_IV[2] | 0;
|
|
9424
|
-
D = SHA256_IV[3] | 0;
|
|
9425
|
-
E = SHA256_IV[4] | 0;
|
|
9426
|
-
F = SHA256_IV[5] | 0;
|
|
9427
|
-
G = SHA256_IV[6] | 0;
|
|
9428
|
-
H = SHA256_IV[7] | 0;
|
|
9429
|
-
constructor() {
|
|
9430
|
-
super(32);
|
|
9431
|
-
}
|
|
9432
|
-
};
|
|
9433
|
-
var sha2564 = /* @__PURE__ */ createHasher(
|
|
9434
|
-
() => new _SHA256(),
|
|
9435
|
-
/* @__PURE__ */ oidNist(1)
|
|
9436
|
-
);
|
|
9437
|
-
|
|
9438
|
-
// node_modules/@noble/curves/utils.js
|
|
9439
|
-
var _0n = /* @__PURE__ */ BigInt(0);
|
|
9440
|
-
var _1n = /* @__PURE__ */ BigInt(1);
|
|
9441
|
-
function abool(value, title = "") {
|
|
9442
|
-
if (typeof value !== "boolean") {
|
|
9443
|
-
const prefix = title && `"${title}" `;
|
|
9444
|
-
throw new Error(prefix + "expected boolean, got type=" + typeof value);
|
|
9445
|
-
}
|
|
9446
|
-
return value;
|
|
9447
|
-
}
|
|
9448
|
-
function abignumber(n) {
|
|
9449
|
-
if (typeof n === "bigint") {
|
|
9450
|
-
if (!isPosBig(n))
|
|
9451
|
-
throw new Error("positive bigint expected, got " + n);
|
|
9452
|
-
} else
|
|
9453
|
-
anumber(n);
|
|
9454
|
-
return n;
|
|
9455
|
-
}
|
|
9456
|
-
function numberToHexUnpadded(num) {
|
|
9457
|
-
const hex = abignumber(num).toString(16);
|
|
9458
|
-
return hex.length & 1 ? "0" + hex : hex;
|
|
9459
|
-
}
|
|
9460
|
-
function hexToNumber(hex) {
|
|
9461
|
-
if (typeof hex !== "string")
|
|
9462
|
-
throw new Error("hex string expected, got " + typeof hex);
|
|
9463
|
-
return hex === "" ? _0n : BigInt("0x" + hex);
|
|
9464
|
-
}
|
|
9465
|
-
function bytesToNumberBE(bytes) {
|
|
9466
|
-
return hexToNumber(bytesToHex4(bytes));
|
|
9467
|
-
}
|
|
9468
|
-
function bytesToNumberLE(bytes) {
|
|
9469
|
-
return hexToNumber(bytesToHex4(copyBytes(abytes(bytes)).reverse()));
|
|
9470
|
-
}
|
|
9471
|
-
function numberToBytesBE(n, len) {
|
|
9472
|
-
anumber(len);
|
|
9473
|
-
n = abignumber(n);
|
|
9474
|
-
const res = hexToBytes2(n.toString(16).padStart(len * 2, "0"));
|
|
9475
|
-
if (res.length !== len)
|
|
9476
|
-
throw new Error("number too large");
|
|
9477
|
-
return res;
|
|
9478
|
-
}
|
|
9479
|
-
function numberToBytesLE(n, len) {
|
|
9480
|
-
return numberToBytesBE(n, len).reverse();
|
|
9481
|
-
}
|
|
9482
|
-
function copyBytes(bytes) {
|
|
9483
|
-
return Uint8Array.from(bytes);
|
|
9484
|
-
}
|
|
9485
|
-
var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
|
|
9486
|
-
function inRange(n, min, max) {
|
|
9487
|
-
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
|
|
9488
|
-
}
|
|
9489
|
-
function aInRange(title, n, min, max) {
|
|
9490
|
-
if (!inRange(n, min, max))
|
|
9491
|
-
throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
|
|
9492
|
-
}
|
|
9493
|
-
function bitLen(n) {
|
|
9494
|
-
let len;
|
|
9495
|
-
for (len = 0; n > _0n; n >>= _1n, len += 1)
|
|
9496
|
-
;
|
|
9497
|
-
return len;
|
|
9498
|
-
}
|
|
9499
|
-
var bitMask = (n) => (_1n << BigInt(n)) - _1n;
|
|
9500
|
-
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
9501
|
-
anumber(hashLen, "hashLen");
|
|
9502
|
-
anumber(qByteLen, "qByteLen");
|
|
9503
|
-
if (typeof hmacFn !== "function")
|
|
9504
|
-
throw new Error("hmacFn must be a function");
|
|
9505
|
-
const u8n = (len) => new Uint8Array(len);
|
|
9506
|
-
const NULL = Uint8Array.of();
|
|
9507
|
-
const byte0 = Uint8Array.of(0);
|
|
9508
|
-
const byte1 = Uint8Array.of(1);
|
|
9509
|
-
const _maxDrbgIters = 1e3;
|
|
9510
|
-
let v = u8n(hashLen);
|
|
9511
|
-
let k = u8n(hashLen);
|
|
9512
|
-
let i = 0;
|
|
9513
|
-
const reset = () => {
|
|
9514
|
-
v.fill(1);
|
|
9515
|
-
k.fill(0);
|
|
9516
|
-
i = 0;
|
|
9517
|
-
};
|
|
9518
|
-
const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));
|
|
9519
|
-
const reseed = (seed = NULL) => {
|
|
9520
|
-
k = h(byte0, seed);
|
|
9521
|
-
v = h();
|
|
9522
|
-
if (seed.length === 0)
|
|
9523
|
-
return;
|
|
9524
|
-
k = h(byte1, seed);
|
|
9525
|
-
v = h();
|
|
9526
|
-
};
|
|
9527
|
-
const gen = () => {
|
|
9528
|
-
if (i++ >= _maxDrbgIters)
|
|
9529
|
-
throw new Error("drbg: tried max amount of iterations");
|
|
9530
|
-
let len = 0;
|
|
9531
|
-
const out = [];
|
|
9532
|
-
while (len < qByteLen) {
|
|
9533
|
-
v = h();
|
|
9534
|
-
const sl = v.slice();
|
|
9535
|
-
out.push(sl);
|
|
9536
|
-
len += v.length;
|
|
9537
|
-
}
|
|
9538
|
-
return concatBytes(...out);
|
|
9539
|
-
};
|
|
9540
|
-
const genUntil = (seed, pred) => {
|
|
9541
|
-
reset();
|
|
9542
|
-
reseed(seed);
|
|
9543
|
-
let res = void 0;
|
|
9544
|
-
while (!(res = pred(gen())))
|
|
9545
|
-
reseed();
|
|
9546
|
-
reset();
|
|
9547
|
-
return res;
|
|
9548
|
-
};
|
|
9549
|
-
return genUntil;
|
|
9550
|
-
}
|
|
9551
|
-
function validateObject(object, fields = {}, optFields = {}) {
|
|
9552
|
-
if (!object || typeof object !== "object")
|
|
9553
|
-
throw new Error("expected valid options object");
|
|
9554
|
-
function checkField(fieldName, expectedType, isOpt) {
|
|
9555
|
-
const val = object[fieldName];
|
|
9556
|
-
if (isOpt && val === void 0)
|
|
9557
|
-
return;
|
|
9558
|
-
const current = typeof val;
|
|
9559
|
-
if (current !== expectedType || val === null)
|
|
9560
|
-
throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
|
|
9561
|
-
}
|
|
9562
|
-
const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
|
|
9563
|
-
iter(fields, false);
|
|
9564
|
-
iter(optFields, true);
|
|
9565
|
-
}
|
|
9566
|
-
function memoized(fn) {
|
|
9567
|
-
const map = /* @__PURE__ */ new WeakMap();
|
|
9568
|
-
return (arg, ...args) => {
|
|
9569
|
-
const val = map.get(arg);
|
|
9570
|
-
if (val !== void 0)
|
|
9571
|
-
return val;
|
|
9572
|
-
const computed = fn(arg, ...args);
|
|
9573
|
-
map.set(arg, computed);
|
|
9574
|
-
return computed;
|
|
9575
|
-
};
|
|
9576
|
-
}
|
|
9577
|
-
|
|
9578
|
-
// node_modules/@noble/curves/abstract/modular.js
|
|
9579
|
-
var _0n2 = /* @__PURE__ */ BigInt(0);
|
|
9580
|
-
var _1n2 = /* @__PURE__ */ BigInt(1);
|
|
9581
|
-
var _2n = /* @__PURE__ */ BigInt(2);
|
|
9582
|
-
var _3n = /* @__PURE__ */ BigInt(3);
|
|
9583
|
-
var _4n = /* @__PURE__ */ BigInt(4);
|
|
9584
|
-
var _5n = /* @__PURE__ */ BigInt(5);
|
|
9585
|
-
var _7n = /* @__PURE__ */ BigInt(7);
|
|
9586
|
-
var _8n = /* @__PURE__ */ BigInt(8);
|
|
9587
|
-
var _9n = /* @__PURE__ */ BigInt(9);
|
|
9588
|
-
var _16n = /* @__PURE__ */ BigInt(16);
|
|
9589
|
-
function mod(a, b) {
|
|
9590
|
-
const result = a % b;
|
|
9591
|
-
return result >= _0n2 ? result : b + result;
|
|
9592
|
-
}
|
|
9593
|
-
function pow2(x, power, modulo) {
|
|
9594
|
-
let res = x;
|
|
9595
|
-
while (power-- > _0n2) {
|
|
9596
|
-
res *= res;
|
|
9597
|
-
res %= modulo;
|
|
9598
|
-
}
|
|
9599
|
-
return res;
|
|
9600
|
-
}
|
|
9601
|
-
function invert(number, modulo) {
|
|
9602
|
-
if (number === _0n2)
|
|
9603
|
-
throw new Error("invert: expected non-zero number");
|
|
9604
|
-
if (modulo <= _0n2)
|
|
9605
|
-
throw new Error("invert: expected positive modulus, got " + modulo);
|
|
9606
|
-
let a = mod(number, modulo);
|
|
9607
|
-
let b = modulo;
|
|
9608
|
-
let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
|
|
9609
|
-
while (a !== _0n2) {
|
|
9610
|
-
const q = b / a;
|
|
9611
|
-
const r = b % a;
|
|
9612
|
-
const m = x - u * q;
|
|
9613
|
-
const n = y - v * q;
|
|
9614
|
-
b = a, a = r, x = u, y = v, u = m, v = n;
|
|
9615
|
-
}
|
|
9616
|
-
const gcd = b;
|
|
9617
|
-
if (gcd !== _1n2)
|
|
9618
|
-
throw new Error("invert: does not exist");
|
|
9619
|
-
return mod(x, modulo);
|
|
9620
|
-
}
|
|
9621
|
-
function assertIsSquare(Fp, root, n) {
|
|
9622
|
-
if (!Fp.eql(Fp.sqr(root), n))
|
|
9623
|
-
throw new Error("Cannot find square root");
|
|
9624
|
-
}
|
|
9625
|
-
function sqrt3mod4(Fp, n) {
|
|
9626
|
-
const p1div4 = (Fp.ORDER + _1n2) / _4n;
|
|
9627
|
-
const root = Fp.pow(n, p1div4);
|
|
9628
|
-
assertIsSquare(Fp, root, n);
|
|
9629
|
-
return root;
|
|
9630
|
-
}
|
|
9631
|
-
function sqrt5mod8(Fp, n) {
|
|
9632
|
-
const p5div8 = (Fp.ORDER - _5n) / _8n;
|
|
9633
|
-
const n2 = Fp.mul(n, _2n);
|
|
9634
|
-
const v = Fp.pow(n2, p5div8);
|
|
9635
|
-
const nv = Fp.mul(n, v);
|
|
9636
|
-
const i = Fp.mul(Fp.mul(nv, _2n), v);
|
|
9637
|
-
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
|
|
9638
|
-
assertIsSquare(Fp, root, n);
|
|
9639
|
-
return root;
|
|
9640
|
-
}
|
|
9641
|
-
function sqrt9mod16(P) {
|
|
9642
|
-
const Fp_ = Field(P);
|
|
9643
|
-
const tn = tonelliShanks(P);
|
|
9644
|
-
const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
|
|
9645
|
-
const c2 = tn(Fp_, c1);
|
|
9646
|
-
const c3 = tn(Fp_, Fp_.neg(c1));
|
|
9647
|
-
const c4 = (P + _7n) / _16n;
|
|
9648
|
-
return (Fp, n) => {
|
|
9649
|
-
let tv1 = Fp.pow(n, c4);
|
|
9650
|
-
let tv2 = Fp.mul(tv1, c1);
|
|
9651
|
-
const tv3 = Fp.mul(tv1, c2);
|
|
9652
|
-
const tv4 = Fp.mul(tv1, c3);
|
|
9653
|
-
const e1 = Fp.eql(Fp.sqr(tv2), n);
|
|
9654
|
-
const e2 = Fp.eql(Fp.sqr(tv3), n);
|
|
9655
|
-
tv1 = Fp.cmov(tv1, tv2, e1);
|
|
9656
|
-
tv2 = Fp.cmov(tv4, tv3, e2);
|
|
9657
|
-
const e3 = Fp.eql(Fp.sqr(tv2), n);
|
|
9658
|
-
const root = Fp.cmov(tv1, tv2, e3);
|
|
9659
|
-
assertIsSquare(Fp, root, n);
|
|
9660
|
-
return root;
|
|
9661
|
-
};
|
|
9662
|
-
}
|
|
9663
|
-
function tonelliShanks(P) {
|
|
9664
|
-
if (P < _3n)
|
|
9665
|
-
throw new Error("sqrt is not defined for small field");
|
|
9666
|
-
let Q = P - _1n2;
|
|
9667
|
-
let S = 0;
|
|
9668
|
-
while (Q % _2n === _0n2) {
|
|
9669
|
-
Q /= _2n;
|
|
9670
|
-
S++;
|
|
9671
|
-
}
|
|
9672
|
-
let Z = _2n;
|
|
9673
|
-
const _Fp = Field(P);
|
|
9674
|
-
while (FpLegendre(_Fp, Z) === 1) {
|
|
9675
|
-
if (Z++ > 1e3)
|
|
9676
|
-
throw new Error("Cannot find square root: probably non-prime P");
|
|
9677
|
-
}
|
|
9678
|
-
if (S === 1)
|
|
9679
|
-
return sqrt3mod4;
|
|
9680
|
-
let cc = _Fp.pow(Z, Q);
|
|
9681
|
-
const Q1div2 = (Q + _1n2) / _2n;
|
|
9682
|
-
return function tonelliSlow(Fp, n) {
|
|
9683
|
-
if (Fp.is0(n))
|
|
9684
|
-
return n;
|
|
9685
|
-
if (FpLegendre(Fp, n) !== 1)
|
|
9686
|
-
throw new Error("Cannot find square root");
|
|
9687
|
-
let M = S;
|
|
9688
|
-
let c = Fp.mul(Fp.ONE, cc);
|
|
9689
|
-
let t = Fp.pow(n, Q);
|
|
9690
|
-
let R = Fp.pow(n, Q1div2);
|
|
9691
|
-
while (!Fp.eql(t, Fp.ONE)) {
|
|
9692
|
-
if (Fp.is0(t))
|
|
9693
|
-
return Fp.ZERO;
|
|
9694
|
-
let i = 1;
|
|
9695
|
-
let t_tmp = Fp.sqr(t);
|
|
9696
|
-
while (!Fp.eql(t_tmp, Fp.ONE)) {
|
|
9697
|
-
i++;
|
|
9698
|
-
t_tmp = Fp.sqr(t_tmp);
|
|
9699
|
-
if (i === M)
|
|
9700
|
-
throw new Error("Cannot find square root");
|
|
9701
|
-
}
|
|
9702
|
-
const exponent = _1n2 << BigInt(M - i - 1);
|
|
9703
|
-
const b = Fp.pow(c, exponent);
|
|
9704
|
-
M = i;
|
|
9705
|
-
c = Fp.sqr(b);
|
|
9706
|
-
t = Fp.mul(t, c);
|
|
9707
|
-
R = Fp.mul(R, b);
|
|
9708
|
-
}
|
|
9709
|
-
return R;
|
|
9710
|
-
};
|
|
9711
|
-
}
|
|
9712
|
-
function FpSqrt(P) {
|
|
9713
|
-
if (P % _4n === _3n)
|
|
9714
|
-
return sqrt3mod4;
|
|
9715
|
-
if (P % _8n === _5n)
|
|
9716
|
-
return sqrt5mod8;
|
|
9717
|
-
if (P % _16n === _9n)
|
|
9718
|
-
return sqrt9mod16(P);
|
|
9719
|
-
return tonelliShanks(P);
|
|
9720
|
-
}
|
|
9721
|
-
var FIELD_FIELDS = [
|
|
9722
|
-
"create",
|
|
9723
|
-
"isValid",
|
|
9724
|
-
"is0",
|
|
9725
|
-
"neg",
|
|
9726
|
-
"inv",
|
|
9727
|
-
"sqrt",
|
|
9728
|
-
"sqr",
|
|
9729
|
-
"eql",
|
|
9730
|
-
"add",
|
|
9731
|
-
"sub",
|
|
9732
|
-
"mul",
|
|
9733
|
-
"pow",
|
|
9734
|
-
"div",
|
|
9735
|
-
"addN",
|
|
9736
|
-
"subN",
|
|
9737
|
-
"mulN",
|
|
9738
|
-
"sqrN"
|
|
9739
|
-
];
|
|
9740
|
-
function validateField(field) {
|
|
9741
|
-
const initial = {
|
|
9742
|
-
ORDER: "bigint",
|
|
9743
|
-
BYTES: "number",
|
|
9744
|
-
BITS: "number"
|
|
9745
|
-
};
|
|
9746
|
-
const opts = FIELD_FIELDS.reduce((map, val) => {
|
|
9747
|
-
map[val] = "function";
|
|
9748
|
-
return map;
|
|
9749
|
-
}, initial);
|
|
9750
|
-
validateObject(field, opts);
|
|
9751
|
-
return field;
|
|
9752
|
-
}
|
|
9753
|
-
function FpPow(Fp, num, power) {
|
|
9754
|
-
if (power < _0n2)
|
|
9755
|
-
throw new Error("invalid exponent, negatives unsupported");
|
|
9756
|
-
if (power === _0n2)
|
|
9757
|
-
return Fp.ONE;
|
|
9758
|
-
if (power === _1n2)
|
|
9759
|
-
return num;
|
|
9760
|
-
let p = Fp.ONE;
|
|
9761
|
-
let d = num;
|
|
9762
|
-
while (power > _0n2) {
|
|
9763
|
-
if (power & _1n2)
|
|
9764
|
-
p = Fp.mul(p, d);
|
|
9765
|
-
d = Fp.sqr(d);
|
|
9766
|
-
power >>= _1n2;
|
|
9767
|
-
}
|
|
9768
|
-
return p;
|
|
9769
|
-
}
|
|
9770
|
-
function FpInvertBatch(Fp, nums, passZero = false) {
|
|
9771
|
-
const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
|
|
9772
|
-
const multipliedAcc = nums.reduce((acc, num, i) => {
|
|
9773
|
-
if (Fp.is0(num))
|
|
9774
|
-
return acc;
|
|
9775
|
-
inverted[i] = acc;
|
|
9776
|
-
return Fp.mul(acc, num);
|
|
9777
|
-
}, Fp.ONE);
|
|
9778
|
-
const invertedAcc = Fp.inv(multipliedAcc);
|
|
9779
|
-
nums.reduceRight((acc, num, i) => {
|
|
9780
|
-
if (Fp.is0(num))
|
|
9781
|
-
return acc;
|
|
9782
|
-
inverted[i] = Fp.mul(acc, inverted[i]);
|
|
9783
|
-
return Fp.mul(acc, num);
|
|
9784
|
-
}, invertedAcc);
|
|
9785
|
-
return inverted;
|
|
9786
|
-
}
|
|
9787
|
-
function FpLegendre(Fp, n) {
|
|
9788
|
-
const p1mod2 = (Fp.ORDER - _1n2) / _2n;
|
|
9789
|
-
const powered = Fp.pow(n, p1mod2);
|
|
9790
|
-
const yes = Fp.eql(powered, Fp.ONE);
|
|
9791
|
-
const zero = Fp.eql(powered, Fp.ZERO);
|
|
9792
|
-
const no = Fp.eql(powered, Fp.neg(Fp.ONE));
|
|
9793
|
-
if (!yes && !zero && !no)
|
|
9794
|
-
throw new Error("invalid Legendre symbol result");
|
|
9795
|
-
return yes ? 1 : zero ? 0 : -1;
|
|
9796
|
-
}
|
|
9797
|
-
function nLength(n, nBitLength) {
|
|
9798
|
-
if (nBitLength !== void 0)
|
|
9799
|
-
anumber(nBitLength);
|
|
9800
|
-
const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
|
|
9801
|
-
const nByteLength = Math.ceil(_nBitLength / 8);
|
|
9802
|
-
return { nBitLength: _nBitLength, nByteLength };
|
|
9803
|
-
}
|
|
9804
|
-
var _Field = class {
|
|
9805
|
-
ORDER;
|
|
9806
|
-
BITS;
|
|
9807
|
-
BYTES;
|
|
9808
|
-
isLE;
|
|
9809
|
-
ZERO = _0n2;
|
|
9810
|
-
ONE = _1n2;
|
|
9811
|
-
_lengths;
|
|
9812
|
-
_sqrt;
|
|
9813
|
-
// cached sqrt
|
|
9814
|
-
_mod;
|
|
9815
|
-
constructor(ORDER, opts = {}) {
|
|
9816
|
-
if (ORDER <= _0n2)
|
|
9817
|
-
throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
|
|
9818
|
-
let _nbitLength = void 0;
|
|
9819
|
-
this.isLE = false;
|
|
9820
|
-
if (opts != null && typeof opts === "object") {
|
|
9821
|
-
if (typeof opts.BITS === "number")
|
|
9822
|
-
_nbitLength = opts.BITS;
|
|
9823
|
-
if (typeof opts.sqrt === "function")
|
|
9824
|
-
this.sqrt = opts.sqrt;
|
|
9825
|
-
if (typeof opts.isLE === "boolean")
|
|
9826
|
-
this.isLE = opts.isLE;
|
|
9827
|
-
if (opts.allowedLengths)
|
|
9828
|
-
this._lengths = opts.allowedLengths?.slice();
|
|
9829
|
-
if (typeof opts.modFromBytes === "boolean")
|
|
9830
|
-
this._mod = opts.modFromBytes;
|
|
9831
|
-
}
|
|
9832
|
-
const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
|
|
9833
|
-
if (nByteLength > 2048)
|
|
9834
|
-
throw new Error("invalid field: expected ORDER of <= 2048 bytes");
|
|
9835
|
-
this.ORDER = ORDER;
|
|
9836
|
-
this.BITS = nBitLength;
|
|
9837
|
-
this.BYTES = nByteLength;
|
|
9838
|
-
this._sqrt = void 0;
|
|
9839
|
-
Object.preventExtensions(this);
|
|
9840
|
-
}
|
|
9841
|
-
create(num) {
|
|
9842
|
-
return mod(num, this.ORDER);
|
|
9843
|
-
}
|
|
9844
|
-
isValid(num) {
|
|
9845
|
-
if (typeof num !== "bigint")
|
|
9846
|
-
throw new Error("invalid field element: expected bigint, got " + typeof num);
|
|
9847
|
-
return _0n2 <= num && num < this.ORDER;
|
|
9848
|
-
}
|
|
9849
|
-
is0(num) {
|
|
9850
|
-
return num === _0n2;
|
|
9851
|
-
}
|
|
9852
|
-
// is valid and invertible
|
|
9853
|
-
isValidNot0(num) {
|
|
9854
|
-
return !this.is0(num) && this.isValid(num);
|
|
9855
|
-
}
|
|
9856
|
-
isOdd(num) {
|
|
9857
|
-
return (num & _1n2) === _1n2;
|
|
9858
|
-
}
|
|
9859
|
-
neg(num) {
|
|
9860
|
-
return mod(-num, this.ORDER);
|
|
9861
|
-
}
|
|
9862
|
-
eql(lhs, rhs) {
|
|
9863
|
-
return lhs === rhs;
|
|
9864
|
-
}
|
|
9865
|
-
sqr(num) {
|
|
9866
|
-
return mod(num * num, this.ORDER);
|
|
9867
|
-
}
|
|
9868
|
-
add(lhs, rhs) {
|
|
9869
|
-
return mod(lhs + rhs, this.ORDER);
|
|
9870
|
-
}
|
|
9871
|
-
sub(lhs, rhs) {
|
|
9872
|
-
return mod(lhs - rhs, this.ORDER);
|
|
9873
|
-
}
|
|
9874
|
-
mul(lhs, rhs) {
|
|
9875
|
-
return mod(lhs * rhs, this.ORDER);
|
|
9876
|
-
}
|
|
9877
|
-
pow(num, power) {
|
|
9878
|
-
return FpPow(this, num, power);
|
|
9879
|
-
}
|
|
9880
|
-
div(lhs, rhs) {
|
|
9881
|
-
return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
|
|
9882
|
-
}
|
|
9883
|
-
// Same as above, but doesn't normalize
|
|
9884
|
-
sqrN(num) {
|
|
9885
|
-
return num * num;
|
|
9886
|
-
}
|
|
9887
|
-
addN(lhs, rhs) {
|
|
9888
|
-
return lhs + rhs;
|
|
9889
|
-
}
|
|
9890
|
-
subN(lhs, rhs) {
|
|
9891
|
-
return lhs - rhs;
|
|
9892
|
-
}
|
|
9893
|
-
mulN(lhs, rhs) {
|
|
9894
|
-
return lhs * rhs;
|
|
9895
|
-
}
|
|
9896
|
-
inv(num) {
|
|
9897
|
-
return invert(num, this.ORDER);
|
|
9898
|
-
}
|
|
9899
|
-
sqrt(num) {
|
|
9900
|
-
if (!this._sqrt)
|
|
9901
|
-
this._sqrt = FpSqrt(this.ORDER);
|
|
9902
|
-
return this._sqrt(this, num);
|
|
9903
|
-
}
|
|
9904
|
-
toBytes(num) {
|
|
9905
|
-
return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
|
|
9906
|
-
}
|
|
9907
|
-
fromBytes(bytes, skipValidation = false) {
|
|
9908
|
-
abytes(bytes);
|
|
9909
|
-
const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
|
|
9910
|
-
if (allowedLengths) {
|
|
9911
|
-
if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
|
|
9912
|
-
throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
|
|
9913
|
-
}
|
|
9914
|
-
const padded = new Uint8Array(BYTES);
|
|
9915
|
-
padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
|
|
9916
|
-
bytes = padded;
|
|
9917
|
-
}
|
|
9918
|
-
if (bytes.length !== BYTES)
|
|
9919
|
-
throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
|
|
9920
|
-
let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
|
|
9921
|
-
if (modFromBytes)
|
|
9922
|
-
scalar = mod(scalar, ORDER);
|
|
9923
|
-
if (!skipValidation) {
|
|
9924
|
-
if (!this.isValid(scalar))
|
|
9925
|
-
throw new Error("invalid field element: outside of range 0..ORDER");
|
|
9926
|
-
}
|
|
9927
|
-
return scalar;
|
|
9928
|
-
}
|
|
9929
|
-
// TODO: we don't need it here, move out to separate fn
|
|
9930
|
-
invertBatch(lst) {
|
|
9931
|
-
return FpInvertBatch(this, lst);
|
|
9932
|
-
}
|
|
9933
|
-
// We can't move this out because Fp6, Fp12 implement it
|
|
9934
|
-
// and it's unclear what to return in there.
|
|
9935
|
-
cmov(a, b, condition) {
|
|
9936
|
-
return condition ? b : a;
|
|
9937
|
-
}
|
|
9938
|
-
};
|
|
9939
|
-
function Field(ORDER, opts = {}) {
|
|
9940
|
-
return new _Field(ORDER, opts);
|
|
9941
|
-
}
|
|
9942
|
-
function getFieldBytesLength(fieldOrder) {
|
|
9943
|
-
if (typeof fieldOrder !== "bigint")
|
|
9944
|
-
throw new Error("field order must be bigint");
|
|
9945
|
-
const bitLength = fieldOrder.toString(2).length;
|
|
9946
|
-
return Math.ceil(bitLength / 8);
|
|
9947
|
-
}
|
|
9948
|
-
function getMinHashLength(fieldOrder) {
|
|
9949
|
-
const length = getFieldBytesLength(fieldOrder);
|
|
9950
|
-
return length + Math.ceil(length / 2);
|
|
9951
|
-
}
|
|
9952
|
-
function mapHashToField(key, fieldOrder, isLE = false) {
|
|
9953
|
-
abytes(key);
|
|
9954
|
-
const len = key.length;
|
|
9955
|
-
const fieldLen = getFieldBytesLength(fieldOrder);
|
|
9956
|
-
const minLen = getMinHashLength(fieldOrder);
|
|
9957
|
-
if (len < 16 || len < minLen || len > 1024)
|
|
9958
|
-
throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
|
|
9959
|
-
const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
|
|
9960
|
-
const reduced = mod(num, fieldOrder - _1n2) + _1n2;
|
|
9961
|
-
return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
|
|
9962
|
-
}
|
|
9963
|
-
|
|
9964
|
-
// node_modules/@noble/curves/abstract/curve.js
|
|
9965
|
-
var _0n3 = /* @__PURE__ */ BigInt(0);
|
|
9966
|
-
var _1n3 = /* @__PURE__ */ BigInt(1);
|
|
9967
|
-
function negateCt(condition, item) {
|
|
9968
|
-
const neg = item.negate();
|
|
9969
|
-
return condition ? neg : item;
|
|
9970
|
-
}
|
|
9971
|
-
function normalizeZ(c, points) {
|
|
9972
|
-
const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
|
|
9973
|
-
return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
|
|
9974
|
-
}
|
|
9975
|
-
function validateW(W, bits) {
|
|
9976
|
-
if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
|
|
9977
|
-
throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
|
|
9978
|
-
}
|
|
9979
|
-
function calcWOpts(W, scalarBits) {
|
|
9980
|
-
validateW(W, scalarBits);
|
|
9981
|
-
const windows = Math.ceil(scalarBits / W) + 1;
|
|
9982
|
-
const windowSize = 2 ** (W - 1);
|
|
9983
|
-
const maxNumber = 2 ** W;
|
|
9984
|
-
const mask = bitMask(W);
|
|
9985
|
-
const shiftBy = BigInt(W);
|
|
9986
|
-
return { windows, windowSize, mask, maxNumber, shiftBy };
|
|
9987
|
-
}
|
|
9988
|
-
function calcOffsets(n, window, wOpts) {
|
|
9989
|
-
const { windowSize, mask, maxNumber, shiftBy } = wOpts;
|
|
9990
|
-
let wbits = Number(n & mask);
|
|
9991
|
-
let nextN = n >> shiftBy;
|
|
9992
|
-
if (wbits > windowSize) {
|
|
9993
|
-
wbits -= maxNumber;
|
|
9994
|
-
nextN += _1n3;
|
|
9995
|
-
}
|
|
9996
|
-
const offsetStart = window * windowSize;
|
|
9997
|
-
const offset = offsetStart + Math.abs(wbits) - 1;
|
|
9998
|
-
const isZero = wbits === 0;
|
|
9999
|
-
const isNeg = wbits < 0;
|
|
10000
|
-
const isNegF = window % 2 !== 0;
|
|
10001
|
-
const offsetF = offsetStart;
|
|
10002
|
-
return { nextN, offset, isZero, isNeg, isNegF, offsetF };
|
|
10003
|
-
}
|
|
10004
|
-
var pointPrecomputes = /* @__PURE__ */ new WeakMap();
|
|
10005
|
-
var pointWindowSizes = /* @__PURE__ */ new WeakMap();
|
|
10006
|
-
function getW(P) {
|
|
10007
|
-
return pointWindowSizes.get(P) || 1;
|
|
10008
|
-
}
|
|
10009
|
-
function assert0(n) {
|
|
10010
|
-
if (n !== _0n3)
|
|
10011
|
-
throw new Error("invalid wNAF");
|
|
10012
|
-
}
|
|
10013
|
-
var wNAF = class {
|
|
10014
|
-
BASE;
|
|
10015
|
-
ZERO;
|
|
10016
|
-
Fn;
|
|
10017
|
-
bits;
|
|
10018
|
-
// Parametrized with a given Point class (not individual point)
|
|
10019
|
-
constructor(Point, bits) {
|
|
10020
|
-
this.BASE = Point.BASE;
|
|
10021
|
-
this.ZERO = Point.ZERO;
|
|
10022
|
-
this.Fn = Point.Fn;
|
|
10023
|
-
this.bits = bits;
|
|
10024
|
-
}
|
|
10025
|
-
// non-const time multiplication ladder
|
|
10026
|
-
_unsafeLadder(elm, n, p = this.ZERO) {
|
|
10027
|
-
let d = elm;
|
|
10028
|
-
while (n > _0n3) {
|
|
10029
|
-
if (n & _1n3)
|
|
10030
|
-
p = p.add(d);
|
|
10031
|
-
d = d.double();
|
|
10032
|
-
n >>= _1n3;
|
|
10033
|
-
}
|
|
10034
|
-
return p;
|
|
10035
|
-
}
|
|
10036
|
-
/**
|
|
10037
|
-
* Creates a wNAF precomputation window. Used for caching.
|
|
10038
|
-
* Default window size is set by `utils.precompute()` and is equal to 8.
|
|
10039
|
-
* Number of precomputed points depends on the curve size:
|
|
10040
|
-
* 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
|
|
10041
|
-
* - 𝑊 is the window size
|
|
10042
|
-
* - 𝑛 is the bitlength of the curve order.
|
|
10043
|
-
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
|
|
10044
|
-
* @param point Point instance
|
|
10045
|
-
* @param W window size
|
|
10046
|
-
* @returns precomputed point tables flattened to a single array
|
|
10047
|
-
*/
|
|
10048
|
-
precomputeWindow(point, W) {
|
|
10049
|
-
const { windows, windowSize } = calcWOpts(W, this.bits);
|
|
10050
|
-
const points = [];
|
|
10051
|
-
let p = point;
|
|
10052
|
-
let base = p;
|
|
10053
|
-
for (let window = 0; window < windows; window++) {
|
|
10054
|
-
base = p;
|
|
10055
|
-
points.push(base);
|
|
10056
|
-
for (let i = 1; i < windowSize; i++) {
|
|
10057
|
-
base = base.add(p);
|
|
10058
|
-
points.push(base);
|
|
10059
|
-
}
|
|
10060
|
-
p = base.double();
|
|
10061
|
-
}
|
|
10062
|
-
return points;
|
|
10063
|
-
}
|
|
10064
|
-
/**
|
|
10065
|
-
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
|
|
10066
|
-
* More compact implementation:
|
|
10067
|
-
* https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
|
|
10068
|
-
* @returns real and fake (for const-time) points
|
|
10069
|
-
*/
|
|
10070
|
-
wNAF(W, precomputes, n) {
|
|
10071
|
-
if (!this.Fn.isValid(n))
|
|
10072
|
-
throw new Error("invalid scalar");
|
|
10073
|
-
let p = this.ZERO;
|
|
10074
|
-
let f = this.BASE;
|
|
10075
|
-
const wo = calcWOpts(W, this.bits);
|
|
10076
|
-
for (let window = 0; window < wo.windows; window++) {
|
|
10077
|
-
const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
|
|
10078
|
-
n = nextN;
|
|
10079
|
-
if (isZero) {
|
|
10080
|
-
f = f.add(negateCt(isNegF, precomputes[offsetF]));
|
|
10081
|
-
} else {
|
|
10082
|
-
p = p.add(negateCt(isNeg, precomputes[offset]));
|
|
10083
|
-
}
|
|
10084
|
-
}
|
|
10085
|
-
assert0(n);
|
|
10086
|
-
return { p, f };
|
|
10087
|
-
}
|
|
10088
|
-
/**
|
|
10089
|
-
* Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
|
|
10090
|
-
* @param acc accumulator point to add result of multiplication
|
|
10091
|
-
* @returns point
|
|
10092
|
-
*/
|
|
10093
|
-
wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
|
|
10094
|
-
const wo = calcWOpts(W, this.bits);
|
|
10095
|
-
for (let window = 0; window < wo.windows; window++) {
|
|
10096
|
-
if (n === _0n3)
|
|
10097
|
-
break;
|
|
10098
|
-
const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
|
|
10099
|
-
n = nextN;
|
|
10100
|
-
if (isZero) {
|
|
10101
|
-
continue;
|
|
10102
|
-
} else {
|
|
10103
|
-
const item = precomputes[offset];
|
|
10104
|
-
acc = acc.add(isNeg ? item.negate() : item);
|
|
10105
|
-
}
|
|
10106
|
-
}
|
|
10107
|
-
assert0(n);
|
|
10108
|
-
return acc;
|
|
10109
|
-
}
|
|
10110
|
-
getPrecomputes(W, point, transform) {
|
|
10111
|
-
let comp = pointPrecomputes.get(point);
|
|
10112
|
-
if (!comp) {
|
|
10113
|
-
comp = this.precomputeWindow(point, W);
|
|
10114
|
-
if (W !== 1) {
|
|
10115
|
-
if (typeof transform === "function")
|
|
10116
|
-
comp = transform(comp);
|
|
10117
|
-
pointPrecomputes.set(point, comp);
|
|
10118
|
-
}
|
|
10119
|
-
}
|
|
10120
|
-
return comp;
|
|
10121
|
-
}
|
|
10122
|
-
cached(point, scalar, transform) {
|
|
10123
|
-
const W = getW(point);
|
|
10124
|
-
return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
|
|
10125
|
-
}
|
|
10126
|
-
unsafe(point, scalar, transform, prev) {
|
|
10127
|
-
const W = getW(point);
|
|
10128
|
-
if (W === 1)
|
|
10129
|
-
return this._unsafeLadder(point, scalar, prev);
|
|
10130
|
-
return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
|
|
10131
|
-
}
|
|
10132
|
-
// We calculate precomputes for elliptic curve point multiplication
|
|
10133
|
-
// using windowed method. This specifies window size and
|
|
10134
|
-
// stores precomputed values. Usually only base point would be precomputed.
|
|
10135
|
-
createCache(P, W) {
|
|
10136
|
-
validateW(W, this.bits);
|
|
10137
|
-
pointWindowSizes.set(P, W);
|
|
10138
|
-
pointPrecomputes.delete(P);
|
|
10139
|
-
}
|
|
10140
|
-
hasCache(elm) {
|
|
10141
|
-
return getW(elm) !== 1;
|
|
10142
|
-
}
|
|
10143
|
-
};
|
|
10144
|
-
function mulEndoUnsafe(Point, point, k1, k2) {
|
|
10145
|
-
let acc = point;
|
|
10146
|
-
let p1 = Point.ZERO;
|
|
10147
|
-
let p2 = Point.ZERO;
|
|
10148
|
-
while (k1 > _0n3 || k2 > _0n3) {
|
|
10149
|
-
if (k1 & _1n3)
|
|
10150
|
-
p1 = p1.add(acc);
|
|
10151
|
-
if (k2 & _1n3)
|
|
10152
|
-
p2 = p2.add(acc);
|
|
10153
|
-
acc = acc.double();
|
|
10154
|
-
k1 >>= _1n3;
|
|
10155
|
-
k2 >>= _1n3;
|
|
10156
|
-
}
|
|
10157
|
-
return { p1, p2 };
|
|
10158
|
-
}
|
|
10159
|
-
function createField(order, field, isLE) {
|
|
10160
|
-
if (field) {
|
|
10161
|
-
if (field.ORDER !== order)
|
|
10162
|
-
throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
|
|
10163
|
-
validateField(field);
|
|
10164
|
-
return field;
|
|
10165
|
-
} else {
|
|
10166
|
-
return Field(order, { isLE });
|
|
10167
|
-
}
|
|
10168
|
-
}
|
|
10169
|
-
function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
|
|
10170
|
-
if (FpFnLE === void 0)
|
|
10171
|
-
FpFnLE = type === "edwards";
|
|
10172
|
-
if (!CURVE || typeof CURVE !== "object")
|
|
10173
|
-
throw new Error(`expected valid ${type} CURVE object`);
|
|
10174
|
-
for (const p of ["p", "n", "h"]) {
|
|
10175
|
-
const val = CURVE[p];
|
|
10176
|
-
if (!(typeof val === "bigint" && val > _0n3))
|
|
10177
|
-
throw new Error(`CURVE.${p} must be positive bigint`);
|
|
10178
|
-
}
|
|
10179
|
-
const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
|
|
10180
|
-
const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
|
|
10181
|
-
const _b = type === "weierstrass" ? "b" : "d";
|
|
10182
|
-
const params = ["Gx", "Gy", "a", _b];
|
|
10183
|
-
for (const p of params) {
|
|
10184
|
-
if (!Fp.isValid(CURVE[p]))
|
|
10185
|
-
throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
|
|
10186
|
-
}
|
|
10187
|
-
CURVE = Object.freeze(Object.assign({}, CURVE));
|
|
10188
|
-
return { CURVE, Fp, Fn };
|
|
10189
|
-
}
|
|
10190
|
-
function createKeygen(randomSecretKey, getPublicKey2) {
|
|
10191
|
-
return function keygen(seed) {
|
|
10192
|
-
const secretKey = randomSecretKey(seed);
|
|
10193
|
-
return { secretKey, publicKey: getPublicKey2(secretKey) };
|
|
10194
|
-
};
|
|
10195
|
-
}
|
|
10196
|
-
|
|
10197
|
-
// node_modules/@noble/hashes/hmac.js
|
|
10198
|
-
var _HMAC = class {
|
|
10199
|
-
oHash;
|
|
10200
|
-
iHash;
|
|
10201
|
-
blockLen;
|
|
10202
|
-
outputLen;
|
|
10203
|
-
finished = false;
|
|
10204
|
-
destroyed = false;
|
|
10205
|
-
constructor(hash, key) {
|
|
10206
|
-
ahash(hash);
|
|
10207
|
-
abytes(key, void 0, "key");
|
|
10208
|
-
this.iHash = hash.create();
|
|
10209
|
-
if (typeof this.iHash.update !== "function")
|
|
10210
|
-
throw new Error("Expected instance of class which extends utils.Hash");
|
|
10211
|
-
this.blockLen = this.iHash.blockLen;
|
|
10212
|
-
this.outputLen = this.iHash.outputLen;
|
|
10213
|
-
const blockLen = this.blockLen;
|
|
10214
|
-
const pad = new Uint8Array(blockLen);
|
|
10215
|
-
pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
|
|
10216
|
-
for (let i = 0; i < pad.length; i++)
|
|
10217
|
-
pad[i] ^= 54;
|
|
10218
|
-
this.iHash.update(pad);
|
|
10219
|
-
this.oHash = hash.create();
|
|
10220
|
-
for (let i = 0; i < pad.length; i++)
|
|
10221
|
-
pad[i] ^= 54 ^ 92;
|
|
10222
|
-
this.oHash.update(pad);
|
|
10223
|
-
clean(pad);
|
|
10224
|
-
}
|
|
10225
|
-
update(buf) {
|
|
10226
|
-
aexists(this);
|
|
10227
|
-
this.iHash.update(buf);
|
|
10228
|
-
return this;
|
|
10229
|
-
}
|
|
10230
|
-
digestInto(out) {
|
|
10231
|
-
aexists(this);
|
|
10232
|
-
abytes(out, this.outputLen, "output");
|
|
10233
|
-
this.finished = true;
|
|
10234
|
-
this.iHash.digestInto(out);
|
|
10235
|
-
this.oHash.update(out);
|
|
10236
|
-
this.oHash.digestInto(out);
|
|
10237
|
-
this.destroy();
|
|
10238
|
-
}
|
|
10239
|
-
digest() {
|
|
10240
|
-
const out = new Uint8Array(this.oHash.outputLen);
|
|
10241
|
-
this.digestInto(out);
|
|
10242
|
-
return out;
|
|
10243
|
-
}
|
|
10244
|
-
_cloneInto(to) {
|
|
10245
|
-
to ||= Object.create(Object.getPrototypeOf(this), {});
|
|
10246
|
-
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
|
|
10247
|
-
to = to;
|
|
10248
|
-
to.finished = finished;
|
|
10249
|
-
to.destroyed = destroyed;
|
|
10250
|
-
to.blockLen = blockLen;
|
|
10251
|
-
to.outputLen = outputLen;
|
|
10252
|
-
to.oHash = oHash._cloneInto(to.oHash);
|
|
10253
|
-
to.iHash = iHash._cloneInto(to.iHash);
|
|
10254
|
-
return to;
|
|
10255
|
-
}
|
|
10256
|
-
clone() {
|
|
10257
|
-
return this._cloneInto();
|
|
10258
|
-
}
|
|
10259
|
-
destroy() {
|
|
10260
|
-
this.destroyed = true;
|
|
10261
|
-
this.oHash.destroy();
|
|
10262
|
-
this.iHash.destroy();
|
|
10263
|
-
}
|
|
10264
|
-
};
|
|
10265
|
-
var hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();
|
|
10266
|
-
hmac.create = (hash, key) => new _HMAC(hash, key);
|
|
10267
|
-
|
|
10268
|
-
// node_modules/@noble/curves/abstract/weierstrass.js
|
|
10269
|
-
var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den;
|
|
10270
|
-
function _splitEndoScalar(k, basis, n) {
|
|
10271
|
-
const [[a1, b1], [a2, b2]] = basis;
|
|
10272
|
-
const c1 = divNearest(b2 * k, n);
|
|
10273
|
-
const c2 = divNearest(-b1 * k, n);
|
|
10274
|
-
let k1 = k - c1 * a1 - c2 * a2;
|
|
10275
|
-
let k2 = -c1 * b1 - c2 * b2;
|
|
10276
|
-
const k1neg = k1 < _0n4;
|
|
10277
|
-
const k2neg = k2 < _0n4;
|
|
10278
|
-
if (k1neg)
|
|
10279
|
-
k1 = -k1;
|
|
10280
|
-
if (k2neg)
|
|
10281
|
-
k2 = -k2;
|
|
10282
|
-
const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
|
|
10283
|
-
if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) {
|
|
10284
|
-
throw new Error("splitScalar (endomorphism): failed, k=" + k);
|
|
10285
|
-
}
|
|
10286
|
-
return { k1neg, k1, k2neg, k2 };
|
|
10287
|
-
}
|
|
10288
|
-
function validateSigFormat(format) {
|
|
10289
|
-
if (!["compact", "recovered", "der"].includes(format))
|
|
10290
|
-
throw new Error('Signature format must be "compact", "recovered", or "der"');
|
|
10291
|
-
return format;
|
|
10292
|
-
}
|
|
10293
|
-
function validateSigOpts(opts, def) {
|
|
10294
|
-
const optsn = {};
|
|
10295
|
-
for (let optName of Object.keys(def)) {
|
|
10296
|
-
optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
|
|
10297
|
-
}
|
|
10298
|
-
abool(optsn.lowS, "lowS");
|
|
10299
|
-
abool(optsn.prehash, "prehash");
|
|
10300
|
-
if (optsn.format !== void 0)
|
|
10301
|
-
validateSigFormat(optsn.format);
|
|
10302
|
-
return optsn;
|
|
10303
|
-
}
|
|
10304
|
-
var DERErr = class extends Error {
|
|
10305
|
-
constructor(m = "") {
|
|
10306
|
-
super(m);
|
|
10307
|
-
}
|
|
10308
|
-
};
|
|
10309
|
-
var DER = {
|
|
10310
|
-
// asn.1 DER encoding utils
|
|
10311
|
-
Err: DERErr,
|
|
10312
|
-
// Basic building block is TLV (Tag-Length-Value)
|
|
10313
|
-
_tlv: {
|
|
10314
|
-
encode: (tag, data) => {
|
|
10315
|
-
const { Err: E } = DER;
|
|
10316
|
-
if (tag < 0 || tag > 256)
|
|
10317
|
-
throw new E("tlv.encode: wrong tag");
|
|
10318
|
-
if (data.length & 1)
|
|
10319
|
-
throw new E("tlv.encode: unpadded data");
|
|
10320
|
-
const dataLen = data.length / 2;
|
|
10321
|
-
const len = numberToHexUnpadded(dataLen);
|
|
10322
|
-
if (len.length / 2 & 128)
|
|
10323
|
-
throw new E("tlv.encode: long form length too big");
|
|
10324
|
-
const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
|
|
10325
|
-
const t = numberToHexUnpadded(tag);
|
|
10326
|
-
return t + lenLen + len + data;
|
|
10327
|
-
},
|
|
10328
|
-
// v - value, l - left bytes (unparsed)
|
|
10329
|
-
decode(tag, data) {
|
|
10330
|
-
const { Err: E } = DER;
|
|
10331
|
-
let pos = 0;
|
|
10332
|
-
if (tag < 0 || tag > 256)
|
|
10333
|
-
throw new E("tlv.encode: wrong tag");
|
|
10334
|
-
if (data.length < 2 || data[pos++] !== tag)
|
|
10335
|
-
throw new E("tlv.decode: wrong tlv");
|
|
10336
|
-
const first = data[pos++];
|
|
10337
|
-
const isLong = !!(first & 128);
|
|
10338
|
-
let length = 0;
|
|
10339
|
-
if (!isLong)
|
|
10340
|
-
length = first;
|
|
10341
|
-
else {
|
|
10342
|
-
const lenLen = first & 127;
|
|
10343
|
-
if (!lenLen)
|
|
10344
|
-
throw new E("tlv.decode(long): indefinite length not supported");
|
|
10345
|
-
if (lenLen > 4)
|
|
10346
|
-
throw new E("tlv.decode(long): byte length is too big");
|
|
10347
|
-
const lengthBytes = data.subarray(pos, pos + lenLen);
|
|
10348
|
-
if (lengthBytes.length !== lenLen)
|
|
10349
|
-
throw new E("tlv.decode: length bytes not complete");
|
|
10350
|
-
if (lengthBytes[0] === 0)
|
|
10351
|
-
throw new E("tlv.decode(long): zero leftmost byte");
|
|
10352
|
-
for (const b of lengthBytes)
|
|
10353
|
-
length = length << 8 | b;
|
|
10354
|
-
pos += lenLen;
|
|
10355
|
-
if (length < 128)
|
|
10356
|
-
throw new E("tlv.decode(long): not minimal encoding");
|
|
10357
|
-
}
|
|
10358
|
-
const v = data.subarray(pos, pos + length);
|
|
10359
|
-
if (v.length !== length)
|
|
10360
|
-
throw new E("tlv.decode: wrong value length");
|
|
10361
|
-
return { v, l: data.subarray(pos + length) };
|
|
10362
|
-
}
|
|
10363
|
-
},
|
|
10364
|
-
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
|
|
10365
|
-
// since we always use positive integers here. It must always be empty:
|
|
10366
|
-
// - add zero byte if exists
|
|
10367
|
-
// - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
|
|
10368
|
-
_int: {
|
|
10369
|
-
encode(num) {
|
|
10370
|
-
const { Err: E } = DER;
|
|
10371
|
-
if (num < _0n4)
|
|
10372
|
-
throw new E("integer: negative integers are not allowed");
|
|
10373
|
-
let hex = numberToHexUnpadded(num);
|
|
10374
|
-
if (Number.parseInt(hex[0], 16) & 8)
|
|
10375
|
-
hex = "00" + hex;
|
|
10376
|
-
if (hex.length & 1)
|
|
10377
|
-
throw new E("unexpected DER parsing assertion: unpadded hex");
|
|
10378
|
-
return hex;
|
|
10379
|
-
},
|
|
10380
|
-
decode(data) {
|
|
10381
|
-
const { Err: E } = DER;
|
|
10382
|
-
if (data[0] & 128)
|
|
10383
|
-
throw new E("invalid signature integer: negative");
|
|
10384
|
-
if (data[0] === 0 && !(data[1] & 128))
|
|
10385
|
-
throw new E("invalid signature integer: unnecessary leading zero");
|
|
10386
|
-
return bytesToNumberBE(data);
|
|
10387
|
-
}
|
|
10388
|
-
},
|
|
10389
|
-
toSig(bytes) {
|
|
10390
|
-
const { Err: E, _int: int, _tlv: tlv } = DER;
|
|
10391
|
-
const data = abytes(bytes, void 0, "signature");
|
|
10392
|
-
const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
|
|
10393
|
-
if (seqLeftBytes.length)
|
|
10394
|
-
throw new E("invalid signature: left bytes after parsing");
|
|
10395
|
-
const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
|
|
10396
|
-
const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
|
|
10397
|
-
if (sLeftBytes.length)
|
|
10398
|
-
throw new E("invalid signature: left bytes after parsing");
|
|
10399
|
-
return { r: int.decode(rBytes), s: int.decode(sBytes) };
|
|
10400
|
-
},
|
|
10401
|
-
hexFromSig(sig) {
|
|
10402
|
-
const { _tlv: tlv, _int: int } = DER;
|
|
10403
|
-
const rs = tlv.encode(2, int.encode(sig.r));
|
|
10404
|
-
const ss = tlv.encode(2, int.encode(sig.s));
|
|
10405
|
-
const seq = rs + ss;
|
|
10406
|
-
return tlv.encode(48, seq);
|
|
10407
|
-
}
|
|
10408
|
-
};
|
|
10409
|
-
var _0n4 = BigInt(0);
|
|
10410
|
-
var _1n4 = BigInt(1);
|
|
10411
|
-
var _2n2 = BigInt(2);
|
|
10412
|
-
var _3n2 = BigInt(3);
|
|
10413
|
-
var _4n2 = BigInt(4);
|
|
10414
|
-
function weierstrass(params, extraOpts = {}) {
|
|
10415
|
-
const validated = createCurveFields("weierstrass", params, extraOpts);
|
|
10416
|
-
const { Fp, Fn } = validated;
|
|
10417
|
-
let CURVE = validated.CURVE;
|
|
10418
|
-
const { h: cofactor, n: CURVE_ORDER2 } = CURVE;
|
|
10419
|
-
validateObject(extraOpts, {}, {
|
|
10420
|
-
allowInfinityPoint: "boolean",
|
|
10421
|
-
clearCofactor: "function",
|
|
10422
|
-
isTorsionFree: "function",
|
|
10423
|
-
fromBytes: "function",
|
|
10424
|
-
toBytes: "function",
|
|
10425
|
-
endo: "object"
|
|
10426
|
-
});
|
|
10427
|
-
const { endo } = extraOpts;
|
|
10428
|
-
if (endo) {
|
|
10429
|
-
if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
|
|
10430
|
-
throw new Error('invalid endo: expected "beta": bigint and "basises": array');
|
|
10431
|
-
}
|
|
10432
|
-
}
|
|
10433
|
-
const lengths = getWLengths(Fp, Fn);
|
|
10434
|
-
function assertCompressionIsSupported() {
|
|
10435
|
-
if (!Fp.isOdd)
|
|
10436
|
-
throw new Error("compression is not supported: Field does not have .isOdd()");
|
|
10437
|
-
}
|
|
10438
|
-
function pointToBytes(_c, point, isCompressed) {
|
|
10439
|
-
const { x, y } = point.toAffine();
|
|
10440
|
-
const bx = Fp.toBytes(x);
|
|
10441
|
-
abool(isCompressed, "isCompressed");
|
|
10442
|
-
if (isCompressed) {
|
|
10443
|
-
assertCompressionIsSupported();
|
|
10444
|
-
const hasEvenY = !Fp.isOdd(y);
|
|
10445
|
-
return concatBytes(pprefix(hasEvenY), bx);
|
|
10446
|
-
} else {
|
|
10447
|
-
return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
|
|
10448
|
-
}
|
|
10449
|
-
}
|
|
10450
|
-
function pointFromBytes(bytes) {
|
|
10451
|
-
abytes(bytes, void 0, "Point");
|
|
10452
|
-
const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
|
|
10453
|
-
const length = bytes.length;
|
|
10454
|
-
const head = bytes[0];
|
|
10455
|
-
const tail = bytes.subarray(1);
|
|
10456
|
-
if (length === comp && (head === 2 || head === 3)) {
|
|
10457
|
-
const x = Fp.fromBytes(tail);
|
|
10458
|
-
if (!Fp.isValid(x))
|
|
10459
|
-
throw new Error("bad point: is not on curve, wrong x");
|
|
10460
|
-
const y2 = weierstrassEquation(x);
|
|
10461
|
-
let y;
|
|
10462
|
-
try {
|
|
10463
|
-
y = Fp.sqrt(y2);
|
|
10464
|
-
} catch (sqrtError) {
|
|
10465
|
-
const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
|
|
10466
|
-
throw new Error("bad point: is not on curve, sqrt error" + err);
|
|
10467
|
-
}
|
|
10468
|
-
assertCompressionIsSupported();
|
|
10469
|
-
const evenY = Fp.isOdd(y);
|
|
10470
|
-
const evenH = (head & 1) === 1;
|
|
10471
|
-
if (evenH !== evenY)
|
|
10472
|
-
y = Fp.neg(y);
|
|
10473
|
-
return { x, y };
|
|
10474
|
-
} else if (length === uncomp && head === 4) {
|
|
10475
|
-
const L = Fp.BYTES;
|
|
10476
|
-
const x = Fp.fromBytes(tail.subarray(0, L));
|
|
10477
|
-
const y = Fp.fromBytes(tail.subarray(L, L * 2));
|
|
10478
|
-
if (!isValidXY(x, y))
|
|
10479
|
-
throw new Error("bad point: is not on curve");
|
|
10480
|
-
return { x, y };
|
|
10481
|
-
} else {
|
|
10482
|
-
throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
|
|
10483
|
-
}
|
|
10484
|
-
}
|
|
10485
|
-
const encodePoint = extraOpts.toBytes || pointToBytes;
|
|
10486
|
-
const decodePoint = extraOpts.fromBytes || pointFromBytes;
|
|
10487
|
-
function weierstrassEquation(x) {
|
|
10488
|
-
const x2 = Fp.sqr(x);
|
|
10489
|
-
const x3 = Fp.mul(x2, x);
|
|
10490
|
-
return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
|
|
10491
|
-
}
|
|
10492
|
-
function isValidXY(x, y) {
|
|
10493
|
-
const left = Fp.sqr(y);
|
|
10494
|
-
const right = weierstrassEquation(x);
|
|
10495
|
-
return Fp.eql(left, right);
|
|
10496
|
-
}
|
|
10497
|
-
if (!isValidXY(CURVE.Gx, CURVE.Gy))
|
|
10498
|
-
throw new Error("bad curve params: generator point");
|
|
10499
|
-
const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
|
|
10500
|
-
const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
|
|
10501
|
-
if (Fp.is0(Fp.add(_4a3, _27b2)))
|
|
10502
|
-
throw new Error("bad curve params: a or b");
|
|
10503
|
-
function acoord(title, n, banZero = false) {
|
|
10504
|
-
if (!Fp.isValid(n) || banZero && Fp.is0(n))
|
|
10505
|
-
throw new Error(`bad point coordinate ${title}`);
|
|
10506
|
-
return n;
|
|
10507
|
-
}
|
|
10508
|
-
function aprjpoint(other) {
|
|
10509
|
-
if (!(other instanceof Point))
|
|
10510
|
-
throw new Error("Weierstrass Point expected");
|
|
10511
|
-
}
|
|
10512
|
-
function splitEndoScalarN(k) {
|
|
10513
|
-
if (!endo || !endo.basises)
|
|
10514
|
-
throw new Error("no endo");
|
|
10515
|
-
return _splitEndoScalar(k, endo.basises, Fn.ORDER);
|
|
10516
|
-
}
|
|
10517
|
-
const toAffineMemo = memoized((p, iz) => {
|
|
10518
|
-
const { X, Y, Z } = p;
|
|
10519
|
-
if (Fp.eql(Z, Fp.ONE))
|
|
10520
|
-
return { x: X, y: Y };
|
|
10521
|
-
const is0 = p.is0();
|
|
10522
|
-
if (iz == null)
|
|
10523
|
-
iz = is0 ? Fp.ONE : Fp.inv(Z);
|
|
10524
|
-
const x = Fp.mul(X, iz);
|
|
10525
|
-
const y = Fp.mul(Y, iz);
|
|
10526
|
-
const zz = Fp.mul(Z, iz);
|
|
10527
|
-
if (is0)
|
|
10528
|
-
return { x: Fp.ZERO, y: Fp.ZERO };
|
|
10529
|
-
if (!Fp.eql(zz, Fp.ONE))
|
|
10530
|
-
throw new Error("invZ was invalid");
|
|
10531
|
-
return { x, y };
|
|
10532
|
-
});
|
|
10533
|
-
const assertValidMemo = memoized((p) => {
|
|
10534
|
-
if (p.is0()) {
|
|
10535
|
-
if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
|
|
10536
|
-
return;
|
|
10537
|
-
throw new Error("bad point: ZERO");
|
|
10538
|
-
}
|
|
10539
|
-
const { x, y } = p.toAffine();
|
|
10540
|
-
if (!Fp.isValid(x) || !Fp.isValid(y))
|
|
10541
|
-
throw new Error("bad point: x or y not field elements");
|
|
10542
|
-
if (!isValidXY(x, y))
|
|
10543
|
-
throw new Error("bad point: equation left != right");
|
|
10544
|
-
if (!p.isTorsionFree())
|
|
10545
|
-
throw new Error("bad point: not in prime-order subgroup");
|
|
10546
|
-
return true;
|
|
10547
|
-
});
|
|
10548
|
-
function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
|
|
10549
|
-
k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
|
|
10550
|
-
k1p = negateCt(k1neg, k1p);
|
|
10551
|
-
k2p = negateCt(k2neg, k2p);
|
|
10552
|
-
return k1p.add(k2p);
|
|
10553
|
-
}
|
|
10554
|
-
class Point {
|
|
10555
|
-
// base / generator point
|
|
10556
|
-
static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
|
|
10557
|
-
// zero / infinity / identity point
|
|
10558
|
-
static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
|
|
10559
|
-
// 0, 1, 0
|
|
10560
|
-
// math field
|
|
10561
|
-
static Fp = Fp;
|
|
10562
|
-
// scalar field
|
|
10563
|
-
static Fn = Fn;
|
|
10564
|
-
X;
|
|
10565
|
-
Y;
|
|
10566
|
-
Z;
|
|
10567
|
-
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
10568
|
-
constructor(X, Y, Z) {
|
|
10569
|
-
this.X = acoord("x", X);
|
|
10570
|
-
this.Y = acoord("y", Y, true);
|
|
10571
|
-
this.Z = acoord("z", Z);
|
|
10572
|
-
Object.freeze(this);
|
|
10573
|
-
}
|
|
10574
|
-
static CURVE() {
|
|
10575
|
-
return CURVE;
|
|
10576
|
-
}
|
|
10577
|
-
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
10578
|
-
static fromAffine(p) {
|
|
10579
|
-
const { x, y } = p || {};
|
|
10580
|
-
if (!p || !Fp.isValid(x) || !Fp.isValid(y))
|
|
10581
|
-
throw new Error("invalid affine point");
|
|
10582
|
-
if (p instanceof Point)
|
|
10583
|
-
throw new Error("projective point not allowed");
|
|
10584
|
-
if (Fp.is0(x) && Fp.is0(y))
|
|
10585
|
-
return Point.ZERO;
|
|
10586
|
-
return new Point(x, y, Fp.ONE);
|
|
10587
|
-
}
|
|
10588
|
-
static fromBytes(bytes) {
|
|
10589
|
-
const P = Point.fromAffine(decodePoint(abytes(bytes, void 0, "point")));
|
|
10590
|
-
P.assertValidity();
|
|
10591
|
-
return P;
|
|
10592
|
-
}
|
|
10593
|
-
static fromHex(hex) {
|
|
10594
|
-
return Point.fromBytes(hexToBytes2(hex));
|
|
10595
|
-
}
|
|
10596
|
-
get x() {
|
|
10597
|
-
return this.toAffine().x;
|
|
10598
|
-
}
|
|
10599
|
-
get y() {
|
|
10600
|
-
return this.toAffine().y;
|
|
10601
|
-
}
|
|
10602
|
-
/**
|
|
10603
|
-
*
|
|
10604
|
-
* @param windowSize
|
|
10605
|
-
* @param isLazy true will defer table computation until the first multiplication
|
|
10606
|
-
* @returns
|
|
10607
|
-
*/
|
|
10608
|
-
precompute(windowSize = 8, isLazy = true) {
|
|
10609
|
-
wnaf.createCache(this, windowSize);
|
|
10610
|
-
if (!isLazy)
|
|
10611
|
-
this.multiply(_3n2);
|
|
10612
|
-
return this;
|
|
10613
|
-
}
|
|
10614
|
-
// TODO: return `this`
|
|
10615
|
-
/** A point on curve is valid if it conforms to equation. */
|
|
10616
|
-
assertValidity() {
|
|
10617
|
-
assertValidMemo(this);
|
|
10618
|
-
}
|
|
10619
|
-
hasEvenY() {
|
|
10620
|
-
const { y } = this.toAffine();
|
|
10621
|
-
if (!Fp.isOdd)
|
|
10622
|
-
throw new Error("Field doesn't support isOdd");
|
|
10623
|
-
return !Fp.isOdd(y);
|
|
10624
|
-
}
|
|
10625
|
-
/** Compare one point to another. */
|
|
10626
|
-
equals(other) {
|
|
10627
|
-
aprjpoint(other);
|
|
10628
|
-
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
10629
|
-
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
10630
|
-
const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
|
|
10631
|
-
const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
|
|
10632
|
-
return U1 && U2;
|
|
10633
|
-
}
|
|
10634
|
-
/** Flips point to one corresponding to (x, -y) in Affine coordinates. */
|
|
10635
|
-
negate() {
|
|
10636
|
-
return new Point(this.X, Fp.neg(this.Y), this.Z);
|
|
10637
|
-
}
|
|
10638
|
-
// Renes-Costello-Batina exception-free doubling formula.
|
|
10639
|
-
// There is 30% faster Jacobian formula, but it is not complete.
|
|
10640
|
-
// https://eprint.iacr.org/2015/1060, algorithm 3
|
|
10641
|
-
// Cost: 8M + 3S + 3*a + 2*b3 + 15add.
|
|
10642
|
-
double() {
|
|
10643
|
-
const { a, b } = CURVE;
|
|
10644
|
-
const b3 = Fp.mul(b, _3n2);
|
|
10645
|
-
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
10646
|
-
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
|
|
10647
|
-
let t0 = Fp.mul(X1, X1);
|
|
10648
|
-
let t1 = Fp.mul(Y1, Y1);
|
|
10649
|
-
let t2 = Fp.mul(Z1, Z1);
|
|
10650
|
-
let t3 = Fp.mul(X1, Y1);
|
|
10651
|
-
t3 = Fp.add(t3, t3);
|
|
10652
|
-
Z3 = Fp.mul(X1, Z1);
|
|
10653
|
-
Z3 = Fp.add(Z3, Z3);
|
|
10654
|
-
X3 = Fp.mul(a, Z3);
|
|
10655
|
-
Y3 = Fp.mul(b3, t2);
|
|
10656
|
-
Y3 = Fp.add(X3, Y3);
|
|
10657
|
-
X3 = Fp.sub(t1, Y3);
|
|
10658
|
-
Y3 = Fp.add(t1, Y3);
|
|
10659
|
-
Y3 = Fp.mul(X3, Y3);
|
|
10660
|
-
X3 = Fp.mul(t3, X3);
|
|
10661
|
-
Z3 = Fp.mul(b3, Z3);
|
|
10662
|
-
t2 = Fp.mul(a, t2);
|
|
10663
|
-
t3 = Fp.sub(t0, t2);
|
|
10664
|
-
t3 = Fp.mul(a, t3);
|
|
10665
|
-
t3 = Fp.add(t3, Z3);
|
|
10666
|
-
Z3 = Fp.add(t0, t0);
|
|
10667
|
-
t0 = Fp.add(Z3, t0);
|
|
10668
|
-
t0 = Fp.add(t0, t2);
|
|
10669
|
-
t0 = Fp.mul(t0, t3);
|
|
10670
|
-
Y3 = Fp.add(Y3, t0);
|
|
10671
|
-
t2 = Fp.mul(Y1, Z1);
|
|
10672
|
-
t2 = Fp.add(t2, t2);
|
|
10673
|
-
t0 = Fp.mul(t2, t3);
|
|
10674
|
-
X3 = Fp.sub(X3, t0);
|
|
10675
|
-
Z3 = Fp.mul(t2, t1);
|
|
10676
|
-
Z3 = Fp.add(Z3, Z3);
|
|
10677
|
-
Z3 = Fp.add(Z3, Z3);
|
|
10678
|
-
return new Point(X3, Y3, Z3);
|
|
10679
|
-
}
|
|
10680
|
-
// Renes-Costello-Batina exception-free addition formula.
|
|
10681
|
-
// There is 30% faster Jacobian formula, but it is not complete.
|
|
10682
|
-
// https://eprint.iacr.org/2015/1060, algorithm 1
|
|
10683
|
-
// Cost: 12M + 0S + 3*a + 3*b3 + 23add.
|
|
10684
|
-
add(other) {
|
|
10685
|
-
aprjpoint(other);
|
|
10686
|
-
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
10687
|
-
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
10688
|
-
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
|
|
10689
|
-
const a = CURVE.a;
|
|
10690
|
-
const b3 = Fp.mul(CURVE.b, _3n2);
|
|
10691
|
-
let t0 = Fp.mul(X1, X2);
|
|
10692
|
-
let t1 = Fp.mul(Y1, Y2);
|
|
10693
|
-
let t2 = Fp.mul(Z1, Z2);
|
|
10694
|
-
let t3 = Fp.add(X1, Y1);
|
|
10695
|
-
let t4 = Fp.add(X2, Y2);
|
|
10696
|
-
t3 = Fp.mul(t3, t4);
|
|
10697
|
-
t4 = Fp.add(t0, t1);
|
|
10698
|
-
t3 = Fp.sub(t3, t4);
|
|
10699
|
-
t4 = Fp.add(X1, Z1);
|
|
10700
|
-
let t5 = Fp.add(X2, Z2);
|
|
10701
|
-
t4 = Fp.mul(t4, t5);
|
|
10702
|
-
t5 = Fp.add(t0, t2);
|
|
10703
|
-
t4 = Fp.sub(t4, t5);
|
|
10704
|
-
t5 = Fp.add(Y1, Z1);
|
|
10705
|
-
X3 = Fp.add(Y2, Z2);
|
|
10706
|
-
t5 = Fp.mul(t5, X3);
|
|
10707
|
-
X3 = Fp.add(t1, t2);
|
|
10708
|
-
t5 = Fp.sub(t5, X3);
|
|
10709
|
-
Z3 = Fp.mul(a, t4);
|
|
10710
|
-
X3 = Fp.mul(b3, t2);
|
|
10711
|
-
Z3 = Fp.add(X3, Z3);
|
|
10712
|
-
X3 = Fp.sub(t1, Z3);
|
|
10713
|
-
Z3 = Fp.add(t1, Z3);
|
|
10714
|
-
Y3 = Fp.mul(X3, Z3);
|
|
10715
|
-
t1 = Fp.add(t0, t0);
|
|
10716
|
-
t1 = Fp.add(t1, t0);
|
|
10717
|
-
t2 = Fp.mul(a, t2);
|
|
10718
|
-
t4 = Fp.mul(b3, t4);
|
|
10719
|
-
t1 = Fp.add(t1, t2);
|
|
10720
|
-
t2 = Fp.sub(t0, t2);
|
|
10721
|
-
t2 = Fp.mul(a, t2);
|
|
10722
|
-
t4 = Fp.add(t4, t2);
|
|
10723
|
-
t0 = Fp.mul(t1, t4);
|
|
10724
|
-
Y3 = Fp.add(Y3, t0);
|
|
10725
|
-
t0 = Fp.mul(t5, t4);
|
|
10726
|
-
X3 = Fp.mul(t3, X3);
|
|
10727
|
-
X3 = Fp.sub(X3, t0);
|
|
10728
|
-
t0 = Fp.mul(t3, t1);
|
|
10729
|
-
Z3 = Fp.mul(t5, Z3);
|
|
10730
|
-
Z3 = Fp.add(Z3, t0);
|
|
10731
|
-
return new Point(X3, Y3, Z3);
|
|
10732
|
-
}
|
|
10733
|
-
subtract(other) {
|
|
10734
|
-
return this.add(other.negate());
|
|
10735
|
-
}
|
|
10736
|
-
is0() {
|
|
10737
|
-
return this.equals(Point.ZERO);
|
|
10738
|
-
}
|
|
10739
|
-
/**
|
|
10740
|
-
* Constant time multiplication.
|
|
10741
|
-
* Uses wNAF method. Windowed method may be 10% faster,
|
|
10742
|
-
* but takes 2x longer to generate and consumes 2x memory.
|
|
10743
|
-
* Uses precomputes when available.
|
|
10744
|
-
* Uses endomorphism for Koblitz curves.
|
|
10745
|
-
* @param scalar by which the point would be multiplied
|
|
10746
|
-
* @returns New point
|
|
10747
|
-
*/
|
|
10748
|
-
multiply(scalar) {
|
|
10749
|
-
const { endo: endo2 } = extraOpts;
|
|
10750
|
-
if (!Fn.isValidNot0(scalar))
|
|
10751
|
-
throw new Error("invalid scalar: out of range");
|
|
10752
|
-
let point, fake;
|
|
10753
|
-
const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
|
|
10754
|
-
if (endo2) {
|
|
10755
|
-
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
|
|
10756
|
-
const { p: k1p, f: k1f } = mul(k1);
|
|
10757
|
-
const { p: k2p, f: k2f } = mul(k2);
|
|
10758
|
-
fake = k1f.add(k2f);
|
|
10759
|
-
point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
|
|
10760
|
-
} else {
|
|
10761
|
-
const { p, f } = mul(scalar);
|
|
10762
|
-
point = p;
|
|
10763
|
-
fake = f;
|
|
10764
|
-
}
|
|
10765
|
-
return normalizeZ(Point, [point, fake])[0];
|
|
10766
|
-
}
|
|
10767
|
-
/**
|
|
10768
|
-
* Non-constant-time multiplication. Uses double-and-add algorithm.
|
|
10769
|
-
* It's faster, but should only be used when you don't care about
|
|
10770
|
-
* an exposed secret key e.g. sig verification, which works over *public* keys.
|
|
10771
|
-
*/
|
|
10772
|
-
multiplyUnsafe(sc) {
|
|
10773
|
-
const { endo: endo2 } = extraOpts;
|
|
10774
|
-
const p = this;
|
|
10775
|
-
if (!Fn.isValid(sc))
|
|
10776
|
-
throw new Error("invalid scalar: out of range");
|
|
10777
|
-
if (sc === _0n4 || p.is0())
|
|
10778
|
-
return Point.ZERO;
|
|
10779
|
-
if (sc === _1n4)
|
|
10780
|
-
return p;
|
|
10781
|
-
if (wnaf.hasCache(this))
|
|
10782
|
-
return this.multiply(sc);
|
|
10783
|
-
if (endo2) {
|
|
10784
|
-
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
|
|
10785
|
-
const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
|
|
10786
|
-
return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
|
|
10787
|
-
} else {
|
|
10788
|
-
return wnaf.unsafe(p, sc);
|
|
10789
|
-
}
|
|
10790
|
-
}
|
|
10791
|
-
/**
|
|
10792
|
-
* Converts Projective point to affine (x, y) coordinates.
|
|
10793
|
-
* @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
|
|
10794
|
-
*/
|
|
10795
|
-
toAffine(invertedZ) {
|
|
10796
|
-
return toAffineMemo(this, invertedZ);
|
|
10797
|
-
}
|
|
10798
|
-
/**
|
|
10799
|
-
* Checks whether Point is free of torsion elements (is in prime subgroup).
|
|
10800
|
-
* Always torsion-free for cofactor=1 curves.
|
|
10801
|
-
*/
|
|
10802
|
-
isTorsionFree() {
|
|
10803
|
-
const { isTorsionFree } = extraOpts;
|
|
10804
|
-
if (cofactor === _1n4)
|
|
10805
|
-
return true;
|
|
10806
|
-
if (isTorsionFree)
|
|
10807
|
-
return isTorsionFree(Point, this);
|
|
10808
|
-
return wnaf.unsafe(this, CURVE_ORDER2).is0();
|
|
10809
|
-
}
|
|
10810
|
-
clearCofactor() {
|
|
10811
|
-
const { clearCofactor } = extraOpts;
|
|
10812
|
-
if (cofactor === _1n4)
|
|
10813
|
-
return this;
|
|
10814
|
-
if (clearCofactor)
|
|
10815
|
-
return clearCofactor(Point, this);
|
|
10816
|
-
return this.multiplyUnsafe(cofactor);
|
|
10817
|
-
}
|
|
10818
|
-
isSmallOrder() {
|
|
10819
|
-
return this.multiplyUnsafe(cofactor).is0();
|
|
10820
|
-
}
|
|
10821
|
-
toBytes(isCompressed = true) {
|
|
10822
|
-
abool(isCompressed, "isCompressed");
|
|
10823
|
-
this.assertValidity();
|
|
10824
|
-
return encodePoint(Point, this, isCompressed);
|
|
10825
|
-
}
|
|
10826
|
-
toHex(isCompressed = true) {
|
|
10827
|
-
return bytesToHex4(this.toBytes(isCompressed));
|
|
10828
|
-
}
|
|
10829
|
-
toString() {
|
|
10830
|
-
return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
|
|
10831
|
-
}
|
|
10832
|
-
}
|
|
10833
|
-
const bits = Fn.BITS;
|
|
10834
|
-
const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
|
|
10835
|
-
Point.BASE.precompute(8);
|
|
10836
|
-
return Point;
|
|
10837
|
-
}
|
|
10838
|
-
function pprefix(hasEvenY) {
|
|
10839
|
-
return Uint8Array.of(hasEvenY ? 2 : 3);
|
|
10840
|
-
}
|
|
10841
|
-
function getWLengths(Fp, Fn) {
|
|
10842
|
-
return {
|
|
10843
|
-
secretKey: Fn.BYTES,
|
|
10844
|
-
publicKey: 1 + Fp.BYTES,
|
|
10845
|
-
publicKeyUncompressed: 1 + 2 * Fp.BYTES,
|
|
10846
|
-
publicKeyHasPrefix: true,
|
|
10847
|
-
signature: 2 * Fn.BYTES
|
|
10848
|
-
};
|
|
10849
|
-
}
|
|
10850
|
-
function ecdh(Point, ecdhOpts = {}) {
|
|
10851
|
-
const { Fn } = Point;
|
|
10852
|
-
const randomBytes_ = ecdhOpts.randomBytes || randomBytes2;
|
|
10853
|
-
const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
|
|
10854
|
-
function isValidSecretKey(secretKey) {
|
|
10855
|
-
try {
|
|
10856
|
-
const num = Fn.fromBytes(secretKey);
|
|
10857
|
-
return Fn.isValidNot0(num);
|
|
10858
|
-
} catch (error) {
|
|
10859
|
-
return false;
|
|
10860
|
-
}
|
|
10861
|
-
}
|
|
10862
|
-
function isValidPublicKey(publicKey, isCompressed) {
|
|
10863
|
-
const { publicKey: comp, publicKeyUncompressed } = lengths;
|
|
10864
|
-
try {
|
|
10865
|
-
const l = publicKey.length;
|
|
10866
|
-
if (isCompressed === true && l !== comp)
|
|
10867
|
-
return false;
|
|
10868
|
-
if (isCompressed === false && l !== publicKeyUncompressed)
|
|
10869
|
-
return false;
|
|
10870
|
-
return !!Point.fromBytes(publicKey);
|
|
10871
|
-
} catch (error) {
|
|
10872
|
-
return false;
|
|
10873
|
-
}
|
|
10874
|
-
}
|
|
10875
|
-
function randomSecretKey(seed = randomBytes_(lengths.seed)) {
|
|
10876
|
-
return mapHashToField(abytes(seed, lengths.seed, "seed"), Fn.ORDER);
|
|
10877
|
-
}
|
|
10878
|
-
function getPublicKey2(secretKey, isCompressed = true) {
|
|
10879
|
-
return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
|
|
10880
|
-
}
|
|
10881
|
-
function isProbPub(item) {
|
|
10882
|
-
const { secretKey, publicKey, publicKeyUncompressed } = lengths;
|
|
10883
|
-
if (!isBytes(item))
|
|
10884
|
-
return void 0;
|
|
10885
|
-
if ("_lengths" in Fn && Fn._lengths || secretKey === publicKey)
|
|
10886
|
-
return void 0;
|
|
10887
|
-
const l = abytes(item, void 0, "key").length;
|
|
10888
|
-
return l === publicKey || l === publicKeyUncompressed;
|
|
10889
|
-
}
|
|
10890
|
-
function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
|
|
10891
|
-
if (isProbPub(secretKeyA) === true)
|
|
10892
|
-
throw new Error("first arg must be private key");
|
|
10893
|
-
if (isProbPub(publicKeyB) === false)
|
|
10894
|
-
throw new Error("second arg must be public key");
|
|
10895
|
-
const s = Fn.fromBytes(secretKeyA);
|
|
10896
|
-
const b = Point.fromBytes(publicKeyB);
|
|
10897
|
-
return b.multiply(s).toBytes(isCompressed);
|
|
10898
|
-
}
|
|
10899
|
-
const utils = {
|
|
10900
|
-
isValidSecretKey,
|
|
10901
|
-
isValidPublicKey,
|
|
10902
|
-
randomSecretKey
|
|
10903
|
-
};
|
|
10904
|
-
const keygen = createKeygen(randomSecretKey, getPublicKey2);
|
|
10905
|
-
return Object.freeze({ getPublicKey: getPublicKey2, getSharedSecret, keygen, Point, utils, lengths });
|
|
10906
|
-
}
|
|
10907
|
-
function ecdsa(Point, hash, ecdsaOpts = {}) {
|
|
10908
|
-
ahash(hash);
|
|
10909
|
-
validateObject(ecdsaOpts, {}, {
|
|
10910
|
-
hmac: "function",
|
|
10911
|
-
lowS: "boolean",
|
|
10912
|
-
randomBytes: "function",
|
|
10913
|
-
bits2int: "function",
|
|
10914
|
-
bits2int_modN: "function"
|
|
10915
|
-
});
|
|
10916
|
-
ecdsaOpts = Object.assign({}, ecdsaOpts);
|
|
10917
|
-
const randomBytes3 = ecdsaOpts.randomBytes || randomBytes2;
|
|
10918
|
-
const hmac2 = ecdsaOpts.hmac || ((key, msg) => hmac(hash, key, msg));
|
|
10919
|
-
const { Fp, Fn } = Point;
|
|
10920
|
-
const { ORDER: CURVE_ORDER2, BITS: fnBits } = Fn;
|
|
10921
|
-
const { keygen, getPublicKey: getPublicKey2, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
|
|
10922
|
-
const defaultSigOpts = {
|
|
10923
|
-
prehash: true,
|
|
10924
|
-
lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
|
|
10925
|
-
format: "compact",
|
|
10926
|
-
extraEntropy: false
|
|
10927
|
-
};
|
|
10928
|
-
const hasLargeCofactor = CURVE_ORDER2 * _2n2 < Fp.ORDER;
|
|
10929
|
-
function isBiggerThanHalfOrder(number) {
|
|
10930
|
-
const HALF = CURVE_ORDER2 >> _1n4;
|
|
10931
|
-
return number > HALF;
|
|
10932
|
-
}
|
|
10933
|
-
function validateRS(title, num) {
|
|
10934
|
-
if (!Fn.isValidNot0(num))
|
|
10935
|
-
throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
|
|
10936
|
-
return num;
|
|
10937
|
-
}
|
|
10938
|
-
function assertSmallCofactor() {
|
|
10939
|
-
if (hasLargeCofactor)
|
|
10940
|
-
throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
|
|
10941
|
-
}
|
|
10942
|
-
function validateSigLength(bytes, format) {
|
|
10943
|
-
validateSigFormat(format);
|
|
10944
|
-
const size = lengths.signature;
|
|
10945
|
-
const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
|
|
10946
|
-
return abytes(bytes, sizer);
|
|
10947
|
-
}
|
|
10948
|
-
class Signature {
|
|
10949
|
-
r;
|
|
10950
|
-
s;
|
|
10951
|
-
recovery;
|
|
10952
|
-
constructor(r, s, recovery) {
|
|
10953
|
-
this.r = validateRS("r", r);
|
|
10954
|
-
this.s = validateRS("s", s);
|
|
10955
|
-
if (recovery != null) {
|
|
10956
|
-
assertSmallCofactor();
|
|
10957
|
-
if (![0, 1, 2, 3].includes(recovery))
|
|
10958
|
-
throw new Error("invalid recovery id");
|
|
10959
|
-
this.recovery = recovery;
|
|
10960
|
-
}
|
|
10961
|
-
Object.freeze(this);
|
|
10962
|
-
}
|
|
10963
|
-
static fromBytes(bytes, format = defaultSigOpts.format) {
|
|
10964
|
-
validateSigLength(bytes, format);
|
|
10965
|
-
let recid;
|
|
10966
|
-
if (format === "der") {
|
|
10967
|
-
const { r: r2, s: s2 } = DER.toSig(abytes(bytes));
|
|
10968
|
-
return new Signature(r2, s2);
|
|
10969
|
-
}
|
|
10970
|
-
if (format === "recovered") {
|
|
10971
|
-
recid = bytes[0];
|
|
10972
|
-
format = "compact";
|
|
10973
|
-
bytes = bytes.subarray(1);
|
|
10974
|
-
}
|
|
10975
|
-
const L = lengths.signature / 2;
|
|
10976
|
-
const r = bytes.subarray(0, L);
|
|
10977
|
-
const s = bytes.subarray(L, L * 2);
|
|
10978
|
-
return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
|
|
10979
|
-
}
|
|
10980
|
-
static fromHex(hex, format) {
|
|
10981
|
-
return this.fromBytes(hexToBytes2(hex), format);
|
|
10982
|
-
}
|
|
10983
|
-
assertRecovery() {
|
|
10984
|
-
const { recovery } = this;
|
|
10985
|
-
if (recovery == null)
|
|
10986
|
-
throw new Error("invalid recovery id: must be present");
|
|
10987
|
-
return recovery;
|
|
10988
|
-
}
|
|
10989
|
-
addRecoveryBit(recovery) {
|
|
10990
|
-
return new Signature(this.r, this.s, recovery);
|
|
10991
|
-
}
|
|
10992
|
-
recoverPublicKey(messageHash) {
|
|
10993
|
-
const { r, s } = this;
|
|
10994
|
-
const recovery = this.assertRecovery();
|
|
10995
|
-
const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER2 : r;
|
|
10996
|
-
if (!Fp.isValid(radj))
|
|
10997
|
-
throw new Error("invalid recovery id: sig.r+curve.n != R.x");
|
|
10998
|
-
const x = Fp.toBytes(radj);
|
|
10999
|
-
const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));
|
|
11000
|
-
const ir = Fn.inv(radj);
|
|
11001
|
-
const h = bits2int_modN(abytes(messageHash, void 0, "msgHash"));
|
|
11002
|
-
const u1 = Fn.create(-h * ir);
|
|
11003
|
-
const u2 = Fn.create(s * ir);
|
|
11004
|
-
const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
|
|
11005
|
-
if (Q.is0())
|
|
11006
|
-
throw new Error("invalid recovery: point at infinify");
|
|
11007
|
-
Q.assertValidity();
|
|
11008
|
-
return Q;
|
|
11009
|
-
}
|
|
11010
|
-
// Signatures should be low-s, to prevent malleability.
|
|
11011
|
-
hasHighS() {
|
|
11012
|
-
return isBiggerThanHalfOrder(this.s);
|
|
11013
|
-
}
|
|
11014
|
-
toBytes(format = defaultSigOpts.format) {
|
|
11015
|
-
validateSigFormat(format);
|
|
11016
|
-
if (format === "der")
|
|
11017
|
-
return hexToBytes2(DER.hexFromSig(this));
|
|
11018
|
-
const { r, s } = this;
|
|
11019
|
-
const rb = Fn.toBytes(r);
|
|
11020
|
-
const sb = Fn.toBytes(s);
|
|
11021
|
-
if (format === "recovered") {
|
|
11022
|
-
assertSmallCofactor();
|
|
11023
|
-
return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);
|
|
11024
|
-
}
|
|
11025
|
-
return concatBytes(rb, sb);
|
|
11026
|
-
}
|
|
11027
|
-
toHex(format) {
|
|
11028
|
-
return bytesToHex4(this.toBytes(format));
|
|
11029
|
-
}
|
|
11030
|
-
}
|
|
11031
|
-
const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
|
|
11032
|
-
if (bytes.length > 8192)
|
|
11033
|
-
throw new Error("input is too large");
|
|
11034
|
-
const num = bytesToNumberBE(bytes);
|
|
11035
|
-
const delta = bytes.length * 8 - fnBits;
|
|
11036
|
-
return delta > 0 ? num >> BigInt(delta) : num;
|
|
11037
|
-
};
|
|
11038
|
-
const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
|
|
11039
|
-
return Fn.create(bits2int(bytes));
|
|
11040
|
-
};
|
|
11041
|
-
const ORDER_MASK = bitMask(fnBits);
|
|
11042
|
-
function int2octets(num) {
|
|
11043
|
-
aInRange("num < 2^" + fnBits, num, _0n4, ORDER_MASK);
|
|
11044
|
-
return Fn.toBytes(num);
|
|
11045
|
-
}
|
|
11046
|
-
function validateMsgAndHash(message, prehash) {
|
|
11047
|
-
abytes(message, void 0, "message");
|
|
11048
|
-
return prehash ? abytes(hash(message), void 0, "prehashed message") : message;
|
|
11049
|
-
}
|
|
11050
|
-
function prepSig(message, secretKey, opts) {
|
|
11051
|
-
const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
|
|
11052
|
-
message = validateMsgAndHash(message, prehash);
|
|
11053
|
-
const h1int = bits2int_modN(message);
|
|
11054
|
-
const d = Fn.fromBytes(secretKey);
|
|
11055
|
-
if (!Fn.isValidNot0(d))
|
|
11056
|
-
throw new Error("invalid private key");
|
|
11057
|
-
const seedArgs = [int2octets(d), int2octets(h1int)];
|
|
11058
|
-
if (extraEntropy != null && extraEntropy !== false) {
|
|
11059
|
-
const e = extraEntropy === true ? randomBytes3(lengths.secretKey) : extraEntropy;
|
|
11060
|
-
seedArgs.push(abytes(e, void 0, "extraEntropy"));
|
|
11061
|
-
}
|
|
11062
|
-
const seed = concatBytes(...seedArgs);
|
|
11063
|
-
const m = h1int;
|
|
11064
|
-
function k2sig(kBytes) {
|
|
11065
|
-
const k = bits2int(kBytes);
|
|
11066
|
-
if (!Fn.isValidNot0(k))
|
|
11067
|
-
return;
|
|
11068
|
-
const ik = Fn.inv(k);
|
|
11069
|
-
const q = Point.BASE.multiply(k).toAffine();
|
|
11070
|
-
const r = Fn.create(q.x);
|
|
11071
|
-
if (r === _0n4)
|
|
11072
|
-
return;
|
|
11073
|
-
const s = Fn.create(ik * Fn.create(m + r * d));
|
|
11074
|
-
if (s === _0n4)
|
|
11075
|
-
return;
|
|
11076
|
-
let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
|
|
11077
|
-
let normS = s;
|
|
11078
|
-
if (lowS && isBiggerThanHalfOrder(s)) {
|
|
11079
|
-
normS = Fn.neg(s);
|
|
11080
|
-
recovery ^= 1;
|
|
11081
|
-
}
|
|
11082
|
-
return new Signature(r, normS, hasLargeCofactor ? void 0 : recovery);
|
|
11083
|
-
}
|
|
11084
|
-
return { seed, k2sig };
|
|
11085
|
-
}
|
|
11086
|
-
function sign(message, secretKey, opts = {}) {
|
|
11087
|
-
const { seed, k2sig } = prepSig(message, secretKey, opts);
|
|
11088
|
-
const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac2);
|
|
11089
|
-
const sig = drbg(seed, k2sig);
|
|
11090
|
-
return sig.toBytes(opts.format);
|
|
11091
|
-
}
|
|
11092
|
-
function verify(signature, message, publicKey, opts = {}) {
|
|
11093
|
-
const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
|
|
11094
|
-
publicKey = abytes(publicKey, void 0, "publicKey");
|
|
11095
|
-
message = validateMsgAndHash(message, prehash);
|
|
11096
|
-
if (!isBytes(signature)) {
|
|
11097
|
-
const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
|
|
11098
|
-
throw new Error("verify expects Uint8Array signature" + end);
|
|
11099
|
-
}
|
|
11100
|
-
validateSigLength(signature, format);
|
|
11101
|
-
try {
|
|
11102
|
-
const sig = Signature.fromBytes(signature, format);
|
|
11103
|
-
const P = Point.fromBytes(publicKey);
|
|
11104
|
-
if (lowS && sig.hasHighS())
|
|
11105
|
-
return false;
|
|
11106
|
-
const { r, s } = sig;
|
|
11107
|
-
const h = bits2int_modN(message);
|
|
11108
|
-
const is = Fn.inv(s);
|
|
11109
|
-
const u1 = Fn.create(h * is);
|
|
11110
|
-
const u2 = Fn.create(r * is);
|
|
11111
|
-
const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
|
|
11112
|
-
if (R.is0())
|
|
11113
|
-
return false;
|
|
11114
|
-
const v = Fn.create(R.x);
|
|
11115
|
-
return v === r;
|
|
11116
|
-
} catch (e) {
|
|
11117
|
-
return false;
|
|
11118
|
-
}
|
|
11119
|
-
}
|
|
11120
|
-
function recoverPublicKey(signature, message, opts = {}) {
|
|
11121
|
-
const { prehash } = validateSigOpts(opts, defaultSigOpts);
|
|
11122
|
-
message = validateMsgAndHash(message, prehash);
|
|
11123
|
-
return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
|
|
11124
|
-
}
|
|
11125
|
-
return Object.freeze({
|
|
11126
|
-
keygen,
|
|
11127
|
-
getPublicKey: getPublicKey2,
|
|
11128
|
-
getSharedSecret,
|
|
11129
|
-
utils,
|
|
11130
|
-
lengths,
|
|
11131
|
-
Point,
|
|
11132
|
-
sign,
|
|
11133
|
-
verify,
|
|
11134
|
-
recoverPublicKey,
|
|
11135
|
-
Signature,
|
|
11136
|
-
hash
|
|
11137
|
-
});
|
|
11138
|
-
}
|
|
11139
|
-
|
|
11140
|
-
// node_modules/@noble/curves/secp256k1.js
|
|
11141
|
-
var secp256k1_CURVE = {
|
|
11142
|
-
p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
|
|
11143
|
-
n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
|
|
11144
|
-
h: BigInt(1),
|
|
11145
|
-
a: BigInt(0),
|
|
11146
|
-
b: BigInt(7),
|
|
11147
|
-
Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
|
|
11148
|
-
Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
|
|
11149
|
-
};
|
|
11150
|
-
var secp256k1_ENDO = {
|
|
11151
|
-
beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
|
|
11152
|
-
basises: [
|
|
11153
|
-
[BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
|
|
11154
|
-
[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
|
|
11155
|
-
]
|
|
11156
|
-
};
|
|
11157
|
-
var _2n3 = /* @__PURE__ */ BigInt(2);
|
|
11158
|
-
function sqrtMod(y) {
|
|
11159
|
-
const P = secp256k1_CURVE.p;
|
|
11160
|
-
const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
|
|
11161
|
-
const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
|
|
11162
|
-
const b2 = y * y * y % P;
|
|
11163
|
-
const b3 = b2 * b2 * y % P;
|
|
11164
|
-
const b6 = pow2(b3, _3n3, P) * b3 % P;
|
|
11165
|
-
const b9 = pow2(b6, _3n3, P) * b3 % P;
|
|
11166
|
-
const b11 = pow2(b9, _2n3, P) * b2 % P;
|
|
11167
|
-
const b22 = pow2(b11, _11n, P) * b11 % P;
|
|
11168
|
-
const b44 = pow2(b22, _22n, P) * b22 % P;
|
|
11169
|
-
const b88 = pow2(b44, _44n, P) * b44 % P;
|
|
11170
|
-
const b176 = pow2(b88, _88n, P) * b88 % P;
|
|
11171
|
-
const b220 = pow2(b176, _44n, P) * b44 % P;
|
|
11172
|
-
const b223 = pow2(b220, _3n3, P) * b3 % P;
|
|
11173
|
-
const t1 = pow2(b223, _23n, P) * b22 % P;
|
|
11174
|
-
const t2 = pow2(t1, _6n, P) * b2 % P;
|
|
11175
|
-
const root = pow2(t2, _2n3, P);
|
|
11176
|
-
if (!Fpk1.eql(Fpk1.sqr(root), y))
|
|
11177
|
-
throw new Error("Cannot find square root");
|
|
11178
|
-
return root;
|
|
11179
|
-
}
|
|
11180
|
-
var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
|
|
11181
|
-
var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
|
|
11182
|
-
Fp: Fpk1,
|
|
11183
|
-
endo: secp256k1_ENDO
|
|
11184
|
-
});
|
|
11185
|
-
var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha2564);
|
|
11186
|
-
|
|
11187
|
-
// modules/market/MarketModule.ts
|
|
11188
|
-
function hexToBytes3(hex) {
|
|
11189
|
-
const len = hex.length >> 1;
|
|
11190
|
-
const bytes = new Uint8Array(len);
|
|
11191
|
-
for (let i = 0; i < len; i++) {
|
|
11192
|
-
bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
11193
|
-
}
|
|
11194
|
-
return bytes;
|
|
11195
|
-
}
|
|
11196
|
-
function signRequest(body, privateKeyHex) {
|
|
11197
|
-
const timestamp = Date.now();
|
|
11198
|
-
const payload = JSON.stringify({ body, timestamp });
|
|
11199
|
-
const messageHash = sha2564(new TextEncoder().encode(payload));
|
|
11200
|
-
const privateKeyBytes = hexToBytes3(privateKeyHex);
|
|
11201
|
-
const signature = secp256k1.sign(messageHash, privateKeyBytes);
|
|
11202
|
-
const publicKey = bytesToHex4(secp256k1.getPublicKey(privateKeyBytes, true));
|
|
11203
|
-
return {
|
|
11204
|
-
body: JSON.stringify(body),
|
|
11205
|
-
headers: {
|
|
11206
|
-
"x-signature": bytesToHex4(signature),
|
|
11207
|
-
"x-public-key": publicKey,
|
|
11208
|
-
"x-timestamp": String(timestamp),
|
|
11209
|
-
"content-type": "application/json"
|
|
11210
|
-
}
|
|
11211
|
-
};
|
|
11212
|
-
}
|
|
11213
|
-
function toSnakeCaseIntent(req) {
|
|
11214
|
-
const result = {
|
|
11215
|
-
description: req.description,
|
|
11216
|
-
intent_type: req.intentType
|
|
11217
|
-
};
|
|
11218
|
-
if (req.category !== void 0) result.category = req.category;
|
|
11219
|
-
if (req.price !== void 0) result.price = req.price;
|
|
11220
|
-
if (req.currency !== void 0) result.currency = req.currency;
|
|
11221
|
-
if (req.location !== void 0) result.location = req.location;
|
|
11222
|
-
if (req.contactHandle !== void 0) result.contact_handle = req.contactHandle;
|
|
11223
|
-
if (req.expiresInDays !== void 0) result.expires_in_days = req.expiresInDays;
|
|
11224
|
-
return result;
|
|
11225
|
-
}
|
|
11226
|
-
function toSnakeCaseFilters(opts) {
|
|
11227
|
-
const result = {};
|
|
11228
|
-
if (opts?.filters) {
|
|
11229
|
-
const f = opts.filters;
|
|
11230
|
-
if (f.intentType !== void 0) result.intent_type = f.intentType;
|
|
11231
|
-
if (f.category !== void 0) result.category = f.category;
|
|
11232
|
-
if (f.minPrice !== void 0) result.min_price = f.minPrice;
|
|
11233
|
-
if (f.maxPrice !== void 0) result.max_price = f.maxPrice;
|
|
11234
|
-
if (f.location !== void 0) result.location = f.location;
|
|
11235
|
-
}
|
|
11236
|
-
if (opts?.limit !== void 0) result.limit = opts.limit;
|
|
11237
|
-
return result;
|
|
11238
|
-
}
|
|
11239
|
-
function mapSearchResult(raw) {
|
|
11240
|
-
return {
|
|
11241
|
-
id: raw.id,
|
|
11242
|
-
score: raw.score,
|
|
11243
|
-
agentNametag: raw.agent_nametag ?? void 0,
|
|
11244
|
-
agentPublicKey: raw.agent_public_key,
|
|
11245
|
-
description: raw.description,
|
|
11246
|
-
intentType: raw.intent_type,
|
|
11247
|
-
category: raw.category ?? void 0,
|
|
11248
|
-
price: raw.price ?? void 0,
|
|
11249
|
-
currency: raw.currency,
|
|
11250
|
-
location: raw.location ?? void 0,
|
|
11251
|
-
contactMethod: raw.contact_method,
|
|
11252
|
-
contactHandle: raw.contact_handle ?? void 0,
|
|
11253
|
-
createdAt: raw.created_at,
|
|
11254
|
-
expiresAt: raw.expires_at
|
|
11255
|
-
};
|
|
11256
|
-
}
|
|
11257
|
-
function mapMyIntent(raw) {
|
|
11258
|
-
return {
|
|
11259
|
-
id: raw.id,
|
|
11260
|
-
intentType: raw.intent_type,
|
|
11261
|
-
category: raw.category ?? void 0,
|
|
11262
|
-
price: raw.price ?? void 0,
|
|
11263
|
-
currency: raw.currency,
|
|
11264
|
-
location: raw.location ?? void 0,
|
|
11265
|
-
status: raw.status,
|
|
11266
|
-
createdAt: raw.created_at,
|
|
11267
|
-
expiresAt: raw.expires_at
|
|
11268
|
-
};
|
|
11269
|
-
}
|
|
11270
|
-
function mapFeedListing(raw) {
|
|
11271
|
-
return {
|
|
11272
|
-
id: raw.id,
|
|
11273
|
-
title: raw.title,
|
|
11274
|
-
descriptionPreview: raw.description_preview,
|
|
11275
|
-
agentName: raw.agent_name,
|
|
11276
|
-
agentId: raw.agent_id,
|
|
11277
|
-
type: raw.type,
|
|
11278
|
-
createdAt: raw.created_at
|
|
11279
|
-
};
|
|
11280
|
-
}
|
|
11281
|
-
function mapFeedMessage(raw) {
|
|
11282
|
-
if (raw.type === "initial") {
|
|
11283
|
-
return { type: "initial", listings: (raw.listings ?? []).map(mapFeedListing) };
|
|
11284
|
-
}
|
|
11285
|
-
return { type: "new", listing: mapFeedListing(raw.listing) };
|
|
11286
|
-
}
|
|
11287
|
-
var MarketModule = class {
|
|
11288
|
-
apiUrl;
|
|
11289
|
-
timeout;
|
|
11290
|
-
identity = null;
|
|
11291
|
-
registered = false;
|
|
11292
|
-
constructor(config) {
|
|
11293
|
-
this.apiUrl = (config?.apiUrl ?? DEFAULT_MARKET_API_URL).replace(/\/+$/, "");
|
|
11294
|
-
this.timeout = config?.timeout ?? 3e4;
|
|
11295
|
-
}
|
|
11296
|
-
/** Called by Sphere after construction */
|
|
11297
|
-
initialize(deps) {
|
|
11298
|
-
this.identity = deps.identity;
|
|
11299
|
-
}
|
|
11300
|
-
/** No-op — stateless module */
|
|
11301
|
-
async load() {
|
|
11302
|
-
}
|
|
11303
|
-
/** No-op — stateless module */
|
|
11304
|
-
destroy() {
|
|
11305
|
-
}
|
|
11306
|
-
// ---------------------------------------------------------------------------
|
|
11307
|
-
// Public API
|
|
11308
|
-
// ---------------------------------------------------------------------------
|
|
11309
|
-
/** Post a new intent (agent is auto-registered on first post) */
|
|
11310
|
-
async postIntent(intent) {
|
|
11311
|
-
const body = toSnakeCaseIntent(intent);
|
|
11312
|
-
const data = await this.apiPost("/api/intents", body);
|
|
11313
|
-
return {
|
|
11314
|
-
intentId: data.intent_id ?? data.intentId,
|
|
11315
|
-
message: data.message,
|
|
11316
|
-
expiresAt: data.expires_at ?? data.expiresAt
|
|
11317
|
-
};
|
|
11318
|
-
}
|
|
11319
|
-
/** Semantic search for intents (public — no auth required) */
|
|
11320
|
-
async search(query, opts) {
|
|
11321
|
-
const body = {
|
|
11322
|
-
query,
|
|
11323
|
-
...toSnakeCaseFilters(opts)
|
|
11324
|
-
};
|
|
11325
|
-
const data = await this.apiPublicPost("/api/search", body);
|
|
11326
|
-
let results = (data.intents ?? []).map(mapSearchResult);
|
|
11327
|
-
const minScore = opts?.filters?.minScore;
|
|
11328
|
-
if (minScore != null) {
|
|
11329
|
-
results = results.filter((r) => Math.round(r.score * 100) >= Math.round(minScore * 100));
|
|
11330
|
-
}
|
|
11331
|
-
return { intents: results, count: results.length };
|
|
11332
|
-
}
|
|
11333
|
-
/** List own intents (authenticated) */
|
|
11334
|
-
async getMyIntents() {
|
|
11335
|
-
const data = await this.apiGet("/api/intents");
|
|
11336
|
-
return (data.intents ?? []).map(mapMyIntent);
|
|
11337
|
-
}
|
|
11338
|
-
/** Close (delete) an intent */
|
|
11339
|
-
async closeIntent(intentId) {
|
|
11340
|
-
await this.apiDelete(`/api/intents/${encodeURIComponent(intentId)}`);
|
|
11341
|
-
}
|
|
11342
|
-
/** Fetch the most recent listings via REST (public — no auth required) */
|
|
11343
|
-
async getRecentListings() {
|
|
11344
|
-
const res = await fetch(`${this.apiUrl}/api/feed/recent`, {
|
|
11345
|
-
signal: AbortSignal.timeout(this.timeout)
|
|
11346
|
-
});
|
|
11347
|
-
const data = await this.parseResponse(res);
|
|
11348
|
-
return (data.listings ?? []).map(mapFeedListing);
|
|
11349
|
-
}
|
|
11350
|
-
/**
|
|
11351
|
-
* Subscribe to the live listing feed via WebSocket.
|
|
11352
|
-
* Returns an unsubscribe function that closes the connection.
|
|
11353
|
-
*
|
|
11354
|
-
* Requires a WebSocket implementation — works natively in browsers
|
|
11355
|
-
* and in Node.js 21+ (or with the `ws` package).
|
|
11356
|
-
*/
|
|
11357
|
-
subscribeFeed(listener) {
|
|
11358
|
-
const wsUrl = this.apiUrl.replace(/^http/, "ws") + "/ws/feed";
|
|
11359
|
-
const ws2 = new WebSocket(wsUrl);
|
|
11360
|
-
ws2.onmessage = (event) => {
|
|
11361
|
-
try {
|
|
11362
|
-
const raw = JSON.parse(typeof event.data === "string" ? event.data : event.data.toString());
|
|
11363
|
-
listener(mapFeedMessage(raw));
|
|
11364
|
-
} catch {
|
|
11365
|
-
}
|
|
11366
|
-
};
|
|
11367
|
-
return () => {
|
|
11368
|
-
ws2.close();
|
|
11369
|
-
};
|
|
11370
|
-
}
|
|
11371
|
-
// ---------------------------------------------------------------------------
|
|
11372
|
-
// Private: HTTP helpers
|
|
11373
|
-
// ---------------------------------------------------------------------------
|
|
11374
|
-
ensureIdentity() {
|
|
11375
|
-
if (!this.identity) {
|
|
11376
|
-
throw new Error("MarketModule not initialized \u2014 call initialize() first");
|
|
11377
|
-
}
|
|
11378
|
-
}
|
|
11379
|
-
/** Register the agent's public key with the server (idempotent) */
|
|
11380
|
-
async ensureRegistered() {
|
|
11381
|
-
if (this.registered) return;
|
|
11382
|
-
this.ensureIdentity();
|
|
11383
|
-
const publicKey = bytesToHex4(secp256k1.getPublicKey(hexToBytes3(this.identity.privateKey), true));
|
|
11384
|
-
const body = { public_key: publicKey };
|
|
11385
|
-
if (this.identity.nametag) body.nametag = this.identity.nametag;
|
|
11386
|
-
const res = await fetch(`${this.apiUrl}/api/agent/register`, {
|
|
11387
|
-
method: "POST",
|
|
11388
|
-
headers: { "content-type": "application/json" },
|
|
11389
|
-
body: JSON.stringify(body),
|
|
11390
|
-
signal: AbortSignal.timeout(this.timeout)
|
|
11391
|
-
});
|
|
11392
|
-
if (res.ok || res.status === 409) {
|
|
11393
|
-
this.registered = true;
|
|
11394
|
-
return;
|
|
11395
|
-
}
|
|
11396
|
-
const text = await res.text();
|
|
11397
|
-
let data;
|
|
11398
|
-
try {
|
|
11399
|
-
data = JSON.parse(text);
|
|
11400
|
-
} catch {
|
|
11401
|
-
}
|
|
11402
|
-
throw new Error(data?.error ?? `Agent registration failed: HTTP ${res.status}`);
|
|
11403
|
-
}
|
|
11404
|
-
async parseResponse(res) {
|
|
11405
|
-
const text = await res.text();
|
|
11406
|
-
let data;
|
|
11407
|
-
try {
|
|
11408
|
-
data = JSON.parse(text);
|
|
11409
|
-
} catch {
|
|
11410
|
-
throw new Error(`Market API error: HTTP ${res.status} \u2014 unexpected response (not JSON)`);
|
|
11411
|
-
}
|
|
11412
|
-
if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
|
|
11413
|
-
return data;
|
|
11414
|
-
}
|
|
11415
|
-
async apiPost(path, body) {
|
|
11416
|
-
this.ensureIdentity();
|
|
11417
|
-
await this.ensureRegistered();
|
|
11418
|
-
const signed = signRequest(body, this.identity.privateKey);
|
|
11419
|
-
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11420
|
-
method: "POST",
|
|
11421
|
-
headers: signed.headers,
|
|
11422
|
-
body: signed.body,
|
|
11423
|
-
signal: AbortSignal.timeout(this.timeout)
|
|
11424
|
-
});
|
|
11425
|
-
return this.parseResponse(res);
|
|
11426
|
-
}
|
|
11427
|
-
async apiGet(path) {
|
|
11428
|
-
this.ensureIdentity();
|
|
11429
|
-
await this.ensureRegistered();
|
|
11430
|
-
const signed = signRequest({}, this.identity.privateKey);
|
|
11431
|
-
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11432
|
-
method: "GET",
|
|
11433
|
-
headers: signed.headers,
|
|
11434
|
-
signal: AbortSignal.timeout(this.timeout)
|
|
11435
|
-
});
|
|
11436
|
-
return this.parseResponse(res);
|
|
11437
|
-
}
|
|
11438
|
-
async apiDelete(path) {
|
|
11439
|
-
this.ensureIdentity();
|
|
11440
|
-
await this.ensureRegistered();
|
|
11441
|
-
const signed = signRequest({}, this.identity.privateKey);
|
|
11442
|
-
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11443
|
-
method: "DELETE",
|
|
11444
|
-
headers: signed.headers,
|
|
11445
|
-
signal: AbortSignal.timeout(this.timeout)
|
|
11446
|
-
});
|
|
11447
|
-
return this.parseResponse(res);
|
|
11448
|
-
}
|
|
11449
|
-
async apiPublicPost(path, body) {
|
|
11450
|
-
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11451
|
-
method: "POST",
|
|
11452
|
-
headers: { "content-type": "application/json" },
|
|
11453
|
-
body: JSON.stringify(body),
|
|
11454
|
-
signal: AbortSignal.timeout(this.timeout)
|
|
11455
|
-
});
|
|
11456
|
-
return this.parseResponse(res);
|
|
11457
|
-
}
|
|
11458
|
-
};
|
|
11459
|
-
function createMarketModule(config) {
|
|
11460
|
-
return new MarketModule(config);
|
|
11461
|
-
}
|
|
11462
|
-
|
|
11463
9029
|
// core/encryption.ts
|
|
11464
9030
|
var import_crypto_js6 = __toESM(require("crypto-js"), 1);
|
|
11465
9031
|
var DEFAULT_ITERATIONS = 1e5;
|
|
@@ -12380,7 +9946,6 @@ var Sphere = class _Sphere {
|
|
|
12380
9946
|
_payments;
|
|
12381
9947
|
_communications;
|
|
12382
9948
|
_groupChat = null;
|
|
12383
|
-
_market = null;
|
|
12384
9949
|
// Events
|
|
12385
9950
|
eventHandlers = /* @__PURE__ */ new Map();
|
|
12386
9951
|
// Provider management
|
|
@@ -12390,7 +9955,7 @@ var Sphere = class _Sphere {
|
|
|
12390
9955
|
// ===========================================================================
|
|
12391
9956
|
// Constructor (private)
|
|
12392
9957
|
// ===========================================================================
|
|
12393
|
-
constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig
|
|
9958
|
+
constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig) {
|
|
12394
9959
|
this._storage = storage;
|
|
12395
9960
|
this._transport = transport;
|
|
12396
9961
|
this._oracle = oracle;
|
|
@@ -12401,7 +9966,6 @@ var Sphere = class _Sphere {
|
|
|
12401
9966
|
this._payments = createPaymentsModule({ l1: l1Config });
|
|
12402
9967
|
this._communications = createCommunicationsModule();
|
|
12403
9968
|
this._groupChat = groupChatConfig ? createGroupChatModule(groupChatConfig) : null;
|
|
12404
|
-
this._market = marketConfig ? createMarketModule(marketConfig) : null;
|
|
12405
9969
|
}
|
|
12406
9970
|
// ===========================================================================
|
|
12407
9971
|
// Static Methods - Wallet Management
|
|
@@ -12449,8 +10013,8 @@ var Sphere = class _Sphere {
|
|
|
12449
10013
|
* ```
|
|
12450
10014
|
*/
|
|
12451
10015
|
static async init(options) {
|
|
10016
|
+
_Sphere.configureTokenRegistry(options.storage, options.network);
|
|
12452
10017
|
const groupChat = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
|
|
12453
|
-
const market = _Sphere.resolveMarketConfig(options.market);
|
|
12454
10018
|
const walletExists = await _Sphere.exists(options.storage);
|
|
12455
10019
|
if (walletExists) {
|
|
12456
10020
|
const sphere2 = await _Sphere.load({
|
|
@@ -12461,8 +10025,7 @@ var Sphere = class _Sphere {
|
|
|
12461
10025
|
l1: options.l1,
|
|
12462
10026
|
price: options.price,
|
|
12463
10027
|
groupChat,
|
|
12464
|
-
password: options.password
|
|
12465
|
-
market
|
|
10028
|
+
password: options.password
|
|
12466
10029
|
});
|
|
12467
10030
|
return { sphere: sphere2, created: false };
|
|
12468
10031
|
}
|
|
@@ -12489,8 +10052,7 @@ var Sphere = class _Sphere {
|
|
|
12489
10052
|
l1: options.l1,
|
|
12490
10053
|
price: options.price,
|
|
12491
10054
|
groupChat,
|
|
12492
|
-
password: options.password
|
|
12493
|
-
market
|
|
10055
|
+
password: options.password
|
|
12494
10056
|
});
|
|
12495
10057
|
return { sphere, created: true, generatedMnemonic };
|
|
12496
10058
|
}
|
|
@@ -12518,20 +10080,17 @@ var Sphere = class _Sphere {
|
|
|
12518
10080
|
return config;
|
|
12519
10081
|
}
|
|
12520
10082
|
/**
|
|
12521
|
-
*
|
|
12522
|
-
*
|
|
12523
|
-
*
|
|
12524
|
-
*
|
|
10083
|
+
* Configure TokenRegistry in the main bundle context.
|
|
10084
|
+
*
|
|
10085
|
+
* The provider factory functions (createBrowserProviders / createNodeProviders)
|
|
10086
|
+
* are compiled into separate bundles by tsup, each with their own inlined copy
|
|
10087
|
+
* of TokenRegistry. Their TokenRegistry.configure() call configures a different
|
|
10088
|
+
* singleton than the one used by PaymentsModule (which lives in the main bundle).
|
|
10089
|
+
* This method ensures the main bundle's TokenRegistry is properly configured.
|
|
12525
10090
|
*/
|
|
12526
|
-
static
|
|
12527
|
-
|
|
12528
|
-
|
|
12529
|
-
return { apiUrl: DEFAULT_MARKET_API_URL };
|
|
12530
|
-
}
|
|
12531
|
-
return {
|
|
12532
|
-
apiUrl: config.apiUrl ?? DEFAULT_MARKET_API_URL,
|
|
12533
|
-
timeout: config.timeout
|
|
12534
|
-
};
|
|
10091
|
+
static configureTokenRegistry(storage, network) {
|
|
10092
|
+
const netConfig = network ? NETWORKS[network] : NETWORKS.testnet;
|
|
10093
|
+
TokenRegistry.configure({ remoteUrl: netConfig.tokenRegistryUrl, storage });
|
|
12535
10094
|
}
|
|
12536
10095
|
/**
|
|
12537
10096
|
* Create new wallet with mnemonic
|
|
@@ -12543,8 +10102,8 @@ var Sphere = class _Sphere {
|
|
|
12543
10102
|
if (await _Sphere.exists(options.storage)) {
|
|
12544
10103
|
throw new Error("Wallet already exists. Use Sphere.load() or Sphere.clear() first.");
|
|
12545
10104
|
}
|
|
10105
|
+
_Sphere.configureTokenRegistry(options.storage, options.network);
|
|
12546
10106
|
const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
|
|
12547
|
-
const marketConfig = _Sphere.resolveMarketConfig(options.market);
|
|
12548
10107
|
const sphere = new _Sphere(
|
|
12549
10108
|
options.storage,
|
|
12550
10109
|
options.transport,
|
|
@@ -12552,8 +10111,7 @@ var Sphere = class _Sphere {
|
|
|
12552
10111
|
options.tokenStorage,
|
|
12553
10112
|
options.l1,
|
|
12554
10113
|
options.price,
|
|
12555
|
-
groupChatConfig
|
|
12556
|
-
marketConfig
|
|
10114
|
+
groupChatConfig
|
|
12557
10115
|
);
|
|
12558
10116
|
sphere._password = options.password ?? null;
|
|
12559
10117
|
await sphere.storeMnemonic(options.mnemonic, options.derivationPath);
|
|
@@ -12579,8 +10137,8 @@ var Sphere = class _Sphere {
|
|
|
12579
10137
|
if (!await _Sphere.exists(options.storage)) {
|
|
12580
10138
|
throw new Error("No wallet found. Use Sphere.create() to create a new wallet.");
|
|
12581
10139
|
}
|
|
10140
|
+
_Sphere.configureTokenRegistry(options.storage, options.network);
|
|
12582
10141
|
const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
|
|
12583
|
-
const marketConfig = _Sphere.resolveMarketConfig(options.market);
|
|
12584
10142
|
const sphere = new _Sphere(
|
|
12585
10143
|
options.storage,
|
|
12586
10144
|
options.transport,
|
|
@@ -12588,8 +10146,7 @@ var Sphere = class _Sphere {
|
|
|
12588
10146
|
options.tokenStorage,
|
|
12589
10147
|
options.l1,
|
|
12590
10148
|
options.price,
|
|
12591
|
-
groupChatConfig
|
|
12592
|
-
marketConfig
|
|
10149
|
+
groupChatConfig
|
|
12593
10150
|
);
|
|
12594
10151
|
sphere._password = options.password ?? null;
|
|
12595
10152
|
await sphere.loadIdentityFromStorage();
|
|
@@ -12635,7 +10192,6 @@ var Sphere = class _Sphere {
|
|
|
12635
10192
|
console.log("[Sphere.import] Storage reconnected");
|
|
12636
10193
|
}
|
|
12637
10194
|
const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat);
|
|
12638
|
-
const marketConfig = _Sphere.resolveMarketConfig(options.market);
|
|
12639
10195
|
const sphere = new _Sphere(
|
|
12640
10196
|
options.storage,
|
|
12641
10197
|
options.transport,
|
|
@@ -12643,8 +10199,7 @@ var Sphere = class _Sphere {
|
|
|
12643
10199
|
options.tokenStorage,
|
|
12644
10200
|
options.l1,
|
|
12645
10201
|
options.price,
|
|
12646
|
-
groupChatConfig
|
|
12647
|
-
marketConfig
|
|
10202
|
+
groupChatConfig
|
|
12648
10203
|
);
|
|
12649
10204
|
sphere._password = options.password ?? null;
|
|
12650
10205
|
if (options.mnemonic) {
|
|
@@ -12809,10 +10364,6 @@ var Sphere = class _Sphere {
|
|
|
12809
10364
|
get groupChat() {
|
|
12810
10365
|
return this._groupChat;
|
|
12811
10366
|
}
|
|
12812
|
-
/** Market module (intent bulletin board). Null if not configured. */
|
|
12813
|
-
get market() {
|
|
12814
|
-
return this._market;
|
|
12815
|
-
}
|
|
12816
10367
|
// ===========================================================================
|
|
12817
10368
|
// Public Properties - State
|
|
12818
10369
|
// ===========================================================================
|
|
@@ -13688,14 +11239,9 @@ var Sphere = class _Sphere {
|
|
|
13688
11239
|
storage: this._storage,
|
|
13689
11240
|
emitEvent
|
|
13690
11241
|
});
|
|
13691
|
-
this._market?.initialize({
|
|
13692
|
-
identity: this._identity,
|
|
13693
|
-
emitEvent
|
|
13694
|
-
});
|
|
13695
11242
|
await this._payments.load();
|
|
13696
11243
|
await this._communications.load();
|
|
13697
11244
|
await this._groupChat?.load();
|
|
13698
|
-
await this._market?.load();
|
|
13699
11245
|
}
|
|
13700
11246
|
/**
|
|
13701
11247
|
* Derive address at a specific index
|
|
@@ -14396,22 +11942,12 @@ var Sphere = class _Sphere {
|
|
|
14396
11942
|
return;
|
|
14397
11943
|
}
|
|
14398
11944
|
try {
|
|
14399
|
-
|
|
14400
|
-
if (transportPubkey && this._transport.resolve) {
|
|
11945
|
+
if (this._identity?.directAddress && this._transport.resolve) {
|
|
14401
11946
|
try {
|
|
14402
|
-
const existing = await this._transport.resolve(
|
|
11947
|
+
const existing = await this._transport.resolve(this._identity.directAddress);
|
|
14403
11948
|
if (existing) {
|
|
14404
|
-
|
|
14405
|
-
|
|
14406
|
-
if (!recoveredNametag && !this._identity?.nametag && this._transport.recoverNametag) {
|
|
14407
|
-
try {
|
|
14408
|
-
recoveredNametag = await this._transport.recoverNametag() ?? void 0;
|
|
14409
|
-
if (recoveredNametag) fromLegacy = true;
|
|
14410
|
-
} catch {
|
|
14411
|
-
}
|
|
14412
|
-
}
|
|
14413
|
-
if (recoveredNametag && !this._identity?.nametag) {
|
|
14414
|
-
this._identity.nametag = recoveredNametag;
|
|
11949
|
+
if (existing.nametag && !this._identity.nametag) {
|
|
11950
|
+
this._identity.nametag = existing.nametag;
|
|
14415
11951
|
await this._updateCachedProxyAddress();
|
|
14416
11952
|
const entry = await this.ensureAddressTracked(this._currentAddressIndex);
|
|
14417
11953
|
let nametags = this._addressNametags.get(entry.addressId);
|
|
@@ -14420,20 +11956,10 @@ var Sphere = class _Sphere {
|
|
|
14420
11956
|
this._addressNametags.set(entry.addressId, nametags);
|
|
14421
11957
|
}
|
|
14422
11958
|
if (!nametags.has(0)) {
|
|
14423
|
-
nametags.set(0,
|
|
11959
|
+
nametags.set(0, existing.nametag);
|
|
14424
11960
|
await this.persistAddressNametags();
|
|
14425
11961
|
}
|
|
14426
|
-
this.emitEvent("nametag:recovered", { nametag:
|
|
14427
|
-
if (fromLegacy) {
|
|
14428
|
-
await this._transport.publishIdentityBinding(
|
|
14429
|
-
this._identity.chainPubkey,
|
|
14430
|
-
this._identity.l1Address,
|
|
14431
|
-
this._identity.directAddress || "",
|
|
14432
|
-
recoveredNametag
|
|
14433
|
-
);
|
|
14434
|
-
console.log(`[Sphere] Migrated legacy binding with nametag @${recoveredNametag}`);
|
|
14435
|
-
return;
|
|
14436
|
-
}
|
|
11962
|
+
this.emitEvent("nametag:recovered", { nametag: existing.nametag });
|
|
14437
11963
|
}
|
|
14438
11964
|
console.log("[Sphere] Existing binding found, skipping re-publish");
|
|
14439
11965
|
return;
|
|
@@ -14520,7 +12046,6 @@ var Sphere = class _Sphere {
|
|
|
14520
12046
|
this._payments.destroy();
|
|
14521
12047
|
this._communications.destroy();
|
|
14522
12048
|
this._groupChat?.destroy();
|
|
14523
|
-
this._market?.destroy();
|
|
14524
12049
|
await this._transport.disconnect();
|
|
14525
12050
|
await this._storage.disconnect();
|
|
14526
12051
|
await this._oracle.disconnect();
|
|
@@ -14828,14 +12353,9 @@ var Sphere = class _Sphere {
|
|
|
14828
12353
|
storage: this._storage,
|
|
14829
12354
|
emitEvent
|
|
14830
12355
|
});
|
|
14831
|
-
this._market?.initialize({
|
|
14832
|
-
identity: this._identity,
|
|
14833
|
-
emitEvent
|
|
14834
|
-
});
|
|
14835
12356
|
await this._payments.load();
|
|
14836
12357
|
await this._communications.load();
|
|
14837
12358
|
await this._groupChat?.load();
|
|
14838
|
-
await this._market?.load();
|
|
14839
12359
|
}
|
|
14840
12360
|
// ===========================================================================
|
|
14841
12361
|
// Private: Helpers
|
|
@@ -15025,7 +12545,7 @@ async function checkWebSocket(url, timeoutMs) {
|
|
|
15025
12545
|
resolve({ healthy: true, url, responseTimeMs });
|
|
15026
12546
|
}
|
|
15027
12547
|
};
|
|
15028
|
-
ws2.onerror = (
|
|
12548
|
+
ws2.onerror = (_event) => {
|
|
15029
12549
|
if (!resolved) {
|
|
15030
12550
|
resolved = true;
|
|
15031
12551
|
clearTimeout(timer);
|
|
@@ -15186,16 +12706,4 @@ async function runCustomCheck(name, checkFn, timeoutMs) {
|
|
|
15186
12706
|
toSmallestUnit,
|
|
15187
12707
|
validateMnemonic
|
|
15188
12708
|
});
|
|
15189
|
-
/*! Bundled license information:
|
|
15190
|
-
|
|
15191
|
-
@noble/hashes/utils.js:
|
|
15192
|
-
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
15193
|
-
|
|
15194
|
-
@noble/curves/utils.js:
|
|
15195
|
-
@noble/curves/abstract/modular.js:
|
|
15196
|
-
@noble/curves/abstract/curve.js:
|
|
15197
|
-
@noble/curves/abstract/weierstrass.js:
|
|
15198
|
-
@noble/curves/secp256k1.js:
|
|
15199
|
-
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
15200
|
-
*/
|
|
15201
12709
|
//# sourceMappingURL=index.cjs.map
|