@unicitylabs/sphere-sdk 0.3.4 → 0.3.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/index.cjs +2722 -153
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +169 -0
- package/dist/core/index.d.ts +169 -0
- package/dist/core/index.js +2718 -149
- package/dist/core/index.js.map +1 -1
- package/dist/impl/browser/index.cjs +385 -4
- package/dist/impl/browser/index.cjs.map +1 -1
- package/dist/impl/browser/index.js +385 -4
- package/dist/impl/browser/index.js.map +1 -1
- package/dist/impl/browser/ipfs.cjs +5 -1
- package/dist/impl/browser/ipfs.cjs.map +1 -1
- package/dist/impl/browser/ipfs.js +5 -1
- package/dist/impl/browser/ipfs.js.map +1 -1
- package/dist/impl/nodejs/index.cjs +385 -4
- package/dist/impl/nodejs/index.cjs.map +1 -1
- package/dist/impl/nodejs/index.d.cts +23 -0
- package/dist/impl/nodejs/index.d.ts +23 -0
- package/dist/impl/nodejs/index.js +385 -4
- package/dist/impl/nodejs/index.js.map +1 -1
- package/dist/index.cjs +2728 -153
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +270 -6
- package/dist/index.d.ts +270 -6
- package/dist/index.js +2721 -149
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
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 = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __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 || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
|
|
29
|
+
mod2
|
|
30
30
|
));
|
|
31
|
-
var __toCommonJS = (
|
|
31
|
+
var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
|
|
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 mod2 = bech32Polymod(values) ^ 1;
|
|
79
79
|
const ret = [];
|
|
80
80
|
for (let p = 0; p < 6; p++) {
|
|
81
|
-
ret.push(
|
|
81
|
+
ret.push(mod2 >> 5 * (5 - p) & 31);
|
|
82
82
|
}
|
|
83
83
|
return ret;
|
|
84
84
|
}
|
|
@@ -2429,7 +2429,11 @@ var STORAGE_KEYS_GLOBAL = {
|
|
|
2429
2429
|
/** Group chat: processed event IDs for deduplication */
|
|
2430
2430
|
GROUP_CHAT_PROCESSED_EVENTS: "group_chat_processed_events",
|
|
2431
2431
|
/** Group chat: last used relay URL (stale data detection) */
|
|
2432
|
-
GROUP_CHAT_RELAY_URL: "group_chat_relay_url"
|
|
2432
|
+
GROUP_CHAT_RELAY_URL: "group_chat_relay_url",
|
|
2433
|
+
/** Cached token registry JSON (fetched from remote) */
|
|
2434
|
+
TOKEN_REGISTRY_CACHE: "token_registry_cache",
|
|
2435
|
+
/** Timestamp of last token registry cache update (ms since epoch) */
|
|
2436
|
+
TOKEN_REGISTRY_CACHE_TS: "token_registry_cache_ts"
|
|
2433
2437
|
};
|
|
2434
2438
|
var STORAGE_KEYS_ADDRESS = {
|
|
2435
2439
|
/** Pending transfers for this address */
|
|
@@ -2510,6 +2514,8 @@ var DEFAULT_BASE_PATH = "m/44'/0'/0'";
|
|
|
2510
2514
|
var DEFAULT_DERIVATION_PATH2 = `${DEFAULT_BASE_PATH}/0/0`;
|
|
2511
2515
|
var DEFAULT_ELECTRUM_URL = "wss://fulcrum.alpha.unicity.network:50004";
|
|
2512
2516
|
var TEST_ELECTRUM_URL = "wss://fulcrum.alpha.testnet.unicity.network:50004";
|
|
2517
|
+
var TOKEN_REGISTRY_URL = "https://raw.githubusercontent.com/unicitynetwork/unicity-ids/refs/heads/main/unicity-ids.testnet.json";
|
|
2518
|
+
var TOKEN_REGISTRY_REFRESH_INTERVAL = 36e5;
|
|
2513
2519
|
var TEST_NOSTR_RELAYS = [
|
|
2514
2520
|
"wss://nostr-relay.testnet.unicity.network"
|
|
2515
2521
|
];
|
|
@@ -2523,7 +2529,8 @@ var NETWORKS = {
|
|
|
2523
2529
|
nostrRelays: DEFAULT_NOSTR_RELAYS,
|
|
2524
2530
|
ipfsGateways: DEFAULT_IPFS_GATEWAYS,
|
|
2525
2531
|
electrumUrl: DEFAULT_ELECTRUM_URL,
|
|
2526
|
-
groupRelays: DEFAULT_GROUP_RELAYS
|
|
2532
|
+
groupRelays: DEFAULT_GROUP_RELAYS,
|
|
2533
|
+
tokenRegistryUrl: TOKEN_REGISTRY_URL
|
|
2527
2534
|
},
|
|
2528
2535
|
testnet: {
|
|
2529
2536
|
name: "Testnet",
|
|
@@ -2531,7 +2538,8 @@ var NETWORKS = {
|
|
|
2531
2538
|
nostrRelays: TEST_NOSTR_RELAYS,
|
|
2532
2539
|
ipfsGateways: DEFAULT_IPFS_GATEWAYS,
|
|
2533
2540
|
electrumUrl: TEST_ELECTRUM_URL,
|
|
2534
|
-
groupRelays: DEFAULT_GROUP_RELAYS
|
|
2541
|
+
groupRelays: DEFAULT_GROUP_RELAYS,
|
|
2542
|
+
tokenRegistryUrl: TOKEN_REGISTRY_URL
|
|
2535
2543
|
},
|
|
2536
2544
|
dev: {
|
|
2537
2545
|
name: "Development",
|
|
@@ -2539,9 +2547,11 @@ var NETWORKS = {
|
|
|
2539
2547
|
nostrRelays: TEST_NOSTR_RELAYS,
|
|
2540
2548
|
ipfsGateways: DEFAULT_IPFS_GATEWAYS,
|
|
2541
2549
|
electrumUrl: TEST_ELECTRUM_URL,
|
|
2542
|
-
groupRelays: DEFAULT_GROUP_RELAYS
|
|
2550
|
+
groupRelays: DEFAULT_GROUP_RELAYS,
|
|
2551
|
+
tokenRegistryUrl: TOKEN_REGISTRY_URL
|
|
2543
2552
|
}
|
|
2544
2553
|
};
|
|
2554
|
+
var DEFAULT_MARKET_API_URL = "https://market-api.unicity.network";
|
|
2545
2555
|
|
|
2546
2556
|
// types/txf.ts
|
|
2547
2557
|
var ARCHIVED_PREFIX = "archived-";
|
|
@@ -2582,141 +2592,24 @@ function parseForkedKey(key) {
|
|
|
2582
2592
|
};
|
|
2583
2593
|
}
|
|
2584
2594
|
|
|
2585
|
-
// registry/token-registry.testnet.json
|
|
2586
|
-
var token_registry_testnet_default = [
|
|
2587
|
-
{
|
|
2588
|
-
network: "unicity:testnet",
|
|
2589
|
-
assetKind: "non-fungible",
|
|
2590
|
-
name: "unicity",
|
|
2591
|
-
description: "Unicity testnet token type",
|
|
2592
|
-
id: "f8aa13834268d29355ff12183066f0cb902003629bbc5eb9ef0efbe397867509"
|
|
2593
|
-
},
|
|
2594
|
-
{
|
|
2595
|
-
network: "unicity:testnet",
|
|
2596
|
-
assetKind: "fungible",
|
|
2597
|
-
name: "unicity",
|
|
2598
|
-
symbol: "UCT",
|
|
2599
|
-
decimals: 18,
|
|
2600
|
-
description: "Unicity testnet native coin",
|
|
2601
|
-
icons: [
|
|
2602
|
-
{ url: "https://raw.githubusercontent.com/unicitynetwork/unicity-ids/refs/heads/main/unicity_logo_32.png" }
|
|
2603
|
-
],
|
|
2604
|
-
id: "455ad8720656b08e8dbd5bac1f3c73eeea5431565f6c1c3af742b1aa12d41d89"
|
|
2605
|
-
},
|
|
2606
|
-
{
|
|
2607
|
-
network: "unicity:testnet",
|
|
2608
|
-
assetKind: "fungible",
|
|
2609
|
-
name: "unicity-usd",
|
|
2610
|
-
symbol: "USDU",
|
|
2611
|
-
decimals: 6,
|
|
2612
|
-
description: "Unicity testnet USD stablecoin",
|
|
2613
|
-
icons: [
|
|
2614
|
-
{ url: "https://raw.githubusercontent.com/unicitynetwork/unicity-ids/refs/heads/main/usdu_logo_32.png" }
|
|
2615
|
-
],
|
|
2616
|
-
id: "8f0f3d7a5e7297be0ee98c63b81bcebb2740f43f616566fc290f9823a54f52d7"
|
|
2617
|
-
},
|
|
2618
|
-
{
|
|
2619
|
-
network: "unicity:testnet",
|
|
2620
|
-
assetKind: "fungible",
|
|
2621
|
-
name: "unicity-eur",
|
|
2622
|
-
symbol: "EURU",
|
|
2623
|
-
decimals: 6,
|
|
2624
|
-
description: "Unicity testnet EUR stablecoin",
|
|
2625
|
-
icons: [
|
|
2626
|
-
{ url: "https://raw.githubusercontent.com/unicitynetwork/unicity-ids/refs/heads/main/euru_logo_32.png" }
|
|
2627
|
-
],
|
|
2628
|
-
id: "5e160d5e9fdbb03b553fb9c3f6e6c30efa41fa807be39fb4f18e43776e492925"
|
|
2629
|
-
},
|
|
2630
|
-
{
|
|
2631
|
-
network: "unicity:testnet",
|
|
2632
|
-
assetKind: "fungible",
|
|
2633
|
-
name: "solana",
|
|
2634
|
-
symbol: "SOL",
|
|
2635
|
-
decimals: 9,
|
|
2636
|
-
description: "Solana testnet coin on Unicity",
|
|
2637
|
-
icons: [
|
|
2638
|
-
{ url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/svg/icon/sol.svg" },
|
|
2639
|
-
{ url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/32/icon/sol.png" }
|
|
2640
|
-
],
|
|
2641
|
-
id: "dee5f8ce778562eec90e9c38a91296a023210ccc76ff4c29d527ac3eb64ade93"
|
|
2642
|
-
},
|
|
2643
|
-
{
|
|
2644
|
-
network: "unicity:testnet",
|
|
2645
|
-
assetKind: "fungible",
|
|
2646
|
-
name: "bitcoin",
|
|
2647
|
-
symbol: "BTC",
|
|
2648
|
-
decimals: 8,
|
|
2649
|
-
description: "Bitcoin testnet coin on Unicity",
|
|
2650
|
-
icons: [
|
|
2651
|
-
{ url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/svg/icon/btc.svg" },
|
|
2652
|
-
{ url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/32/icon/btc.png" }
|
|
2653
|
-
],
|
|
2654
|
-
id: "86bc190fcf7b2d07c6078de93db803578760148b16d4431aa2f42a3241ff0daa"
|
|
2655
|
-
},
|
|
2656
|
-
{
|
|
2657
|
-
network: "unicity:testnet",
|
|
2658
|
-
assetKind: "fungible",
|
|
2659
|
-
name: "ethereum",
|
|
2660
|
-
symbol: "ETH",
|
|
2661
|
-
decimals: 18,
|
|
2662
|
-
description: "Ethereum testnet coin on Unicity",
|
|
2663
|
-
icons: [
|
|
2664
|
-
{ url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/svg/icon/eth.svg" },
|
|
2665
|
-
{ url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/32/icon/eth.png" }
|
|
2666
|
-
],
|
|
2667
|
-
id: "3c2450f2fd867e7bb60c6a69d7ad0e53ce967078c201a3ecaa6074ed4c0deafb"
|
|
2668
|
-
},
|
|
2669
|
-
{
|
|
2670
|
-
network: "unicity:testnet",
|
|
2671
|
-
assetKind: "fungible",
|
|
2672
|
-
name: "alpha_test",
|
|
2673
|
-
symbol: "ALPHT",
|
|
2674
|
-
decimals: 8,
|
|
2675
|
-
description: "ALPHA testnet coin on Unicity",
|
|
2676
|
-
icons: [
|
|
2677
|
-
{ url: "https://raw.githubusercontent.com/unicitynetwork/unicity-ids/refs/heads/main/alpha_coin.png" }
|
|
2678
|
-
],
|
|
2679
|
-
id: "cde78ded16ef65818a51f43138031c4284e519300ab0cb60c30a8f9078080e5f"
|
|
2680
|
-
},
|
|
2681
|
-
{
|
|
2682
|
-
network: "unicity:testnet",
|
|
2683
|
-
assetKind: "fungible",
|
|
2684
|
-
name: "tether",
|
|
2685
|
-
symbol: "USDT",
|
|
2686
|
-
decimals: 6,
|
|
2687
|
-
description: "Tether (Ethereum) testnet coin on Unicity",
|
|
2688
|
-
icons: [
|
|
2689
|
-
{ url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/svg/icon/usdt.svg" },
|
|
2690
|
-
{ url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/32/icon/usdt.png" }
|
|
2691
|
-
],
|
|
2692
|
-
id: "40d25444648418fe7efd433e147187a3a6adf049ac62bc46038bda5b960bf690"
|
|
2693
|
-
},
|
|
2694
|
-
{
|
|
2695
|
-
network: "unicity:testnet",
|
|
2696
|
-
assetKind: "fungible",
|
|
2697
|
-
name: "usd-coin",
|
|
2698
|
-
symbol: "USDC",
|
|
2699
|
-
decimals: 6,
|
|
2700
|
-
description: "USDC (Ethereum) testnet coin on Unicity",
|
|
2701
|
-
icons: [
|
|
2702
|
-
{ url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/svg/icon/usdc.svg" },
|
|
2703
|
-
{ url: "https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/32/icon/usdc.png" }
|
|
2704
|
-
],
|
|
2705
|
-
id: "2265121770fa6f41131dd9a6cc571e28679263d09a53eb2642e145b5b9a5b0a2"
|
|
2706
|
-
}
|
|
2707
|
-
];
|
|
2708
|
-
|
|
2709
2595
|
// registry/TokenRegistry.ts
|
|
2596
|
+
var FETCH_TIMEOUT_MS = 1e4;
|
|
2710
2597
|
var TokenRegistry = class _TokenRegistry {
|
|
2711
2598
|
static instance = null;
|
|
2712
2599
|
definitionsById;
|
|
2713
2600
|
definitionsBySymbol;
|
|
2714
2601
|
definitionsByName;
|
|
2602
|
+
// Remote refresh state
|
|
2603
|
+
remoteUrl = null;
|
|
2604
|
+
storage = null;
|
|
2605
|
+
refreshIntervalMs = TOKEN_REGISTRY_REFRESH_INTERVAL;
|
|
2606
|
+
refreshTimer = null;
|
|
2607
|
+
lastRefreshAt = 0;
|
|
2608
|
+
refreshPromise = null;
|
|
2715
2609
|
constructor() {
|
|
2716
2610
|
this.definitionsById = /* @__PURE__ */ new Map();
|
|
2717
2611
|
this.definitionsBySymbol = /* @__PURE__ */ new Map();
|
|
2718
2612
|
this.definitionsByName = /* @__PURE__ */ new Map();
|
|
2719
|
-
this.loadRegistry();
|
|
2720
2613
|
}
|
|
2721
2614
|
/**
|
|
2722
2615
|
* Get singleton instance of TokenRegistry
|
|
@@ -2728,16 +2621,106 @@ var TokenRegistry = class _TokenRegistry {
|
|
|
2728
2621
|
return _TokenRegistry.instance;
|
|
2729
2622
|
}
|
|
2730
2623
|
/**
|
|
2731
|
-
*
|
|
2624
|
+
* Configure remote registry refresh with persistent caching.
|
|
2625
|
+
*
|
|
2626
|
+
* On first call:
|
|
2627
|
+
* 1. Loads cached data from StorageProvider (if available and fresh)
|
|
2628
|
+
* 2. Starts periodic remote fetch (if autoRefresh is true, which is default)
|
|
2629
|
+
*
|
|
2630
|
+
* @param options - Configuration options
|
|
2631
|
+
* @param options.remoteUrl - Remote URL to fetch definitions from
|
|
2632
|
+
* @param options.storage - StorageProvider for persistent caching
|
|
2633
|
+
* @param options.refreshIntervalMs - Refresh interval in ms (default: 1 hour)
|
|
2634
|
+
* @param options.autoRefresh - Start auto-refresh immediately (default: true)
|
|
2635
|
+
*/
|
|
2636
|
+
static configure(options) {
|
|
2637
|
+
const instance = _TokenRegistry.getInstance();
|
|
2638
|
+
if (options.remoteUrl !== void 0) {
|
|
2639
|
+
instance.remoteUrl = options.remoteUrl;
|
|
2640
|
+
}
|
|
2641
|
+
if (options.storage !== void 0) {
|
|
2642
|
+
instance.storage = options.storage;
|
|
2643
|
+
}
|
|
2644
|
+
if (options.refreshIntervalMs !== void 0) {
|
|
2645
|
+
instance.refreshIntervalMs = options.refreshIntervalMs;
|
|
2646
|
+
}
|
|
2647
|
+
if (instance.storage) {
|
|
2648
|
+
instance.loadFromCache();
|
|
2649
|
+
}
|
|
2650
|
+
const autoRefresh = options.autoRefresh ?? true;
|
|
2651
|
+
if (autoRefresh && instance.remoteUrl) {
|
|
2652
|
+
instance.startAutoRefresh();
|
|
2653
|
+
}
|
|
2654
|
+
}
|
|
2655
|
+
/**
|
|
2656
|
+
* Reset the singleton instance (useful for testing).
|
|
2657
|
+
* Stops auto-refresh if running.
|
|
2732
2658
|
*/
|
|
2733
2659
|
static resetInstance() {
|
|
2660
|
+
if (_TokenRegistry.instance) {
|
|
2661
|
+
_TokenRegistry.instance.stopAutoRefresh();
|
|
2662
|
+
}
|
|
2734
2663
|
_TokenRegistry.instance = null;
|
|
2735
2664
|
}
|
|
2736
2665
|
/**
|
|
2737
|
-
*
|
|
2666
|
+
* Destroy the singleton: stop auto-refresh and reset.
|
|
2667
|
+
*/
|
|
2668
|
+
static destroy() {
|
|
2669
|
+
_TokenRegistry.resetInstance();
|
|
2670
|
+
}
|
|
2671
|
+
// ===========================================================================
|
|
2672
|
+
// Cache (StorageProvider)
|
|
2673
|
+
// ===========================================================================
|
|
2674
|
+
/**
|
|
2675
|
+
* Load definitions from StorageProvider cache.
|
|
2676
|
+
* Only applies if cache exists and is fresh (within refreshIntervalMs).
|
|
2677
|
+
*/
|
|
2678
|
+
async loadFromCache() {
|
|
2679
|
+
if (!this.storage) return false;
|
|
2680
|
+
try {
|
|
2681
|
+
const [cached, cachedTs] = await Promise.all([
|
|
2682
|
+
this.storage.get(STORAGE_KEYS_GLOBAL.TOKEN_REGISTRY_CACHE),
|
|
2683
|
+
this.storage.get(STORAGE_KEYS_GLOBAL.TOKEN_REGISTRY_CACHE_TS)
|
|
2684
|
+
]);
|
|
2685
|
+
if (!cached || !cachedTs) return false;
|
|
2686
|
+
const ts = parseInt(cachedTs, 10);
|
|
2687
|
+
if (isNaN(ts)) return false;
|
|
2688
|
+
const age = Date.now() - ts;
|
|
2689
|
+
if (age > this.refreshIntervalMs) return false;
|
|
2690
|
+
if (this.lastRefreshAt > ts) return false;
|
|
2691
|
+
const data = JSON.parse(cached);
|
|
2692
|
+
if (!this.isValidDefinitionsArray(data)) return false;
|
|
2693
|
+
this.applyDefinitions(data);
|
|
2694
|
+
this.lastRefreshAt = ts;
|
|
2695
|
+
return true;
|
|
2696
|
+
} catch {
|
|
2697
|
+
return false;
|
|
2698
|
+
}
|
|
2699
|
+
}
|
|
2700
|
+
/**
|
|
2701
|
+
* Save definitions to StorageProvider cache.
|
|
2702
|
+
*/
|
|
2703
|
+
async saveToCache(definitions) {
|
|
2704
|
+
if (!this.storage) return;
|
|
2705
|
+
try {
|
|
2706
|
+
await Promise.all([
|
|
2707
|
+
this.storage.set(STORAGE_KEYS_GLOBAL.TOKEN_REGISTRY_CACHE, JSON.stringify(definitions)),
|
|
2708
|
+
this.storage.set(STORAGE_KEYS_GLOBAL.TOKEN_REGISTRY_CACHE_TS, String(Date.now()))
|
|
2709
|
+
]);
|
|
2710
|
+
} catch {
|
|
2711
|
+
}
|
|
2712
|
+
}
|
|
2713
|
+
// ===========================================================================
|
|
2714
|
+
// Remote Refresh
|
|
2715
|
+
// ===========================================================================
|
|
2716
|
+
/**
|
|
2717
|
+
* Apply an array of token definitions to the internal maps.
|
|
2718
|
+
* Clears existing data before applying.
|
|
2738
2719
|
*/
|
|
2739
|
-
|
|
2740
|
-
|
|
2720
|
+
applyDefinitions(definitions) {
|
|
2721
|
+
this.definitionsById.clear();
|
|
2722
|
+
this.definitionsBySymbol.clear();
|
|
2723
|
+
this.definitionsByName.clear();
|
|
2741
2724
|
for (const def of definitions) {
|
|
2742
2725
|
const idLower = def.id.toLowerCase();
|
|
2743
2726
|
this.definitionsById.set(idLower, def);
|
|
@@ -2747,6 +2730,96 @@ var TokenRegistry = class _TokenRegistry {
|
|
|
2747
2730
|
this.definitionsByName.set(def.name.toLowerCase(), def);
|
|
2748
2731
|
}
|
|
2749
2732
|
}
|
|
2733
|
+
/**
|
|
2734
|
+
* Validate that data is an array of objects with 'id' field
|
|
2735
|
+
*/
|
|
2736
|
+
isValidDefinitionsArray(data) {
|
|
2737
|
+
return Array.isArray(data) && data.every((item) => item && typeof item === "object" && "id" in item);
|
|
2738
|
+
}
|
|
2739
|
+
/**
|
|
2740
|
+
* Fetch token definitions from the remote URL and update the registry.
|
|
2741
|
+
* On success, also persists to StorageProvider cache.
|
|
2742
|
+
* Returns true on success, false on failure. On failure, existing data is preserved.
|
|
2743
|
+
* Concurrent calls are deduplicated — only one fetch runs at a time.
|
|
2744
|
+
*/
|
|
2745
|
+
async refreshFromRemote() {
|
|
2746
|
+
if (!this.remoteUrl) {
|
|
2747
|
+
return false;
|
|
2748
|
+
}
|
|
2749
|
+
if (this.refreshPromise) {
|
|
2750
|
+
return this.refreshPromise;
|
|
2751
|
+
}
|
|
2752
|
+
this.refreshPromise = this.doRefresh();
|
|
2753
|
+
try {
|
|
2754
|
+
return await this.refreshPromise;
|
|
2755
|
+
} finally {
|
|
2756
|
+
this.refreshPromise = null;
|
|
2757
|
+
}
|
|
2758
|
+
}
|
|
2759
|
+
async doRefresh() {
|
|
2760
|
+
try {
|
|
2761
|
+
const controller = new AbortController();
|
|
2762
|
+
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
|
2763
|
+
let response;
|
|
2764
|
+
try {
|
|
2765
|
+
response = await fetch(this.remoteUrl, {
|
|
2766
|
+
headers: { Accept: "application/json" },
|
|
2767
|
+
signal: controller.signal
|
|
2768
|
+
});
|
|
2769
|
+
} finally {
|
|
2770
|
+
clearTimeout(timer);
|
|
2771
|
+
}
|
|
2772
|
+
if (!response.ok) {
|
|
2773
|
+
console.warn(
|
|
2774
|
+
`[TokenRegistry] Remote fetch failed: HTTP ${response.status} ${response.statusText}`
|
|
2775
|
+
);
|
|
2776
|
+
return false;
|
|
2777
|
+
}
|
|
2778
|
+
const data = await response.json();
|
|
2779
|
+
if (!this.isValidDefinitionsArray(data)) {
|
|
2780
|
+
console.warn("[TokenRegistry] Remote data is not a valid token definitions array");
|
|
2781
|
+
return false;
|
|
2782
|
+
}
|
|
2783
|
+
const definitions = data;
|
|
2784
|
+
this.applyDefinitions(definitions);
|
|
2785
|
+
this.lastRefreshAt = Date.now();
|
|
2786
|
+
this.saveToCache(definitions);
|
|
2787
|
+
return true;
|
|
2788
|
+
} catch (error) {
|
|
2789
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2790
|
+
console.warn(`[TokenRegistry] Remote refresh failed: ${message}`);
|
|
2791
|
+
return false;
|
|
2792
|
+
}
|
|
2793
|
+
}
|
|
2794
|
+
/**
|
|
2795
|
+
* Start periodic auto-refresh from the remote URL.
|
|
2796
|
+
* Does an immediate fetch, then repeats at the configured interval.
|
|
2797
|
+
*/
|
|
2798
|
+
startAutoRefresh(intervalMs) {
|
|
2799
|
+
this.stopAutoRefresh();
|
|
2800
|
+
if (intervalMs !== void 0) {
|
|
2801
|
+
this.refreshIntervalMs = intervalMs;
|
|
2802
|
+
}
|
|
2803
|
+
this.refreshFromRemote();
|
|
2804
|
+
this.refreshTimer = setInterval(() => {
|
|
2805
|
+
this.refreshFromRemote();
|
|
2806
|
+
}, this.refreshIntervalMs);
|
|
2807
|
+
}
|
|
2808
|
+
/**
|
|
2809
|
+
* Stop periodic auto-refresh
|
|
2810
|
+
*/
|
|
2811
|
+
stopAutoRefresh() {
|
|
2812
|
+
if (this.refreshTimer !== null) {
|
|
2813
|
+
clearInterval(this.refreshTimer);
|
|
2814
|
+
this.refreshTimer = null;
|
|
2815
|
+
}
|
|
2816
|
+
}
|
|
2817
|
+
/**
|
|
2818
|
+
* Timestamp of the last successful remote refresh (0 if never refreshed)
|
|
2819
|
+
*/
|
|
2820
|
+
getLastRefreshAt() {
|
|
2821
|
+
return this.lastRefreshAt;
|
|
2822
|
+
}
|
|
2750
2823
|
// ===========================================================================
|
|
2751
2824
|
// Lookup Methods
|
|
2752
2825
|
// ===========================================================================
|
|
@@ -8907,6 +8980,2426 @@ function createGroupChatModule(config) {
|
|
|
8907
8980
|
return new GroupChatModule(config);
|
|
8908
8981
|
}
|
|
8909
8982
|
|
|
8983
|
+
// node_modules/@noble/hashes/utils.js
|
|
8984
|
+
function isBytes(a) {
|
|
8985
|
+
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
|
|
8986
|
+
}
|
|
8987
|
+
function anumber(n, title = "") {
|
|
8988
|
+
if (!Number.isSafeInteger(n) || n < 0) {
|
|
8989
|
+
const prefix = title && `"${title}" `;
|
|
8990
|
+
throw new Error(`${prefix}expected integer >= 0, got ${n}`);
|
|
8991
|
+
}
|
|
8992
|
+
}
|
|
8993
|
+
function abytes(value, length, title = "") {
|
|
8994
|
+
const bytes = isBytes(value);
|
|
8995
|
+
const len = value?.length;
|
|
8996
|
+
const needsLen = length !== void 0;
|
|
8997
|
+
if (!bytes || needsLen && len !== length) {
|
|
8998
|
+
const prefix = title && `"${title}" `;
|
|
8999
|
+
const ofLen = needsLen ? ` of length ${length}` : "";
|
|
9000
|
+
const got = bytes ? `length=${len}` : `type=${typeof value}`;
|
|
9001
|
+
throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
|
|
9002
|
+
}
|
|
9003
|
+
return value;
|
|
9004
|
+
}
|
|
9005
|
+
function ahash(h) {
|
|
9006
|
+
if (typeof h !== "function" || typeof h.create !== "function")
|
|
9007
|
+
throw new Error("Hash must wrapped by utils.createHasher");
|
|
9008
|
+
anumber(h.outputLen);
|
|
9009
|
+
anumber(h.blockLen);
|
|
9010
|
+
}
|
|
9011
|
+
function aexists(instance, checkFinished = true) {
|
|
9012
|
+
if (instance.destroyed)
|
|
9013
|
+
throw new Error("Hash instance has been destroyed");
|
|
9014
|
+
if (checkFinished && instance.finished)
|
|
9015
|
+
throw new Error("Hash#digest() has already been called");
|
|
9016
|
+
}
|
|
9017
|
+
function aoutput(out, instance) {
|
|
9018
|
+
abytes(out, void 0, "digestInto() output");
|
|
9019
|
+
const min = instance.outputLen;
|
|
9020
|
+
if (out.length < min) {
|
|
9021
|
+
throw new Error('"digestInto() output" expected to be of length >=' + min);
|
|
9022
|
+
}
|
|
9023
|
+
}
|
|
9024
|
+
function clean(...arrays) {
|
|
9025
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
9026
|
+
arrays[i].fill(0);
|
|
9027
|
+
}
|
|
9028
|
+
}
|
|
9029
|
+
function createView(arr) {
|
|
9030
|
+
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
9031
|
+
}
|
|
9032
|
+
function rotr(word, shift) {
|
|
9033
|
+
return word << 32 - shift | word >>> shift;
|
|
9034
|
+
}
|
|
9035
|
+
var hasHexBuiltin = /* @__PURE__ */ (() => (
|
|
9036
|
+
// @ts-ignore
|
|
9037
|
+
typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
|
|
9038
|
+
))();
|
|
9039
|
+
var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
|
|
9040
|
+
function bytesToHex4(bytes) {
|
|
9041
|
+
abytes(bytes);
|
|
9042
|
+
if (hasHexBuiltin)
|
|
9043
|
+
return bytes.toHex();
|
|
9044
|
+
let hex = "";
|
|
9045
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
9046
|
+
hex += hexes[bytes[i]];
|
|
9047
|
+
}
|
|
9048
|
+
return hex;
|
|
9049
|
+
}
|
|
9050
|
+
var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
|
|
9051
|
+
function asciiToBase16(ch) {
|
|
9052
|
+
if (ch >= asciis._0 && ch <= asciis._9)
|
|
9053
|
+
return ch - asciis._0;
|
|
9054
|
+
if (ch >= asciis.A && ch <= asciis.F)
|
|
9055
|
+
return ch - (asciis.A - 10);
|
|
9056
|
+
if (ch >= asciis.a && ch <= asciis.f)
|
|
9057
|
+
return ch - (asciis.a - 10);
|
|
9058
|
+
return;
|
|
9059
|
+
}
|
|
9060
|
+
function hexToBytes2(hex) {
|
|
9061
|
+
if (typeof hex !== "string")
|
|
9062
|
+
throw new Error("hex string expected, got " + typeof hex);
|
|
9063
|
+
if (hasHexBuiltin)
|
|
9064
|
+
return Uint8Array.fromHex(hex);
|
|
9065
|
+
const hl = hex.length;
|
|
9066
|
+
const al = hl / 2;
|
|
9067
|
+
if (hl % 2)
|
|
9068
|
+
throw new Error("hex string expected, got unpadded hex of length " + hl);
|
|
9069
|
+
const array = new Uint8Array(al);
|
|
9070
|
+
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
9071
|
+
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
|
9072
|
+
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
|
9073
|
+
if (n1 === void 0 || n2 === void 0) {
|
|
9074
|
+
const char = hex[hi] + hex[hi + 1];
|
|
9075
|
+
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
9076
|
+
}
|
|
9077
|
+
array[ai] = n1 * 16 + n2;
|
|
9078
|
+
}
|
|
9079
|
+
return array;
|
|
9080
|
+
}
|
|
9081
|
+
function concatBytes(...arrays) {
|
|
9082
|
+
let sum = 0;
|
|
9083
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
9084
|
+
const a = arrays[i];
|
|
9085
|
+
abytes(a);
|
|
9086
|
+
sum += a.length;
|
|
9087
|
+
}
|
|
9088
|
+
const res = new Uint8Array(sum);
|
|
9089
|
+
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
9090
|
+
const a = arrays[i];
|
|
9091
|
+
res.set(a, pad);
|
|
9092
|
+
pad += a.length;
|
|
9093
|
+
}
|
|
9094
|
+
return res;
|
|
9095
|
+
}
|
|
9096
|
+
function createHasher(hashCons, info = {}) {
|
|
9097
|
+
const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
|
|
9098
|
+
const tmp = hashCons(void 0);
|
|
9099
|
+
hashC.outputLen = tmp.outputLen;
|
|
9100
|
+
hashC.blockLen = tmp.blockLen;
|
|
9101
|
+
hashC.create = (opts) => hashCons(opts);
|
|
9102
|
+
Object.assign(hashC, info);
|
|
9103
|
+
return Object.freeze(hashC);
|
|
9104
|
+
}
|
|
9105
|
+
function randomBytes2(bytesLength = 32) {
|
|
9106
|
+
const cr = typeof globalThis === "object" ? globalThis.crypto : null;
|
|
9107
|
+
if (typeof cr?.getRandomValues !== "function")
|
|
9108
|
+
throw new Error("crypto.getRandomValues must be defined");
|
|
9109
|
+
return cr.getRandomValues(new Uint8Array(bytesLength));
|
|
9110
|
+
}
|
|
9111
|
+
var oidNist = (suffix) => ({
|
|
9112
|
+
oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
|
|
9113
|
+
});
|
|
9114
|
+
|
|
9115
|
+
// node_modules/@noble/hashes/_md.js
|
|
9116
|
+
function Chi(a, b, c) {
|
|
9117
|
+
return a & b ^ ~a & c;
|
|
9118
|
+
}
|
|
9119
|
+
function Maj(a, b, c) {
|
|
9120
|
+
return a & b ^ a & c ^ b & c;
|
|
9121
|
+
}
|
|
9122
|
+
var HashMD = class {
|
|
9123
|
+
blockLen;
|
|
9124
|
+
outputLen;
|
|
9125
|
+
padOffset;
|
|
9126
|
+
isLE;
|
|
9127
|
+
// For partial updates less than block size
|
|
9128
|
+
buffer;
|
|
9129
|
+
view;
|
|
9130
|
+
finished = false;
|
|
9131
|
+
length = 0;
|
|
9132
|
+
pos = 0;
|
|
9133
|
+
destroyed = false;
|
|
9134
|
+
constructor(blockLen, outputLen, padOffset, isLE) {
|
|
9135
|
+
this.blockLen = blockLen;
|
|
9136
|
+
this.outputLen = outputLen;
|
|
9137
|
+
this.padOffset = padOffset;
|
|
9138
|
+
this.isLE = isLE;
|
|
9139
|
+
this.buffer = new Uint8Array(blockLen);
|
|
9140
|
+
this.view = createView(this.buffer);
|
|
9141
|
+
}
|
|
9142
|
+
update(data) {
|
|
9143
|
+
aexists(this);
|
|
9144
|
+
abytes(data);
|
|
9145
|
+
const { view, buffer, blockLen } = this;
|
|
9146
|
+
const len = data.length;
|
|
9147
|
+
for (let pos = 0; pos < len; ) {
|
|
9148
|
+
const take = Math.min(blockLen - this.pos, len - pos);
|
|
9149
|
+
if (take === blockLen) {
|
|
9150
|
+
const dataView = createView(data);
|
|
9151
|
+
for (; blockLen <= len - pos; pos += blockLen)
|
|
9152
|
+
this.process(dataView, pos);
|
|
9153
|
+
continue;
|
|
9154
|
+
}
|
|
9155
|
+
buffer.set(data.subarray(pos, pos + take), this.pos);
|
|
9156
|
+
this.pos += take;
|
|
9157
|
+
pos += take;
|
|
9158
|
+
if (this.pos === blockLen) {
|
|
9159
|
+
this.process(view, 0);
|
|
9160
|
+
this.pos = 0;
|
|
9161
|
+
}
|
|
9162
|
+
}
|
|
9163
|
+
this.length += data.length;
|
|
9164
|
+
this.roundClean();
|
|
9165
|
+
return this;
|
|
9166
|
+
}
|
|
9167
|
+
digestInto(out) {
|
|
9168
|
+
aexists(this);
|
|
9169
|
+
aoutput(out, this);
|
|
9170
|
+
this.finished = true;
|
|
9171
|
+
const { buffer, view, blockLen, isLE } = this;
|
|
9172
|
+
let { pos } = this;
|
|
9173
|
+
buffer[pos++] = 128;
|
|
9174
|
+
clean(this.buffer.subarray(pos));
|
|
9175
|
+
if (this.padOffset > blockLen - pos) {
|
|
9176
|
+
this.process(view, 0);
|
|
9177
|
+
pos = 0;
|
|
9178
|
+
}
|
|
9179
|
+
for (let i = pos; i < blockLen; i++)
|
|
9180
|
+
buffer[i] = 0;
|
|
9181
|
+
view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
|
|
9182
|
+
this.process(view, 0);
|
|
9183
|
+
const oview = createView(out);
|
|
9184
|
+
const len = this.outputLen;
|
|
9185
|
+
if (len % 4)
|
|
9186
|
+
throw new Error("_sha2: outputLen must be aligned to 32bit");
|
|
9187
|
+
const outLen = len / 4;
|
|
9188
|
+
const state = this.get();
|
|
9189
|
+
if (outLen > state.length)
|
|
9190
|
+
throw new Error("_sha2: outputLen bigger than state");
|
|
9191
|
+
for (let i = 0; i < outLen; i++)
|
|
9192
|
+
oview.setUint32(4 * i, state[i], isLE);
|
|
9193
|
+
}
|
|
9194
|
+
digest() {
|
|
9195
|
+
const { buffer, outputLen } = this;
|
|
9196
|
+
this.digestInto(buffer);
|
|
9197
|
+
const res = buffer.slice(0, outputLen);
|
|
9198
|
+
this.destroy();
|
|
9199
|
+
return res;
|
|
9200
|
+
}
|
|
9201
|
+
_cloneInto(to) {
|
|
9202
|
+
to ||= new this.constructor();
|
|
9203
|
+
to.set(...this.get());
|
|
9204
|
+
const { blockLen, buffer, length, finished, destroyed, pos } = this;
|
|
9205
|
+
to.destroyed = destroyed;
|
|
9206
|
+
to.finished = finished;
|
|
9207
|
+
to.length = length;
|
|
9208
|
+
to.pos = pos;
|
|
9209
|
+
if (length % blockLen)
|
|
9210
|
+
to.buffer.set(buffer);
|
|
9211
|
+
return to;
|
|
9212
|
+
}
|
|
9213
|
+
clone() {
|
|
9214
|
+
return this._cloneInto();
|
|
9215
|
+
}
|
|
9216
|
+
};
|
|
9217
|
+
var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
|
|
9218
|
+
1779033703,
|
|
9219
|
+
3144134277,
|
|
9220
|
+
1013904242,
|
|
9221
|
+
2773480762,
|
|
9222
|
+
1359893119,
|
|
9223
|
+
2600822924,
|
|
9224
|
+
528734635,
|
|
9225
|
+
1541459225
|
|
9226
|
+
]);
|
|
9227
|
+
|
|
9228
|
+
// node_modules/@noble/hashes/sha2.js
|
|
9229
|
+
var SHA256_K = /* @__PURE__ */ Uint32Array.from([
|
|
9230
|
+
1116352408,
|
|
9231
|
+
1899447441,
|
|
9232
|
+
3049323471,
|
|
9233
|
+
3921009573,
|
|
9234
|
+
961987163,
|
|
9235
|
+
1508970993,
|
|
9236
|
+
2453635748,
|
|
9237
|
+
2870763221,
|
|
9238
|
+
3624381080,
|
|
9239
|
+
310598401,
|
|
9240
|
+
607225278,
|
|
9241
|
+
1426881987,
|
|
9242
|
+
1925078388,
|
|
9243
|
+
2162078206,
|
|
9244
|
+
2614888103,
|
|
9245
|
+
3248222580,
|
|
9246
|
+
3835390401,
|
|
9247
|
+
4022224774,
|
|
9248
|
+
264347078,
|
|
9249
|
+
604807628,
|
|
9250
|
+
770255983,
|
|
9251
|
+
1249150122,
|
|
9252
|
+
1555081692,
|
|
9253
|
+
1996064986,
|
|
9254
|
+
2554220882,
|
|
9255
|
+
2821834349,
|
|
9256
|
+
2952996808,
|
|
9257
|
+
3210313671,
|
|
9258
|
+
3336571891,
|
|
9259
|
+
3584528711,
|
|
9260
|
+
113926993,
|
|
9261
|
+
338241895,
|
|
9262
|
+
666307205,
|
|
9263
|
+
773529912,
|
|
9264
|
+
1294757372,
|
|
9265
|
+
1396182291,
|
|
9266
|
+
1695183700,
|
|
9267
|
+
1986661051,
|
|
9268
|
+
2177026350,
|
|
9269
|
+
2456956037,
|
|
9270
|
+
2730485921,
|
|
9271
|
+
2820302411,
|
|
9272
|
+
3259730800,
|
|
9273
|
+
3345764771,
|
|
9274
|
+
3516065817,
|
|
9275
|
+
3600352804,
|
|
9276
|
+
4094571909,
|
|
9277
|
+
275423344,
|
|
9278
|
+
430227734,
|
|
9279
|
+
506948616,
|
|
9280
|
+
659060556,
|
|
9281
|
+
883997877,
|
|
9282
|
+
958139571,
|
|
9283
|
+
1322822218,
|
|
9284
|
+
1537002063,
|
|
9285
|
+
1747873779,
|
|
9286
|
+
1955562222,
|
|
9287
|
+
2024104815,
|
|
9288
|
+
2227730452,
|
|
9289
|
+
2361852424,
|
|
9290
|
+
2428436474,
|
|
9291
|
+
2756734187,
|
|
9292
|
+
3204031479,
|
|
9293
|
+
3329325298
|
|
9294
|
+
]);
|
|
9295
|
+
var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
|
|
9296
|
+
var SHA2_32B = class extends HashMD {
|
|
9297
|
+
constructor(outputLen) {
|
|
9298
|
+
super(64, outputLen, 8, false);
|
|
9299
|
+
}
|
|
9300
|
+
get() {
|
|
9301
|
+
const { A, B, C, D, E, F, G, H } = this;
|
|
9302
|
+
return [A, B, C, D, E, F, G, H];
|
|
9303
|
+
}
|
|
9304
|
+
// prettier-ignore
|
|
9305
|
+
set(A, B, C, D, E, F, G, H) {
|
|
9306
|
+
this.A = A | 0;
|
|
9307
|
+
this.B = B | 0;
|
|
9308
|
+
this.C = C | 0;
|
|
9309
|
+
this.D = D | 0;
|
|
9310
|
+
this.E = E | 0;
|
|
9311
|
+
this.F = F | 0;
|
|
9312
|
+
this.G = G | 0;
|
|
9313
|
+
this.H = H | 0;
|
|
9314
|
+
}
|
|
9315
|
+
process(view, offset) {
|
|
9316
|
+
for (let i = 0; i < 16; i++, offset += 4)
|
|
9317
|
+
SHA256_W[i] = view.getUint32(offset, false);
|
|
9318
|
+
for (let i = 16; i < 64; i++) {
|
|
9319
|
+
const W15 = SHA256_W[i - 15];
|
|
9320
|
+
const W2 = SHA256_W[i - 2];
|
|
9321
|
+
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
|
|
9322
|
+
const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
|
|
9323
|
+
SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
|
|
9324
|
+
}
|
|
9325
|
+
let { A, B, C, D, E, F, G, H } = this;
|
|
9326
|
+
for (let i = 0; i < 64; i++) {
|
|
9327
|
+
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
|
|
9328
|
+
const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
|
|
9329
|
+
const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
|
|
9330
|
+
const T2 = sigma0 + Maj(A, B, C) | 0;
|
|
9331
|
+
H = G;
|
|
9332
|
+
G = F;
|
|
9333
|
+
F = E;
|
|
9334
|
+
E = D + T1 | 0;
|
|
9335
|
+
D = C;
|
|
9336
|
+
C = B;
|
|
9337
|
+
B = A;
|
|
9338
|
+
A = T1 + T2 | 0;
|
|
9339
|
+
}
|
|
9340
|
+
A = A + this.A | 0;
|
|
9341
|
+
B = B + this.B | 0;
|
|
9342
|
+
C = C + this.C | 0;
|
|
9343
|
+
D = D + this.D | 0;
|
|
9344
|
+
E = E + this.E | 0;
|
|
9345
|
+
F = F + this.F | 0;
|
|
9346
|
+
G = G + this.G | 0;
|
|
9347
|
+
H = H + this.H | 0;
|
|
9348
|
+
this.set(A, B, C, D, E, F, G, H);
|
|
9349
|
+
}
|
|
9350
|
+
roundClean() {
|
|
9351
|
+
clean(SHA256_W);
|
|
9352
|
+
}
|
|
9353
|
+
destroy() {
|
|
9354
|
+
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
|
9355
|
+
clean(this.buffer);
|
|
9356
|
+
}
|
|
9357
|
+
};
|
|
9358
|
+
var _SHA256 = class extends SHA2_32B {
|
|
9359
|
+
// We cannot use array here since array allows indexing by variable
|
|
9360
|
+
// which means optimizer/compiler cannot use registers.
|
|
9361
|
+
A = SHA256_IV[0] | 0;
|
|
9362
|
+
B = SHA256_IV[1] | 0;
|
|
9363
|
+
C = SHA256_IV[2] | 0;
|
|
9364
|
+
D = SHA256_IV[3] | 0;
|
|
9365
|
+
E = SHA256_IV[4] | 0;
|
|
9366
|
+
F = SHA256_IV[5] | 0;
|
|
9367
|
+
G = SHA256_IV[6] | 0;
|
|
9368
|
+
H = SHA256_IV[7] | 0;
|
|
9369
|
+
constructor() {
|
|
9370
|
+
super(32);
|
|
9371
|
+
}
|
|
9372
|
+
};
|
|
9373
|
+
var sha2564 = /* @__PURE__ */ createHasher(
|
|
9374
|
+
() => new _SHA256(),
|
|
9375
|
+
/* @__PURE__ */ oidNist(1)
|
|
9376
|
+
);
|
|
9377
|
+
|
|
9378
|
+
// node_modules/@noble/curves/utils.js
|
|
9379
|
+
var _0n = /* @__PURE__ */ BigInt(0);
|
|
9380
|
+
var _1n = /* @__PURE__ */ BigInt(1);
|
|
9381
|
+
function abool(value, title = "") {
|
|
9382
|
+
if (typeof value !== "boolean") {
|
|
9383
|
+
const prefix = title && `"${title}" `;
|
|
9384
|
+
throw new Error(prefix + "expected boolean, got type=" + typeof value);
|
|
9385
|
+
}
|
|
9386
|
+
return value;
|
|
9387
|
+
}
|
|
9388
|
+
function abignumber(n) {
|
|
9389
|
+
if (typeof n === "bigint") {
|
|
9390
|
+
if (!isPosBig(n))
|
|
9391
|
+
throw new Error("positive bigint expected, got " + n);
|
|
9392
|
+
} else
|
|
9393
|
+
anumber(n);
|
|
9394
|
+
return n;
|
|
9395
|
+
}
|
|
9396
|
+
function numberToHexUnpadded(num) {
|
|
9397
|
+
const hex = abignumber(num).toString(16);
|
|
9398
|
+
return hex.length & 1 ? "0" + hex : hex;
|
|
9399
|
+
}
|
|
9400
|
+
function hexToNumber(hex) {
|
|
9401
|
+
if (typeof hex !== "string")
|
|
9402
|
+
throw new Error("hex string expected, got " + typeof hex);
|
|
9403
|
+
return hex === "" ? _0n : BigInt("0x" + hex);
|
|
9404
|
+
}
|
|
9405
|
+
function bytesToNumberBE(bytes) {
|
|
9406
|
+
return hexToNumber(bytesToHex4(bytes));
|
|
9407
|
+
}
|
|
9408
|
+
function bytesToNumberLE(bytes) {
|
|
9409
|
+
return hexToNumber(bytesToHex4(copyBytes(abytes(bytes)).reverse()));
|
|
9410
|
+
}
|
|
9411
|
+
function numberToBytesBE(n, len) {
|
|
9412
|
+
anumber(len);
|
|
9413
|
+
n = abignumber(n);
|
|
9414
|
+
const res = hexToBytes2(n.toString(16).padStart(len * 2, "0"));
|
|
9415
|
+
if (res.length !== len)
|
|
9416
|
+
throw new Error("number too large");
|
|
9417
|
+
return res;
|
|
9418
|
+
}
|
|
9419
|
+
function numberToBytesLE(n, len) {
|
|
9420
|
+
return numberToBytesBE(n, len).reverse();
|
|
9421
|
+
}
|
|
9422
|
+
function copyBytes(bytes) {
|
|
9423
|
+
return Uint8Array.from(bytes);
|
|
9424
|
+
}
|
|
9425
|
+
var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
|
|
9426
|
+
function inRange(n, min, max) {
|
|
9427
|
+
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
|
|
9428
|
+
}
|
|
9429
|
+
function aInRange(title, n, min, max) {
|
|
9430
|
+
if (!inRange(n, min, max))
|
|
9431
|
+
throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
|
|
9432
|
+
}
|
|
9433
|
+
function bitLen(n) {
|
|
9434
|
+
let len;
|
|
9435
|
+
for (len = 0; n > _0n; n >>= _1n, len += 1)
|
|
9436
|
+
;
|
|
9437
|
+
return len;
|
|
9438
|
+
}
|
|
9439
|
+
var bitMask = (n) => (_1n << BigInt(n)) - _1n;
|
|
9440
|
+
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
9441
|
+
anumber(hashLen, "hashLen");
|
|
9442
|
+
anumber(qByteLen, "qByteLen");
|
|
9443
|
+
if (typeof hmacFn !== "function")
|
|
9444
|
+
throw new Error("hmacFn must be a function");
|
|
9445
|
+
const u8n = (len) => new Uint8Array(len);
|
|
9446
|
+
const NULL = Uint8Array.of();
|
|
9447
|
+
const byte0 = Uint8Array.of(0);
|
|
9448
|
+
const byte1 = Uint8Array.of(1);
|
|
9449
|
+
const _maxDrbgIters = 1e3;
|
|
9450
|
+
let v = u8n(hashLen);
|
|
9451
|
+
let k = u8n(hashLen);
|
|
9452
|
+
let i = 0;
|
|
9453
|
+
const reset = () => {
|
|
9454
|
+
v.fill(1);
|
|
9455
|
+
k.fill(0);
|
|
9456
|
+
i = 0;
|
|
9457
|
+
};
|
|
9458
|
+
const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));
|
|
9459
|
+
const reseed = (seed = NULL) => {
|
|
9460
|
+
k = h(byte0, seed);
|
|
9461
|
+
v = h();
|
|
9462
|
+
if (seed.length === 0)
|
|
9463
|
+
return;
|
|
9464
|
+
k = h(byte1, seed);
|
|
9465
|
+
v = h();
|
|
9466
|
+
};
|
|
9467
|
+
const gen = () => {
|
|
9468
|
+
if (i++ >= _maxDrbgIters)
|
|
9469
|
+
throw new Error("drbg: tried max amount of iterations");
|
|
9470
|
+
let len = 0;
|
|
9471
|
+
const out = [];
|
|
9472
|
+
while (len < qByteLen) {
|
|
9473
|
+
v = h();
|
|
9474
|
+
const sl = v.slice();
|
|
9475
|
+
out.push(sl);
|
|
9476
|
+
len += v.length;
|
|
9477
|
+
}
|
|
9478
|
+
return concatBytes(...out);
|
|
9479
|
+
};
|
|
9480
|
+
const genUntil = (seed, pred) => {
|
|
9481
|
+
reset();
|
|
9482
|
+
reseed(seed);
|
|
9483
|
+
let res = void 0;
|
|
9484
|
+
while (!(res = pred(gen())))
|
|
9485
|
+
reseed();
|
|
9486
|
+
reset();
|
|
9487
|
+
return res;
|
|
9488
|
+
};
|
|
9489
|
+
return genUntil;
|
|
9490
|
+
}
|
|
9491
|
+
function validateObject(object, fields = {}, optFields = {}) {
|
|
9492
|
+
if (!object || typeof object !== "object")
|
|
9493
|
+
throw new Error("expected valid options object");
|
|
9494
|
+
function checkField(fieldName, expectedType, isOpt) {
|
|
9495
|
+
const val = object[fieldName];
|
|
9496
|
+
if (isOpt && val === void 0)
|
|
9497
|
+
return;
|
|
9498
|
+
const current = typeof val;
|
|
9499
|
+
if (current !== expectedType || val === null)
|
|
9500
|
+
throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
|
|
9501
|
+
}
|
|
9502
|
+
const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
|
|
9503
|
+
iter(fields, false);
|
|
9504
|
+
iter(optFields, true);
|
|
9505
|
+
}
|
|
9506
|
+
function memoized(fn) {
|
|
9507
|
+
const map = /* @__PURE__ */ new WeakMap();
|
|
9508
|
+
return (arg, ...args) => {
|
|
9509
|
+
const val = map.get(arg);
|
|
9510
|
+
if (val !== void 0)
|
|
9511
|
+
return val;
|
|
9512
|
+
const computed = fn(arg, ...args);
|
|
9513
|
+
map.set(arg, computed);
|
|
9514
|
+
return computed;
|
|
9515
|
+
};
|
|
9516
|
+
}
|
|
9517
|
+
|
|
9518
|
+
// node_modules/@noble/curves/abstract/modular.js
|
|
9519
|
+
var _0n2 = /* @__PURE__ */ BigInt(0);
|
|
9520
|
+
var _1n2 = /* @__PURE__ */ BigInt(1);
|
|
9521
|
+
var _2n = /* @__PURE__ */ BigInt(2);
|
|
9522
|
+
var _3n = /* @__PURE__ */ BigInt(3);
|
|
9523
|
+
var _4n = /* @__PURE__ */ BigInt(4);
|
|
9524
|
+
var _5n = /* @__PURE__ */ BigInt(5);
|
|
9525
|
+
var _7n = /* @__PURE__ */ BigInt(7);
|
|
9526
|
+
var _8n = /* @__PURE__ */ BigInt(8);
|
|
9527
|
+
var _9n = /* @__PURE__ */ BigInt(9);
|
|
9528
|
+
var _16n = /* @__PURE__ */ BigInt(16);
|
|
9529
|
+
function mod(a, b) {
|
|
9530
|
+
const result = a % b;
|
|
9531
|
+
return result >= _0n2 ? result : b + result;
|
|
9532
|
+
}
|
|
9533
|
+
function pow2(x, power, modulo) {
|
|
9534
|
+
let res = x;
|
|
9535
|
+
while (power-- > _0n2) {
|
|
9536
|
+
res *= res;
|
|
9537
|
+
res %= modulo;
|
|
9538
|
+
}
|
|
9539
|
+
return res;
|
|
9540
|
+
}
|
|
9541
|
+
function invert(number, modulo) {
|
|
9542
|
+
if (number === _0n2)
|
|
9543
|
+
throw new Error("invert: expected non-zero number");
|
|
9544
|
+
if (modulo <= _0n2)
|
|
9545
|
+
throw new Error("invert: expected positive modulus, got " + modulo);
|
|
9546
|
+
let a = mod(number, modulo);
|
|
9547
|
+
let b = modulo;
|
|
9548
|
+
let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
|
|
9549
|
+
while (a !== _0n2) {
|
|
9550
|
+
const q = b / a;
|
|
9551
|
+
const r = b % a;
|
|
9552
|
+
const m = x - u * q;
|
|
9553
|
+
const n = y - v * q;
|
|
9554
|
+
b = a, a = r, x = u, y = v, u = m, v = n;
|
|
9555
|
+
}
|
|
9556
|
+
const gcd = b;
|
|
9557
|
+
if (gcd !== _1n2)
|
|
9558
|
+
throw new Error("invert: does not exist");
|
|
9559
|
+
return mod(x, modulo);
|
|
9560
|
+
}
|
|
9561
|
+
function assertIsSquare(Fp, root, n) {
|
|
9562
|
+
if (!Fp.eql(Fp.sqr(root), n))
|
|
9563
|
+
throw new Error("Cannot find square root");
|
|
9564
|
+
}
|
|
9565
|
+
function sqrt3mod4(Fp, n) {
|
|
9566
|
+
const p1div4 = (Fp.ORDER + _1n2) / _4n;
|
|
9567
|
+
const root = Fp.pow(n, p1div4);
|
|
9568
|
+
assertIsSquare(Fp, root, n);
|
|
9569
|
+
return root;
|
|
9570
|
+
}
|
|
9571
|
+
function sqrt5mod8(Fp, n) {
|
|
9572
|
+
const p5div8 = (Fp.ORDER - _5n) / _8n;
|
|
9573
|
+
const n2 = Fp.mul(n, _2n);
|
|
9574
|
+
const v = Fp.pow(n2, p5div8);
|
|
9575
|
+
const nv = Fp.mul(n, v);
|
|
9576
|
+
const i = Fp.mul(Fp.mul(nv, _2n), v);
|
|
9577
|
+
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
|
|
9578
|
+
assertIsSquare(Fp, root, n);
|
|
9579
|
+
return root;
|
|
9580
|
+
}
|
|
9581
|
+
function sqrt9mod16(P) {
|
|
9582
|
+
const Fp_ = Field(P);
|
|
9583
|
+
const tn = tonelliShanks(P);
|
|
9584
|
+
const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
|
|
9585
|
+
const c2 = tn(Fp_, c1);
|
|
9586
|
+
const c3 = tn(Fp_, Fp_.neg(c1));
|
|
9587
|
+
const c4 = (P + _7n) / _16n;
|
|
9588
|
+
return (Fp, n) => {
|
|
9589
|
+
let tv1 = Fp.pow(n, c4);
|
|
9590
|
+
let tv2 = Fp.mul(tv1, c1);
|
|
9591
|
+
const tv3 = Fp.mul(tv1, c2);
|
|
9592
|
+
const tv4 = Fp.mul(tv1, c3);
|
|
9593
|
+
const e1 = Fp.eql(Fp.sqr(tv2), n);
|
|
9594
|
+
const e2 = Fp.eql(Fp.sqr(tv3), n);
|
|
9595
|
+
tv1 = Fp.cmov(tv1, tv2, e1);
|
|
9596
|
+
tv2 = Fp.cmov(tv4, tv3, e2);
|
|
9597
|
+
const e3 = Fp.eql(Fp.sqr(tv2), n);
|
|
9598
|
+
const root = Fp.cmov(tv1, tv2, e3);
|
|
9599
|
+
assertIsSquare(Fp, root, n);
|
|
9600
|
+
return root;
|
|
9601
|
+
};
|
|
9602
|
+
}
|
|
9603
|
+
function tonelliShanks(P) {
|
|
9604
|
+
if (P < _3n)
|
|
9605
|
+
throw new Error("sqrt is not defined for small field");
|
|
9606
|
+
let Q = P - _1n2;
|
|
9607
|
+
let S = 0;
|
|
9608
|
+
while (Q % _2n === _0n2) {
|
|
9609
|
+
Q /= _2n;
|
|
9610
|
+
S++;
|
|
9611
|
+
}
|
|
9612
|
+
let Z = _2n;
|
|
9613
|
+
const _Fp = Field(P);
|
|
9614
|
+
while (FpLegendre(_Fp, Z) === 1) {
|
|
9615
|
+
if (Z++ > 1e3)
|
|
9616
|
+
throw new Error("Cannot find square root: probably non-prime P");
|
|
9617
|
+
}
|
|
9618
|
+
if (S === 1)
|
|
9619
|
+
return sqrt3mod4;
|
|
9620
|
+
let cc = _Fp.pow(Z, Q);
|
|
9621
|
+
const Q1div2 = (Q + _1n2) / _2n;
|
|
9622
|
+
return function tonelliSlow(Fp, n) {
|
|
9623
|
+
if (Fp.is0(n))
|
|
9624
|
+
return n;
|
|
9625
|
+
if (FpLegendre(Fp, n) !== 1)
|
|
9626
|
+
throw new Error("Cannot find square root");
|
|
9627
|
+
let M = S;
|
|
9628
|
+
let c = Fp.mul(Fp.ONE, cc);
|
|
9629
|
+
let t = Fp.pow(n, Q);
|
|
9630
|
+
let R = Fp.pow(n, Q1div2);
|
|
9631
|
+
while (!Fp.eql(t, Fp.ONE)) {
|
|
9632
|
+
if (Fp.is0(t))
|
|
9633
|
+
return Fp.ZERO;
|
|
9634
|
+
let i = 1;
|
|
9635
|
+
let t_tmp = Fp.sqr(t);
|
|
9636
|
+
while (!Fp.eql(t_tmp, Fp.ONE)) {
|
|
9637
|
+
i++;
|
|
9638
|
+
t_tmp = Fp.sqr(t_tmp);
|
|
9639
|
+
if (i === M)
|
|
9640
|
+
throw new Error("Cannot find square root");
|
|
9641
|
+
}
|
|
9642
|
+
const exponent = _1n2 << BigInt(M - i - 1);
|
|
9643
|
+
const b = Fp.pow(c, exponent);
|
|
9644
|
+
M = i;
|
|
9645
|
+
c = Fp.sqr(b);
|
|
9646
|
+
t = Fp.mul(t, c);
|
|
9647
|
+
R = Fp.mul(R, b);
|
|
9648
|
+
}
|
|
9649
|
+
return R;
|
|
9650
|
+
};
|
|
9651
|
+
}
|
|
9652
|
+
function FpSqrt(P) {
|
|
9653
|
+
if (P % _4n === _3n)
|
|
9654
|
+
return sqrt3mod4;
|
|
9655
|
+
if (P % _8n === _5n)
|
|
9656
|
+
return sqrt5mod8;
|
|
9657
|
+
if (P % _16n === _9n)
|
|
9658
|
+
return sqrt9mod16(P);
|
|
9659
|
+
return tonelliShanks(P);
|
|
9660
|
+
}
|
|
9661
|
+
var FIELD_FIELDS = [
|
|
9662
|
+
"create",
|
|
9663
|
+
"isValid",
|
|
9664
|
+
"is0",
|
|
9665
|
+
"neg",
|
|
9666
|
+
"inv",
|
|
9667
|
+
"sqrt",
|
|
9668
|
+
"sqr",
|
|
9669
|
+
"eql",
|
|
9670
|
+
"add",
|
|
9671
|
+
"sub",
|
|
9672
|
+
"mul",
|
|
9673
|
+
"pow",
|
|
9674
|
+
"div",
|
|
9675
|
+
"addN",
|
|
9676
|
+
"subN",
|
|
9677
|
+
"mulN",
|
|
9678
|
+
"sqrN"
|
|
9679
|
+
];
|
|
9680
|
+
function validateField(field) {
|
|
9681
|
+
const initial = {
|
|
9682
|
+
ORDER: "bigint",
|
|
9683
|
+
BYTES: "number",
|
|
9684
|
+
BITS: "number"
|
|
9685
|
+
};
|
|
9686
|
+
const opts = FIELD_FIELDS.reduce((map, val) => {
|
|
9687
|
+
map[val] = "function";
|
|
9688
|
+
return map;
|
|
9689
|
+
}, initial);
|
|
9690
|
+
validateObject(field, opts);
|
|
9691
|
+
return field;
|
|
9692
|
+
}
|
|
9693
|
+
function FpPow(Fp, num, power) {
|
|
9694
|
+
if (power < _0n2)
|
|
9695
|
+
throw new Error("invalid exponent, negatives unsupported");
|
|
9696
|
+
if (power === _0n2)
|
|
9697
|
+
return Fp.ONE;
|
|
9698
|
+
if (power === _1n2)
|
|
9699
|
+
return num;
|
|
9700
|
+
let p = Fp.ONE;
|
|
9701
|
+
let d = num;
|
|
9702
|
+
while (power > _0n2) {
|
|
9703
|
+
if (power & _1n2)
|
|
9704
|
+
p = Fp.mul(p, d);
|
|
9705
|
+
d = Fp.sqr(d);
|
|
9706
|
+
power >>= _1n2;
|
|
9707
|
+
}
|
|
9708
|
+
return p;
|
|
9709
|
+
}
|
|
9710
|
+
function FpInvertBatch(Fp, nums, passZero = false) {
|
|
9711
|
+
const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
|
|
9712
|
+
const multipliedAcc = nums.reduce((acc, num, i) => {
|
|
9713
|
+
if (Fp.is0(num))
|
|
9714
|
+
return acc;
|
|
9715
|
+
inverted[i] = acc;
|
|
9716
|
+
return Fp.mul(acc, num);
|
|
9717
|
+
}, Fp.ONE);
|
|
9718
|
+
const invertedAcc = Fp.inv(multipliedAcc);
|
|
9719
|
+
nums.reduceRight((acc, num, i) => {
|
|
9720
|
+
if (Fp.is0(num))
|
|
9721
|
+
return acc;
|
|
9722
|
+
inverted[i] = Fp.mul(acc, inverted[i]);
|
|
9723
|
+
return Fp.mul(acc, num);
|
|
9724
|
+
}, invertedAcc);
|
|
9725
|
+
return inverted;
|
|
9726
|
+
}
|
|
9727
|
+
function FpLegendre(Fp, n) {
|
|
9728
|
+
const p1mod2 = (Fp.ORDER - _1n2) / _2n;
|
|
9729
|
+
const powered = Fp.pow(n, p1mod2);
|
|
9730
|
+
const yes = Fp.eql(powered, Fp.ONE);
|
|
9731
|
+
const zero = Fp.eql(powered, Fp.ZERO);
|
|
9732
|
+
const no = Fp.eql(powered, Fp.neg(Fp.ONE));
|
|
9733
|
+
if (!yes && !zero && !no)
|
|
9734
|
+
throw new Error("invalid Legendre symbol result");
|
|
9735
|
+
return yes ? 1 : zero ? 0 : -1;
|
|
9736
|
+
}
|
|
9737
|
+
function nLength(n, nBitLength) {
|
|
9738
|
+
if (nBitLength !== void 0)
|
|
9739
|
+
anumber(nBitLength);
|
|
9740
|
+
const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
|
|
9741
|
+
const nByteLength = Math.ceil(_nBitLength / 8);
|
|
9742
|
+
return { nBitLength: _nBitLength, nByteLength };
|
|
9743
|
+
}
|
|
9744
|
+
var _Field = class {
|
|
9745
|
+
ORDER;
|
|
9746
|
+
BITS;
|
|
9747
|
+
BYTES;
|
|
9748
|
+
isLE;
|
|
9749
|
+
ZERO = _0n2;
|
|
9750
|
+
ONE = _1n2;
|
|
9751
|
+
_lengths;
|
|
9752
|
+
_sqrt;
|
|
9753
|
+
// cached sqrt
|
|
9754
|
+
_mod;
|
|
9755
|
+
constructor(ORDER, opts = {}) {
|
|
9756
|
+
if (ORDER <= _0n2)
|
|
9757
|
+
throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
|
|
9758
|
+
let _nbitLength = void 0;
|
|
9759
|
+
this.isLE = false;
|
|
9760
|
+
if (opts != null && typeof opts === "object") {
|
|
9761
|
+
if (typeof opts.BITS === "number")
|
|
9762
|
+
_nbitLength = opts.BITS;
|
|
9763
|
+
if (typeof opts.sqrt === "function")
|
|
9764
|
+
this.sqrt = opts.sqrt;
|
|
9765
|
+
if (typeof opts.isLE === "boolean")
|
|
9766
|
+
this.isLE = opts.isLE;
|
|
9767
|
+
if (opts.allowedLengths)
|
|
9768
|
+
this._lengths = opts.allowedLengths?.slice();
|
|
9769
|
+
if (typeof opts.modFromBytes === "boolean")
|
|
9770
|
+
this._mod = opts.modFromBytes;
|
|
9771
|
+
}
|
|
9772
|
+
const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
|
|
9773
|
+
if (nByteLength > 2048)
|
|
9774
|
+
throw new Error("invalid field: expected ORDER of <= 2048 bytes");
|
|
9775
|
+
this.ORDER = ORDER;
|
|
9776
|
+
this.BITS = nBitLength;
|
|
9777
|
+
this.BYTES = nByteLength;
|
|
9778
|
+
this._sqrt = void 0;
|
|
9779
|
+
Object.preventExtensions(this);
|
|
9780
|
+
}
|
|
9781
|
+
create(num) {
|
|
9782
|
+
return mod(num, this.ORDER);
|
|
9783
|
+
}
|
|
9784
|
+
isValid(num) {
|
|
9785
|
+
if (typeof num !== "bigint")
|
|
9786
|
+
throw new Error("invalid field element: expected bigint, got " + typeof num);
|
|
9787
|
+
return _0n2 <= num && num < this.ORDER;
|
|
9788
|
+
}
|
|
9789
|
+
is0(num) {
|
|
9790
|
+
return num === _0n2;
|
|
9791
|
+
}
|
|
9792
|
+
// is valid and invertible
|
|
9793
|
+
isValidNot0(num) {
|
|
9794
|
+
return !this.is0(num) && this.isValid(num);
|
|
9795
|
+
}
|
|
9796
|
+
isOdd(num) {
|
|
9797
|
+
return (num & _1n2) === _1n2;
|
|
9798
|
+
}
|
|
9799
|
+
neg(num) {
|
|
9800
|
+
return mod(-num, this.ORDER);
|
|
9801
|
+
}
|
|
9802
|
+
eql(lhs, rhs) {
|
|
9803
|
+
return lhs === rhs;
|
|
9804
|
+
}
|
|
9805
|
+
sqr(num) {
|
|
9806
|
+
return mod(num * num, this.ORDER);
|
|
9807
|
+
}
|
|
9808
|
+
add(lhs, rhs) {
|
|
9809
|
+
return mod(lhs + rhs, this.ORDER);
|
|
9810
|
+
}
|
|
9811
|
+
sub(lhs, rhs) {
|
|
9812
|
+
return mod(lhs - rhs, this.ORDER);
|
|
9813
|
+
}
|
|
9814
|
+
mul(lhs, rhs) {
|
|
9815
|
+
return mod(lhs * rhs, this.ORDER);
|
|
9816
|
+
}
|
|
9817
|
+
pow(num, power) {
|
|
9818
|
+
return FpPow(this, num, power);
|
|
9819
|
+
}
|
|
9820
|
+
div(lhs, rhs) {
|
|
9821
|
+
return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
|
|
9822
|
+
}
|
|
9823
|
+
// Same as above, but doesn't normalize
|
|
9824
|
+
sqrN(num) {
|
|
9825
|
+
return num * num;
|
|
9826
|
+
}
|
|
9827
|
+
addN(lhs, rhs) {
|
|
9828
|
+
return lhs + rhs;
|
|
9829
|
+
}
|
|
9830
|
+
subN(lhs, rhs) {
|
|
9831
|
+
return lhs - rhs;
|
|
9832
|
+
}
|
|
9833
|
+
mulN(lhs, rhs) {
|
|
9834
|
+
return lhs * rhs;
|
|
9835
|
+
}
|
|
9836
|
+
inv(num) {
|
|
9837
|
+
return invert(num, this.ORDER);
|
|
9838
|
+
}
|
|
9839
|
+
sqrt(num) {
|
|
9840
|
+
if (!this._sqrt)
|
|
9841
|
+
this._sqrt = FpSqrt(this.ORDER);
|
|
9842
|
+
return this._sqrt(this, num);
|
|
9843
|
+
}
|
|
9844
|
+
toBytes(num) {
|
|
9845
|
+
return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
|
|
9846
|
+
}
|
|
9847
|
+
fromBytes(bytes, skipValidation = false) {
|
|
9848
|
+
abytes(bytes);
|
|
9849
|
+
const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
|
|
9850
|
+
if (allowedLengths) {
|
|
9851
|
+
if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
|
|
9852
|
+
throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
|
|
9853
|
+
}
|
|
9854
|
+
const padded = new Uint8Array(BYTES);
|
|
9855
|
+
padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
|
|
9856
|
+
bytes = padded;
|
|
9857
|
+
}
|
|
9858
|
+
if (bytes.length !== BYTES)
|
|
9859
|
+
throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
|
|
9860
|
+
let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
|
|
9861
|
+
if (modFromBytes)
|
|
9862
|
+
scalar = mod(scalar, ORDER);
|
|
9863
|
+
if (!skipValidation) {
|
|
9864
|
+
if (!this.isValid(scalar))
|
|
9865
|
+
throw new Error("invalid field element: outside of range 0..ORDER");
|
|
9866
|
+
}
|
|
9867
|
+
return scalar;
|
|
9868
|
+
}
|
|
9869
|
+
// TODO: we don't need it here, move out to separate fn
|
|
9870
|
+
invertBatch(lst) {
|
|
9871
|
+
return FpInvertBatch(this, lst);
|
|
9872
|
+
}
|
|
9873
|
+
// We can't move this out because Fp6, Fp12 implement it
|
|
9874
|
+
// and it's unclear what to return in there.
|
|
9875
|
+
cmov(a, b, condition) {
|
|
9876
|
+
return condition ? b : a;
|
|
9877
|
+
}
|
|
9878
|
+
};
|
|
9879
|
+
function Field(ORDER, opts = {}) {
|
|
9880
|
+
return new _Field(ORDER, opts);
|
|
9881
|
+
}
|
|
9882
|
+
function getFieldBytesLength(fieldOrder) {
|
|
9883
|
+
if (typeof fieldOrder !== "bigint")
|
|
9884
|
+
throw new Error("field order must be bigint");
|
|
9885
|
+
const bitLength = fieldOrder.toString(2).length;
|
|
9886
|
+
return Math.ceil(bitLength / 8);
|
|
9887
|
+
}
|
|
9888
|
+
function getMinHashLength(fieldOrder) {
|
|
9889
|
+
const length = getFieldBytesLength(fieldOrder);
|
|
9890
|
+
return length + Math.ceil(length / 2);
|
|
9891
|
+
}
|
|
9892
|
+
function mapHashToField(key, fieldOrder, isLE = false) {
|
|
9893
|
+
abytes(key);
|
|
9894
|
+
const len = key.length;
|
|
9895
|
+
const fieldLen = getFieldBytesLength(fieldOrder);
|
|
9896
|
+
const minLen = getMinHashLength(fieldOrder);
|
|
9897
|
+
if (len < 16 || len < minLen || len > 1024)
|
|
9898
|
+
throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
|
|
9899
|
+
const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
|
|
9900
|
+
const reduced = mod(num, fieldOrder - _1n2) + _1n2;
|
|
9901
|
+
return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
|
|
9902
|
+
}
|
|
9903
|
+
|
|
9904
|
+
// node_modules/@noble/curves/abstract/curve.js
|
|
9905
|
+
var _0n3 = /* @__PURE__ */ BigInt(0);
|
|
9906
|
+
var _1n3 = /* @__PURE__ */ BigInt(1);
|
|
9907
|
+
function negateCt(condition, item) {
|
|
9908
|
+
const neg = item.negate();
|
|
9909
|
+
return condition ? neg : item;
|
|
9910
|
+
}
|
|
9911
|
+
function normalizeZ(c, points) {
|
|
9912
|
+
const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
|
|
9913
|
+
return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
|
|
9914
|
+
}
|
|
9915
|
+
function validateW(W, bits) {
|
|
9916
|
+
if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
|
|
9917
|
+
throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
|
|
9918
|
+
}
|
|
9919
|
+
function calcWOpts(W, scalarBits) {
|
|
9920
|
+
validateW(W, scalarBits);
|
|
9921
|
+
const windows = Math.ceil(scalarBits / W) + 1;
|
|
9922
|
+
const windowSize = 2 ** (W - 1);
|
|
9923
|
+
const maxNumber = 2 ** W;
|
|
9924
|
+
const mask = bitMask(W);
|
|
9925
|
+
const shiftBy = BigInt(W);
|
|
9926
|
+
return { windows, windowSize, mask, maxNumber, shiftBy };
|
|
9927
|
+
}
|
|
9928
|
+
function calcOffsets(n, window, wOpts) {
|
|
9929
|
+
const { windowSize, mask, maxNumber, shiftBy } = wOpts;
|
|
9930
|
+
let wbits = Number(n & mask);
|
|
9931
|
+
let nextN = n >> shiftBy;
|
|
9932
|
+
if (wbits > windowSize) {
|
|
9933
|
+
wbits -= maxNumber;
|
|
9934
|
+
nextN += _1n3;
|
|
9935
|
+
}
|
|
9936
|
+
const offsetStart = window * windowSize;
|
|
9937
|
+
const offset = offsetStart + Math.abs(wbits) - 1;
|
|
9938
|
+
const isZero = wbits === 0;
|
|
9939
|
+
const isNeg = wbits < 0;
|
|
9940
|
+
const isNegF = window % 2 !== 0;
|
|
9941
|
+
const offsetF = offsetStart;
|
|
9942
|
+
return { nextN, offset, isZero, isNeg, isNegF, offsetF };
|
|
9943
|
+
}
|
|
9944
|
+
var pointPrecomputes = /* @__PURE__ */ new WeakMap();
|
|
9945
|
+
var pointWindowSizes = /* @__PURE__ */ new WeakMap();
|
|
9946
|
+
function getW(P) {
|
|
9947
|
+
return pointWindowSizes.get(P) || 1;
|
|
9948
|
+
}
|
|
9949
|
+
function assert0(n) {
|
|
9950
|
+
if (n !== _0n3)
|
|
9951
|
+
throw new Error("invalid wNAF");
|
|
9952
|
+
}
|
|
9953
|
+
var wNAF = class {
|
|
9954
|
+
BASE;
|
|
9955
|
+
ZERO;
|
|
9956
|
+
Fn;
|
|
9957
|
+
bits;
|
|
9958
|
+
// Parametrized with a given Point class (not individual point)
|
|
9959
|
+
constructor(Point, bits) {
|
|
9960
|
+
this.BASE = Point.BASE;
|
|
9961
|
+
this.ZERO = Point.ZERO;
|
|
9962
|
+
this.Fn = Point.Fn;
|
|
9963
|
+
this.bits = bits;
|
|
9964
|
+
}
|
|
9965
|
+
// non-const time multiplication ladder
|
|
9966
|
+
_unsafeLadder(elm, n, p = this.ZERO) {
|
|
9967
|
+
let d = elm;
|
|
9968
|
+
while (n > _0n3) {
|
|
9969
|
+
if (n & _1n3)
|
|
9970
|
+
p = p.add(d);
|
|
9971
|
+
d = d.double();
|
|
9972
|
+
n >>= _1n3;
|
|
9973
|
+
}
|
|
9974
|
+
return p;
|
|
9975
|
+
}
|
|
9976
|
+
/**
|
|
9977
|
+
* Creates a wNAF precomputation window. Used for caching.
|
|
9978
|
+
* Default window size is set by `utils.precompute()` and is equal to 8.
|
|
9979
|
+
* Number of precomputed points depends on the curve size:
|
|
9980
|
+
* 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
|
|
9981
|
+
* - 𝑊 is the window size
|
|
9982
|
+
* - 𝑛 is the bitlength of the curve order.
|
|
9983
|
+
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
|
|
9984
|
+
* @param point Point instance
|
|
9985
|
+
* @param W window size
|
|
9986
|
+
* @returns precomputed point tables flattened to a single array
|
|
9987
|
+
*/
|
|
9988
|
+
precomputeWindow(point, W) {
|
|
9989
|
+
const { windows, windowSize } = calcWOpts(W, this.bits);
|
|
9990
|
+
const points = [];
|
|
9991
|
+
let p = point;
|
|
9992
|
+
let base = p;
|
|
9993
|
+
for (let window = 0; window < windows; window++) {
|
|
9994
|
+
base = p;
|
|
9995
|
+
points.push(base);
|
|
9996
|
+
for (let i = 1; i < windowSize; i++) {
|
|
9997
|
+
base = base.add(p);
|
|
9998
|
+
points.push(base);
|
|
9999
|
+
}
|
|
10000
|
+
p = base.double();
|
|
10001
|
+
}
|
|
10002
|
+
return points;
|
|
10003
|
+
}
|
|
10004
|
+
/**
|
|
10005
|
+
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
|
|
10006
|
+
* More compact implementation:
|
|
10007
|
+
* https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
|
|
10008
|
+
* @returns real and fake (for const-time) points
|
|
10009
|
+
*/
|
|
10010
|
+
wNAF(W, precomputes, n) {
|
|
10011
|
+
if (!this.Fn.isValid(n))
|
|
10012
|
+
throw new Error("invalid scalar");
|
|
10013
|
+
let p = this.ZERO;
|
|
10014
|
+
let f = this.BASE;
|
|
10015
|
+
const wo = calcWOpts(W, this.bits);
|
|
10016
|
+
for (let window = 0; window < wo.windows; window++) {
|
|
10017
|
+
const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
|
|
10018
|
+
n = nextN;
|
|
10019
|
+
if (isZero) {
|
|
10020
|
+
f = f.add(negateCt(isNegF, precomputes[offsetF]));
|
|
10021
|
+
} else {
|
|
10022
|
+
p = p.add(negateCt(isNeg, precomputes[offset]));
|
|
10023
|
+
}
|
|
10024
|
+
}
|
|
10025
|
+
assert0(n);
|
|
10026
|
+
return { p, f };
|
|
10027
|
+
}
|
|
10028
|
+
/**
|
|
10029
|
+
* Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
|
|
10030
|
+
* @param acc accumulator point to add result of multiplication
|
|
10031
|
+
* @returns point
|
|
10032
|
+
*/
|
|
10033
|
+
wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
|
|
10034
|
+
const wo = calcWOpts(W, this.bits);
|
|
10035
|
+
for (let window = 0; window < wo.windows; window++) {
|
|
10036
|
+
if (n === _0n3)
|
|
10037
|
+
break;
|
|
10038
|
+
const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
|
|
10039
|
+
n = nextN;
|
|
10040
|
+
if (isZero) {
|
|
10041
|
+
continue;
|
|
10042
|
+
} else {
|
|
10043
|
+
const item = precomputes[offset];
|
|
10044
|
+
acc = acc.add(isNeg ? item.negate() : item);
|
|
10045
|
+
}
|
|
10046
|
+
}
|
|
10047
|
+
assert0(n);
|
|
10048
|
+
return acc;
|
|
10049
|
+
}
|
|
10050
|
+
getPrecomputes(W, point, transform) {
|
|
10051
|
+
let comp = pointPrecomputes.get(point);
|
|
10052
|
+
if (!comp) {
|
|
10053
|
+
comp = this.precomputeWindow(point, W);
|
|
10054
|
+
if (W !== 1) {
|
|
10055
|
+
if (typeof transform === "function")
|
|
10056
|
+
comp = transform(comp);
|
|
10057
|
+
pointPrecomputes.set(point, comp);
|
|
10058
|
+
}
|
|
10059
|
+
}
|
|
10060
|
+
return comp;
|
|
10061
|
+
}
|
|
10062
|
+
cached(point, scalar, transform) {
|
|
10063
|
+
const W = getW(point);
|
|
10064
|
+
return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
|
|
10065
|
+
}
|
|
10066
|
+
unsafe(point, scalar, transform, prev) {
|
|
10067
|
+
const W = getW(point);
|
|
10068
|
+
if (W === 1)
|
|
10069
|
+
return this._unsafeLadder(point, scalar, prev);
|
|
10070
|
+
return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
|
|
10071
|
+
}
|
|
10072
|
+
// We calculate precomputes for elliptic curve point multiplication
|
|
10073
|
+
// using windowed method. This specifies window size and
|
|
10074
|
+
// stores precomputed values. Usually only base point would be precomputed.
|
|
10075
|
+
createCache(P, W) {
|
|
10076
|
+
validateW(W, this.bits);
|
|
10077
|
+
pointWindowSizes.set(P, W);
|
|
10078
|
+
pointPrecomputes.delete(P);
|
|
10079
|
+
}
|
|
10080
|
+
hasCache(elm) {
|
|
10081
|
+
return getW(elm) !== 1;
|
|
10082
|
+
}
|
|
10083
|
+
};
|
|
10084
|
+
function mulEndoUnsafe(Point, point, k1, k2) {
|
|
10085
|
+
let acc = point;
|
|
10086
|
+
let p1 = Point.ZERO;
|
|
10087
|
+
let p2 = Point.ZERO;
|
|
10088
|
+
while (k1 > _0n3 || k2 > _0n3) {
|
|
10089
|
+
if (k1 & _1n3)
|
|
10090
|
+
p1 = p1.add(acc);
|
|
10091
|
+
if (k2 & _1n3)
|
|
10092
|
+
p2 = p2.add(acc);
|
|
10093
|
+
acc = acc.double();
|
|
10094
|
+
k1 >>= _1n3;
|
|
10095
|
+
k2 >>= _1n3;
|
|
10096
|
+
}
|
|
10097
|
+
return { p1, p2 };
|
|
10098
|
+
}
|
|
10099
|
+
function createField(order, field, isLE) {
|
|
10100
|
+
if (field) {
|
|
10101
|
+
if (field.ORDER !== order)
|
|
10102
|
+
throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
|
|
10103
|
+
validateField(field);
|
|
10104
|
+
return field;
|
|
10105
|
+
} else {
|
|
10106
|
+
return Field(order, { isLE });
|
|
10107
|
+
}
|
|
10108
|
+
}
|
|
10109
|
+
function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
|
|
10110
|
+
if (FpFnLE === void 0)
|
|
10111
|
+
FpFnLE = type === "edwards";
|
|
10112
|
+
if (!CURVE || typeof CURVE !== "object")
|
|
10113
|
+
throw new Error(`expected valid ${type} CURVE object`);
|
|
10114
|
+
for (const p of ["p", "n", "h"]) {
|
|
10115
|
+
const val = CURVE[p];
|
|
10116
|
+
if (!(typeof val === "bigint" && val > _0n3))
|
|
10117
|
+
throw new Error(`CURVE.${p} must be positive bigint`);
|
|
10118
|
+
}
|
|
10119
|
+
const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
|
|
10120
|
+
const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
|
|
10121
|
+
const _b = type === "weierstrass" ? "b" : "d";
|
|
10122
|
+
const params = ["Gx", "Gy", "a", _b];
|
|
10123
|
+
for (const p of params) {
|
|
10124
|
+
if (!Fp.isValid(CURVE[p]))
|
|
10125
|
+
throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
|
|
10126
|
+
}
|
|
10127
|
+
CURVE = Object.freeze(Object.assign({}, CURVE));
|
|
10128
|
+
return { CURVE, Fp, Fn };
|
|
10129
|
+
}
|
|
10130
|
+
function createKeygen(randomSecretKey, getPublicKey2) {
|
|
10131
|
+
return function keygen(seed) {
|
|
10132
|
+
const secretKey = randomSecretKey(seed);
|
|
10133
|
+
return { secretKey, publicKey: getPublicKey2(secretKey) };
|
|
10134
|
+
};
|
|
10135
|
+
}
|
|
10136
|
+
|
|
10137
|
+
// node_modules/@noble/hashes/hmac.js
|
|
10138
|
+
var _HMAC = class {
|
|
10139
|
+
oHash;
|
|
10140
|
+
iHash;
|
|
10141
|
+
blockLen;
|
|
10142
|
+
outputLen;
|
|
10143
|
+
finished = false;
|
|
10144
|
+
destroyed = false;
|
|
10145
|
+
constructor(hash, key) {
|
|
10146
|
+
ahash(hash);
|
|
10147
|
+
abytes(key, void 0, "key");
|
|
10148
|
+
this.iHash = hash.create();
|
|
10149
|
+
if (typeof this.iHash.update !== "function")
|
|
10150
|
+
throw new Error("Expected instance of class which extends utils.Hash");
|
|
10151
|
+
this.blockLen = this.iHash.blockLen;
|
|
10152
|
+
this.outputLen = this.iHash.outputLen;
|
|
10153
|
+
const blockLen = this.blockLen;
|
|
10154
|
+
const pad = new Uint8Array(blockLen);
|
|
10155
|
+
pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
|
|
10156
|
+
for (let i = 0; i < pad.length; i++)
|
|
10157
|
+
pad[i] ^= 54;
|
|
10158
|
+
this.iHash.update(pad);
|
|
10159
|
+
this.oHash = hash.create();
|
|
10160
|
+
for (let i = 0; i < pad.length; i++)
|
|
10161
|
+
pad[i] ^= 54 ^ 92;
|
|
10162
|
+
this.oHash.update(pad);
|
|
10163
|
+
clean(pad);
|
|
10164
|
+
}
|
|
10165
|
+
update(buf) {
|
|
10166
|
+
aexists(this);
|
|
10167
|
+
this.iHash.update(buf);
|
|
10168
|
+
return this;
|
|
10169
|
+
}
|
|
10170
|
+
digestInto(out) {
|
|
10171
|
+
aexists(this);
|
|
10172
|
+
abytes(out, this.outputLen, "output");
|
|
10173
|
+
this.finished = true;
|
|
10174
|
+
this.iHash.digestInto(out);
|
|
10175
|
+
this.oHash.update(out);
|
|
10176
|
+
this.oHash.digestInto(out);
|
|
10177
|
+
this.destroy();
|
|
10178
|
+
}
|
|
10179
|
+
digest() {
|
|
10180
|
+
const out = new Uint8Array(this.oHash.outputLen);
|
|
10181
|
+
this.digestInto(out);
|
|
10182
|
+
return out;
|
|
10183
|
+
}
|
|
10184
|
+
_cloneInto(to) {
|
|
10185
|
+
to ||= Object.create(Object.getPrototypeOf(this), {});
|
|
10186
|
+
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
|
|
10187
|
+
to = to;
|
|
10188
|
+
to.finished = finished;
|
|
10189
|
+
to.destroyed = destroyed;
|
|
10190
|
+
to.blockLen = blockLen;
|
|
10191
|
+
to.outputLen = outputLen;
|
|
10192
|
+
to.oHash = oHash._cloneInto(to.oHash);
|
|
10193
|
+
to.iHash = iHash._cloneInto(to.iHash);
|
|
10194
|
+
return to;
|
|
10195
|
+
}
|
|
10196
|
+
clone() {
|
|
10197
|
+
return this._cloneInto();
|
|
10198
|
+
}
|
|
10199
|
+
destroy() {
|
|
10200
|
+
this.destroyed = true;
|
|
10201
|
+
this.oHash.destroy();
|
|
10202
|
+
this.iHash.destroy();
|
|
10203
|
+
}
|
|
10204
|
+
};
|
|
10205
|
+
var hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();
|
|
10206
|
+
hmac.create = (hash, key) => new _HMAC(hash, key);
|
|
10207
|
+
|
|
10208
|
+
// node_modules/@noble/curves/abstract/weierstrass.js
|
|
10209
|
+
var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den;
|
|
10210
|
+
function _splitEndoScalar(k, basis, n) {
|
|
10211
|
+
const [[a1, b1], [a2, b2]] = basis;
|
|
10212
|
+
const c1 = divNearest(b2 * k, n);
|
|
10213
|
+
const c2 = divNearest(-b1 * k, n);
|
|
10214
|
+
let k1 = k - c1 * a1 - c2 * a2;
|
|
10215
|
+
let k2 = -c1 * b1 - c2 * b2;
|
|
10216
|
+
const k1neg = k1 < _0n4;
|
|
10217
|
+
const k2neg = k2 < _0n4;
|
|
10218
|
+
if (k1neg)
|
|
10219
|
+
k1 = -k1;
|
|
10220
|
+
if (k2neg)
|
|
10221
|
+
k2 = -k2;
|
|
10222
|
+
const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
|
|
10223
|
+
if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) {
|
|
10224
|
+
throw new Error("splitScalar (endomorphism): failed, k=" + k);
|
|
10225
|
+
}
|
|
10226
|
+
return { k1neg, k1, k2neg, k2 };
|
|
10227
|
+
}
|
|
10228
|
+
function validateSigFormat(format) {
|
|
10229
|
+
if (!["compact", "recovered", "der"].includes(format))
|
|
10230
|
+
throw new Error('Signature format must be "compact", "recovered", or "der"');
|
|
10231
|
+
return format;
|
|
10232
|
+
}
|
|
10233
|
+
function validateSigOpts(opts, def) {
|
|
10234
|
+
const optsn = {};
|
|
10235
|
+
for (let optName of Object.keys(def)) {
|
|
10236
|
+
optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
|
|
10237
|
+
}
|
|
10238
|
+
abool(optsn.lowS, "lowS");
|
|
10239
|
+
abool(optsn.prehash, "prehash");
|
|
10240
|
+
if (optsn.format !== void 0)
|
|
10241
|
+
validateSigFormat(optsn.format);
|
|
10242
|
+
return optsn;
|
|
10243
|
+
}
|
|
10244
|
+
var DERErr = class extends Error {
|
|
10245
|
+
constructor(m = "") {
|
|
10246
|
+
super(m);
|
|
10247
|
+
}
|
|
10248
|
+
};
|
|
10249
|
+
var DER = {
|
|
10250
|
+
// asn.1 DER encoding utils
|
|
10251
|
+
Err: DERErr,
|
|
10252
|
+
// Basic building block is TLV (Tag-Length-Value)
|
|
10253
|
+
_tlv: {
|
|
10254
|
+
encode: (tag, data) => {
|
|
10255
|
+
const { Err: E } = DER;
|
|
10256
|
+
if (tag < 0 || tag > 256)
|
|
10257
|
+
throw new E("tlv.encode: wrong tag");
|
|
10258
|
+
if (data.length & 1)
|
|
10259
|
+
throw new E("tlv.encode: unpadded data");
|
|
10260
|
+
const dataLen = data.length / 2;
|
|
10261
|
+
const len = numberToHexUnpadded(dataLen);
|
|
10262
|
+
if (len.length / 2 & 128)
|
|
10263
|
+
throw new E("tlv.encode: long form length too big");
|
|
10264
|
+
const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
|
|
10265
|
+
const t = numberToHexUnpadded(tag);
|
|
10266
|
+
return t + lenLen + len + data;
|
|
10267
|
+
},
|
|
10268
|
+
// v - value, l - left bytes (unparsed)
|
|
10269
|
+
decode(tag, data) {
|
|
10270
|
+
const { Err: E } = DER;
|
|
10271
|
+
let pos = 0;
|
|
10272
|
+
if (tag < 0 || tag > 256)
|
|
10273
|
+
throw new E("tlv.encode: wrong tag");
|
|
10274
|
+
if (data.length < 2 || data[pos++] !== tag)
|
|
10275
|
+
throw new E("tlv.decode: wrong tlv");
|
|
10276
|
+
const first = data[pos++];
|
|
10277
|
+
const isLong = !!(first & 128);
|
|
10278
|
+
let length = 0;
|
|
10279
|
+
if (!isLong)
|
|
10280
|
+
length = first;
|
|
10281
|
+
else {
|
|
10282
|
+
const lenLen = first & 127;
|
|
10283
|
+
if (!lenLen)
|
|
10284
|
+
throw new E("tlv.decode(long): indefinite length not supported");
|
|
10285
|
+
if (lenLen > 4)
|
|
10286
|
+
throw new E("tlv.decode(long): byte length is too big");
|
|
10287
|
+
const lengthBytes = data.subarray(pos, pos + lenLen);
|
|
10288
|
+
if (lengthBytes.length !== lenLen)
|
|
10289
|
+
throw new E("tlv.decode: length bytes not complete");
|
|
10290
|
+
if (lengthBytes[0] === 0)
|
|
10291
|
+
throw new E("tlv.decode(long): zero leftmost byte");
|
|
10292
|
+
for (const b of lengthBytes)
|
|
10293
|
+
length = length << 8 | b;
|
|
10294
|
+
pos += lenLen;
|
|
10295
|
+
if (length < 128)
|
|
10296
|
+
throw new E("tlv.decode(long): not minimal encoding");
|
|
10297
|
+
}
|
|
10298
|
+
const v = data.subarray(pos, pos + length);
|
|
10299
|
+
if (v.length !== length)
|
|
10300
|
+
throw new E("tlv.decode: wrong value length");
|
|
10301
|
+
return { v, l: data.subarray(pos + length) };
|
|
10302
|
+
}
|
|
10303
|
+
},
|
|
10304
|
+
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
|
|
10305
|
+
// since we always use positive integers here. It must always be empty:
|
|
10306
|
+
// - add zero byte if exists
|
|
10307
|
+
// - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
|
|
10308
|
+
_int: {
|
|
10309
|
+
encode(num) {
|
|
10310
|
+
const { Err: E } = DER;
|
|
10311
|
+
if (num < _0n4)
|
|
10312
|
+
throw new E("integer: negative integers are not allowed");
|
|
10313
|
+
let hex = numberToHexUnpadded(num);
|
|
10314
|
+
if (Number.parseInt(hex[0], 16) & 8)
|
|
10315
|
+
hex = "00" + hex;
|
|
10316
|
+
if (hex.length & 1)
|
|
10317
|
+
throw new E("unexpected DER parsing assertion: unpadded hex");
|
|
10318
|
+
return hex;
|
|
10319
|
+
},
|
|
10320
|
+
decode(data) {
|
|
10321
|
+
const { Err: E } = DER;
|
|
10322
|
+
if (data[0] & 128)
|
|
10323
|
+
throw new E("invalid signature integer: negative");
|
|
10324
|
+
if (data[0] === 0 && !(data[1] & 128))
|
|
10325
|
+
throw new E("invalid signature integer: unnecessary leading zero");
|
|
10326
|
+
return bytesToNumberBE(data);
|
|
10327
|
+
}
|
|
10328
|
+
},
|
|
10329
|
+
toSig(bytes) {
|
|
10330
|
+
const { Err: E, _int: int, _tlv: tlv } = DER;
|
|
10331
|
+
const data = abytes(bytes, void 0, "signature");
|
|
10332
|
+
const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
|
|
10333
|
+
if (seqLeftBytes.length)
|
|
10334
|
+
throw new E("invalid signature: left bytes after parsing");
|
|
10335
|
+
const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
|
|
10336
|
+
const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
|
|
10337
|
+
if (sLeftBytes.length)
|
|
10338
|
+
throw new E("invalid signature: left bytes after parsing");
|
|
10339
|
+
return { r: int.decode(rBytes), s: int.decode(sBytes) };
|
|
10340
|
+
},
|
|
10341
|
+
hexFromSig(sig) {
|
|
10342
|
+
const { _tlv: tlv, _int: int } = DER;
|
|
10343
|
+
const rs = tlv.encode(2, int.encode(sig.r));
|
|
10344
|
+
const ss = tlv.encode(2, int.encode(sig.s));
|
|
10345
|
+
const seq = rs + ss;
|
|
10346
|
+
return tlv.encode(48, seq);
|
|
10347
|
+
}
|
|
10348
|
+
};
|
|
10349
|
+
var _0n4 = BigInt(0);
|
|
10350
|
+
var _1n4 = BigInt(1);
|
|
10351
|
+
var _2n2 = BigInt(2);
|
|
10352
|
+
var _3n2 = BigInt(3);
|
|
10353
|
+
var _4n2 = BigInt(4);
|
|
10354
|
+
function weierstrass(params, extraOpts = {}) {
|
|
10355
|
+
const validated = createCurveFields("weierstrass", params, extraOpts);
|
|
10356
|
+
const { Fp, Fn } = validated;
|
|
10357
|
+
let CURVE = validated.CURVE;
|
|
10358
|
+
const { h: cofactor, n: CURVE_ORDER2 } = CURVE;
|
|
10359
|
+
validateObject(extraOpts, {}, {
|
|
10360
|
+
allowInfinityPoint: "boolean",
|
|
10361
|
+
clearCofactor: "function",
|
|
10362
|
+
isTorsionFree: "function",
|
|
10363
|
+
fromBytes: "function",
|
|
10364
|
+
toBytes: "function",
|
|
10365
|
+
endo: "object"
|
|
10366
|
+
});
|
|
10367
|
+
const { endo } = extraOpts;
|
|
10368
|
+
if (endo) {
|
|
10369
|
+
if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
|
|
10370
|
+
throw new Error('invalid endo: expected "beta": bigint and "basises": array');
|
|
10371
|
+
}
|
|
10372
|
+
}
|
|
10373
|
+
const lengths = getWLengths(Fp, Fn);
|
|
10374
|
+
function assertCompressionIsSupported() {
|
|
10375
|
+
if (!Fp.isOdd)
|
|
10376
|
+
throw new Error("compression is not supported: Field does not have .isOdd()");
|
|
10377
|
+
}
|
|
10378
|
+
function pointToBytes(_c, point, isCompressed) {
|
|
10379
|
+
const { x, y } = point.toAffine();
|
|
10380
|
+
const bx = Fp.toBytes(x);
|
|
10381
|
+
abool(isCompressed, "isCompressed");
|
|
10382
|
+
if (isCompressed) {
|
|
10383
|
+
assertCompressionIsSupported();
|
|
10384
|
+
const hasEvenY = !Fp.isOdd(y);
|
|
10385
|
+
return concatBytes(pprefix(hasEvenY), bx);
|
|
10386
|
+
} else {
|
|
10387
|
+
return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
|
|
10388
|
+
}
|
|
10389
|
+
}
|
|
10390
|
+
function pointFromBytes(bytes) {
|
|
10391
|
+
abytes(bytes, void 0, "Point");
|
|
10392
|
+
const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
|
|
10393
|
+
const length = bytes.length;
|
|
10394
|
+
const head = bytes[0];
|
|
10395
|
+
const tail = bytes.subarray(1);
|
|
10396
|
+
if (length === comp && (head === 2 || head === 3)) {
|
|
10397
|
+
const x = Fp.fromBytes(tail);
|
|
10398
|
+
if (!Fp.isValid(x))
|
|
10399
|
+
throw new Error("bad point: is not on curve, wrong x");
|
|
10400
|
+
const y2 = weierstrassEquation(x);
|
|
10401
|
+
let y;
|
|
10402
|
+
try {
|
|
10403
|
+
y = Fp.sqrt(y2);
|
|
10404
|
+
} catch (sqrtError) {
|
|
10405
|
+
const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
|
|
10406
|
+
throw new Error("bad point: is not on curve, sqrt error" + err);
|
|
10407
|
+
}
|
|
10408
|
+
assertCompressionIsSupported();
|
|
10409
|
+
const evenY = Fp.isOdd(y);
|
|
10410
|
+
const evenH = (head & 1) === 1;
|
|
10411
|
+
if (evenH !== evenY)
|
|
10412
|
+
y = Fp.neg(y);
|
|
10413
|
+
return { x, y };
|
|
10414
|
+
} else if (length === uncomp && head === 4) {
|
|
10415
|
+
const L = Fp.BYTES;
|
|
10416
|
+
const x = Fp.fromBytes(tail.subarray(0, L));
|
|
10417
|
+
const y = Fp.fromBytes(tail.subarray(L, L * 2));
|
|
10418
|
+
if (!isValidXY(x, y))
|
|
10419
|
+
throw new Error("bad point: is not on curve");
|
|
10420
|
+
return { x, y };
|
|
10421
|
+
} else {
|
|
10422
|
+
throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
|
|
10423
|
+
}
|
|
10424
|
+
}
|
|
10425
|
+
const encodePoint = extraOpts.toBytes || pointToBytes;
|
|
10426
|
+
const decodePoint = extraOpts.fromBytes || pointFromBytes;
|
|
10427
|
+
function weierstrassEquation(x) {
|
|
10428
|
+
const x2 = Fp.sqr(x);
|
|
10429
|
+
const x3 = Fp.mul(x2, x);
|
|
10430
|
+
return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
|
|
10431
|
+
}
|
|
10432
|
+
function isValidXY(x, y) {
|
|
10433
|
+
const left = Fp.sqr(y);
|
|
10434
|
+
const right = weierstrassEquation(x);
|
|
10435
|
+
return Fp.eql(left, right);
|
|
10436
|
+
}
|
|
10437
|
+
if (!isValidXY(CURVE.Gx, CURVE.Gy))
|
|
10438
|
+
throw new Error("bad curve params: generator point");
|
|
10439
|
+
const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
|
|
10440
|
+
const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
|
|
10441
|
+
if (Fp.is0(Fp.add(_4a3, _27b2)))
|
|
10442
|
+
throw new Error("bad curve params: a or b");
|
|
10443
|
+
function acoord(title, n, banZero = false) {
|
|
10444
|
+
if (!Fp.isValid(n) || banZero && Fp.is0(n))
|
|
10445
|
+
throw new Error(`bad point coordinate ${title}`);
|
|
10446
|
+
return n;
|
|
10447
|
+
}
|
|
10448
|
+
function aprjpoint(other) {
|
|
10449
|
+
if (!(other instanceof Point))
|
|
10450
|
+
throw new Error("Weierstrass Point expected");
|
|
10451
|
+
}
|
|
10452
|
+
function splitEndoScalarN(k) {
|
|
10453
|
+
if (!endo || !endo.basises)
|
|
10454
|
+
throw new Error("no endo");
|
|
10455
|
+
return _splitEndoScalar(k, endo.basises, Fn.ORDER);
|
|
10456
|
+
}
|
|
10457
|
+
const toAffineMemo = memoized((p, iz) => {
|
|
10458
|
+
const { X, Y, Z } = p;
|
|
10459
|
+
if (Fp.eql(Z, Fp.ONE))
|
|
10460
|
+
return { x: X, y: Y };
|
|
10461
|
+
const is0 = p.is0();
|
|
10462
|
+
if (iz == null)
|
|
10463
|
+
iz = is0 ? Fp.ONE : Fp.inv(Z);
|
|
10464
|
+
const x = Fp.mul(X, iz);
|
|
10465
|
+
const y = Fp.mul(Y, iz);
|
|
10466
|
+
const zz = Fp.mul(Z, iz);
|
|
10467
|
+
if (is0)
|
|
10468
|
+
return { x: Fp.ZERO, y: Fp.ZERO };
|
|
10469
|
+
if (!Fp.eql(zz, Fp.ONE))
|
|
10470
|
+
throw new Error("invZ was invalid");
|
|
10471
|
+
return { x, y };
|
|
10472
|
+
});
|
|
10473
|
+
const assertValidMemo = memoized((p) => {
|
|
10474
|
+
if (p.is0()) {
|
|
10475
|
+
if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
|
|
10476
|
+
return;
|
|
10477
|
+
throw new Error("bad point: ZERO");
|
|
10478
|
+
}
|
|
10479
|
+
const { x, y } = p.toAffine();
|
|
10480
|
+
if (!Fp.isValid(x) || !Fp.isValid(y))
|
|
10481
|
+
throw new Error("bad point: x or y not field elements");
|
|
10482
|
+
if (!isValidXY(x, y))
|
|
10483
|
+
throw new Error("bad point: equation left != right");
|
|
10484
|
+
if (!p.isTorsionFree())
|
|
10485
|
+
throw new Error("bad point: not in prime-order subgroup");
|
|
10486
|
+
return true;
|
|
10487
|
+
});
|
|
10488
|
+
function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
|
|
10489
|
+
k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
|
|
10490
|
+
k1p = negateCt(k1neg, k1p);
|
|
10491
|
+
k2p = negateCt(k2neg, k2p);
|
|
10492
|
+
return k1p.add(k2p);
|
|
10493
|
+
}
|
|
10494
|
+
class Point {
|
|
10495
|
+
// base / generator point
|
|
10496
|
+
static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
|
|
10497
|
+
// zero / infinity / identity point
|
|
10498
|
+
static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
|
|
10499
|
+
// 0, 1, 0
|
|
10500
|
+
// math field
|
|
10501
|
+
static Fp = Fp;
|
|
10502
|
+
// scalar field
|
|
10503
|
+
static Fn = Fn;
|
|
10504
|
+
X;
|
|
10505
|
+
Y;
|
|
10506
|
+
Z;
|
|
10507
|
+
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
10508
|
+
constructor(X, Y, Z) {
|
|
10509
|
+
this.X = acoord("x", X);
|
|
10510
|
+
this.Y = acoord("y", Y, true);
|
|
10511
|
+
this.Z = acoord("z", Z);
|
|
10512
|
+
Object.freeze(this);
|
|
10513
|
+
}
|
|
10514
|
+
static CURVE() {
|
|
10515
|
+
return CURVE;
|
|
10516
|
+
}
|
|
10517
|
+
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
10518
|
+
static fromAffine(p) {
|
|
10519
|
+
const { x, y } = p || {};
|
|
10520
|
+
if (!p || !Fp.isValid(x) || !Fp.isValid(y))
|
|
10521
|
+
throw new Error("invalid affine point");
|
|
10522
|
+
if (p instanceof Point)
|
|
10523
|
+
throw new Error("projective point not allowed");
|
|
10524
|
+
if (Fp.is0(x) && Fp.is0(y))
|
|
10525
|
+
return Point.ZERO;
|
|
10526
|
+
return new Point(x, y, Fp.ONE);
|
|
10527
|
+
}
|
|
10528
|
+
static fromBytes(bytes) {
|
|
10529
|
+
const P = Point.fromAffine(decodePoint(abytes(bytes, void 0, "point")));
|
|
10530
|
+
P.assertValidity();
|
|
10531
|
+
return P;
|
|
10532
|
+
}
|
|
10533
|
+
static fromHex(hex) {
|
|
10534
|
+
return Point.fromBytes(hexToBytes2(hex));
|
|
10535
|
+
}
|
|
10536
|
+
get x() {
|
|
10537
|
+
return this.toAffine().x;
|
|
10538
|
+
}
|
|
10539
|
+
get y() {
|
|
10540
|
+
return this.toAffine().y;
|
|
10541
|
+
}
|
|
10542
|
+
/**
|
|
10543
|
+
*
|
|
10544
|
+
* @param windowSize
|
|
10545
|
+
* @param isLazy true will defer table computation until the first multiplication
|
|
10546
|
+
* @returns
|
|
10547
|
+
*/
|
|
10548
|
+
precompute(windowSize = 8, isLazy = true) {
|
|
10549
|
+
wnaf.createCache(this, windowSize);
|
|
10550
|
+
if (!isLazy)
|
|
10551
|
+
this.multiply(_3n2);
|
|
10552
|
+
return this;
|
|
10553
|
+
}
|
|
10554
|
+
// TODO: return `this`
|
|
10555
|
+
/** A point on curve is valid if it conforms to equation. */
|
|
10556
|
+
assertValidity() {
|
|
10557
|
+
assertValidMemo(this);
|
|
10558
|
+
}
|
|
10559
|
+
hasEvenY() {
|
|
10560
|
+
const { y } = this.toAffine();
|
|
10561
|
+
if (!Fp.isOdd)
|
|
10562
|
+
throw new Error("Field doesn't support isOdd");
|
|
10563
|
+
return !Fp.isOdd(y);
|
|
10564
|
+
}
|
|
10565
|
+
/** Compare one point to another. */
|
|
10566
|
+
equals(other) {
|
|
10567
|
+
aprjpoint(other);
|
|
10568
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
10569
|
+
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
10570
|
+
const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
|
|
10571
|
+
const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
|
|
10572
|
+
return U1 && U2;
|
|
10573
|
+
}
|
|
10574
|
+
/** Flips point to one corresponding to (x, -y) in Affine coordinates. */
|
|
10575
|
+
negate() {
|
|
10576
|
+
return new Point(this.X, Fp.neg(this.Y), this.Z);
|
|
10577
|
+
}
|
|
10578
|
+
// Renes-Costello-Batina exception-free doubling formula.
|
|
10579
|
+
// There is 30% faster Jacobian formula, but it is not complete.
|
|
10580
|
+
// https://eprint.iacr.org/2015/1060, algorithm 3
|
|
10581
|
+
// Cost: 8M + 3S + 3*a + 2*b3 + 15add.
|
|
10582
|
+
double() {
|
|
10583
|
+
const { a, b } = CURVE;
|
|
10584
|
+
const b3 = Fp.mul(b, _3n2);
|
|
10585
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
10586
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
|
|
10587
|
+
let t0 = Fp.mul(X1, X1);
|
|
10588
|
+
let t1 = Fp.mul(Y1, Y1);
|
|
10589
|
+
let t2 = Fp.mul(Z1, Z1);
|
|
10590
|
+
let t3 = Fp.mul(X1, Y1);
|
|
10591
|
+
t3 = Fp.add(t3, t3);
|
|
10592
|
+
Z3 = Fp.mul(X1, Z1);
|
|
10593
|
+
Z3 = Fp.add(Z3, Z3);
|
|
10594
|
+
X3 = Fp.mul(a, Z3);
|
|
10595
|
+
Y3 = Fp.mul(b3, t2);
|
|
10596
|
+
Y3 = Fp.add(X3, Y3);
|
|
10597
|
+
X3 = Fp.sub(t1, Y3);
|
|
10598
|
+
Y3 = Fp.add(t1, Y3);
|
|
10599
|
+
Y3 = Fp.mul(X3, Y3);
|
|
10600
|
+
X3 = Fp.mul(t3, X3);
|
|
10601
|
+
Z3 = Fp.mul(b3, Z3);
|
|
10602
|
+
t2 = Fp.mul(a, t2);
|
|
10603
|
+
t3 = Fp.sub(t0, t2);
|
|
10604
|
+
t3 = Fp.mul(a, t3);
|
|
10605
|
+
t3 = Fp.add(t3, Z3);
|
|
10606
|
+
Z3 = Fp.add(t0, t0);
|
|
10607
|
+
t0 = Fp.add(Z3, t0);
|
|
10608
|
+
t0 = Fp.add(t0, t2);
|
|
10609
|
+
t0 = Fp.mul(t0, t3);
|
|
10610
|
+
Y3 = Fp.add(Y3, t0);
|
|
10611
|
+
t2 = Fp.mul(Y1, Z1);
|
|
10612
|
+
t2 = Fp.add(t2, t2);
|
|
10613
|
+
t0 = Fp.mul(t2, t3);
|
|
10614
|
+
X3 = Fp.sub(X3, t0);
|
|
10615
|
+
Z3 = Fp.mul(t2, t1);
|
|
10616
|
+
Z3 = Fp.add(Z3, Z3);
|
|
10617
|
+
Z3 = Fp.add(Z3, Z3);
|
|
10618
|
+
return new Point(X3, Y3, Z3);
|
|
10619
|
+
}
|
|
10620
|
+
// Renes-Costello-Batina exception-free addition formula.
|
|
10621
|
+
// There is 30% faster Jacobian formula, but it is not complete.
|
|
10622
|
+
// https://eprint.iacr.org/2015/1060, algorithm 1
|
|
10623
|
+
// Cost: 12M + 0S + 3*a + 3*b3 + 23add.
|
|
10624
|
+
add(other) {
|
|
10625
|
+
aprjpoint(other);
|
|
10626
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
10627
|
+
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
10628
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
|
|
10629
|
+
const a = CURVE.a;
|
|
10630
|
+
const b3 = Fp.mul(CURVE.b, _3n2);
|
|
10631
|
+
let t0 = Fp.mul(X1, X2);
|
|
10632
|
+
let t1 = Fp.mul(Y1, Y2);
|
|
10633
|
+
let t2 = Fp.mul(Z1, Z2);
|
|
10634
|
+
let t3 = Fp.add(X1, Y1);
|
|
10635
|
+
let t4 = Fp.add(X2, Y2);
|
|
10636
|
+
t3 = Fp.mul(t3, t4);
|
|
10637
|
+
t4 = Fp.add(t0, t1);
|
|
10638
|
+
t3 = Fp.sub(t3, t4);
|
|
10639
|
+
t4 = Fp.add(X1, Z1);
|
|
10640
|
+
let t5 = Fp.add(X2, Z2);
|
|
10641
|
+
t4 = Fp.mul(t4, t5);
|
|
10642
|
+
t5 = Fp.add(t0, t2);
|
|
10643
|
+
t4 = Fp.sub(t4, t5);
|
|
10644
|
+
t5 = Fp.add(Y1, Z1);
|
|
10645
|
+
X3 = Fp.add(Y2, Z2);
|
|
10646
|
+
t5 = Fp.mul(t5, X3);
|
|
10647
|
+
X3 = Fp.add(t1, t2);
|
|
10648
|
+
t5 = Fp.sub(t5, X3);
|
|
10649
|
+
Z3 = Fp.mul(a, t4);
|
|
10650
|
+
X3 = Fp.mul(b3, t2);
|
|
10651
|
+
Z3 = Fp.add(X3, Z3);
|
|
10652
|
+
X3 = Fp.sub(t1, Z3);
|
|
10653
|
+
Z3 = Fp.add(t1, Z3);
|
|
10654
|
+
Y3 = Fp.mul(X3, Z3);
|
|
10655
|
+
t1 = Fp.add(t0, t0);
|
|
10656
|
+
t1 = Fp.add(t1, t0);
|
|
10657
|
+
t2 = Fp.mul(a, t2);
|
|
10658
|
+
t4 = Fp.mul(b3, t4);
|
|
10659
|
+
t1 = Fp.add(t1, t2);
|
|
10660
|
+
t2 = Fp.sub(t0, t2);
|
|
10661
|
+
t2 = Fp.mul(a, t2);
|
|
10662
|
+
t4 = Fp.add(t4, t2);
|
|
10663
|
+
t0 = Fp.mul(t1, t4);
|
|
10664
|
+
Y3 = Fp.add(Y3, t0);
|
|
10665
|
+
t0 = Fp.mul(t5, t4);
|
|
10666
|
+
X3 = Fp.mul(t3, X3);
|
|
10667
|
+
X3 = Fp.sub(X3, t0);
|
|
10668
|
+
t0 = Fp.mul(t3, t1);
|
|
10669
|
+
Z3 = Fp.mul(t5, Z3);
|
|
10670
|
+
Z3 = Fp.add(Z3, t0);
|
|
10671
|
+
return new Point(X3, Y3, Z3);
|
|
10672
|
+
}
|
|
10673
|
+
subtract(other) {
|
|
10674
|
+
return this.add(other.negate());
|
|
10675
|
+
}
|
|
10676
|
+
is0() {
|
|
10677
|
+
return this.equals(Point.ZERO);
|
|
10678
|
+
}
|
|
10679
|
+
/**
|
|
10680
|
+
* Constant time multiplication.
|
|
10681
|
+
* Uses wNAF method. Windowed method may be 10% faster,
|
|
10682
|
+
* but takes 2x longer to generate and consumes 2x memory.
|
|
10683
|
+
* Uses precomputes when available.
|
|
10684
|
+
* Uses endomorphism for Koblitz curves.
|
|
10685
|
+
* @param scalar by which the point would be multiplied
|
|
10686
|
+
* @returns New point
|
|
10687
|
+
*/
|
|
10688
|
+
multiply(scalar) {
|
|
10689
|
+
const { endo: endo2 } = extraOpts;
|
|
10690
|
+
if (!Fn.isValidNot0(scalar))
|
|
10691
|
+
throw new Error("invalid scalar: out of range");
|
|
10692
|
+
let point, fake;
|
|
10693
|
+
const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
|
|
10694
|
+
if (endo2) {
|
|
10695
|
+
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
|
|
10696
|
+
const { p: k1p, f: k1f } = mul(k1);
|
|
10697
|
+
const { p: k2p, f: k2f } = mul(k2);
|
|
10698
|
+
fake = k1f.add(k2f);
|
|
10699
|
+
point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
|
|
10700
|
+
} else {
|
|
10701
|
+
const { p, f } = mul(scalar);
|
|
10702
|
+
point = p;
|
|
10703
|
+
fake = f;
|
|
10704
|
+
}
|
|
10705
|
+
return normalizeZ(Point, [point, fake])[0];
|
|
10706
|
+
}
|
|
10707
|
+
/**
|
|
10708
|
+
* Non-constant-time multiplication. Uses double-and-add algorithm.
|
|
10709
|
+
* It's faster, but should only be used when you don't care about
|
|
10710
|
+
* an exposed secret key e.g. sig verification, which works over *public* keys.
|
|
10711
|
+
*/
|
|
10712
|
+
multiplyUnsafe(sc) {
|
|
10713
|
+
const { endo: endo2 } = extraOpts;
|
|
10714
|
+
const p = this;
|
|
10715
|
+
if (!Fn.isValid(sc))
|
|
10716
|
+
throw new Error("invalid scalar: out of range");
|
|
10717
|
+
if (sc === _0n4 || p.is0())
|
|
10718
|
+
return Point.ZERO;
|
|
10719
|
+
if (sc === _1n4)
|
|
10720
|
+
return p;
|
|
10721
|
+
if (wnaf.hasCache(this))
|
|
10722
|
+
return this.multiply(sc);
|
|
10723
|
+
if (endo2) {
|
|
10724
|
+
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
|
|
10725
|
+
const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
|
|
10726
|
+
return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
|
|
10727
|
+
} else {
|
|
10728
|
+
return wnaf.unsafe(p, sc);
|
|
10729
|
+
}
|
|
10730
|
+
}
|
|
10731
|
+
/**
|
|
10732
|
+
* Converts Projective point to affine (x, y) coordinates.
|
|
10733
|
+
* @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
|
|
10734
|
+
*/
|
|
10735
|
+
toAffine(invertedZ) {
|
|
10736
|
+
return toAffineMemo(this, invertedZ);
|
|
10737
|
+
}
|
|
10738
|
+
/**
|
|
10739
|
+
* Checks whether Point is free of torsion elements (is in prime subgroup).
|
|
10740
|
+
* Always torsion-free for cofactor=1 curves.
|
|
10741
|
+
*/
|
|
10742
|
+
isTorsionFree() {
|
|
10743
|
+
const { isTorsionFree } = extraOpts;
|
|
10744
|
+
if (cofactor === _1n4)
|
|
10745
|
+
return true;
|
|
10746
|
+
if (isTorsionFree)
|
|
10747
|
+
return isTorsionFree(Point, this);
|
|
10748
|
+
return wnaf.unsafe(this, CURVE_ORDER2).is0();
|
|
10749
|
+
}
|
|
10750
|
+
clearCofactor() {
|
|
10751
|
+
const { clearCofactor } = extraOpts;
|
|
10752
|
+
if (cofactor === _1n4)
|
|
10753
|
+
return this;
|
|
10754
|
+
if (clearCofactor)
|
|
10755
|
+
return clearCofactor(Point, this);
|
|
10756
|
+
return this.multiplyUnsafe(cofactor);
|
|
10757
|
+
}
|
|
10758
|
+
isSmallOrder() {
|
|
10759
|
+
return this.multiplyUnsafe(cofactor).is0();
|
|
10760
|
+
}
|
|
10761
|
+
toBytes(isCompressed = true) {
|
|
10762
|
+
abool(isCompressed, "isCompressed");
|
|
10763
|
+
this.assertValidity();
|
|
10764
|
+
return encodePoint(Point, this, isCompressed);
|
|
10765
|
+
}
|
|
10766
|
+
toHex(isCompressed = true) {
|
|
10767
|
+
return bytesToHex4(this.toBytes(isCompressed));
|
|
10768
|
+
}
|
|
10769
|
+
toString() {
|
|
10770
|
+
return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
|
|
10771
|
+
}
|
|
10772
|
+
}
|
|
10773
|
+
const bits = Fn.BITS;
|
|
10774
|
+
const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
|
|
10775
|
+
Point.BASE.precompute(8);
|
|
10776
|
+
return Point;
|
|
10777
|
+
}
|
|
10778
|
+
function pprefix(hasEvenY) {
|
|
10779
|
+
return Uint8Array.of(hasEvenY ? 2 : 3);
|
|
10780
|
+
}
|
|
10781
|
+
function getWLengths(Fp, Fn) {
|
|
10782
|
+
return {
|
|
10783
|
+
secretKey: Fn.BYTES,
|
|
10784
|
+
publicKey: 1 + Fp.BYTES,
|
|
10785
|
+
publicKeyUncompressed: 1 + 2 * Fp.BYTES,
|
|
10786
|
+
publicKeyHasPrefix: true,
|
|
10787
|
+
signature: 2 * Fn.BYTES
|
|
10788
|
+
};
|
|
10789
|
+
}
|
|
10790
|
+
function ecdh(Point, ecdhOpts = {}) {
|
|
10791
|
+
const { Fn } = Point;
|
|
10792
|
+
const randomBytes_ = ecdhOpts.randomBytes || randomBytes2;
|
|
10793
|
+
const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
|
|
10794
|
+
function isValidSecretKey(secretKey) {
|
|
10795
|
+
try {
|
|
10796
|
+
const num = Fn.fromBytes(secretKey);
|
|
10797
|
+
return Fn.isValidNot0(num);
|
|
10798
|
+
} catch (error) {
|
|
10799
|
+
return false;
|
|
10800
|
+
}
|
|
10801
|
+
}
|
|
10802
|
+
function isValidPublicKey(publicKey, isCompressed) {
|
|
10803
|
+
const { publicKey: comp, publicKeyUncompressed } = lengths;
|
|
10804
|
+
try {
|
|
10805
|
+
const l = publicKey.length;
|
|
10806
|
+
if (isCompressed === true && l !== comp)
|
|
10807
|
+
return false;
|
|
10808
|
+
if (isCompressed === false && l !== publicKeyUncompressed)
|
|
10809
|
+
return false;
|
|
10810
|
+
return !!Point.fromBytes(publicKey);
|
|
10811
|
+
} catch (error) {
|
|
10812
|
+
return false;
|
|
10813
|
+
}
|
|
10814
|
+
}
|
|
10815
|
+
function randomSecretKey(seed = randomBytes_(lengths.seed)) {
|
|
10816
|
+
return mapHashToField(abytes(seed, lengths.seed, "seed"), Fn.ORDER);
|
|
10817
|
+
}
|
|
10818
|
+
function getPublicKey2(secretKey, isCompressed = true) {
|
|
10819
|
+
return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
|
|
10820
|
+
}
|
|
10821
|
+
function isProbPub(item) {
|
|
10822
|
+
const { secretKey, publicKey, publicKeyUncompressed } = lengths;
|
|
10823
|
+
if (!isBytes(item))
|
|
10824
|
+
return void 0;
|
|
10825
|
+
if ("_lengths" in Fn && Fn._lengths || secretKey === publicKey)
|
|
10826
|
+
return void 0;
|
|
10827
|
+
const l = abytes(item, void 0, "key").length;
|
|
10828
|
+
return l === publicKey || l === publicKeyUncompressed;
|
|
10829
|
+
}
|
|
10830
|
+
function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
|
|
10831
|
+
if (isProbPub(secretKeyA) === true)
|
|
10832
|
+
throw new Error("first arg must be private key");
|
|
10833
|
+
if (isProbPub(publicKeyB) === false)
|
|
10834
|
+
throw new Error("second arg must be public key");
|
|
10835
|
+
const s = Fn.fromBytes(secretKeyA);
|
|
10836
|
+
const b = Point.fromBytes(publicKeyB);
|
|
10837
|
+
return b.multiply(s).toBytes(isCompressed);
|
|
10838
|
+
}
|
|
10839
|
+
const utils = {
|
|
10840
|
+
isValidSecretKey,
|
|
10841
|
+
isValidPublicKey,
|
|
10842
|
+
randomSecretKey
|
|
10843
|
+
};
|
|
10844
|
+
const keygen = createKeygen(randomSecretKey, getPublicKey2);
|
|
10845
|
+
return Object.freeze({ getPublicKey: getPublicKey2, getSharedSecret, keygen, Point, utils, lengths });
|
|
10846
|
+
}
|
|
10847
|
+
function ecdsa(Point, hash, ecdsaOpts = {}) {
|
|
10848
|
+
ahash(hash);
|
|
10849
|
+
validateObject(ecdsaOpts, {}, {
|
|
10850
|
+
hmac: "function",
|
|
10851
|
+
lowS: "boolean",
|
|
10852
|
+
randomBytes: "function",
|
|
10853
|
+
bits2int: "function",
|
|
10854
|
+
bits2int_modN: "function"
|
|
10855
|
+
});
|
|
10856
|
+
ecdsaOpts = Object.assign({}, ecdsaOpts);
|
|
10857
|
+
const randomBytes3 = ecdsaOpts.randomBytes || randomBytes2;
|
|
10858
|
+
const hmac2 = ecdsaOpts.hmac || ((key, msg) => hmac(hash, key, msg));
|
|
10859
|
+
const { Fp, Fn } = Point;
|
|
10860
|
+
const { ORDER: CURVE_ORDER2, BITS: fnBits } = Fn;
|
|
10861
|
+
const { keygen, getPublicKey: getPublicKey2, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
|
|
10862
|
+
const defaultSigOpts = {
|
|
10863
|
+
prehash: true,
|
|
10864
|
+
lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
|
|
10865
|
+
format: "compact",
|
|
10866
|
+
extraEntropy: false
|
|
10867
|
+
};
|
|
10868
|
+
const hasLargeCofactor = CURVE_ORDER2 * _2n2 < Fp.ORDER;
|
|
10869
|
+
function isBiggerThanHalfOrder(number) {
|
|
10870
|
+
const HALF = CURVE_ORDER2 >> _1n4;
|
|
10871
|
+
return number > HALF;
|
|
10872
|
+
}
|
|
10873
|
+
function validateRS(title, num) {
|
|
10874
|
+
if (!Fn.isValidNot0(num))
|
|
10875
|
+
throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
|
|
10876
|
+
return num;
|
|
10877
|
+
}
|
|
10878
|
+
function assertSmallCofactor() {
|
|
10879
|
+
if (hasLargeCofactor)
|
|
10880
|
+
throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
|
|
10881
|
+
}
|
|
10882
|
+
function validateSigLength(bytes, format) {
|
|
10883
|
+
validateSigFormat(format);
|
|
10884
|
+
const size = lengths.signature;
|
|
10885
|
+
const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
|
|
10886
|
+
return abytes(bytes, sizer);
|
|
10887
|
+
}
|
|
10888
|
+
class Signature {
|
|
10889
|
+
r;
|
|
10890
|
+
s;
|
|
10891
|
+
recovery;
|
|
10892
|
+
constructor(r, s, recovery) {
|
|
10893
|
+
this.r = validateRS("r", r);
|
|
10894
|
+
this.s = validateRS("s", s);
|
|
10895
|
+
if (recovery != null) {
|
|
10896
|
+
assertSmallCofactor();
|
|
10897
|
+
if (![0, 1, 2, 3].includes(recovery))
|
|
10898
|
+
throw new Error("invalid recovery id");
|
|
10899
|
+
this.recovery = recovery;
|
|
10900
|
+
}
|
|
10901
|
+
Object.freeze(this);
|
|
10902
|
+
}
|
|
10903
|
+
static fromBytes(bytes, format = defaultSigOpts.format) {
|
|
10904
|
+
validateSigLength(bytes, format);
|
|
10905
|
+
let recid;
|
|
10906
|
+
if (format === "der") {
|
|
10907
|
+
const { r: r2, s: s2 } = DER.toSig(abytes(bytes));
|
|
10908
|
+
return new Signature(r2, s2);
|
|
10909
|
+
}
|
|
10910
|
+
if (format === "recovered") {
|
|
10911
|
+
recid = bytes[0];
|
|
10912
|
+
format = "compact";
|
|
10913
|
+
bytes = bytes.subarray(1);
|
|
10914
|
+
}
|
|
10915
|
+
const L = lengths.signature / 2;
|
|
10916
|
+
const r = bytes.subarray(0, L);
|
|
10917
|
+
const s = bytes.subarray(L, L * 2);
|
|
10918
|
+
return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
|
|
10919
|
+
}
|
|
10920
|
+
static fromHex(hex, format) {
|
|
10921
|
+
return this.fromBytes(hexToBytes2(hex), format);
|
|
10922
|
+
}
|
|
10923
|
+
assertRecovery() {
|
|
10924
|
+
const { recovery } = this;
|
|
10925
|
+
if (recovery == null)
|
|
10926
|
+
throw new Error("invalid recovery id: must be present");
|
|
10927
|
+
return recovery;
|
|
10928
|
+
}
|
|
10929
|
+
addRecoveryBit(recovery) {
|
|
10930
|
+
return new Signature(this.r, this.s, recovery);
|
|
10931
|
+
}
|
|
10932
|
+
recoverPublicKey(messageHash) {
|
|
10933
|
+
const { r, s } = this;
|
|
10934
|
+
const recovery = this.assertRecovery();
|
|
10935
|
+
const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER2 : r;
|
|
10936
|
+
if (!Fp.isValid(radj))
|
|
10937
|
+
throw new Error("invalid recovery id: sig.r+curve.n != R.x");
|
|
10938
|
+
const x = Fp.toBytes(radj);
|
|
10939
|
+
const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));
|
|
10940
|
+
const ir = Fn.inv(radj);
|
|
10941
|
+
const h = bits2int_modN(abytes(messageHash, void 0, "msgHash"));
|
|
10942
|
+
const u1 = Fn.create(-h * ir);
|
|
10943
|
+
const u2 = Fn.create(s * ir);
|
|
10944
|
+
const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
|
|
10945
|
+
if (Q.is0())
|
|
10946
|
+
throw new Error("invalid recovery: point at infinify");
|
|
10947
|
+
Q.assertValidity();
|
|
10948
|
+
return Q;
|
|
10949
|
+
}
|
|
10950
|
+
// Signatures should be low-s, to prevent malleability.
|
|
10951
|
+
hasHighS() {
|
|
10952
|
+
return isBiggerThanHalfOrder(this.s);
|
|
10953
|
+
}
|
|
10954
|
+
toBytes(format = defaultSigOpts.format) {
|
|
10955
|
+
validateSigFormat(format);
|
|
10956
|
+
if (format === "der")
|
|
10957
|
+
return hexToBytes2(DER.hexFromSig(this));
|
|
10958
|
+
const { r, s } = this;
|
|
10959
|
+
const rb = Fn.toBytes(r);
|
|
10960
|
+
const sb = Fn.toBytes(s);
|
|
10961
|
+
if (format === "recovered") {
|
|
10962
|
+
assertSmallCofactor();
|
|
10963
|
+
return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);
|
|
10964
|
+
}
|
|
10965
|
+
return concatBytes(rb, sb);
|
|
10966
|
+
}
|
|
10967
|
+
toHex(format) {
|
|
10968
|
+
return bytesToHex4(this.toBytes(format));
|
|
10969
|
+
}
|
|
10970
|
+
}
|
|
10971
|
+
const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
|
|
10972
|
+
if (bytes.length > 8192)
|
|
10973
|
+
throw new Error("input is too large");
|
|
10974
|
+
const num = bytesToNumberBE(bytes);
|
|
10975
|
+
const delta = bytes.length * 8 - fnBits;
|
|
10976
|
+
return delta > 0 ? num >> BigInt(delta) : num;
|
|
10977
|
+
};
|
|
10978
|
+
const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
|
|
10979
|
+
return Fn.create(bits2int(bytes));
|
|
10980
|
+
};
|
|
10981
|
+
const ORDER_MASK = bitMask(fnBits);
|
|
10982
|
+
function int2octets(num) {
|
|
10983
|
+
aInRange("num < 2^" + fnBits, num, _0n4, ORDER_MASK);
|
|
10984
|
+
return Fn.toBytes(num);
|
|
10985
|
+
}
|
|
10986
|
+
function validateMsgAndHash(message, prehash) {
|
|
10987
|
+
abytes(message, void 0, "message");
|
|
10988
|
+
return prehash ? abytes(hash(message), void 0, "prehashed message") : message;
|
|
10989
|
+
}
|
|
10990
|
+
function prepSig(message, secretKey, opts) {
|
|
10991
|
+
const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
|
|
10992
|
+
message = validateMsgAndHash(message, prehash);
|
|
10993
|
+
const h1int = bits2int_modN(message);
|
|
10994
|
+
const d = Fn.fromBytes(secretKey);
|
|
10995
|
+
if (!Fn.isValidNot0(d))
|
|
10996
|
+
throw new Error("invalid private key");
|
|
10997
|
+
const seedArgs = [int2octets(d), int2octets(h1int)];
|
|
10998
|
+
if (extraEntropy != null && extraEntropy !== false) {
|
|
10999
|
+
const e = extraEntropy === true ? randomBytes3(lengths.secretKey) : extraEntropy;
|
|
11000
|
+
seedArgs.push(abytes(e, void 0, "extraEntropy"));
|
|
11001
|
+
}
|
|
11002
|
+
const seed = concatBytes(...seedArgs);
|
|
11003
|
+
const m = h1int;
|
|
11004
|
+
function k2sig(kBytes) {
|
|
11005
|
+
const k = bits2int(kBytes);
|
|
11006
|
+
if (!Fn.isValidNot0(k))
|
|
11007
|
+
return;
|
|
11008
|
+
const ik = Fn.inv(k);
|
|
11009
|
+
const q = Point.BASE.multiply(k).toAffine();
|
|
11010
|
+
const r = Fn.create(q.x);
|
|
11011
|
+
if (r === _0n4)
|
|
11012
|
+
return;
|
|
11013
|
+
const s = Fn.create(ik * Fn.create(m + r * d));
|
|
11014
|
+
if (s === _0n4)
|
|
11015
|
+
return;
|
|
11016
|
+
let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
|
|
11017
|
+
let normS = s;
|
|
11018
|
+
if (lowS && isBiggerThanHalfOrder(s)) {
|
|
11019
|
+
normS = Fn.neg(s);
|
|
11020
|
+
recovery ^= 1;
|
|
11021
|
+
}
|
|
11022
|
+
return new Signature(r, normS, hasLargeCofactor ? void 0 : recovery);
|
|
11023
|
+
}
|
|
11024
|
+
return { seed, k2sig };
|
|
11025
|
+
}
|
|
11026
|
+
function sign(message, secretKey, opts = {}) {
|
|
11027
|
+
const { seed, k2sig } = prepSig(message, secretKey, opts);
|
|
11028
|
+
const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac2);
|
|
11029
|
+
const sig = drbg(seed, k2sig);
|
|
11030
|
+
return sig.toBytes(opts.format);
|
|
11031
|
+
}
|
|
11032
|
+
function verify(signature, message, publicKey, opts = {}) {
|
|
11033
|
+
const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
|
|
11034
|
+
publicKey = abytes(publicKey, void 0, "publicKey");
|
|
11035
|
+
message = validateMsgAndHash(message, prehash);
|
|
11036
|
+
if (!isBytes(signature)) {
|
|
11037
|
+
const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
|
|
11038
|
+
throw new Error("verify expects Uint8Array signature" + end);
|
|
11039
|
+
}
|
|
11040
|
+
validateSigLength(signature, format);
|
|
11041
|
+
try {
|
|
11042
|
+
const sig = Signature.fromBytes(signature, format);
|
|
11043
|
+
const P = Point.fromBytes(publicKey);
|
|
11044
|
+
if (lowS && sig.hasHighS())
|
|
11045
|
+
return false;
|
|
11046
|
+
const { r, s } = sig;
|
|
11047
|
+
const h = bits2int_modN(message);
|
|
11048
|
+
const is = Fn.inv(s);
|
|
11049
|
+
const u1 = Fn.create(h * is);
|
|
11050
|
+
const u2 = Fn.create(r * is);
|
|
11051
|
+
const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
|
|
11052
|
+
if (R.is0())
|
|
11053
|
+
return false;
|
|
11054
|
+
const v = Fn.create(R.x);
|
|
11055
|
+
return v === r;
|
|
11056
|
+
} catch (e) {
|
|
11057
|
+
return false;
|
|
11058
|
+
}
|
|
11059
|
+
}
|
|
11060
|
+
function recoverPublicKey(signature, message, opts = {}) {
|
|
11061
|
+
const { prehash } = validateSigOpts(opts, defaultSigOpts);
|
|
11062
|
+
message = validateMsgAndHash(message, prehash);
|
|
11063
|
+
return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
|
|
11064
|
+
}
|
|
11065
|
+
return Object.freeze({
|
|
11066
|
+
keygen,
|
|
11067
|
+
getPublicKey: getPublicKey2,
|
|
11068
|
+
getSharedSecret,
|
|
11069
|
+
utils,
|
|
11070
|
+
lengths,
|
|
11071
|
+
Point,
|
|
11072
|
+
sign,
|
|
11073
|
+
verify,
|
|
11074
|
+
recoverPublicKey,
|
|
11075
|
+
Signature,
|
|
11076
|
+
hash
|
|
11077
|
+
});
|
|
11078
|
+
}
|
|
11079
|
+
|
|
11080
|
+
// node_modules/@noble/curves/secp256k1.js
|
|
11081
|
+
var secp256k1_CURVE = {
|
|
11082
|
+
p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
|
|
11083
|
+
n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
|
|
11084
|
+
h: BigInt(1),
|
|
11085
|
+
a: BigInt(0),
|
|
11086
|
+
b: BigInt(7),
|
|
11087
|
+
Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
|
|
11088
|
+
Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
|
|
11089
|
+
};
|
|
11090
|
+
var secp256k1_ENDO = {
|
|
11091
|
+
beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
|
|
11092
|
+
basises: [
|
|
11093
|
+
[BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
|
|
11094
|
+
[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
|
|
11095
|
+
]
|
|
11096
|
+
};
|
|
11097
|
+
var _2n3 = /* @__PURE__ */ BigInt(2);
|
|
11098
|
+
function sqrtMod(y) {
|
|
11099
|
+
const P = secp256k1_CURVE.p;
|
|
11100
|
+
const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
|
|
11101
|
+
const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
|
|
11102
|
+
const b2 = y * y * y % P;
|
|
11103
|
+
const b3 = b2 * b2 * y % P;
|
|
11104
|
+
const b6 = pow2(b3, _3n3, P) * b3 % P;
|
|
11105
|
+
const b9 = pow2(b6, _3n3, P) * b3 % P;
|
|
11106
|
+
const b11 = pow2(b9, _2n3, P) * b2 % P;
|
|
11107
|
+
const b22 = pow2(b11, _11n, P) * b11 % P;
|
|
11108
|
+
const b44 = pow2(b22, _22n, P) * b22 % P;
|
|
11109
|
+
const b88 = pow2(b44, _44n, P) * b44 % P;
|
|
11110
|
+
const b176 = pow2(b88, _88n, P) * b88 % P;
|
|
11111
|
+
const b220 = pow2(b176, _44n, P) * b44 % P;
|
|
11112
|
+
const b223 = pow2(b220, _3n3, P) * b3 % P;
|
|
11113
|
+
const t1 = pow2(b223, _23n, P) * b22 % P;
|
|
11114
|
+
const t2 = pow2(t1, _6n, P) * b2 % P;
|
|
11115
|
+
const root = pow2(t2, _2n3, P);
|
|
11116
|
+
if (!Fpk1.eql(Fpk1.sqr(root), y))
|
|
11117
|
+
throw new Error("Cannot find square root");
|
|
11118
|
+
return root;
|
|
11119
|
+
}
|
|
11120
|
+
var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
|
|
11121
|
+
var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
|
|
11122
|
+
Fp: Fpk1,
|
|
11123
|
+
endo: secp256k1_ENDO
|
|
11124
|
+
});
|
|
11125
|
+
var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha2564);
|
|
11126
|
+
|
|
11127
|
+
// modules/market/MarketModule.ts
|
|
11128
|
+
function hexToBytes3(hex) {
|
|
11129
|
+
const len = hex.length >> 1;
|
|
11130
|
+
const bytes = new Uint8Array(len);
|
|
11131
|
+
for (let i = 0; i < len; i++) {
|
|
11132
|
+
bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
11133
|
+
}
|
|
11134
|
+
return bytes;
|
|
11135
|
+
}
|
|
11136
|
+
function signRequest(body, privateKeyHex) {
|
|
11137
|
+
const timestamp = Date.now();
|
|
11138
|
+
const payload = JSON.stringify({ body, timestamp });
|
|
11139
|
+
const messageHash = sha2564(new TextEncoder().encode(payload));
|
|
11140
|
+
const privateKeyBytes = hexToBytes3(privateKeyHex);
|
|
11141
|
+
const signature = secp256k1.sign(messageHash, privateKeyBytes);
|
|
11142
|
+
const publicKey = bytesToHex4(secp256k1.getPublicKey(privateKeyBytes, true));
|
|
11143
|
+
return {
|
|
11144
|
+
body: JSON.stringify(body),
|
|
11145
|
+
headers: {
|
|
11146
|
+
"x-signature": bytesToHex4(signature),
|
|
11147
|
+
"x-public-key": publicKey,
|
|
11148
|
+
"x-timestamp": String(timestamp),
|
|
11149
|
+
"content-type": "application/json"
|
|
11150
|
+
}
|
|
11151
|
+
};
|
|
11152
|
+
}
|
|
11153
|
+
function toSnakeCaseIntent(req) {
|
|
11154
|
+
const result = {
|
|
11155
|
+
description: req.description,
|
|
11156
|
+
intent_type: req.intentType
|
|
11157
|
+
};
|
|
11158
|
+
if (req.category !== void 0) result.category = req.category;
|
|
11159
|
+
if (req.price !== void 0) result.price = req.price;
|
|
11160
|
+
if (req.currency !== void 0) result.currency = req.currency;
|
|
11161
|
+
if (req.location !== void 0) result.location = req.location;
|
|
11162
|
+
if (req.contactHandle !== void 0) result.contact_handle = req.contactHandle;
|
|
11163
|
+
if (req.expiresInDays !== void 0) result.expires_in_days = req.expiresInDays;
|
|
11164
|
+
return result;
|
|
11165
|
+
}
|
|
11166
|
+
function toSnakeCaseFilters(opts) {
|
|
11167
|
+
const result = {};
|
|
11168
|
+
if (opts?.filters) {
|
|
11169
|
+
const f = opts.filters;
|
|
11170
|
+
if (f.intentType !== void 0) result.intent_type = f.intentType;
|
|
11171
|
+
if (f.category !== void 0) result.category = f.category;
|
|
11172
|
+
if (f.minPrice !== void 0) result.min_price = f.minPrice;
|
|
11173
|
+
if (f.maxPrice !== void 0) result.max_price = f.maxPrice;
|
|
11174
|
+
if (f.location !== void 0) result.location = f.location;
|
|
11175
|
+
}
|
|
11176
|
+
if (opts?.limit !== void 0) result.limit = opts.limit;
|
|
11177
|
+
return result;
|
|
11178
|
+
}
|
|
11179
|
+
function mapSearchResult(raw) {
|
|
11180
|
+
return {
|
|
11181
|
+
id: raw.id,
|
|
11182
|
+
score: raw.score,
|
|
11183
|
+
agentNametag: raw.agent_nametag ?? void 0,
|
|
11184
|
+
agentPublicKey: raw.agent_public_key,
|
|
11185
|
+
description: raw.description,
|
|
11186
|
+
intentType: raw.intent_type,
|
|
11187
|
+
category: raw.category ?? void 0,
|
|
11188
|
+
price: raw.price ?? void 0,
|
|
11189
|
+
currency: raw.currency,
|
|
11190
|
+
location: raw.location ?? void 0,
|
|
11191
|
+
contactMethod: raw.contact_method,
|
|
11192
|
+
contactHandle: raw.contact_handle ?? void 0,
|
|
11193
|
+
createdAt: raw.created_at,
|
|
11194
|
+
expiresAt: raw.expires_at
|
|
11195
|
+
};
|
|
11196
|
+
}
|
|
11197
|
+
function mapMyIntent(raw) {
|
|
11198
|
+
return {
|
|
11199
|
+
id: raw.id,
|
|
11200
|
+
intentType: raw.intent_type,
|
|
11201
|
+
category: raw.category ?? void 0,
|
|
11202
|
+
price: raw.price ?? void 0,
|
|
11203
|
+
currency: raw.currency,
|
|
11204
|
+
location: raw.location ?? void 0,
|
|
11205
|
+
status: raw.status,
|
|
11206
|
+
createdAt: raw.created_at,
|
|
11207
|
+
expiresAt: raw.expires_at
|
|
11208
|
+
};
|
|
11209
|
+
}
|
|
11210
|
+
function mapFeedListing(raw) {
|
|
11211
|
+
return {
|
|
11212
|
+
id: raw.id,
|
|
11213
|
+
title: raw.title,
|
|
11214
|
+
descriptionPreview: raw.description_preview,
|
|
11215
|
+
agentName: raw.agent_name,
|
|
11216
|
+
agentId: raw.agent_id,
|
|
11217
|
+
type: raw.type,
|
|
11218
|
+
createdAt: raw.created_at
|
|
11219
|
+
};
|
|
11220
|
+
}
|
|
11221
|
+
function mapFeedMessage(raw) {
|
|
11222
|
+
if (raw.type === "initial") {
|
|
11223
|
+
return { type: "initial", listings: (raw.listings ?? []).map(mapFeedListing) };
|
|
11224
|
+
}
|
|
11225
|
+
return { type: "new", listing: mapFeedListing(raw.listing) };
|
|
11226
|
+
}
|
|
11227
|
+
var MarketModule = class {
|
|
11228
|
+
apiUrl;
|
|
11229
|
+
timeout;
|
|
11230
|
+
identity = null;
|
|
11231
|
+
registered = false;
|
|
11232
|
+
constructor(config) {
|
|
11233
|
+
this.apiUrl = (config?.apiUrl ?? DEFAULT_MARKET_API_URL).replace(/\/+$/, "");
|
|
11234
|
+
this.timeout = config?.timeout ?? 3e4;
|
|
11235
|
+
}
|
|
11236
|
+
/** Called by Sphere after construction */
|
|
11237
|
+
initialize(deps) {
|
|
11238
|
+
this.identity = deps.identity;
|
|
11239
|
+
}
|
|
11240
|
+
/** No-op — stateless module */
|
|
11241
|
+
async load() {
|
|
11242
|
+
}
|
|
11243
|
+
/** No-op — stateless module */
|
|
11244
|
+
destroy() {
|
|
11245
|
+
}
|
|
11246
|
+
// ---------------------------------------------------------------------------
|
|
11247
|
+
// Public API
|
|
11248
|
+
// ---------------------------------------------------------------------------
|
|
11249
|
+
/** Post a new intent (agent is auto-registered on first post) */
|
|
11250
|
+
async postIntent(intent) {
|
|
11251
|
+
const body = toSnakeCaseIntent(intent);
|
|
11252
|
+
const data = await this.apiPost("/api/intents", body);
|
|
11253
|
+
return {
|
|
11254
|
+
intentId: data.intent_id ?? data.intentId,
|
|
11255
|
+
message: data.message,
|
|
11256
|
+
expiresAt: data.expires_at ?? data.expiresAt
|
|
11257
|
+
};
|
|
11258
|
+
}
|
|
11259
|
+
/** Semantic search for intents (public — no auth required) */
|
|
11260
|
+
async search(query, opts) {
|
|
11261
|
+
const body = {
|
|
11262
|
+
query,
|
|
11263
|
+
...toSnakeCaseFilters(opts)
|
|
11264
|
+
};
|
|
11265
|
+
const data = await this.apiPublicPost("/api/search", body);
|
|
11266
|
+
let results = (data.intents ?? []).map(mapSearchResult);
|
|
11267
|
+
const minScore = opts?.filters?.minScore;
|
|
11268
|
+
if (minScore != null) {
|
|
11269
|
+
results = results.filter((r) => Math.round(r.score * 100) >= Math.round(minScore * 100));
|
|
11270
|
+
}
|
|
11271
|
+
return { intents: results, count: results.length };
|
|
11272
|
+
}
|
|
11273
|
+
/** List own intents (authenticated) */
|
|
11274
|
+
async getMyIntents() {
|
|
11275
|
+
const data = await this.apiGet("/api/intents");
|
|
11276
|
+
return (data.intents ?? []).map(mapMyIntent);
|
|
11277
|
+
}
|
|
11278
|
+
/** Close (delete) an intent */
|
|
11279
|
+
async closeIntent(intentId) {
|
|
11280
|
+
await this.apiDelete(`/api/intents/${encodeURIComponent(intentId)}`);
|
|
11281
|
+
}
|
|
11282
|
+
/** Fetch the most recent listings via REST (public — no auth required) */
|
|
11283
|
+
async getRecentListings() {
|
|
11284
|
+
const res = await fetch(`${this.apiUrl}/api/feed/recent`, {
|
|
11285
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
11286
|
+
});
|
|
11287
|
+
const data = await this.parseResponse(res);
|
|
11288
|
+
return (data.listings ?? []).map(mapFeedListing);
|
|
11289
|
+
}
|
|
11290
|
+
/**
|
|
11291
|
+
* Subscribe to the live listing feed via WebSocket.
|
|
11292
|
+
* Returns an unsubscribe function that closes the connection.
|
|
11293
|
+
*
|
|
11294
|
+
* Requires a WebSocket implementation — works natively in browsers
|
|
11295
|
+
* and in Node.js 21+ (or with the `ws` package).
|
|
11296
|
+
*/
|
|
11297
|
+
subscribeFeed(listener) {
|
|
11298
|
+
const wsUrl = this.apiUrl.replace(/^http/, "ws") + "/ws/feed";
|
|
11299
|
+
const ws2 = new WebSocket(wsUrl);
|
|
11300
|
+
ws2.onmessage = (event) => {
|
|
11301
|
+
try {
|
|
11302
|
+
const raw = JSON.parse(typeof event.data === "string" ? event.data : event.data.toString());
|
|
11303
|
+
listener(mapFeedMessage(raw));
|
|
11304
|
+
} catch {
|
|
11305
|
+
}
|
|
11306
|
+
};
|
|
11307
|
+
return () => {
|
|
11308
|
+
ws2.close();
|
|
11309
|
+
};
|
|
11310
|
+
}
|
|
11311
|
+
// ---------------------------------------------------------------------------
|
|
11312
|
+
// Private: HTTP helpers
|
|
11313
|
+
// ---------------------------------------------------------------------------
|
|
11314
|
+
ensureIdentity() {
|
|
11315
|
+
if (!this.identity) {
|
|
11316
|
+
throw new Error("MarketModule not initialized \u2014 call initialize() first");
|
|
11317
|
+
}
|
|
11318
|
+
}
|
|
11319
|
+
/** Register the agent's public key with the server (idempotent) */
|
|
11320
|
+
async ensureRegistered() {
|
|
11321
|
+
if (this.registered) return;
|
|
11322
|
+
this.ensureIdentity();
|
|
11323
|
+
const publicKey = bytesToHex4(secp256k1.getPublicKey(hexToBytes3(this.identity.privateKey), true));
|
|
11324
|
+
const body = { public_key: publicKey };
|
|
11325
|
+
if (this.identity.nametag) body.nametag = this.identity.nametag;
|
|
11326
|
+
const res = await fetch(`${this.apiUrl}/api/agent/register`, {
|
|
11327
|
+
method: "POST",
|
|
11328
|
+
headers: { "content-type": "application/json" },
|
|
11329
|
+
body: JSON.stringify(body),
|
|
11330
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
11331
|
+
});
|
|
11332
|
+
if (res.ok || res.status === 409) {
|
|
11333
|
+
this.registered = true;
|
|
11334
|
+
return;
|
|
11335
|
+
}
|
|
11336
|
+
const text = await res.text();
|
|
11337
|
+
let data;
|
|
11338
|
+
try {
|
|
11339
|
+
data = JSON.parse(text);
|
|
11340
|
+
} catch {
|
|
11341
|
+
}
|
|
11342
|
+
throw new Error(data?.error ?? `Agent registration failed: HTTP ${res.status}`);
|
|
11343
|
+
}
|
|
11344
|
+
async parseResponse(res) {
|
|
11345
|
+
const text = await res.text();
|
|
11346
|
+
let data;
|
|
11347
|
+
try {
|
|
11348
|
+
data = JSON.parse(text);
|
|
11349
|
+
} catch {
|
|
11350
|
+
throw new Error(`Market API error: HTTP ${res.status} \u2014 unexpected response (not JSON)`);
|
|
11351
|
+
}
|
|
11352
|
+
if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
|
|
11353
|
+
return data;
|
|
11354
|
+
}
|
|
11355
|
+
async apiPost(path, body) {
|
|
11356
|
+
this.ensureIdentity();
|
|
11357
|
+
await this.ensureRegistered();
|
|
11358
|
+
const signed = signRequest(body, this.identity.privateKey);
|
|
11359
|
+
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11360
|
+
method: "POST",
|
|
11361
|
+
headers: signed.headers,
|
|
11362
|
+
body: signed.body,
|
|
11363
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
11364
|
+
});
|
|
11365
|
+
return this.parseResponse(res);
|
|
11366
|
+
}
|
|
11367
|
+
async apiGet(path) {
|
|
11368
|
+
this.ensureIdentity();
|
|
11369
|
+
await this.ensureRegistered();
|
|
11370
|
+
const signed = signRequest({}, this.identity.privateKey);
|
|
11371
|
+
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11372
|
+
method: "GET",
|
|
11373
|
+
headers: signed.headers,
|
|
11374
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
11375
|
+
});
|
|
11376
|
+
return this.parseResponse(res);
|
|
11377
|
+
}
|
|
11378
|
+
async apiDelete(path) {
|
|
11379
|
+
this.ensureIdentity();
|
|
11380
|
+
await this.ensureRegistered();
|
|
11381
|
+
const signed = signRequest({}, this.identity.privateKey);
|
|
11382
|
+
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11383
|
+
method: "DELETE",
|
|
11384
|
+
headers: signed.headers,
|
|
11385
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
11386
|
+
});
|
|
11387
|
+
return this.parseResponse(res);
|
|
11388
|
+
}
|
|
11389
|
+
async apiPublicPost(path, body) {
|
|
11390
|
+
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11391
|
+
method: "POST",
|
|
11392
|
+
headers: { "content-type": "application/json" },
|
|
11393
|
+
body: JSON.stringify(body),
|
|
11394
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
11395
|
+
});
|
|
11396
|
+
return this.parseResponse(res);
|
|
11397
|
+
}
|
|
11398
|
+
};
|
|
11399
|
+
function createMarketModule(config) {
|
|
11400
|
+
return new MarketModule(config);
|
|
11401
|
+
}
|
|
11402
|
+
|
|
8910
11403
|
// core/encryption.ts
|
|
8911
11404
|
var import_crypto_js6 = __toESM(require("crypto-js"), 1);
|
|
8912
11405
|
var DEFAULT_ITERATIONS = 1e5;
|
|
@@ -9210,7 +11703,9 @@ function decryptTextFormatKey(encryptedKey, password) {
|
|
|
9210
11703
|
const key = deriveLegacyKey(password);
|
|
9211
11704
|
const decrypted = import_crypto_js7.default.AES.decrypt(encryptedKey, key);
|
|
9212
11705
|
const result = decrypted.toString(import_crypto_js7.default.enc.Utf8);
|
|
9213
|
-
|
|
11706
|
+
if (!result) return null;
|
|
11707
|
+
if (!/^[0-9a-fA-F]+$/.test(result)) return null;
|
|
11708
|
+
return result;
|
|
9214
11709
|
} catch {
|
|
9215
11710
|
return null;
|
|
9216
11711
|
}
|
|
@@ -9825,6 +12320,7 @@ var Sphere = class _Sphere {
|
|
|
9825
12320
|
_payments;
|
|
9826
12321
|
_communications;
|
|
9827
12322
|
_groupChat = null;
|
|
12323
|
+
_market = null;
|
|
9828
12324
|
// Events
|
|
9829
12325
|
eventHandlers = /* @__PURE__ */ new Map();
|
|
9830
12326
|
// Provider management
|
|
@@ -9834,7 +12330,7 @@ var Sphere = class _Sphere {
|
|
|
9834
12330
|
// ===========================================================================
|
|
9835
12331
|
// Constructor (private)
|
|
9836
12332
|
// ===========================================================================
|
|
9837
|
-
constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig) {
|
|
12333
|
+
constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig, marketConfig) {
|
|
9838
12334
|
this._storage = storage;
|
|
9839
12335
|
this._transport = transport;
|
|
9840
12336
|
this._oracle = oracle;
|
|
@@ -9845,6 +12341,7 @@ var Sphere = class _Sphere {
|
|
|
9845
12341
|
this._payments = createPaymentsModule({ l1: l1Config });
|
|
9846
12342
|
this._communications = createCommunicationsModule();
|
|
9847
12343
|
this._groupChat = groupChatConfig ? createGroupChatModule(groupChatConfig) : null;
|
|
12344
|
+
this._market = marketConfig ? createMarketModule(marketConfig) : null;
|
|
9848
12345
|
}
|
|
9849
12346
|
// ===========================================================================
|
|
9850
12347
|
// Static Methods - Wallet Management
|
|
@@ -9893,6 +12390,7 @@ var Sphere = class _Sphere {
|
|
|
9893
12390
|
*/
|
|
9894
12391
|
static async init(options) {
|
|
9895
12392
|
const groupChat = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
|
|
12393
|
+
const market = _Sphere.resolveMarketConfig(options.market);
|
|
9896
12394
|
const walletExists = await _Sphere.exists(options.storage);
|
|
9897
12395
|
if (walletExists) {
|
|
9898
12396
|
const sphere2 = await _Sphere.load({
|
|
@@ -9903,7 +12401,8 @@ var Sphere = class _Sphere {
|
|
|
9903
12401
|
l1: options.l1,
|
|
9904
12402
|
price: options.price,
|
|
9905
12403
|
groupChat,
|
|
9906
|
-
password: options.password
|
|
12404
|
+
password: options.password,
|
|
12405
|
+
market
|
|
9907
12406
|
});
|
|
9908
12407
|
return { sphere: sphere2, created: false };
|
|
9909
12408
|
}
|
|
@@ -9930,7 +12429,8 @@ var Sphere = class _Sphere {
|
|
|
9930
12429
|
l1: options.l1,
|
|
9931
12430
|
price: options.price,
|
|
9932
12431
|
groupChat,
|
|
9933
|
-
password: options.password
|
|
12432
|
+
password: options.password,
|
|
12433
|
+
market
|
|
9934
12434
|
});
|
|
9935
12435
|
return { sphere, created: true, generatedMnemonic };
|
|
9936
12436
|
}
|
|
@@ -9957,6 +12457,22 @@ var Sphere = class _Sphere {
|
|
|
9957
12457
|
}
|
|
9958
12458
|
return config;
|
|
9959
12459
|
}
|
|
12460
|
+
/**
|
|
12461
|
+
* Resolve market module config from Sphere.init() options.
|
|
12462
|
+
* - `true` → enable with default API URL
|
|
12463
|
+
* - `MarketModuleConfig` → pass through with defaults
|
|
12464
|
+
* - `undefined` → no market module
|
|
12465
|
+
*/
|
|
12466
|
+
static resolveMarketConfig(config) {
|
|
12467
|
+
if (!config) return void 0;
|
|
12468
|
+
if (config === true) {
|
|
12469
|
+
return { apiUrl: DEFAULT_MARKET_API_URL };
|
|
12470
|
+
}
|
|
12471
|
+
return {
|
|
12472
|
+
apiUrl: config.apiUrl ?? DEFAULT_MARKET_API_URL,
|
|
12473
|
+
timeout: config.timeout
|
|
12474
|
+
};
|
|
12475
|
+
}
|
|
9960
12476
|
/**
|
|
9961
12477
|
* Create new wallet with mnemonic
|
|
9962
12478
|
*/
|
|
@@ -9968,6 +12484,7 @@ var Sphere = class _Sphere {
|
|
|
9968
12484
|
throw new Error("Wallet already exists. Use Sphere.load() or Sphere.clear() first.");
|
|
9969
12485
|
}
|
|
9970
12486
|
const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
|
|
12487
|
+
const marketConfig = _Sphere.resolveMarketConfig(options.market);
|
|
9971
12488
|
const sphere = new _Sphere(
|
|
9972
12489
|
options.storage,
|
|
9973
12490
|
options.transport,
|
|
@@ -9975,7 +12492,8 @@ var Sphere = class _Sphere {
|
|
|
9975
12492
|
options.tokenStorage,
|
|
9976
12493
|
options.l1,
|
|
9977
12494
|
options.price,
|
|
9978
|
-
groupChatConfig
|
|
12495
|
+
groupChatConfig,
|
|
12496
|
+
marketConfig
|
|
9979
12497
|
);
|
|
9980
12498
|
sphere._password = options.password ?? null;
|
|
9981
12499
|
await sphere.storeMnemonic(options.mnemonic, options.derivationPath);
|
|
@@ -10002,6 +12520,7 @@ var Sphere = class _Sphere {
|
|
|
10002
12520
|
throw new Error("No wallet found. Use Sphere.create() to create a new wallet.");
|
|
10003
12521
|
}
|
|
10004
12522
|
const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
|
|
12523
|
+
const marketConfig = _Sphere.resolveMarketConfig(options.market);
|
|
10005
12524
|
const sphere = new _Sphere(
|
|
10006
12525
|
options.storage,
|
|
10007
12526
|
options.transport,
|
|
@@ -10009,7 +12528,8 @@ var Sphere = class _Sphere {
|
|
|
10009
12528
|
options.tokenStorage,
|
|
10010
12529
|
options.l1,
|
|
10011
12530
|
options.price,
|
|
10012
|
-
groupChatConfig
|
|
12531
|
+
groupChatConfig,
|
|
12532
|
+
marketConfig
|
|
10013
12533
|
);
|
|
10014
12534
|
sphere._password = options.password ?? null;
|
|
10015
12535
|
await sphere.loadIdentityFromStorage();
|
|
@@ -10055,6 +12575,7 @@ var Sphere = class _Sphere {
|
|
|
10055
12575
|
console.log("[Sphere.import] Storage reconnected");
|
|
10056
12576
|
}
|
|
10057
12577
|
const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat);
|
|
12578
|
+
const marketConfig = _Sphere.resolveMarketConfig(options.market);
|
|
10058
12579
|
const sphere = new _Sphere(
|
|
10059
12580
|
options.storage,
|
|
10060
12581
|
options.transport,
|
|
@@ -10062,7 +12583,8 @@ var Sphere = class _Sphere {
|
|
|
10062
12583
|
options.tokenStorage,
|
|
10063
12584
|
options.l1,
|
|
10064
12585
|
options.price,
|
|
10065
|
-
groupChatConfig
|
|
12586
|
+
groupChatConfig,
|
|
12587
|
+
marketConfig
|
|
10066
12588
|
);
|
|
10067
12589
|
sphere._password = options.password ?? null;
|
|
10068
12590
|
if (options.mnemonic) {
|
|
@@ -10227,6 +12749,10 @@ var Sphere = class _Sphere {
|
|
|
10227
12749
|
get groupChat() {
|
|
10228
12750
|
return this._groupChat;
|
|
10229
12751
|
}
|
|
12752
|
+
/** Market module (intent bulletin board). Null if not configured. */
|
|
12753
|
+
get market() {
|
|
12754
|
+
return this._market;
|
|
12755
|
+
}
|
|
10230
12756
|
// ===========================================================================
|
|
10231
12757
|
// Public Properties - State
|
|
10232
12758
|
// ===========================================================================
|
|
@@ -11032,7 +13558,7 @@ var Sphere = class _Sphere {
|
|
|
11032
13558
|
await provider.initialize();
|
|
11033
13559
|
}
|
|
11034
13560
|
await this.reinitializeModulesForNewAddress();
|
|
11035
|
-
if (
|
|
13561
|
+
if (!newNametag) {
|
|
11036
13562
|
await this.syncIdentityWithTransport();
|
|
11037
13563
|
}
|
|
11038
13564
|
if (newNametag) {
|
|
@@ -11102,9 +13628,14 @@ var Sphere = class _Sphere {
|
|
|
11102
13628
|
storage: this._storage,
|
|
11103
13629
|
emitEvent
|
|
11104
13630
|
});
|
|
13631
|
+
this._market?.initialize({
|
|
13632
|
+
identity: this._identity,
|
|
13633
|
+
emitEvent
|
|
13634
|
+
});
|
|
11105
13635
|
await this._payments.load();
|
|
11106
13636
|
await this._communications.load();
|
|
11107
13637
|
await this._groupChat?.load();
|
|
13638
|
+
await this._market?.load();
|
|
11108
13639
|
}
|
|
11109
13640
|
/**
|
|
11110
13641
|
* Derive address at a specific index
|
|
@@ -11805,12 +14336,22 @@ var Sphere = class _Sphere {
|
|
|
11805
14336
|
return;
|
|
11806
14337
|
}
|
|
11807
14338
|
try {
|
|
11808
|
-
|
|
14339
|
+
const transportPubkey = this._identity?.chainPubkey?.slice(2);
|
|
14340
|
+
if (transportPubkey && this._transport.resolve) {
|
|
11809
14341
|
try {
|
|
11810
|
-
const existing = await this._transport.resolve(
|
|
14342
|
+
const existing = await this._transport.resolve(transportPubkey);
|
|
11811
14343
|
if (existing) {
|
|
11812
|
-
|
|
11813
|
-
|
|
14344
|
+
let recoveredNametag = existing.nametag;
|
|
14345
|
+
let fromLegacy = false;
|
|
14346
|
+
if (!recoveredNametag && !this._identity?.nametag && this._transport.recoverNametag) {
|
|
14347
|
+
try {
|
|
14348
|
+
recoveredNametag = await this._transport.recoverNametag() ?? void 0;
|
|
14349
|
+
if (recoveredNametag) fromLegacy = true;
|
|
14350
|
+
} catch {
|
|
14351
|
+
}
|
|
14352
|
+
}
|
|
14353
|
+
if (recoveredNametag && !this._identity?.nametag) {
|
|
14354
|
+
this._identity.nametag = recoveredNametag;
|
|
11814
14355
|
await this._updateCachedProxyAddress();
|
|
11815
14356
|
const entry = await this.ensureAddressTracked(this._currentAddressIndex);
|
|
11816
14357
|
let nametags = this._addressNametags.get(entry.addressId);
|
|
@@ -11819,10 +14360,20 @@ var Sphere = class _Sphere {
|
|
|
11819
14360
|
this._addressNametags.set(entry.addressId, nametags);
|
|
11820
14361
|
}
|
|
11821
14362
|
if (!nametags.has(0)) {
|
|
11822
|
-
nametags.set(0,
|
|
14363
|
+
nametags.set(0, recoveredNametag);
|
|
11823
14364
|
await this.persistAddressNametags();
|
|
11824
14365
|
}
|
|
11825
|
-
this.emitEvent("nametag:recovered", { nametag:
|
|
14366
|
+
this.emitEvent("nametag:recovered", { nametag: recoveredNametag });
|
|
14367
|
+
if (fromLegacy) {
|
|
14368
|
+
await this._transport.publishIdentityBinding(
|
|
14369
|
+
this._identity.chainPubkey,
|
|
14370
|
+
this._identity.l1Address,
|
|
14371
|
+
this._identity.directAddress || "",
|
|
14372
|
+
recoveredNametag
|
|
14373
|
+
);
|
|
14374
|
+
console.log(`[Sphere] Migrated legacy binding with nametag @${recoveredNametag}`);
|
|
14375
|
+
return;
|
|
14376
|
+
}
|
|
11826
14377
|
}
|
|
11827
14378
|
console.log("[Sphere] Existing binding found, skipping re-publish");
|
|
11828
14379
|
return;
|
|
@@ -11909,6 +14460,7 @@ var Sphere = class _Sphere {
|
|
|
11909
14460
|
this._payments.destroy();
|
|
11910
14461
|
this._communications.destroy();
|
|
11911
14462
|
this._groupChat?.destroy();
|
|
14463
|
+
this._market?.destroy();
|
|
11912
14464
|
await this._transport.disconnect();
|
|
11913
14465
|
await this._storage.disconnect();
|
|
11914
14466
|
await this._oracle.disconnect();
|
|
@@ -12216,9 +14768,14 @@ var Sphere = class _Sphere {
|
|
|
12216
14768
|
storage: this._storage,
|
|
12217
14769
|
emitEvent
|
|
12218
14770
|
});
|
|
14771
|
+
this._market?.initialize({
|
|
14772
|
+
identity: this._identity,
|
|
14773
|
+
emitEvent
|
|
14774
|
+
});
|
|
12219
14775
|
await this._payments.load();
|
|
12220
14776
|
await this._communications.load();
|
|
12221
14777
|
await this._groupChat?.load();
|
|
14778
|
+
await this._market?.load();
|
|
12222
14779
|
}
|
|
12223
14780
|
// ===========================================================================
|
|
12224
14781
|
// Private: Helpers
|
|
@@ -12569,4 +15126,16 @@ async function runCustomCheck(name, checkFn, timeoutMs) {
|
|
|
12569
15126
|
toSmallestUnit,
|
|
12570
15127
|
validateMnemonic
|
|
12571
15128
|
});
|
|
15129
|
+
/*! Bundled license information:
|
|
15130
|
+
|
|
15131
|
+
@noble/hashes/utils.js:
|
|
15132
|
+
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
15133
|
+
|
|
15134
|
+
@noble/curves/utils.js:
|
|
15135
|
+
@noble/curves/abstract/modular.js:
|
|
15136
|
+
@noble/curves/abstract/curve.js:
|
|
15137
|
+
@noble/curves/abstract/weierstrass.js:
|
|
15138
|
+
@noble/curves/secp256k1.js:
|
|
15139
|
+
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
15140
|
+
*/
|
|
12572
15141
|
//# sourceMappingURL=index.cjs.map
|