@unicitylabs/sphere-sdk 0.3.9 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/connect/index.cjs +79 -3
- package/dist/connect/index.cjs.map +1 -1
- package/dist/connect/index.d.cts +16 -0
- package/dist/connect/index.d.ts +16 -0
- package/dist/connect/index.js +79 -3
- package/dist/connect/index.js.map +1 -1
- package/dist/core/index.cjs +2686 -56
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +228 -3
- package/dist/core/index.d.ts +228 -3
- package/dist/core/index.js +2682 -52
- package/dist/core/index.js.map +1 -1
- package/dist/impl/browser/connect/index.cjs +11 -2
- package/dist/impl/browser/connect/index.cjs.map +1 -1
- package/dist/impl/browser/connect/index.js +11 -2
- package/dist/impl/browser/connect/index.js.map +1 -1
- package/dist/impl/browser/index.cjs +467 -47
- package/dist/impl/browser/index.cjs.map +1 -1
- package/dist/impl/browser/index.js +468 -47
- package/dist/impl/browser/index.js.map +1 -1
- package/dist/impl/nodejs/connect/index.cjs +11 -2
- package/dist/impl/nodejs/connect/index.cjs.map +1 -1
- package/dist/impl/nodejs/connect/index.js +11 -2
- package/dist/impl/nodejs/connect/index.js.map +1 -1
- package/dist/impl/nodejs/index.cjs +152 -8
- package/dist/impl/nodejs/index.cjs.map +1 -1
- package/dist/impl/nodejs/index.d.cts +47 -0
- package/dist/impl/nodejs/index.d.ts +47 -0
- package/dist/impl/nodejs/index.js +153 -8
- package/dist/impl/nodejs/index.js.map +1 -1
- package/dist/index.cjs +2703 -56
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +326 -5
- package/dist/index.d.ts +326 -5
- package/dist/index.js +2692 -52
- package/dist/index.js.map +1 -1
- package/dist/l1/index.cjs +5 -1
- package/dist/l1/index.cjs.map +1 -1
- package/dist/l1/index.d.cts +2 -1
- package/dist/l1/index.d.ts +2 -1
- package/dist/l1/index.js +5 -1
- package/dist/l1/index.js.map +1 -1
- package/package.json +1 -1
package/dist/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
|
}
|
|
@@ -480,6 +480,7 @@ __export(index_exports, {
|
|
|
480
480
|
DEFAULT_GROUP_RELAYS: () => DEFAULT_GROUP_RELAYS,
|
|
481
481
|
DEFAULT_IPFS_BOOTSTRAP_PEERS: () => DEFAULT_IPFS_BOOTSTRAP_PEERS,
|
|
482
482
|
DEFAULT_IPFS_GATEWAYS: () => DEFAULT_IPFS_GATEWAYS,
|
|
483
|
+
DEFAULT_MARKET_API_URL: () => DEFAULT_MARKET_API_URL,
|
|
483
484
|
DEFAULT_NOSTR_RELAYS: () => DEFAULT_NOSTR_RELAYS,
|
|
484
485
|
DEV_AGGREGATOR_URL: () => DEV_AGGREGATOR_URL,
|
|
485
486
|
GroupChatModule: () => GroupChatModule,
|
|
@@ -488,11 +489,14 @@ __export(index_exports, {
|
|
|
488
489
|
L1: () => l1_exports,
|
|
489
490
|
L1PaymentsModule: () => L1PaymentsModule,
|
|
490
491
|
LIMITS: () => LIMITS,
|
|
492
|
+
MarketModule: () => MarketModule,
|
|
491
493
|
NETWORKS: () => NETWORKS,
|
|
492
494
|
NIP29_KINDS: () => NIP29_KINDS,
|
|
493
495
|
NOSTR_EVENT_KINDS: () => NOSTR_EVENT_KINDS,
|
|
494
496
|
PaymentsModule: () => PaymentsModule,
|
|
495
497
|
STORAGE_KEYS: () => STORAGE_KEYS,
|
|
498
|
+
STORAGE_KEYS_ADDRESS: () => STORAGE_KEYS_ADDRESS,
|
|
499
|
+
STORAGE_KEYS_GLOBAL: () => STORAGE_KEYS_GLOBAL,
|
|
496
500
|
STORAGE_PREFIX: () => STORAGE_PREFIX,
|
|
497
501
|
Sphere: () => Sphere,
|
|
498
502
|
SphereError: () => SphereError,
|
|
@@ -515,6 +519,7 @@ __export(index_exports, {
|
|
|
515
519
|
createGroupChatModule: () => createGroupChatModule,
|
|
516
520
|
createKeyPair: () => createKeyPair,
|
|
517
521
|
createL1PaymentsModule: () => createL1PaymentsModule,
|
|
522
|
+
createMarketModule: () => createMarketModule,
|
|
518
523
|
createPaymentSession: () => createPaymentSession,
|
|
519
524
|
createPaymentSessionError: () => createPaymentSessionError,
|
|
520
525
|
createPaymentsModule: () => createPaymentsModule,
|
|
@@ -538,6 +543,8 @@ __export(index_exports, {
|
|
|
538
543
|
generateMasterKey: () => generateMasterKey,
|
|
539
544
|
generateMnemonic: () => generateMnemonic2,
|
|
540
545
|
getAddressHrp: () => getAddressHrp,
|
|
546
|
+
getAddressId: () => getAddressId,
|
|
547
|
+
getAddressStorageKey: () => getAddressStorageKey,
|
|
541
548
|
getCoinIdByName: () => getCoinIdByName,
|
|
542
549
|
getCoinIdBySymbol: () => getCoinIdBySymbol,
|
|
543
550
|
getCurrentStateHash: () => getCurrentStateHash,
|
|
@@ -987,9 +994,13 @@ var VestingClassifier = class {
|
|
|
987
994
|
storeName = "vestingCache";
|
|
988
995
|
db = null;
|
|
989
996
|
/**
|
|
990
|
-
* Initialize IndexedDB for persistent caching
|
|
997
|
+
* Initialize IndexedDB for persistent caching.
|
|
998
|
+
* In Node.js (no IndexedDB), silently falls back to memory-only caching.
|
|
991
999
|
*/
|
|
992
1000
|
async initDB() {
|
|
1001
|
+
if (typeof indexedDB === "undefined") {
|
|
1002
|
+
return;
|
|
1003
|
+
}
|
|
993
1004
|
return new Promise((resolve, reject) => {
|
|
994
1005
|
const request = indexedDB.open(this.dbName, 1);
|
|
995
1006
|
request.onupgradeneeded = (event) => {
|
|
@@ -2672,6 +2683,9 @@ var STORAGE_KEYS = {
|
|
|
2672
2683
|
...STORAGE_KEYS_GLOBAL,
|
|
2673
2684
|
...STORAGE_KEYS_ADDRESS
|
|
2674
2685
|
};
|
|
2686
|
+
function getAddressStorageKey(addressId, key) {
|
|
2687
|
+
return `${addressId}_${key}`;
|
|
2688
|
+
}
|
|
2675
2689
|
function getAddressId(directAddress) {
|
|
2676
2690
|
let hash = directAddress;
|
|
2677
2691
|
if (hash.startsWith("DIRECT://")) {
|
|
@@ -6722,6 +6736,29 @@ var PaymentsModule = class _PaymentsModule {
|
|
|
6722
6736
|
this.nametags = [];
|
|
6723
6737
|
await this.save();
|
|
6724
6738
|
}
|
|
6739
|
+
/**
|
|
6740
|
+
* Reload nametag data from storage providers into memory.
|
|
6741
|
+
*
|
|
6742
|
+
* Used as a recovery mechanism when `this.nametags` is unexpectedly empty
|
|
6743
|
+
* (e.g., wiped by sync or race condition) but nametag data exists in storage.
|
|
6744
|
+
*/
|
|
6745
|
+
async reloadNametagsFromStorage() {
|
|
6746
|
+
const providers = this.getTokenStorageProviders();
|
|
6747
|
+
for (const [, provider] of providers) {
|
|
6748
|
+
try {
|
|
6749
|
+
const result = await provider.load();
|
|
6750
|
+
if (result.success && result.data) {
|
|
6751
|
+
const parsed = parseTxfStorageData(result.data);
|
|
6752
|
+
if (parsed.nametags.length > 0) {
|
|
6753
|
+
this.nametags = parsed.nametags;
|
|
6754
|
+
this.log(`Reloaded ${parsed.nametags.length} nametag(s) from storage`);
|
|
6755
|
+
return;
|
|
6756
|
+
}
|
|
6757
|
+
}
|
|
6758
|
+
} catch {
|
|
6759
|
+
}
|
|
6760
|
+
}
|
|
6761
|
+
}
|
|
6725
6762
|
/**
|
|
6726
6763
|
* Mint a nametag token on-chain (like Sphere wallet and lottery)
|
|
6727
6764
|
* This creates the nametag token required for receiving tokens via PROXY addresses
|
|
@@ -6846,11 +6883,15 @@ var PaymentsModule = class _PaymentsModule {
|
|
|
6846
6883
|
const localData = await this.createStorageData();
|
|
6847
6884
|
let totalAdded = 0;
|
|
6848
6885
|
let totalRemoved = 0;
|
|
6886
|
+
const savedNametags = [...this.nametags];
|
|
6849
6887
|
for (const [providerId, provider] of providers) {
|
|
6850
6888
|
try {
|
|
6851
6889
|
const result = await provider.sync(localData);
|
|
6852
6890
|
if (result.success && result.merged) {
|
|
6853
6891
|
this.loadFromStorageData(result.merged);
|
|
6892
|
+
if (this.nametags.length === 0 && savedNametags.length > 0) {
|
|
6893
|
+
this.nametags = savedNametags;
|
|
6894
|
+
}
|
|
6854
6895
|
totalAdded += result.added;
|
|
6855
6896
|
totalRemoved += result.removed;
|
|
6856
6897
|
}
|
|
@@ -7079,6 +7120,15 @@ var PaymentsModule = class _PaymentsModule {
|
|
|
7079
7120
|
);
|
|
7080
7121
|
return import_SigningService.SigningService.createFromSecret(privateKeyBytes);
|
|
7081
7122
|
}
|
|
7123
|
+
/**
|
|
7124
|
+
* Get the wallet's signing public key (used for token ownership predicates).
|
|
7125
|
+
* This is the key that token state predicates are checked against.
|
|
7126
|
+
*/
|
|
7127
|
+
async getSigningPublicKey() {
|
|
7128
|
+
this.ensureInitialized();
|
|
7129
|
+
const signer = await this.createSigningService();
|
|
7130
|
+
return signer.publicKey;
|
|
7131
|
+
}
|
|
7082
7132
|
/**
|
|
7083
7133
|
* Create DirectAddress from a public key using UnmaskedPredicateReference
|
|
7084
7134
|
*/
|
|
@@ -7229,7 +7279,12 @@ var PaymentsModule = class _PaymentsModule {
|
|
|
7229
7279
|
let nametagTokens = [];
|
|
7230
7280
|
if (addressScheme === import_AddressScheme.AddressScheme.PROXY) {
|
|
7231
7281
|
const { ProxyAddress } = await import("@unicitylabs/state-transition-sdk/lib/address/ProxyAddress");
|
|
7232
|
-
|
|
7282
|
+
let proxyNametag = this.getNametag();
|
|
7283
|
+
if (!proxyNametag?.token) {
|
|
7284
|
+
this.log("Nametag missing in memory, attempting reload from storage...");
|
|
7285
|
+
await this.reloadNametagsFromStorage();
|
|
7286
|
+
proxyNametag = this.getNametag();
|
|
7287
|
+
}
|
|
7233
7288
|
if (!proxyNametag?.token) {
|
|
7234
7289
|
throw new Error("Cannot finalize PROXY transfer - no nametag token");
|
|
7235
7290
|
}
|
|
@@ -7727,14 +7782,17 @@ var CommunicationsModule = class {
|
|
|
7727
7782
|
broadcasts = /* @__PURE__ */ new Map();
|
|
7728
7783
|
// Subscriptions
|
|
7729
7784
|
unsubscribeMessages = null;
|
|
7785
|
+
unsubscribeComposing = null;
|
|
7730
7786
|
broadcastSubscriptions = /* @__PURE__ */ new Map();
|
|
7731
7787
|
// Handlers
|
|
7732
7788
|
dmHandlers = /* @__PURE__ */ new Set();
|
|
7789
|
+
composingHandlers = /* @__PURE__ */ new Set();
|
|
7733
7790
|
broadcastHandlers = /* @__PURE__ */ new Set();
|
|
7734
7791
|
constructor(config) {
|
|
7735
7792
|
this.config = {
|
|
7736
7793
|
autoSave: config?.autoSave ?? true,
|
|
7737
7794
|
maxMessages: config?.maxMessages ?? 1e3,
|
|
7795
|
+
maxPerConversation: config?.maxPerConversation ?? 200,
|
|
7738
7796
|
readReceipts: config?.readReceipts ?? true
|
|
7739
7797
|
};
|
|
7740
7798
|
}
|
|
@@ -7745,6 +7803,8 @@ var CommunicationsModule = class {
|
|
|
7745
7803
|
* Initialize module with dependencies
|
|
7746
7804
|
*/
|
|
7747
7805
|
initialize(deps) {
|
|
7806
|
+
this.unsubscribeMessages?.();
|
|
7807
|
+
this.unsubscribeComposing?.();
|
|
7748
7808
|
this.deps = deps;
|
|
7749
7809
|
this.unsubscribeMessages = deps.transport.onMessage((msg) => {
|
|
7750
7810
|
this.handleIncomingMessage(msg);
|
|
@@ -7771,19 +7831,41 @@ var CommunicationsModule = class {
|
|
|
7771
7831
|
});
|
|
7772
7832
|
});
|
|
7773
7833
|
}
|
|
7834
|
+
this.unsubscribeComposing = deps.transport.onComposing?.((indicator) => {
|
|
7835
|
+
this.handleComposingIndicator(indicator);
|
|
7836
|
+
}) ?? null;
|
|
7774
7837
|
}
|
|
7775
7838
|
/**
|
|
7776
|
-
* Load messages from storage
|
|
7839
|
+
* Load messages from storage.
|
|
7840
|
+
* Uses per-address key (STORAGE_KEYS_ADDRESS.MESSAGES) which is automatically
|
|
7841
|
+
* scoped by LocalStorageProvider to sphere_DIRECT_xxx_yyy_messages.
|
|
7842
|
+
* Falls back to legacy global 'direct_messages' key for migration.
|
|
7777
7843
|
*/
|
|
7778
7844
|
async load() {
|
|
7779
7845
|
this.ensureInitialized();
|
|
7780
|
-
|
|
7846
|
+
this.messages.clear();
|
|
7847
|
+
let data = await this.deps.storage.get(STORAGE_KEYS_ADDRESS.MESSAGES);
|
|
7781
7848
|
if (data) {
|
|
7782
7849
|
const messages = JSON.parse(data);
|
|
7783
|
-
this.messages.clear();
|
|
7784
7850
|
for (const msg of messages) {
|
|
7785
7851
|
this.messages.set(msg.id, msg);
|
|
7786
7852
|
}
|
|
7853
|
+
return;
|
|
7854
|
+
}
|
|
7855
|
+
data = await this.deps.storage.get("direct_messages");
|
|
7856
|
+
if (data) {
|
|
7857
|
+
const allMessages = JSON.parse(data);
|
|
7858
|
+
const myPubkey = this.deps.identity.chainPubkey;
|
|
7859
|
+
const myMessages = allMessages.filter(
|
|
7860
|
+
(m) => m.senderPubkey === myPubkey || m.recipientPubkey === myPubkey
|
|
7861
|
+
);
|
|
7862
|
+
for (const msg of myMessages) {
|
|
7863
|
+
this.messages.set(msg.id, msg);
|
|
7864
|
+
}
|
|
7865
|
+
if (myMessages.length > 0) {
|
|
7866
|
+
await this.save();
|
|
7867
|
+
console.log(`[Communications] Migrated ${myMessages.length} messages to per-address storage`);
|
|
7868
|
+
}
|
|
7787
7869
|
}
|
|
7788
7870
|
}
|
|
7789
7871
|
/**
|
|
@@ -7792,6 +7874,8 @@ var CommunicationsModule = class {
|
|
|
7792
7874
|
destroy() {
|
|
7793
7875
|
this.unsubscribeMessages?.();
|
|
7794
7876
|
this.unsubscribeMessages = null;
|
|
7877
|
+
this.unsubscribeComposing?.();
|
|
7878
|
+
this.unsubscribeComposing = null;
|
|
7795
7879
|
for (const unsub of this.broadcastSubscriptions.values()) {
|
|
7796
7880
|
unsub();
|
|
7797
7881
|
}
|
|
@@ -7805,13 +7889,14 @@ var CommunicationsModule = class {
|
|
|
7805
7889
|
*/
|
|
7806
7890
|
async sendDM(recipient, content) {
|
|
7807
7891
|
this.ensureInitialized();
|
|
7808
|
-
const
|
|
7809
|
-
const eventId = await this.deps.transport.sendMessage(
|
|
7892
|
+
const resolved = await this.resolveRecipient(recipient);
|
|
7893
|
+
const eventId = await this.deps.transport.sendMessage(resolved.pubkey, content);
|
|
7810
7894
|
const message = {
|
|
7811
7895
|
id: eventId,
|
|
7812
7896
|
senderPubkey: this.deps.identity.chainPubkey,
|
|
7813
7897
|
senderNametag: this.deps.identity.nametag,
|
|
7814
|
-
recipientPubkey,
|
|
7898
|
+
recipientPubkey: resolved.pubkey,
|
|
7899
|
+
...resolved.nametag ? { recipientNametag: resolved.nametag } : {},
|
|
7815
7900
|
content,
|
|
7816
7901
|
timestamp: Date.now(),
|
|
7817
7902
|
isRead: false
|
|
@@ -7883,6 +7968,37 @@ var CommunicationsModule = class {
|
|
|
7883
7968
|
}
|
|
7884
7969
|
return messages.length;
|
|
7885
7970
|
}
|
|
7971
|
+
/**
|
|
7972
|
+
* Get a page of messages from a conversation (for lazy loading).
|
|
7973
|
+
* Returns messages in chronological order with a cursor for loading older messages.
|
|
7974
|
+
*/
|
|
7975
|
+
getConversationPage(peerPubkey, options) {
|
|
7976
|
+
const limit = options?.limit ?? 20;
|
|
7977
|
+
const before = options?.before ?? Infinity;
|
|
7978
|
+
const all = Array.from(this.messages.values()).filter(
|
|
7979
|
+
(m) => (m.senderPubkey === peerPubkey || m.recipientPubkey === peerPubkey) && m.timestamp < before
|
|
7980
|
+
).sort((a, b) => b.timestamp - a.timestamp);
|
|
7981
|
+
const page = all.slice(0, limit);
|
|
7982
|
+
return {
|
|
7983
|
+
messages: page.reverse(),
|
|
7984
|
+
// chronological order for display
|
|
7985
|
+
hasMore: all.length > limit,
|
|
7986
|
+
oldestTimestamp: page.length > 0 ? page[0].timestamp : null
|
|
7987
|
+
};
|
|
7988
|
+
}
|
|
7989
|
+
/**
|
|
7990
|
+
* Delete all messages in a conversation with a peer
|
|
7991
|
+
*/
|
|
7992
|
+
async deleteConversation(peerPubkey) {
|
|
7993
|
+
for (const [id, msg] of this.messages) {
|
|
7994
|
+
if (msg.senderPubkey === peerPubkey || msg.recipientPubkey === peerPubkey) {
|
|
7995
|
+
this.messages.delete(id);
|
|
7996
|
+
}
|
|
7997
|
+
}
|
|
7998
|
+
if (this.config.autoSave) {
|
|
7999
|
+
await this.save();
|
|
8000
|
+
}
|
|
8001
|
+
}
|
|
7886
8002
|
/**
|
|
7887
8003
|
* Send typing indicator to a peer
|
|
7888
8004
|
*/
|
|
@@ -7892,6 +8008,26 @@ var CommunicationsModule = class {
|
|
|
7892
8008
|
await this.deps.transport.sendTypingIndicator(peerPubkey);
|
|
7893
8009
|
}
|
|
7894
8010
|
}
|
|
8011
|
+
/**
|
|
8012
|
+
* Send a composing indicator to a peer.
|
|
8013
|
+
* Fire-and-forget — does not save to message history.
|
|
8014
|
+
*/
|
|
8015
|
+
async sendComposingIndicator(recipientPubkeyOrNametag) {
|
|
8016
|
+
this.ensureInitialized();
|
|
8017
|
+
const resolved = await this.resolveRecipient(recipientPubkeyOrNametag);
|
|
8018
|
+
const content = JSON.stringify({
|
|
8019
|
+
senderNametag: this.deps.identity.nametag,
|
|
8020
|
+
expiresIn: 3e4
|
|
8021
|
+
});
|
|
8022
|
+
await this.deps.transport.sendComposingIndicator?.(resolved.pubkey, content);
|
|
8023
|
+
}
|
|
8024
|
+
/**
|
|
8025
|
+
* Subscribe to incoming composing indicators
|
|
8026
|
+
*/
|
|
8027
|
+
onComposingIndicator(handler) {
|
|
8028
|
+
this.composingHandlers.add(handler);
|
|
8029
|
+
return () => this.composingHandlers.delete(handler);
|
|
8030
|
+
}
|
|
7895
8031
|
/**
|
|
7896
8032
|
* Subscribe to incoming DMs
|
|
7897
8033
|
*/
|
|
@@ -8004,6 +8140,21 @@ var CommunicationsModule = class {
|
|
|
8004
8140
|
}
|
|
8005
8141
|
this.pruneIfNeeded();
|
|
8006
8142
|
}
|
|
8143
|
+
handleComposingIndicator(indicator) {
|
|
8144
|
+
const composing = {
|
|
8145
|
+
senderPubkey: indicator.senderPubkey,
|
|
8146
|
+
senderNametag: indicator.senderNametag,
|
|
8147
|
+
expiresIn: indicator.expiresIn
|
|
8148
|
+
};
|
|
8149
|
+
this.deps.emitEvent("composing:started", composing);
|
|
8150
|
+
for (const handler of this.composingHandlers) {
|
|
8151
|
+
try {
|
|
8152
|
+
handler(composing);
|
|
8153
|
+
} catch (error) {
|
|
8154
|
+
console.error("[Communications] Composing handler error:", error);
|
|
8155
|
+
}
|
|
8156
|
+
}
|
|
8157
|
+
}
|
|
8007
8158
|
handleIncomingBroadcast(incoming) {
|
|
8008
8159
|
const message = {
|
|
8009
8160
|
id: incoming.id,
|
|
@@ -8027,9 +8178,23 @@ var CommunicationsModule = class {
|
|
|
8027
8178
|
// ===========================================================================
|
|
8028
8179
|
async save() {
|
|
8029
8180
|
const messages = Array.from(this.messages.values());
|
|
8030
|
-
await this.deps.storage.set(
|
|
8181
|
+
await this.deps.storage.set(STORAGE_KEYS_ADDRESS.MESSAGES, JSON.stringify(messages));
|
|
8031
8182
|
}
|
|
8032
8183
|
pruneIfNeeded() {
|
|
8184
|
+
const byPeer = /* @__PURE__ */ new Map();
|
|
8185
|
+
for (const msg of this.messages.values()) {
|
|
8186
|
+
const peer = msg.senderPubkey === this.deps?.identity.chainPubkey ? msg.recipientPubkey : msg.senderPubkey;
|
|
8187
|
+
if (!byPeer.has(peer)) byPeer.set(peer, []);
|
|
8188
|
+
byPeer.get(peer).push(msg);
|
|
8189
|
+
}
|
|
8190
|
+
for (const [, msgs] of byPeer) {
|
|
8191
|
+
if (msgs.length <= this.config.maxPerConversation) continue;
|
|
8192
|
+
msgs.sort((a, b) => a.timestamp - b.timestamp);
|
|
8193
|
+
const toRemove2 = msgs.slice(0, msgs.length - this.config.maxPerConversation);
|
|
8194
|
+
for (const msg of toRemove2) {
|
|
8195
|
+
this.messages.delete(msg.id);
|
|
8196
|
+
}
|
|
8197
|
+
}
|
|
8033
8198
|
if (this.messages.size <= this.config.maxMessages) return;
|
|
8034
8199
|
const sorted = Array.from(this.messages.entries()).sort(([, a], [, b]) => a.timestamp - b.timestamp);
|
|
8035
8200
|
const toRemove = sorted.slice(0, sorted.length - this.config.maxMessages);
|
|
@@ -8042,13 +8207,14 @@ var CommunicationsModule = class {
|
|
|
8042
8207
|
// ===========================================================================
|
|
8043
8208
|
async resolveRecipient(recipient) {
|
|
8044
8209
|
if (recipient.startsWith("@")) {
|
|
8045
|
-
const
|
|
8210
|
+
const nametag = recipient.slice(1);
|
|
8211
|
+
const pubkey = await this.deps.transport.resolveNametag?.(nametag);
|
|
8046
8212
|
if (!pubkey) {
|
|
8047
8213
|
throw new Error(`Nametag not found: ${recipient}`);
|
|
8048
8214
|
}
|
|
8049
|
-
return pubkey;
|
|
8215
|
+
return { pubkey, nametag };
|
|
8050
8216
|
}
|
|
8051
|
-
return recipient;
|
|
8217
|
+
return { pubkey: recipient };
|
|
8052
8218
|
}
|
|
8053
8219
|
ensureInitialized() {
|
|
8054
8220
|
if (!this.deps) {
|
|
@@ -9438,6 +9604,2427 @@ function createGroupChatModule(config) {
|
|
|
9438
9604
|
return new GroupChatModule(config);
|
|
9439
9605
|
}
|
|
9440
9606
|
|
|
9607
|
+
// node_modules/@noble/hashes/utils.js
|
|
9608
|
+
function isBytes(a) {
|
|
9609
|
+
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
|
|
9610
|
+
}
|
|
9611
|
+
function anumber(n, title = "") {
|
|
9612
|
+
if (!Number.isSafeInteger(n) || n < 0) {
|
|
9613
|
+
const prefix = title && `"${title}" `;
|
|
9614
|
+
throw new Error(`${prefix}expected integer >= 0, got ${n}`);
|
|
9615
|
+
}
|
|
9616
|
+
}
|
|
9617
|
+
function abytes(value, length, title = "") {
|
|
9618
|
+
const bytes = isBytes(value);
|
|
9619
|
+
const len = value?.length;
|
|
9620
|
+
const needsLen = length !== void 0;
|
|
9621
|
+
if (!bytes || needsLen && len !== length) {
|
|
9622
|
+
const prefix = title && `"${title}" `;
|
|
9623
|
+
const ofLen = needsLen ? ` of length ${length}` : "";
|
|
9624
|
+
const got = bytes ? `length=${len}` : `type=${typeof value}`;
|
|
9625
|
+
throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
|
|
9626
|
+
}
|
|
9627
|
+
return value;
|
|
9628
|
+
}
|
|
9629
|
+
function ahash(h) {
|
|
9630
|
+
if (typeof h !== "function" || typeof h.create !== "function")
|
|
9631
|
+
throw new Error("Hash must wrapped by utils.createHasher");
|
|
9632
|
+
anumber(h.outputLen);
|
|
9633
|
+
anumber(h.blockLen);
|
|
9634
|
+
}
|
|
9635
|
+
function aexists(instance, checkFinished = true) {
|
|
9636
|
+
if (instance.destroyed)
|
|
9637
|
+
throw new Error("Hash instance has been destroyed");
|
|
9638
|
+
if (checkFinished && instance.finished)
|
|
9639
|
+
throw new Error("Hash#digest() has already been called");
|
|
9640
|
+
}
|
|
9641
|
+
function aoutput(out, instance) {
|
|
9642
|
+
abytes(out, void 0, "digestInto() output");
|
|
9643
|
+
const min = instance.outputLen;
|
|
9644
|
+
if (out.length < min) {
|
|
9645
|
+
throw new Error('"digestInto() output" expected to be of length >=' + min);
|
|
9646
|
+
}
|
|
9647
|
+
}
|
|
9648
|
+
function clean(...arrays) {
|
|
9649
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
9650
|
+
arrays[i].fill(0);
|
|
9651
|
+
}
|
|
9652
|
+
}
|
|
9653
|
+
function createView(arr) {
|
|
9654
|
+
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
9655
|
+
}
|
|
9656
|
+
function rotr(word, shift) {
|
|
9657
|
+
return word << 32 - shift | word >>> shift;
|
|
9658
|
+
}
|
|
9659
|
+
var hasHexBuiltin = /* @__PURE__ */ (() => (
|
|
9660
|
+
// @ts-ignore
|
|
9661
|
+
typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
|
|
9662
|
+
))();
|
|
9663
|
+
var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
|
|
9664
|
+
function bytesToHex4(bytes) {
|
|
9665
|
+
abytes(bytes);
|
|
9666
|
+
if (hasHexBuiltin)
|
|
9667
|
+
return bytes.toHex();
|
|
9668
|
+
let hex = "";
|
|
9669
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
9670
|
+
hex += hexes[bytes[i]];
|
|
9671
|
+
}
|
|
9672
|
+
return hex;
|
|
9673
|
+
}
|
|
9674
|
+
var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
|
|
9675
|
+
function asciiToBase16(ch) {
|
|
9676
|
+
if (ch >= asciis._0 && ch <= asciis._9)
|
|
9677
|
+
return ch - asciis._0;
|
|
9678
|
+
if (ch >= asciis.A && ch <= asciis.F)
|
|
9679
|
+
return ch - (asciis.A - 10);
|
|
9680
|
+
if (ch >= asciis.a && ch <= asciis.f)
|
|
9681
|
+
return ch - (asciis.a - 10);
|
|
9682
|
+
return;
|
|
9683
|
+
}
|
|
9684
|
+
function hexToBytes2(hex) {
|
|
9685
|
+
if (typeof hex !== "string")
|
|
9686
|
+
throw new Error("hex string expected, got " + typeof hex);
|
|
9687
|
+
if (hasHexBuiltin)
|
|
9688
|
+
return Uint8Array.fromHex(hex);
|
|
9689
|
+
const hl = hex.length;
|
|
9690
|
+
const al = hl / 2;
|
|
9691
|
+
if (hl % 2)
|
|
9692
|
+
throw new Error("hex string expected, got unpadded hex of length " + hl);
|
|
9693
|
+
const array = new Uint8Array(al);
|
|
9694
|
+
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
9695
|
+
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
|
9696
|
+
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
|
9697
|
+
if (n1 === void 0 || n2 === void 0) {
|
|
9698
|
+
const char = hex[hi] + hex[hi + 1];
|
|
9699
|
+
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
9700
|
+
}
|
|
9701
|
+
array[ai] = n1 * 16 + n2;
|
|
9702
|
+
}
|
|
9703
|
+
return array;
|
|
9704
|
+
}
|
|
9705
|
+
function concatBytes(...arrays) {
|
|
9706
|
+
let sum = 0;
|
|
9707
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
9708
|
+
const a = arrays[i];
|
|
9709
|
+
abytes(a);
|
|
9710
|
+
sum += a.length;
|
|
9711
|
+
}
|
|
9712
|
+
const res = new Uint8Array(sum);
|
|
9713
|
+
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
9714
|
+
const a = arrays[i];
|
|
9715
|
+
res.set(a, pad);
|
|
9716
|
+
pad += a.length;
|
|
9717
|
+
}
|
|
9718
|
+
return res;
|
|
9719
|
+
}
|
|
9720
|
+
function createHasher(hashCons, info = {}) {
|
|
9721
|
+
const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
|
|
9722
|
+
const tmp = hashCons(void 0);
|
|
9723
|
+
hashC.outputLen = tmp.outputLen;
|
|
9724
|
+
hashC.blockLen = tmp.blockLen;
|
|
9725
|
+
hashC.create = (opts) => hashCons(opts);
|
|
9726
|
+
Object.assign(hashC, info);
|
|
9727
|
+
return Object.freeze(hashC);
|
|
9728
|
+
}
|
|
9729
|
+
function randomBytes2(bytesLength = 32) {
|
|
9730
|
+
const cr = typeof globalThis === "object" ? globalThis.crypto : null;
|
|
9731
|
+
if (typeof cr?.getRandomValues !== "function")
|
|
9732
|
+
throw new Error("crypto.getRandomValues must be defined");
|
|
9733
|
+
return cr.getRandomValues(new Uint8Array(bytesLength));
|
|
9734
|
+
}
|
|
9735
|
+
var oidNist = (suffix) => ({
|
|
9736
|
+
oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
|
|
9737
|
+
});
|
|
9738
|
+
|
|
9739
|
+
// node_modules/@noble/hashes/_md.js
|
|
9740
|
+
function Chi(a, b, c) {
|
|
9741
|
+
return a & b ^ ~a & c;
|
|
9742
|
+
}
|
|
9743
|
+
function Maj(a, b, c) {
|
|
9744
|
+
return a & b ^ a & c ^ b & c;
|
|
9745
|
+
}
|
|
9746
|
+
var HashMD = class {
|
|
9747
|
+
blockLen;
|
|
9748
|
+
outputLen;
|
|
9749
|
+
padOffset;
|
|
9750
|
+
isLE;
|
|
9751
|
+
// For partial updates less than block size
|
|
9752
|
+
buffer;
|
|
9753
|
+
view;
|
|
9754
|
+
finished = false;
|
|
9755
|
+
length = 0;
|
|
9756
|
+
pos = 0;
|
|
9757
|
+
destroyed = false;
|
|
9758
|
+
constructor(blockLen, outputLen, padOffset, isLE) {
|
|
9759
|
+
this.blockLen = blockLen;
|
|
9760
|
+
this.outputLen = outputLen;
|
|
9761
|
+
this.padOffset = padOffset;
|
|
9762
|
+
this.isLE = isLE;
|
|
9763
|
+
this.buffer = new Uint8Array(blockLen);
|
|
9764
|
+
this.view = createView(this.buffer);
|
|
9765
|
+
}
|
|
9766
|
+
update(data) {
|
|
9767
|
+
aexists(this);
|
|
9768
|
+
abytes(data);
|
|
9769
|
+
const { view, buffer, blockLen } = this;
|
|
9770
|
+
const len = data.length;
|
|
9771
|
+
for (let pos = 0; pos < len; ) {
|
|
9772
|
+
const take = Math.min(blockLen - this.pos, len - pos);
|
|
9773
|
+
if (take === blockLen) {
|
|
9774
|
+
const dataView = createView(data);
|
|
9775
|
+
for (; blockLen <= len - pos; pos += blockLen)
|
|
9776
|
+
this.process(dataView, pos);
|
|
9777
|
+
continue;
|
|
9778
|
+
}
|
|
9779
|
+
buffer.set(data.subarray(pos, pos + take), this.pos);
|
|
9780
|
+
this.pos += take;
|
|
9781
|
+
pos += take;
|
|
9782
|
+
if (this.pos === blockLen) {
|
|
9783
|
+
this.process(view, 0);
|
|
9784
|
+
this.pos = 0;
|
|
9785
|
+
}
|
|
9786
|
+
}
|
|
9787
|
+
this.length += data.length;
|
|
9788
|
+
this.roundClean();
|
|
9789
|
+
return this;
|
|
9790
|
+
}
|
|
9791
|
+
digestInto(out) {
|
|
9792
|
+
aexists(this);
|
|
9793
|
+
aoutput(out, this);
|
|
9794
|
+
this.finished = true;
|
|
9795
|
+
const { buffer, view, blockLen, isLE } = this;
|
|
9796
|
+
let { pos } = this;
|
|
9797
|
+
buffer[pos++] = 128;
|
|
9798
|
+
clean(this.buffer.subarray(pos));
|
|
9799
|
+
if (this.padOffset > blockLen - pos) {
|
|
9800
|
+
this.process(view, 0);
|
|
9801
|
+
pos = 0;
|
|
9802
|
+
}
|
|
9803
|
+
for (let i = pos; i < blockLen; i++)
|
|
9804
|
+
buffer[i] = 0;
|
|
9805
|
+
view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
|
|
9806
|
+
this.process(view, 0);
|
|
9807
|
+
const oview = createView(out);
|
|
9808
|
+
const len = this.outputLen;
|
|
9809
|
+
if (len % 4)
|
|
9810
|
+
throw new Error("_sha2: outputLen must be aligned to 32bit");
|
|
9811
|
+
const outLen = len / 4;
|
|
9812
|
+
const state = this.get();
|
|
9813
|
+
if (outLen > state.length)
|
|
9814
|
+
throw new Error("_sha2: outputLen bigger than state");
|
|
9815
|
+
for (let i = 0; i < outLen; i++)
|
|
9816
|
+
oview.setUint32(4 * i, state[i], isLE);
|
|
9817
|
+
}
|
|
9818
|
+
digest() {
|
|
9819
|
+
const { buffer, outputLen } = this;
|
|
9820
|
+
this.digestInto(buffer);
|
|
9821
|
+
const res = buffer.slice(0, outputLen);
|
|
9822
|
+
this.destroy();
|
|
9823
|
+
return res;
|
|
9824
|
+
}
|
|
9825
|
+
_cloneInto(to) {
|
|
9826
|
+
to ||= new this.constructor();
|
|
9827
|
+
to.set(...this.get());
|
|
9828
|
+
const { blockLen, buffer, length, finished, destroyed, pos } = this;
|
|
9829
|
+
to.destroyed = destroyed;
|
|
9830
|
+
to.finished = finished;
|
|
9831
|
+
to.length = length;
|
|
9832
|
+
to.pos = pos;
|
|
9833
|
+
if (length % blockLen)
|
|
9834
|
+
to.buffer.set(buffer);
|
|
9835
|
+
return to;
|
|
9836
|
+
}
|
|
9837
|
+
clone() {
|
|
9838
|
+
return this._cloneInto();
|
|
9839
|
+
}
|
|
9840
|
+
};
|
|
9841
|
+
var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
|
|
9842
|
+
1779033703,
|
|
9843
|
+
3144134277,
|
|
9844
|
+
1013904242,
|
|
9845
|
+
2773480762,
|
|
9846
|
+
1359893119,
|
|
9847
|
+
2600822924,
|
|
9848
|
+
528734635,
|
|
9849
|
+
1541459225
|
|
9850
|
+
]);
|
|
9851
|
+
|
|
9852
|
+
// node_modules/@noble/hashes/sha2.js
|
|
9853
|
+
var SHA256_K = /* @__PURE__ */ Uint32Array.from([
|
|
9854
|
+
1116352408,
|
|
9855
|
+
1899447441,
|
|
9856
|
+
3049323471,
|
|
9857
|
+
3921009573,
|
|
9858
|
+
961987163,
|
|
9859
|
+
1508970993,
|
|
9860
|
+
2453635748,
|
|
9861
|
+
2870763221,
|
|
9862
|
+
3624381080,
|
|
9863
|
+
310598401,
|
|
9864
|
+
607225278,
|
|
9865
|
+
1426881987,
|
|
9866
|
+
1925078388,
|
|
9867
|
+
2162078206,
|
|
9868
|
+
2614888103,
|
|
9869
|
+
3248222580,
|
|
9870
|
+
3835390401,
|
|
9871
|
+
4022224774,
|
|
9872
|
+
264347078,
|
|
9873
|
+
604807628,
|
|
9874
|
+
770255983,
|
|
9875
|
+
1249150122,
|
|
9876
|
+
1555081692,
|
|
9877
|
+
1996064986,
|
|
9878
|
+
2554220882,
|
|
9879
|
+
2821834349,
|
|
9880
|
+
2952996808,
|
|
9881
|
+
3210313671,
|
|
9882
|
+
3336571891,
|
|
9883
|
+
3584528711,
|
|
9884
|
+
113926993,
|
|
9885
|
+
338241895,
|
|
9886
|
+
666307205,
|
|
9887
|
+
773529912,
|
|
9888
|
+
1294757372,
|
|
9889
|
+
1396182291,
|
|
9890
|
+
1695183700,
|
|
9891
|
+
1986661051,
|
|
9892
|
+
2177026350,
|
|
9893
|
+
2456956037,
|
|
9894
|
+
2730485921,
|
|
9895
|
+
2820302411,
|
|
9896
|
+
3259730800,
|
|
9897
|
+
3345764771,
|
|
9898
|
+
3516065817,
|
|
9899
|
+
3600352804,
|
|
9900
|
+
4094571909,
|
|
9901
|
+
275423344,
|
|
9902
|
+
430227734,
|
|
9903
|
+
506948616,
|
|
9904
|
+
659060556,
|
|
9905
|
+
883997877,
|
|
9906
|
+
958139571,
|
|
9907
|
+
1322822218,
|
|
9908
|
+
1537002063,
|
|
9909
|
+
1747873779,
|
|
9910
|
+
1955562222,
|
|
9911
|
+
2024104815,
|
|
9912
|
+
2227730452,
|
|
9913
|
+
2361852424,
|
|
9914
|
+
2428436474,
|
|
9915
|
+
2756734187,
|
|
9916
|
+
3204031479,
|
|
9917
|
+
3329325298
|
|
9918
|
+
]);
|
|
9919
|
+
var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
|
|
9920
|
+
var SHA2_32B = class extends HashMD {
|
|
9921
|
+
constructor(outputLen) {
|
|
9922
|
+
super(64, outputLen, 8, false);
|
|
9923
|
+
}
|
|
9924
|
+
get() {
|
|
9925
|
+
const { A, B, C, D, E, F, G, H } = this;
|
|
9926
|
+
return [A, B, C, D, E, F, G, H];
|
|
9927
|
+
}
|
|
9928
|
+
// prettier-ignore
|
|
9929
|
+
set(A, B, C, D, E, F, G, H) {
|
|
9930
|
+
this.A = A | 0;
|
|
9931
|
+
this.B = B | 0;
|
|
9932
|
+
this.C = C | 0;
|
|
9933
|
+
this.D = D | 0;
|
|
9934
|
+
this.E = E | 0;
|
|
9935
|
+
this.F = F | 0;
|
|
9936
|
+
this.G = G | 0;
|
|
9937
|
+
this.H = H | 0;
|
|
9938
|
+
}
|
|
9939
|
+
process(view, offset) {
|
|
9940
|
+
for (let i = 0; i < 16; i++, offset += 4)
|
|
9941
|
+
SHA256_W[i] = view.getUint32(offset, false);
|
|
9942
|
+
for (let i = 16; i < 64; i++) {
|
|
9943
|
+
const W15 = SHA256_W[i - 15];
|
|
9944
|
+
const W2 = SHA256_W[i - 2];
|
|
9945
|
+
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
|
|
9946
|
+
const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
|
|
9947
|
+
SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
|
|
9948
|
+
}
|
|
9949
|
+
let { A, B, C, D, E, F, G, H } = this;
|
|
9950
|
+
for (let i = 0; i < 64; i++) {
|
|
9951
|
+
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
|
|
9952
|
+
const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
|
|
9953
|
+
const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
|
|
9954
|
+
const T2 = sigma0 + Maj(A, B, C) | 0;
|
|
9955
|
+
H = G;
|
|
9956
|
+
G = F;
|
|
9957
|
+
F = E;
|
|
9958
|
+
E = D + T1 | 0;
|
|
9959
|
+
D = C;
|
|
9960
|
+
C = B;
|
|
9961
|
+
B = A;
|
|
9962
|
+
A = T1 + T2 | 0;
|
|
9963
|
+
}
|
|
9964
|
+
A = A + this.A | 0;
|
|
9965
|
+
B = B + this.B | 0;
|
|
9966
|
+
C = C + this.C | 0;
|
|
9967
|
+
D = D + this.D | 0;
|
|
9968
|
+
E = E + this.E | 0;
|
|
9969
|
+
F = F + this.F | 0;
|
|
9970
|
+
G = G + this.G | 0;
|
|
9971
|
+
H = H + this.H | 0;
|
|
9972
|
+
this.set(A, B, C, D, E, F, G, H);
|
|
9973
|
+
}
|
|
9974
|
+
roundClean() {
|
|
9975
|
+
clean(SHA256_W);
|
|
9976
|
+
}
|
|
9977
|
+
destroy() {
|
|
9978
|
+
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
|
9979
|
+
clean(this.buffer);
|
|
9980
|
+
}
|
|
9981
|
+
};
|
|
9982
|
+
var _SHA256 = class extends SHA2_32B {
|
|
9983
|
+
// We cannot use array here since array allows indexing by variable
|
|
9984
|
+
// which means optimizer/compiler cannot use registers.
|
|
9985
|
+
A = SHA256_IV[0] | 0;
|
|
9986
|
+
B = SHA256_IV[1] | 0;
|
|
9987
|
+
C = SHA256_IV[2] | 0;
|
|
9988
|
+
D = SHA256_IV[3] | 0;
|
|
9989
|
+
E = SHA256_IV[4] | 0;
|
|
9990
|
+
F = SHA256_IV[5] | 0;
|
|
9991
|
+
G = SHA256_IV[6] | 0;
|
|
9992
|
+
H = SHA256_IV[7] | 0;
|
|
9993
|
+
constructor() {
|
|
9994
|
+
super(32);
|
|
9995
|
+
}
|
|
9996
|
+
};
|
|
9997
|
+
var sha2564 = /* @__PURE__ */ createHasher(
|
|
9998
|
+
() => new _SHA256(),
|
|
9999
|
+
/* @__PURE__ */ oidNist(1)
|
|
10000
|
+
);
|
|
10001
|
+
|
|
10002
|
+
// node_modules/@noble/curves/utils.js
|
|
10003
|
+
var _0n = /* @__PURE__ */ BigInt(0);
|
|
10004
|
+
var _1n = /* @__PURE__ */ BigInt(1);
|
|
10005
|
+
function abool(value, title = "") {
|
|
10006
|
+
if (typeof value !== "boolean") {
|
|
10007
|
+
const prefix = title && `"${title}" `;
|
|
10008
|
+
throw new Error(prefix + "expected boolean, got type=" + typeof value);
|
|
10009
|
+
}
|
|
10010
|
+
return value;
|
|
10011
|
+
}
|
|
10012
|
+
function abignumber(n) {
|
|
10013
|
+
if (typeof n === "bigint") {
|
|
10014
|
+
if (!isPosBig(n))
|
|
10015
|
+
throw new Error("positive bigint expected, got " + n);
|
|
10016
|
+
} else
|
|
10017
|
+
anumber(n);
|
|
10018
|
+
return n;
|
|
10019
|
+
}
|
|
10020
|
+
function numberToHexUnpadded(num) {
|
|
10021
|
+
const hex = abignumber(num).toString(16);
|
|
10022
|
+
return hex.length & 1 ? "0" + hex : hex;
|
|
10023
|
+
}
|
|
10024
|
+
function hexToNumber(hex) {
|
|
10025
|
+
if (typeof hex !== "string")
|
|
10026
|
+
throw new Error("hex string expected, got " + typeof hex);
|
|
10027
|
+
return hex === "" ? _0n : BigInt("0x" + hex);
|
|
10028
|
+
}
|
|
10029
|
+
function bytesToNumberBE(bytes) {
|
|
10030
|
+
return hexToNumber(bytesToHex4(bytes));
|
|
10031
|
+
}
|
|
10032
|
+
function bytesToNumberLE(bytes) {
|
|
10033
|
+
return hexToNumber(bytesToHex4(copyBytes(abytes(bytes)).reverse()));
|
|
10034
|
+
}
|
|
10035
|
+
function numberToBytesBE(n, len) {
|
|
10036
|
+
anumber(len);
|
|
10037
|
+
n = abignumber(n);
|
|
10038
|
+
const res = hexToBytes2(n.toString(16).padStart(len * 2, "0"));
|
|
10039
|
+
if (res.length !== len)
|
|
10040
|
+
throw new Error("number too large");
|
|
10041
|
+
return res;
|
|
10042
|
+
}
|
|
10043
|
+
function numberToBytesLE(n, len) {
|
|
10044
|
+
return numberToBytesBE(n, len).reverse();
|
|
10045
|
+
}
|
|
10046
|
+
function copyBytes(bytes) {
|
|
10047
|
+
return Uint8Array.from(bytes);
|
|
10048
|
+
}
|
|
10049
|
+
var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
|
|
10050
|
+
function inRange(n, min, max) {
|
|
10051
|
+
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
|
|
10052
|
+
}
|
|
10053
|
+
function aInRange(title, n, min, max) {
|
|
10054
|
+
if (!inRange(n, min, max))
|
|
10055
|
+
throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
|
|
10056
|
+
}
|
|
10057
|
+
function bitLen(n) {
|
|
10058
|
+
let len;
|
|
10059
|
+
for (len = 0; n > _0n; n >>= _1n, len += 1)
|
|
10060
|
+
;
|
|
10061
|
+
return len;
|
|
10062
|
+
}
|
|
10063
|
+
var bitMask = (n) => (_1n << BigInt(n)) - _1n;
|
|
10064
|
+
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
10065
|
+
anumber(hashLen, "hashLen");
|
|
10066
|
+
anumber(qByteLen, "qByteLen");
|
|
10067
|
+
if (typeof hmacFn !== "function")
|
|
10068
|
+
throw new Error("hmacFn must be a function");
|
|
10069
|
+
const u8n = (len) => new Uint8Array(len);
|
|
10070
|
+
const NULL = Uint8Array.of();
|
|
10071
|
+
const byte0 = Uint8Array.of(0);
|
|
10072
|
+
const byte1 = Uint8Array.of(1);
|
|
10073
|
+
const _maxDrbgIters = 1e3;
|
|
10074
|
+
let v = u8n(hashLen);
|
|
10075
|
+
let k = u8n(hashLen);
|
|
10076
|
+
let i = 0;
|
|
10077
|
+
const reset = () => {
|
|
10078
|
+
v.fill(1);
|
|
10079
|
+
k.fill(0);
|
|
10080
|
+
i = 0;
|
|
10081
|
+
};
|
|
10082
|
+
const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));
|
|
10083
|
+
const reseed = (seed = NULL) => {
|
|
10084
|
+
k = h(byte0, seed);
|
|
10085
|
+
v = h();
|
|
10086
|
+
if (seed.length === 0)
|
|
10087
|
+
return;
|
|
10088
|
+
k = h(byte1, seed);
|
|
10089
|
+
v = h();
|
|
10090
|
+
};
|
|
10091
|
+
const gen = () => {
|
|
10092
|
+
if (i++ >= _maxDrbgIters)
|
|
10093
|
+
throw new Error("drbg: tried max amount of iterations");
|
|
10094
|
+
let len = 0;
|
|
10095
|
+
const out = [];
|
|
10096
|
+
while (len < qByteLen) {
|
|
10097
|
+
v = h();
|
|
10098
|
+
const sl = v.slice();
|
|
10099
|
+
out.push(sl);
|
|
10100
|
+
len += v.length;
|
|
10101
|
+
}
|
|
10102
|
+
return concatBytes(...out);
|
|
10103
|
+
};
|
|
10104
|
+
const genUntil = (seed, pred) => {
|
|
10105
|
+
reset();
|
|
10106
|
+
reseed(seed);
|
|
10107
|
+
let res = void 0;
|
|
10108
|
+
while (!(res = pred(gen())))
|
|
10109
|
+
reseed();
|
|
10110
|
+
reset();
|
|
10111
|
+
return res;
|
|
10112
|
+
};
|
|
10113
|
+
return genUntil;
|
|
10114
|
+
}
|
|
10115
|
+
function validateObject(object, fields = {}, optFields = {}) {
|
|
10116
|
+
if (!object || typeof object !== "object")
|
|
10117
|
+
throw new Error("expected valid options object");
|
|
10118
|
+
function checkField(fieldName, expectedType, isOpt) {
|
|
10119
|
+
const val = object[fieldName];
|
|
10120
|
+
if (isOpt && val === void 0)
|
|
10121
|
+
return;
|
|
10122
|
+
const current = typeof val;
|
|
10123
|
+
if (current !== expectedType || val === null)
|
|
10124
|
+
throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
|
|
10125
|
+
}
|
|
10126
|
+
const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
|
|
10127
|
+
iter(fields, false);
|
|
10128
|
+
iter(optFields, true);
|
|
10129
|
+
}
|
|
10130
|
+
function memoized(fn) {
|
|
10131
|
+
const map = /* @__PURE__ */ new WeakMap();
|
|
10132
|
+
return (arg, ...args) => {
|
|
10133
|
+
const val = map.get(arg);
|
|
10134
|
+
if (val !== void 0)
|
|
10135
|
+
return val;
|
|
10136
|
+
const computed = fn(arg, ...args);
|
|
10137
|
+
map.set(arg, computed);
|
|
10138
|
+
return computed;
|
|
10139
|
+
};
|
|
10140
|
+
}
|
|
10141
|
+
|
|
10142
|
+
// node_modules/@noble/curves/abstract/modular.js
|
|
10143
|
+
var _0n2 = /* @__PURE__ */ BigInt(0);
|
|
10144
|
+
var _1n2 = /* @__PURE__ */ BigInt(1);
|
|
10145
|
+
var _2n = /* @__PURE__ */ BigInt(2);
|
|
10146
|
+
var _3n = /* @__PURE__ */ BigInt(3);
|
|
10147
|
+
var _4n = /* @__PURE__ */ BigInt(4);
|
|
10148
|
+
var _5n = /* @__PURE__ */ BigInt(5);
|
|
10149
|
+
var _7n = /* @__PURE__ */ BigInt(7);
|
|
10150
|
+
var _8n = /* @__PURE__ */ BigInt(8);
|
|
10151
|
+
var _9n = /* @__PURE__ */ BigInt(9);
|
|
10152
|
+
var _16n = /* @__PURE__ */ BigInt(16);
|
|
10153
|
+
function mod(a, b) {
|
|
10154
|
+
const result = a % b;
|
|
10155
|
+
return result >= _0n2 ? result : b + result;
|
|
10156
|
+
}
|
|
10157
|
+
function pow2(x, power, modulo) {
|
|
10158
|
+
let res = x;
|
|
10159
|
+
while (power-- > _0n2) {
|
|
10160
|
+
res *= res;
|
|
10161
|
+
res %= modulo;
|
|
10162
|
+
}
|
|
10163
|
+
return res;
|
|
10164
|
+
}
|
|
10165
|
+
function invert(number, modulo) {
|
|
10166
|
+
if (number === _0n2)
|
|
10167
|
+
throw new Error("invert: expected non-zero number");
|
|
10168
|
+
if (modulo <= _0n2)
|
|
10169
|
+
throw new Error("invert: expected positive modulus, got " + modulo);
|
|
10170
|
+
let a = mod(number, modulo);
|
|
10171
|
+
let b = modulo;
|
|
10172
|
+
let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
|
|
10173
|
+
while (a !== _0n2) {
|
|
10174
|
+
const q = b / a;
|
|
10175
|
+
const r = b % a;
|
|
10176
|
+
const m = x - u * q;
|
|
10177
|
+
const n = y - v * q;
|
|
10178
|
+
b = a, a = r, x = u, y = v, u = m, v = n;
|
|
10179
|
+
}
|
|
10180
|
+
const gcd = b;
|
|
10181
|
+
if (gcd !== _1n2)
|
|
10182
|
+
throw new Error("invert: does not exist");
|
|
10183
|
+
return mod(x, modulo);
|
|
10184
|
+
}
|
|
10185
|
+
function assertIsSquare(Fp, root, n) {
|
|
10186
|
+
if (!Fp.eql(Fp.sqr(root), n))
|
|
10187
|
+
throw new Error("Cannot find square root");
|
|
10188
|
+
}
|
|
10189
|
+
function sqrt3mod4(Fp, n) {
|
|
10190
|
+
const p1div4 = (Fp.ORDER + _1n2) / _4n;
|
|
10191
|
+
const root = Fp.pow(n, p1div4);
|
|
10192
|
+
assertIsSquare(Fp, root, n);
|
|
10193
|
+
return root;
|
|
10194
|
+
}
|
|
10195
|
+
function sqrt5mod8(Fp, n) {
|
|
10196
|
+
const p5div8 = (Fp.ORDER - _5n) / _8n;
|
|
10197
|
+
const n2 = Fp.mul(n, _2n);
|
|
10198
|
+
const v = Fp.pow(n2, p5div8);
|
|
10199
|
+
const nv = Fp.mul(n, v);
|
|
10200
|
+
const i = Fp.mul(Fp.mul(nv, _2n), v);
|
|
10201
|
+
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
|
|
10202
|
+
assertIsSquare(Fp, root, n);
|
|
10203
|
+
return root;
|
|
10204
|
+
}
|
|
10205
|
+
function sqrt9mod16(P) {
|
|
10206
|
+
const Fp_ = Field(P);
|
|
10207
|
+
const tn = tonelliShanks(P);
|
|
10208
|
+
const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
|
|
10209
|
+
const c2 = tn(Fp_, c1);
|
|
10210
|
+
const c3 = tn(Fp_, Fp_.neg(c1));
|
|
10211
|
+
const c4 = (P + _7n) / _16n;
|
|
10212
|
+
return (Fp, n) => {
|
|
10213
|
+
let tv1 = Fp.pow(n, c4);
|
|
10214
|
+
let tv2 = Fp.mul(tv1, c1);
|
|
10215
|
+
const tv3 = Fp.mul(tv1, c2);
|
|
10216
|
+
const tv4 = Fp.mul(tv1, c3);
|
|
10217
|
+
const e1 = Fp.eql(Fp.sqr(tv2), n);
|
|
10218
|
+
const e2 = Fp.eql(Fp.sqr(tv3), n);
|
|
10219
|
+
tv1 = Fp.cmov(tv1, tv2, e1);
|
|
10220
|
+
tv2 = Fp.cmov(tv4, tv3, e2);
|
|
10221
|
+
const e3 = Fp.eql(Fp.sqr(tv2), n);
|
|
10222
|
+
const root = Fp.cmov(tv1, tv2, e3);
|
|
10223
|
+
assertIsSquare(Fp, root, n);
|
|
10224
|
+
return root;
|
|
10225
|
+
};
|
|
10226
|
+
}
|
|
10227
|
+
function tonelliShanks(P) {
|
|
10228
|
+
if (P < _3n)
|
|
10229
|
+
throw new Error("sqrt is not defined for small field");
|
|
10230
|
+
let Q = P - _1n2;
|
|
10231
|
+
let S = 0;
|
|
10232
|
+
while (Q % _2n === _0n2) {
|
|
10233
|
+
Q /= _2n;
|
|
10234
|
+
S++;
|
|
10235
|
+
}
|
|
10236
|
+
let Z = _2n;
|
|
10237
|
+
const _Fp = Field(P);
|
|
10238
|
+
while (FpLegendre(_Fp, Z) === 1) {
|
|
10239
|
+
if (Z++ > 1e3)
|
|
10240
|
+
throw new Error("Cannot find square root: probably non-prime P");
|
|
10241
|
+
}
|
|
10242
|
+
if (S === 1)
|
|
10243
|
+
return sqrt3mod4;
|
|
10244
|
+
let cc = _Fp.pow(Z, Q);
|
|
10245
|
+
const Q1div2 = (Q + _1n2) / _2n;
|
|
10246
|
+
return function tonelliSlow(Fp, n) {
|
|
10247
|
+
if (Fp.is0(n))
|
|
10248
|
+
return n;
|
|
10249
|
+
if (FpLegendre(Fp, n) !== 1)
|
|
10250
|
+
throw new Error("Cannot find square root");
|
|
10251
|
+
let M = S;
|
|
10252
|
+
let c = Fp.mul(Fp.ONE, cc);
|
|
10253
|
+
let t = Fp.pow(n, Q);
|
|
10254
|
+
let R = Fp.pow(n, Q1div2);
|
|
10255
|
+
while (!Fp.eql(t, Fp.ONE)) {
|
|
10256
|
+
if (Fp.is0(t))
|
|
10257
|
+
return Fp.ZERO;
|
|
10258
|
+
let i = 1;
|
|
10259
|
+
let t_tmp = Fp.sqr(t);
|
|
10260
|
+
while (!Fp.eql(t_tmp, Fp.ONE)) {
|
|
10261
|
+
i++;
|
|
10262
|
+
t_tmp = Fp.sqr(t_tmp);
|
|
10263
|
+
if (i === M)
|
|
10264
|
+
throw new Error("Cannot find square root");
|
|
10265
|
+
}
|
|
10266
|
+
const exponent = _1n2 << BigInt(M - i - 1);
|
|
10267
|
+
const b = Fp.pow(c, exponent);
|
|
10268
|
+
M = i;
|
|
10269
|
+
c = Fp.sqr(b);
|
|
10270
|
+
t = Fp.mul(t, c);
|
|
10271
|
+
R = Fp.mul(R, b);
|
|
10272
|
+
}
|
|
10273
|
+
return R;
|
|
10274
|
+
};
|
|
10275
|
+
}
|
|
10276
|
+
function FpSqrt(P) {
|
|
10277
|
+
if (P % _4n === _3n)
|
|
10278
|
+
return sqrt3mod4;
|
|
10279
|
+
if (P % _8n === _5n)
|
|
10280
|
+
return sqrt5mod8;
|
|
10281
|
+
if (P % _16n === _9n)
|
|
10282
|
+
return sqrt9mod16(P);
|
|
10283
|
+
return tonelliShanks(P);
|
|
10284
|
+
}
|
|
10285
|
+
var FIELD_FIELDS = [
|
|
10286
|
+
"create",
|
|
10287
|
+
"isValid",
|
|
10288
|
+
"is0",
|
|
10289
|
+
"neg",
|
|
10290
|
+
"inv",
|
|
10291
|
+
"sqrt",
|
|
10292
|
+
"sqr",
|
|
10293
|
+
"eql",
|
|
10294
|
+
"add",
|
|
10295
|
+
"sub",
|
|
10296
|
+
"mul",
|
|
10297
|
+
"pow",
|
|
10298
|
+
"div",
|
|
10299
|
+
"addN",
|
|
10300
|
+
"subN",
|
|
10301
|
+
"mulN",
|
|
10302
|
+
"sqrN"
|
|
10303
|
+
];
|
|
10304
|
+
function validateField(field) {
|
|
10305
|
+
const initial = {
|
|
10306
|
+
ORDER: "bigint",
|
|
10307
|
+
BYTES: "number",
|
|
10308
|
+
BITS: "number"
|
|
10309
|
+
};
|
|
10310
|
+
const opts = FIELD_FIELDS.reduce((map, val) => {
|
|
10311
|
+
map[val] = "function";
|
|
10312
|
+
return map;
|
|
10313
|
+
}, initial);
|
|
10314
|
+
validateObject(field, opts);
|
|
10315
|
+
return field;
|
|
10316
|
+
}
|
|
10317
|
+
function FpPow(Fp, num, power) {
|
|
10318
|
+
if (power < _0n2)
|
|
10319
|
+
throw new Error("invalid exponent, negatives unsupported");
|
|
10320
|
+
if (power === _0n2)
|
|
10321
|
+
return Fp.ONE;
|
|
10322
|
+
if (power === _1n2)
|
|
10323
|
+
return num;
|
|
10324
|
+
let p = Fp.ONE;
|
|
10325
|
+
let d = num;
|
|
10326
|
+
while (power > _0n2) {
|
|
10327
|
+
if (power & _1n2)
|
|
10328
|
+
p = Fp.mul(p, d);
|
|
10329
|
+
d = Fp.sqr(d);
|
|
10330
|
+
power >>= _1n2;
|
|
10331
|
+
}
|
|
10332
|
+
return p;
|
|
10333
|
+
}
|
|
10334
|
+
function FpInvertBatch(Fp, nums, passZero = false) {
|
|
10335
|
+
const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
|
|
10336
|
+
const multipliedAcc = nums.reduce((acc, num, i) => {
|
|
10337
|
+
if (Fp.is0(num))
|
|
10338
|
+
return acc;
|
|
10339
|
+
inverted[i] = acc;
|
|
10340
|
+
return Fp.mul(acc, num);
|
|
10341
|
+
}, Fp.ONE);
|
|
10342
|
+
const invertedAcc = Fp.inv(multipliedAcc);
|
|
10343
|
+
nums.reduceRight((acc, num, i) => {
|
|
10344
|
+
if (Fp.is0(num))
|
|
10345
|
+
return acc;
|
|
10346
|
+
inverted[i] = Fp.mul(acc, inverted[i]);
|
|
10347
|
+
return Fp.mul(acc, num);
|
|
10348
|
+
}, invertedAcc);
|
|
10349
|
+
return inverted;
|
|
10350
|
+
}
|
|
10351
|
+
function FpLegendre(Fp, n) {
|
|
10352
|
+
const p1mod2 = (Fp.ORDER - _1n2) / _2n;
|
|
10353
|
+
const powered = Fp.pow(n, p1mod2);
|
|
10354
|
+
const yes = Fp.eql(powered, Fp.ONE);
|
|
10355
|
+
const zero = Fp.eql(powered, Fp.ZERO);
|
|
10356
|
+
const no = Fp.eql(powered, Fp.neg(Fp.ONE));
|
|
10357
|
+
if (!yes && !zero && !no)
|
|
10358
|
+
throw new Error("invalid Legendre symbol result");
|
|
10359
|
+
return yes ? 1 : zero ? 0 : -1;
|
|
10360
|
+
}
|
|
10361
|
+
function nLength(n, nBitLength) {
|
|
10362
|
+
if (nBitLength !== void 0)
|
|
10363
|
+
anumber(nBitLength);
|
|
10364
|
+
const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
|
|
10365
|
+
const nByteLength = Math.ceil(_nBitLength / 8);
|
|
10366
|
+
return { nBitLength: _nBitLength, nByteLength };
|
|
10367
|
+
}
|
|
10368
|
+
var _Field = class {
|
|
10369
|
+
ORDER;
|
|
10370
|
+
BITS;
|
|
10371
|
+
BYTES;
|
|
10372
|
+
isLE;
|
|
10373
|
+
ZERO = _0n2;
|
|
10374
|
+
ONE = _1n2;
|
|
10375
|
+
_lengths;
|
|
10376
|
+
_sqrt;
|
|
10377
|
+
// cached sqrt
|
|
10378
|
+
_mod;
|
|
10379
|
+
constructor(ORDER, opts = {}) {
|
|
10380
|
+
if (ORDER <= _0n2)
|
|
10381
|
+
throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
|
|
10382
|
+
let _nbitLength = void 0;
|
|
10383
|
+
this.isLE = false;
|
|
10384
|
+
if (opts != null && typeof opts === "object") {
|
|
10385
|
+
if (typeof opts.BITS === "number")
|
|
10386
|
+
_nbitLength = opts.BITS;
|
|
10387
|
+
if (typeof opts.sqrt === "function")
|
|
10388
|
+
this.sqrt = opts.sqrt;
|
|
10389
|
+
if (typeof opts.isLE === "boolean")
|
|
10390
|
+
this.isLE = opts.isLE;
|
|
10391
|
+
if (opts.allowedLengths)
|
|
10392
|
+
this._lengths = opts.allowedLengths?.slice();
|
|
10393
|
+
if (typeof opts.modFromBytes === "boolean")
|
|
10394
|
+
this._mod = opts.modFromBytes;
|
|
10395
|
+
}
|
|
10396
|
+
const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
|
|
10397
|
+
if (nByteLength > 2048)
|
|
10398
|
+
throw new Error("invalid field: expected ORDER of <= 2048 bytes");
|
|
10399
|
+
this.ORDER = ORDER;
|
|
10400
|
+
this.BITS = nBitLength;
|
|
10401
|
+
this.BYTES = nByteLength;
|
|
10402
|
+
this._sqrt = void 0;
|
|
10403
|
+
Object.preventExtensions(this);
|
|
10404
|
+
}
|
|
10405
|
+
create(num) {
|
|
10406
|
+
return mod(num, this.ORDER);
|
|
10407
|
+
}
|
|
10408
|
+
isValid(num) {
|
|
10409
|
+
if (typeof num !== "bigint")
|
|
10410
|
+
throw new Error("invalid field element: expected bigint, got " + typeof num);
|
|
10411
|
+
return _0n2 <= num && num < this.ORDER;
|
|
10412
|
+
}
|
|
10413
|
+
is0(num) {
|
|
10414
|
+
return num === _0n2;
|
|
10415
|
+
}
|
|
10416
|
+
// is valid and invertible
|
|
10417
|
+
isValidNot0(num) {
|
|
10418
|
+
return !this.is0(num) && this.isValid(num);
|
|
10419
|
+
}
|
|
10420
|
+
isOdd(num) {
|
|
10421
|
+
return (num & _1n2) === _1n2;
|
|
10422
|
+
}
|
|
10423
|
+
neg(num) {
|
|
10424
|
+
return mod(-num, this.ORDER);
|
|
10425
|
+
}
|
|
10426
|
+
eql(lhs, rhs) {
|
|
10427
|
+
return lhs === rhs;
|
|
10428
|
+
}
|
|
10429
|
+
sqr(num) {
|
|
10430
|
+
return mod(num * num, this.ORDER);
|
|
10431
|
+
}
|
|
10432
|
+
add(lhs, rhs) {
|
|
10433
|
+
return mod(lhs + rhs, this.ORDER);
|
|
10434
|
+
}
|
|
10435
|
+
sub(lhs, rhs) {
|
|
10436
|
+
return mod(lhs - rhs, this.ORDER);
|
|
10437
|
+
}
|
|
10438
|
+
mul(lhs, rhs) {
|
|
10439
|
+
return mod(lhs * rhs, this.ORDER);
|
|
10440
|
+
}
|
|
10441
|
+
pow(num, power) {
|
|
10442
|
+
return FpPow(this, num, power);
|
|
10443
|
+
}
|
|
10444
|
+
div(lhs, rhs) {
|
|
10445
|
+
return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
|
|
10446
|
+
}
|
|
10447
|
+
// Same as above, but doesn't normalize
|
|
10448
|
+
sqrN(num) {
|
|
10449
|
+
return num * num;
|
|
10450
|
+
}
|
|
10451
|
+
addN(lhs, rhs) {
|
|
10452
|
+
return lhs + rhs;
|
|
10453
|
+
}
|
|
10454
|
+
subN(lhs, rhs) {
|
|
10455
|
+
return lhs - rhs;
|
|
10456
|
+
}
|
|
10457
|
+
mulN(lhs, rhs) {
|
|
10458
|
+
return lhs * rhs;
|
|
10459
|
+
}
|
|
10460
|
+
inv(num) {
|
|
10461
|
+
return invert(num, this.ORDER);
|
|
10462
|
+
}
|
|
10463
|
+
sqrt(num) {
|
|
10464
|
+
if (!this._sqrt)
|
|
10465
|
+
this._sqrt = FpSqrt(this.ORDER);
|
|
10466
|
+
return this._sqrt(this, num);
|
|
10467
|
+
}
|
|
10468
|
+
toBytes(num) {
|
|
10469
|
+
return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
|
|
10470
|
+
}
|
|
10471
|
+
fromBytes(bytes, skipValidation = false) {
|
|
10472
|
+
abytes(bytes);
|
|
10473
|
+
const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
|
|
10474
|
+
if (allowedLengths) {
|
|
10475
|
+
if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
|
|
10476
|
+
throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
|
|
10477
|
+
}
|
|
10478
|
+
const padded = new Uint8Array(BYTES);
|
|
10479
|
+
padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
|
|
10480
|
+
bytes = padded;
|
|
10481
|
+
}
|
|
10482
|
+
if (bytes.length !== BYTES)
|
|
10483
|
+
throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
|
|
10484
|
+
let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
|
|
10485
|
+
if (modFromBytes)
|
|
10486
|
+
scalar = mod(scalar, ORDER);
|
|
10487
|
+
if (!skipValidation) {
|
|
10488
|
+
if (!this.isValid(scalar))
|
|
10489
|
+
throw new Error("invalid field element: outside of range 0..ORDER");
|
|
10490
|
+
}
|
|
10491
|
+
return scalar;
|
|
10492
|
+
}
|
|
10493
|
+
// TODO: we don't need it here, move out to separate fn
|
|
10494
|
+
invertBatch(lst) {
|
|
10495
|
+
return FpInvertBatch(this, lst);
|
|
10496
|
+
}
|
|
10497
|
+
// We can't move this out because Fp6, Fp12 implement it
|
|
10498
|
+
// and it's unclear what to return in there.
|
|
10499
|
+
cmov(a, b, condition) {
|
|
10500
|
+
return condition ? b : a;
|
|
10501
|
+
}
|
|
10502
|
+
};
|
|
10503
|
+
function Field(ORDER, opts = {}) {
|
|
10504
|
+
return new _Field(ORDER, opts);
|
|
10505
|
+
}
|
|
10506
|
+
function getFieldBytesLength(fieldOrder) {
|
|
10507
|
+
if (typeof fieldOrder !== "bigint")
|
|
10508
|
+
throw new Error("field order must be bigint");
|
|
10509
|
+
const bitLength = fieldOrder.toString(2).length;
|
|
10510
|
+
return Math.ceil(bitLength / 8);
|
|
10511
|
+
}
|
|
10512
|
+
function getMinHashLength(fieldOrder) {
|
|
10513
|
+
const length = getFieldBytesLength(fieldOrder);
|
|
10514
|
+
return length + Math.ceil(length / 2);
|
|
10515
|
+
}
|
|
10516
|
+
function mapHashToField(key, fieldOrder, isLE = false) {
|
|
10517
|
+
abytes(key);
|
|
10518
|
+
const len = key.length;
|
|
10519
|
+
const fieldLen = getFieldBytesLength(fieldOrder);
|
|
10520
|
+
const minLen = getMinHashLength(fieldOrder);
|
|
10521
|
+
if (len < 16 || len < minLen || len > 1024)
|
|
10522
|
+
throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
|
|
10523
|
+
const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
|
|
10524
|
+
const reduced = mod(num, fieldOrder - _1n2) + _1n2;
|
|
10525
|
+
return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
|
|
10526
|
+
}
|
|
10527
|
+
|
|
10528
|
+
// node_modules/@noble/curves/abstract/curve.js
|
|
10529
|
+
var _0n3 = /* @__PURE__ */ BigInt(0);
|
|
10530
|
+
var _1n3 = /* @__PURE__ */ BigInt(1);
|
|
10531
|
+
function negateCt(condition, item) {
|
|
10532
|
+
const neg = item.negate();
|
|
10533
|
+
return condition ? neg : item;
|
|
10534
|
+
}
|
|
10535
|
+
function normalizeZ(c, points) {
|
|
10536
|
+
const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
|
|
10537
|
+
return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
|
|
10538
|
+
}
|
|
10539
|
+
function validateW(W, bits) {
|
|
10540
|
+
if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
|
|
10541
|
+
throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
|
|
10542
|
+
}
|
|
10543
|
+
function calcWOpts(W, scalarBits) {
|
|
10544
|
+
validateW(W, scalarBits);
|
|
10545
|
+
const windows = Math.ceil(scalarBits / W) + 1;
|
|
10546
|
+
const windowSize = 2 ** (W - 1);
|
|
10547
|
+
const maxNumber = 2 ** W;
|
|
10548
|
+
const mask = bitMask(W);
|
|
10549
|
+
const shiftBy = BigInt(W);
|
|
10550
|
+
return { windows, windowSize, mask, maxNumber, shiftBy };
|
|
10551
|
+
}
|
|
10552
|
+
function calcOffsets(n, window, wOpts) {
|
|
10553
|
+
const { windowSize, mask, maxNumber, shiftBy } = wOpts;
|
|
10554
|
+
let wbits = Number(n & mask);
|
|
10555
|
+
let nextN = n >> shiftBy;
|
|
10556
|
+
if (wbits > windowSize) {
|
|
10557
|
+
wbits -= maxNumber;
|
|
10558
|
+
nextN += _1n3;
|
|
10559
|
+
}
|
|
10560
|
+
const offsetStart = window * windowSize;
|
|
10561
|
+
const offset = offsetStart + Math.abs(wbits) - 1;
|
|
10562
|
+
const isZero = wbits === 0;
|
|
10563
|
+
const isNeg = wbits < 0;
|
|
10564
|
+
const isNegF = window % 2 !== 0;
|
|
10565
|
+
const offsetF = offsetStart;
|
|
10566
|
+
return { nextN, offset, isZero, isNeg, isNegF, offsetF };
|
|
10567
|
+
}
|
|
10568
|
+
var pointPrecomputes = /* @__PURE__ */ new WeakMap();
|
|
10569
|
+
var pointWindowSizes = /* @__PURE__ */ new WeakMap();
|
|
10570
|
+
function getW(P) {
|
|
10571
|
+
return pointWindowSizes.get(P) || 1;
|
|
10572
|
+
}
|
|
10573
|
+
function assert0(n) {
|
|
10574
|
+
if (n !== _0n3)
|
|
10575
|
+
throw new Error("invalid wNAF");
|
|
10576
|
+
}
|
|
10577
|
+
var wNAF = class {
|
|
10578
|
+
BASE;
|
|
10579
|
+
ZERO;
|
|
10580
|
+
Fn;
|
|
10581
|
+
bits;
|
|
10582
|
+
// Parametrized with a given Point class (not individual point)
|
|
10583
|
+
constructor(Point, bits) {
|
|
10584
|
+
this.BASE = Point.BASE;
|
|
10585
|
+
this.ZERO = Point.ZERO;
|
|
10586
|
+
this.Fn = Point.Fn;
|
|
10587
|
+
this.bits = bits;
|
|
10588
|
+
}
|
|
10589
|
+
// non-const time multiplication ladder
|
|
10590
|
+
_unsafeLadder(elm, n, p = this.ZERO) {
|
|
10591
|
+
let d = elm;
|
|
10592
|
+
while (n > _0n3) {
|
|
10593
|
+
if (n & _1n3)
|
|
10594
|
+
p = p.add(d);
|
|
10595
|
+
d = d.double();
|
|
10596
|
+
n >>= _1n3;
|
|
10597
|
+
}
|
|
10598
|
+
return p;
|
|
10599
|
+
}
|
|
10600
|
+
/**
|
|
10601
|
+
* Creates a wNAF precomputation window. Used for caching.
|
|
10602
|
+
* Default window size is set by `utils.precompute()` and is equal to 8.
|
|
10603
|
+
* Number of precomputed points depends on the curve size:
|
|
10604
|
+
* 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
|
|
10605
|
+
* - 𝑊 is the window size
|
|
10606
|
+
* - 𝑛 is the bitlength of the curve order.
|
|
10607
|
+
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
|
|
10608
|
+
* @param point Point instance
|
|
10609
|
+
* @param W window size
|
|
10610
|
+
* @returns precomputed point tables flattened to a single array
|
|
10611
|
+
*/
|
|
10612
|
+
precomputeWindow(point, W) {
|
|
10613
|
+
const { windows, windowSize } = calcWOpts(W, this.bits);
|
|
10614
|
+
const points = [];
|
|
10615
|
+
let p = point;
|
|
10616
|
+
let base = p;
|
|
10617
|
+
for (let window = 0; window < windows; window++) {
|
|
10618
|
+
base = p;
|
|
10619
|
+
points.push(base);
|
|
10620
|
+
for (let i = 1; i < windowSize; i++) {
|
|
10621
|
+
base = base.add(p);
|
|
10622
|
+
points.push(base);
|
|
10623
|
+
}
|
|
10624
|
+
p = base.double();
|
|
10625
|
+
}
|
|
10626
|
+
return points;
|
|
10627
|
+
}
|
|
10628
|
+
/**
|
|
10629
|
+
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
|
|
10630
|
+
* More compact implementation:
|
|
10631
|
+
* https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
|
|
10632
|
+
* @returns real and fake (for const-time) points
|
|
10633
|
+
*/
|
|
10634
|
+
wNAF(W, precomputes, n) {
|
|
10635
|
+
if (!this.Fn.isValid(n))
|
|
10636
|
+
throw new Error("invalid scalar");
|
|
10637
|
+
let p = this.ZERO;
|
|
10638
|
+
let f = this.BASE;
|
|
10639
|
+
const wo = calcWOpts(W, this.bits);
|
|
10640
|
+
for (let window = 0; window < wo.windows; window++) {
|
|
10641
|
+
const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
|
|
10642
|
+
n = nextN;
|
|
10643
|
+
if (isZero) {
|
|
10644
|
+
f = f.add(negateCt(isNegF, precomputes[offsetF]));
|
|
10645
|
+
} else {
|
|
10646
|
+
p = p.add(negateCt(isNeg, precomputes[offset]));
|
|
10647
|
+
}
|
|
10648
|
+
}
|
|
10649
|
+
assert0(n);
|
|
10650
|
+
return { p, f };
|
|
10651
|
+
}
|
|
10652
|
+
/**
|
|
10653
|
+
* Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
|
|
10654
|
+
* @param acc accumulator point to add result of multiplication
|
|
10655
|
+
* @returns point
|
|
10656
|
+
*/
|
|
10657
|
+
wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
|
|
10658
|
+
const wo = calcWOpts(W, this.bits);
|
|
10659
|
+
for (let window = 0; window < wo.windows; window++) {
|
|
10660
|
+
if (n === _0n3)
|
|
10661
|
+
break;
|
|
10662
|
+
const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
|
|
10663
|
+
n = nextN;
|
|
10664
|
+
if (isZero) {
|
|
10665
|
+
continue;
|
|
10666
|
+
} else {
|
|
10667
|
+
const item = precomputes[offset];
|
|
10668
|
+
acc = acc.add(isNeg ? item.negate() : item);
|
|
10669
|
+
}
|
|
10670
|
+
}
|
|
10671
|
+
assert0(n);
|
|
10672
|
+
return acc;
|
|
10673
|
+
}
|
|
10674
|
+
getPrecomputes(W, point, transform) {
|
|
10675
|
+
let comp = pointPrecomputes.get(point);
|
|
10676
|
+
if (!comp) {
|
|
10677
|
+
comp = this.precomputeWindow(point, W);
|
|
10678
|
+
if (W !== 1) {
|
|
10679
|
+
if (typeof transform === "function")
|
|
10680
|
+
comp = transform(comp);
|
|
10681
|
+
pointPrecomputes.set(point, comp);
|
|
10682
|
+
}
|
|
10683
|
+
}
|
|
10684
|
+
return comp;
|
|
10685
|
+
}
|
|
10686
|
+
cached(point, scalar, transform) {
|
|
10687
|
+
const W = getW(point);
|
|
10688
|
+
return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
|
|
10689
|
+
}
|
|
10690
|
+
unsafe(point, scalar, transform, prev) {
|
|
10691
|
+
const W = getW(point);
|
|
10692
|
+
if (W === 1)
|
|
10693
|
+
return this._unsafeLadder(point, scalar, prev);
|
|
10694
|
+
return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
|
|
10695
|
+
}
|
|
10696
|
+
// We calculate precomputes for elliptic curve point multiplication
|
|
10697
|
+
// using windowed method. This specifies window size and
|
|
10698
|
+
// stores precomputed values. Usually only base point would be precomputed.
|
|
10699
|
+
createCache(P, W) {
|
|
10700
|
+
validateW(W, this.bits);
|
|
10701
|
+
pointWindowSizes.set(P, W);
|
|
10702
|
+
pointPrecomputes.delete(P);
|
|
10703
|
+
}
|
|
10704
|
+
hasCache(elm) {
|
|
10705
|
+
return getW(elm) !== 1;
|
|
10706
|
+
}
|
|
10707
|
+
};
|
|
10708
|
+
function mulEndoUnsafe(Point, point, k1, k2) {
|
|
10709
|
+
let acc = point;
|
|
10710
|
+
let p1 = Point.ZERO;
|
|
10711
|
+
let p2 = Point.ZERO;
|
|
10712
|
+
while (k1 > _0n3 || k2 > _0n3) {
|
|
10713
|
+
if (k1 & _1n3)
|
|
10714
|
+
p1 = p1.add(acc);
|
|
10715
|
+
if (k2 & _1n3)
|
|
10716
|
+
p2 = p2.add(acc);
|
|
10717
|
+
acc = acc.double();
|
|
10718
|
+
k1 >>= _1n3;
|
|
10719
|
+
k2 >>= _1n3;
|
|
10720
|
+
}
|
|
10721
|
+
return { p1, p2 };
|
|
10722
|
+
}
|
|
10723
|
+
function createField(order, field, isLE) {
|
|
10724
|
+
if (field) {
|
|
10725
|
+
if (field.ORDER !== order)
|
|
10726
|
+
throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
|
|
10727
|
+
validateField(field);
|
|
10728
|
+
return field;
|
|
10729
|
+
} else {
|
|
10730
|
+
return Field(order, { isLE });
|
|
10731
|
+
}
|
|
10732
|
+
}
|
|
10733
|
+
function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
|
|
10734
|
+
if (FpFnLE === void 0)
|
|
10735
|
+
FpFnLE = type === "edwards";
|
|
10736
|
+
if (!CURVE || typeof CURVE !== "object")
|
|
10737
|
+
throw new Error(`expected valid ${type} CURVE object`);
|
|
10738
|
+
for (const p of ["p", "n", "h"]) {
|
|
10739
|
+
const val = CURVE[p];
|
|
10740
|
+
if (!(typeof val === "bigint" && val > _0n3))
|
|
10741
|
+
throw new Error(`CURVE.${p} must be positive bigint`);
|
|
10742
|
+
}
|
|
10743
|
+
const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
|
|
10744
|
+
const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
|
|
10745
|
+
const _b = type === "weierstrass" ? "b" : "d";
|
|
10746
|
+
const params = ["Gx", "Gy", "a", _b];
|
|
10747
|
+
for (const p of params) {
|
|
10748
|
+
if (!Fp.isValid(CURVE[p]))
|
|
10749
|
+
throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
|
|
10750
|
+
}
|
|
10751
|
+
CURVE = Object.freeze(Object.assign({}, CURVE));
|
|
10752
|
+
return { CURVE, Fp, Fn };
|
|
10753
|
+
}
|
|
10754
|
+
function createKeygen(randomSecretKey, getPublicKey2) {
|
|
10755
|
+
return function keygen(seed) {
|
|
10756
|
+
const secretKey = randomSecretKey(seed);
|
|
10757
|
+
return { secretKey, publicKey: getPublicKey2(secretKey) };
|
|
10758
|
+
};
|
|
10759
|
+
}
|
|
10760
|
+
|
|
10761
|
+
// node_modules/@noble/hashes/hmac.js
|
|
10762
|
+
var _HMAC = class {
|
|
10763
|
+
oHash;
|
|
10764
|
+
iHash;
|
|
10765
|
+
blockLen;
|
|
10766
|
+
outputLen;
|
|
10767
|
+
finished = false;
|
|
10768
|
+
destroyed = false;
|
|
10769
|
+
constructor(hash, key) {
|
|
10770
|
+
ahash(hash);
|
|
10771
|
+
abytes(key, void 0, "key");
|
|
10772
|
+
this.iHash = hash.create();
|
|
10773
|
+
if (typeof this.iHash.update !== "function")
|
|
10774
|
+
throw new Error("Expected instance of class which extends utils.Hash");
|
|
10775
|
+
this.blockLen = this.iHash.blockLen;
|
|
10776
|
+
this.outputLen = this.iHash.outputLen;
|
|
10777
|
+
const blockLen = this.blockLen;
|
|
10778
|
+
const pad = new Uint8Array(blockLen);
|
|
10779
|
+
pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
|
|
10780
|
+
for (let i = 0; i < pad.length; i++)
|
|
10781
|
+
pad[i] ^= 54;
|
|
10782
|
+
this.iHash.update(pad);
|
|
10783
|
+
this.oHash = hash.create();
|
|
10784
|
+
for (let i = 0; i < pad.length; i++)
|
|
10785
|
+
pad[i] ^= 54 ^ 92;
|
|
10786
|
+
this.oHash.update(pad);
|
|
10787
|
+
clean(pad);
|
|
10788
|
+
}
|
|
10789
|
+
update(buf) {
|
|
10790
|
+
aexists(this);
|
|
10791
|
+
this.iHash.update(buf);
|
|
10792
|
+
return this;
|
|
10793
|
+
}
|
|
10794
|
+
digestInto(out) {
|
|
10795
|
+
aexists(this);
|
|
10796
|
+
abytes(out, this.outputLen, "output");
|
|
10797
|
+
this.finished = true;
|
|
10798
|
+
this.iHash.digestInto(out);
|
|
10799
|
+
this.oHash.update(out);
|
|
10800
|
+
this.oHash.digestInto(out);
|
|
10801
|
+
this.destroy();
|
|
10802
|
+
}
|
|
10803
|
+
digest() {
|
|
10804
|
+
const out = new Uint8Array(this.oHash.outputLen);
|
|
10805
|
+
this.digestInto(out);
|
|
10806
|
+
return out;
|
|
10807
|
+
}
|
|
10808
|
+
_cloneInto(to) {
|
|
10809
|
+
to ||= Object.create(Object.getPrototypeOf(this), {});
|
|
10810
|
+
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
|
|
10811
|
+
to = to;
|
|
10812
|
+
to.finished = finished;
|
|
10813
|
+
to.destroyed = destroyed;
|
|
10814
|
+
to.blockLen = blockLen;
|
|
10815
|
+
to.outputLen = outputLen;
|
|
10816
|
+
to.oHash = oHash._cloneInto(to.oHash);
|
|
10817
|
+
to.iHash = iHash._cloneInto(to.iHash);
|
|
10818
|
+
return to;
|
|
10819
|
+
}
|
|
10820
|
+
clone() {
|
|
10821
|
+
return this._cloneInto();
|
|
10822
|
+
}
|
|
10823
|
+
destroy() {
|
|
10824
|
+
this.destroyed = true;
|
|
10825
|
+
this.oHash.destroy();
|
|
10826
|
+
this.iHash.destroy();
|
|
10827
|
+
}
|
|
10828
|
+
};
|
|
10829
|
+
var hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();
|
|
10830
|
+
hmac.create = (hash, key) => new _HMAC(hash, key);
|
|
10831
|
+
|
|
10832
|
+
// node_modules/@noble/curves/abstract/weierstrass.js
|
|
10833
|
+
var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den;
|
|
10834
|
+
function _splitEndoScalar(k, basis, n) {
|
|
10835
|
+
const [[a1, b1], [a2, b2]] = basis;
|
|
10836
|
+
const c1 = divNearest(b2 * k, n);
|
|
10837
|
+
const c2 = divNearest(-b1 * k, n);
|
|
10838
|
+
let k1 = k - c1 * a1 - c2 * a2;
|
|
10839
|
+
let k2 = -c1 * b1 - c2 * b2;
|
|
10840
|
+
const k1neg = k1 < _0n4;
|
|
10841
|
+
const k2neg = k2 < _0n4;
|
|
10842
|
+
if (k1neg)
|
|
10843
|
+
k1 = -k1;
|
|
10844
|
+
if (k2neg)
|
|
10845
|
+
k2 = -k2;
|
|
10846
|
+
const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
|
|
10847
|
+
if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) {
|
|
10848
|
+
throw new Error("splitScalar (endomorphism): failed, k=" + k);
|
|
10849
|
+
}
|
|
10850
|
+
return { k1neg, k1, k2neg, k2 };
|
|
10851
|
+
}
|
|
10852
|
+
function validateSigFormat(format) {
|
|
10853
|
+
if (!["compact", "recovered", "der"].includes(format))
|
|
10854
|
+
throw new Error('Signature format must be "compact", "recovered", or "der"');
|
|
10855
|
+
return format;
|
|
10856
|
+
}
|
|
10857
|
+
function validateSigOpts(opts, def) {
|
|
10858
|
+
const optsn = {};
|
|
10859
|
+
for (let optName of Object.keys(def)) {
|
|
10860
|
+
optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
|
|
10861
|
+
}
|
|
10862
|
+
abool(optsn.lowS, "lowS");
|
|
10863
|
+
abool(optsn.prehash, "prehash");
|
|
10864
|
+
if (optsn.format !== void 0)
|
|
10865
|
+
validateSigFormat(optsn.format);
|
|
10866
|
+
return optsn;
|
|
10867
|
+
}
|
|
10868
|
+
var DERErr = class extends Error {
|
|
10869
|
+
constructor(m = "") {
|
|
10870
|
+
super(m);
|
|
10871
|
+
}
|
|
10872
|
+
};
|
|
10873
|
+
var DER = {
|
|
10874
|
+
// asn.1 DER encoding utils
|
|
10875
|
+
Err: DERErr,
|
|
10876
|
+
// Basic building block is TLV (Tag-Length-Value)
|
|
10877
|
+
_tlv: {
|
|
10878
|
+
encode: (tag, data) => {
|
|
10879
|
+
const { Err: E } = DER;
|
|
10880
|
+
if (tag < 0 || tag > 256)
|
|
10881
|
+
throw new E("tlv.encode: wrong tag");
|
|
10882
|
+
if (data.length & 1)
|
|
10883
|
+
throw new E("tlv.encode: unpadded data");
|
|
10884
|
+
const dataLen = data.length / 2;
|
|
10885
|
+
const len = numberToHexUnpadded(dataLen);
|
|
10886
|
+
if (len.length / 2 & 128)
|
|
10887
|
+
throw new E("tlv.encode: long form length too big");
|
|
10888
|
+
const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
|
|
10889
|
+
const t = numberToHexUnpadded(tag);
|
|
10890
|
+
return t + lenLen + len + data;
|
|
10891
|
+
},
|
|
10892
|
+
// v - value, l - left bytes (unparsed)
|
|
10893
|
+
decode(tag, data) {
|
|
10894
|
+
const { Err: E } = DER;
|
|
10895
|
+
let pos = 0;
|
|
10896
|
+
if (tag < 0 || tag > 256)
|
|
10897
|
+
throw new E("tlv.encode: wrong tag");
|
|
10898
|
+
if (data.length < 2 || data[pos++] !== tag)
|
|
10899
|
+
throw new E("tlv.decode: wrong tlv");
|
|
10900
|
+
const first = data[pos++];
|
|
10901
|
+
const isLong = !!(first & 128);
|
|
10902
|
+
let length = 0;
|
|
10903
|
+
if (!isLong)
|
|
10904
|
+
length = first;
|
|
10905
|
+
else {
|
|
10906
|
+
const lenLen = first & 127;
|
|
10907
|
+
if (!lenLen)
|
|
10908
|
+
throw new E("tlv.decode(long): indefinite length not supported");
|
|
10909
|
+
if (lenLen > 4)
|
|
10910
|
+
throw new E("tlv.decode(long): byte length is too big");
|
|
10911
|
+
const lengthBytes = data.subarray(pos, pos + lenLen);
|
|
10912
|
+
if (lengthBytes.length !== lenLen)
|
|
10913
|
+
throw new E("tlv.decode: length bytes not complete");
|
|
10914
|
+
if (lengthBytes[0] === 0)
|
|
10915
|
+
throw new E("tlv.decode(long): zero leftmost byte");
|
|
10916
|
+
for (const b of lengthBytes)
|
|
10917
|
+
length = length << 8 | b;
|
|
10918
|
+
pos += lenLen;
|
|
10919
|
+
if (length < 128)
|
|
10920
|
+
throw new E("tlv.decode(long): not minimal encoding");
|
|
10921
|
+
}
|
|
10922
|
+
const v = data.subarray(pos, pos + length);
|
|
10923
|
+
if (v.length !== length)
|
|
10924
|
+
throw new E("tlv.decode: wrong value length");
|
|
10925
|
+
return { v, l: data.subarray(pos + length) };
|
|
10926
|
+
}
|
|
10927
|
+
},
|
|
10928
|
+
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
|
|
10929
|
+
// since we always use positive integers here. It must always be empty:
|
|
10930
|
+
// - add zero byte if exists
|
|
10931
|
+
// - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
|
|
10932
|
+
_int: {
|
|
10933
|
+
encode(num) {
|
|
10934
|
+
const { Err: E } = DER;
|
|
10935
|
+
if (num < _0n4)
|
|
10936
|
+
throw new E("integer: negative integers are not allowed");
|
|
10937
|
+
let hex = numberToHexUnpadded(num);
|
|
10938
|
+
if (Number.parseInt(hex[0], 16) & 8)
|
|
10939
|
+
hex = "00" + hex;
|
|
10940
|
+
if (hex.length & 1)
|
|
10941
|
+
throw new E("unexpected DER parsing assertion: unpadded hex");
|
|
10942
|
+
return hex;
|
|
10943
|
+
},
|
|
10944
|
+
decode(data) {
|
|
10945
|
+
const { Err: E } = DER;
|
|
10946
|
+
if (data[0] & 128)
|
|
10947
|
+
throw new E("invalid signature integer: negative");
|
|
10948
|
+
if (data[0] === 0 && !(data[1] & 128))
|
|
10949
|
+
throw new E("invalid signature integer: unnecessary leading zero");
|
|
10950
|
+
return bytesToNumberBE(data);
|
|
10951
|
+
}
|
|
10952
|
+
},
|
|
10953
|
+
toSig(bytes) {
|
|
10954
|
+
const { Err: E, _int: int, _tlv: tlv } = DER;
|
|
10955
|
+
const data = abytes(bytes, void 0, "signature");
|
|
10956
|
+
const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
|
|
10957
|
+
if (seqLeftBytes.length)
|
|
10958
|
+
throw new E("invalid signature: left bytes after parsing");
|
|
10959
|
+
const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
|
|
10960
|
+
const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
|
|
10961
|
+
if (sLeftBytes.length)
|
|
10962
|
+
throw new E("invalid signature: left bytes after parsing");
|
|
10963
|
+
return { r: int.decode(rBytes), s: int.decode(sBytes) };
|
|
10964
|
+
},
|
|
10965
|
+
hexFromSig(sig) {
|
|
10966
|
+
const { _tlv: tlv, _int: int } = DER;
|
|
10967
|
+
const rs = tlv.encode(2, int.encode(sig.r));
|
|
10968
|
+
const ss = tlv.encode(2, int.encode(sig.s));
|
|
10969
|
+
const seq = rs + ss;
|
|
10970
|
+
return tlv.encode(48, seq);
|
|
10971
|
+
}
|
|
10972
|
+
};
|
|
10973
|
+
var _0n4 = BigInt(0);
|
|
10974
|
+
var _1n4 = BigInt(1);
|
|
10975
|
+
var _2n2 = BigInt(2);
|
|
10976
|
+
var _3n2 = BigInt(3);
|
|
10977
|
+
var _4n2 = BigInt(4);
|
|
10978
|
+
function weierstrass(params, extraOpts = {}) {
|
|
10979
|
+
const validated = createCurveFields("weierstrass", params, extraOpts);
|
|
10980
|
+
const { Fp, Fn } = validated;
|
|
10981
|
+
let CURVE = validated.CURVE;
|
|
10982
|
+
const { h: cofactor, n: CURVE_ORDER2 } = CURVE;
|
|
10983
|
+
validateObject(extraOpts, {}, {
|
|
10984
|
+
allowInfinityPoint: "boolean",
|
|
10985
|
+
clearCofactor: "function",
|
|
10986
|
+
isTorsionFree: "function",
|
|
10987
|
+
fromBytes: "function",
|
|
10988
|
+
toBytes: "function",
|
|
10989
|
+
endo: "object"
|
|
10990
|
+
});
|
|
10991
|
+
const { endo } = extraOpts;
|
|
10992
|
+
if (endo) {
|
|
10993
|
+
if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
|
|
10994
|
+
throw new Error('invalid endo: expected "beta": bigint and "basises": array');
|
|
10995
|
+
}
|
|
10996
|
+
}
|
|
10997
|
+
const lengths = getWLengths(Fp, Fn);
|
|
10998
|
+
function assertCompressionIsSupported() {
|
|
10999
|
+
if (!Fp.isOdd)
|
|
11000
|
+
throw new Error("compression is not supported: Field does not have .isOdd()");
|
|
11001
|
+
}
|
|
11002
|
+
function pointToBytes(_c, point, isCompressed) {
|
|
11003
|
+
const { x, y } = point.toAffine();
|
|
11004
|
+
const bx = Fp.toBytes(x);
|
|
11005
|
+
abool(isCompressed, "isCompressed");
|
|
11006
|
+
if (isCompressed) {
|
|
11007
|
+
assertCompressionIsSupported();
|
|
11008
|
+
const hasEvenY = !Fp.isOdd(y);
|
|
11009
|
+
return concatBytes(pprefix(hasEvenY), bx);
|
|
11010
|
+
} else {
|
|
11011
|
+
return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
|
|
11012
|
+
}
|
|
11013
|
+
}
|
|
11014
|
+
function pointFromBytes(bytes) {
|
|
11015
|
+
abytes(bytes, void 0, "Point");
|
|
11016
|
+
const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
|
|
11017
|
+
const length = bytes.length;
|
|
11018
|
+
const head = bytes[0];
|
|
11019
|
+
const tail = bytes.subarray(1);
|
|
11020
|
+
if (length === comp && (head === 2 || head === 3)) {
|
|
11021
|
+
const x = Fp.fromBytes(tail);
|
|
11022
|
+
if (!Fp.isValid(x))
|
|
11023
|
+
throw new Error("bad point: is not on curve, wrong x");
|
|
11024
|
+
const y2 = weierstrassEquation(x);
|
|
11025
|
+
let y;
|
|
11026
|
+
try {
|
|
11027
|
+
y = Fp.sqrt(y2);
|
|
11028
|
+
} catch (sqrtError) {
|
|
11029
|
+
const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
|
|
11030
|
+
throw new Error("bad point: is not on curve, sqrt error" + err);
|
|
11031
|
+
}
|
|
11032
|
+
assertCompressionIsSupported();
|
|
11033
|
+
const evenY = Fp.isOdd(y);
|
|
11034
|
+
const evenH = (head & 1) === 1;
|
|
11035
|
+
if (evenH !== evenY)
|
|
11036
|
+
y = Fp.neg(y);
|
|
11037
|
+
return { x, y };
|
|
11038
|
+
} else if (length === uncomp && head === 4) {
|
|
11039
|
+
const L = Fp.BYTES;
|
|
11040
|
+
const x = Fp.fromBytes(tail.subarray(0, L));
|
|
11041
|
+
const y = Fp.fromBytes(tail.subarray(L, L * 2));
|
|
11042
|
+
if (!isValidXY(x, y))
|
|
11043
|
+
throw new Error("bad point: is not on curve");
|
|
11044
|
+
return { x, y };
|
|
11045
|
+
} else {
|
|
11046
|
+
throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
|
|
11047
|
+
}
|
|
11048
|
+
}
|
|
11049
|
+
const encodePoint = extraOpts.toBytes || pointToBytes;
|
|
11050
|
+
const decodePoint = extraOpts.fromBytes || pointFromBytes;
|
|
11051
|
+
function weierstrassEquation(x) {
|
|
11052
|
+
const x2 = Fp.sqr(x);
|
|
11053
|
+
const x3 = Fp.mul(x2, x);
|
|
11054
|
+
return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
|
|
11055
|
+
}
|
|
11056
|
+
function isValidXY(x, y) {
|
|
11057
|
+
const left = Fp.sqr(y);
|
|
11058
|
+
const right = weierstrassEquation(x);
|
|
11059
|
+
return Fp.eql(left, right);
|
|
11060
|
+
}
|
|
11061
|
+
if (!isValidXY(CURVE.Gx, CURVE.Gy))
|
|
11062
|
+
throw new Error("bad curve params: generator point");
|
|
11063
|
+
const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
|
|
11064
|
+
const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
|
|
11065
|
+
if (Fp.is0(Fp.add(_4a3, _27b2)))
|
|
11066
|
+
throw new Error("bad curve params: a or b");
|
|
11067
|
+
function acoord(title, n, banZero = false) {
|
|
11068
|
+
if (!Fp.isValid(n) || banZero && Fp.is0(n))
|
|
11069
|
+
throw new Error(`bad point coordinate ${title}`);
|
|
11070
|
+
return n;
|
|
11071
|
+
}
|
|
11072
|
+
function aprjpoint(other) {
|
|
11073
|
+
if (!(other instanceof Point))
|
|
11074
|
+
throw new Error("Weierstrass Point expected");
|
|
11075
|
+
}
|
|
11076
|
+
function splitEndoScalarN(k) {
|
|
11077
|
+
if (!endo || !endo.basises)
|
|
11078
|
+
throw new Error("no endo");
|
|
11079
|
+
return _splitEndoScalar(k, endo.basises, Fn.ORDER);
|
|
11080
|
+
}
|
|
11081
|
+
const toAffineMemo = memoized((p, iz) => {
|
|
11082
|
+
const { X, Y, Z } = p;
|
|
11083
|
+
if (Fp.eql(Z, Fp.ONE))
|
|
11084
|
+
return { x: X, y: Y };
|
|
11085
|
+
const is0 = p.is0();
|
|
11086
|
+
if (iz == null)
|
|
11087
|
+
iz = is0 ? Fp.ONE : Fp.inv(Z);
|
|
11088
|
+
const x = Fp.mul(X, iz);
|
|
11089
|
+
const y = Fp.mul(Y, iz);
|
|
11090
|
+
const zz = Fp.mul(Z, iz);
|
|
11091
|
+
if (is0)
|
|
11092
|
+
return { x: Fp.ZERO, y: Fp.ZERO };
|
|
11093
|
+
if (!Fp.eql(zz, Fp.ONE))
|
|
11094
|
+
throw new Error("invZ was invalid");
|
|
11095
|
+
return { x, y };
|
|
11096
|
+
});
|
|
11097
|
+
const assertValidMemo = memoized((p) => {
|
|
11098
|
+
if (p.is0()) {
|
|
11099
|
+
if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
|
|
11100
|
+
return;
|
|
11101
|
+
throw new Error("bad point: ZERO");
|
|
11102
|
+
}
|
|
11103
|
+
const { x, y } = p.toAffine();
|
|
11104
|
+
if (!Fp.isValid(x) || !Fp.isValid(y))
|
|
11105
|
+
throw new Error("bad point: x or y not field elements");
|
|
11106
|
+
if (!isValidXY(x, y))
|
|
11107
|
+
throw new Error("bad point: equation left != right");
|
|
11108
|
+
if (!p.isTorsionFree())
|
|
11109
|
+
throw new Error("bad point: not in prime-order subgroup");
|
|
11110
|
+
return true;
|
|
11111
|
+
});
|
|
11112
|
+
function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
|
|
11113
|
+
k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
|
|
11114
|
+
k1p = negateCt(k1neg, k1p);
|
|
11115
|
+
k2p = negateCt(k2neg, k2p);
|
|
11116
|
+
return k1p.add(k2p);
|
|
11117
|
+
}
|
|
11118
|
+
class Point {
|
|
11119
|
+
// base / generator point
|
|
11120
|
+
static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
|
|
11121
|
+
// zero / infinity / identity point
|
|
11122
|
+
static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
|
|
11123
|
+
// 0, 1, 0
|
|
11124
|
+
// math field
|
|
11125
|
+
static Fp = Fp;
|
|
11126
|
+
// scalar field
|
|
11127
|
+
static Fn = Fn;
|
|
11128
|
+
X;
|
|
11129
|
+
Y;
|
|
11130
|
+
Z;
|
|
11131
|
+
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
11132
|
+
constructor(X, Y, Z) {
|
|
11133
|
+
this.X = acoord("x", X);
|
|
11134
|
+
this.Y = acoord("y", Y, true);
|
|
11135
|
+
this.Z = acoord("z", Z);
|
|
11136
|
+
Object.freeze(this);
|
|
11137
|
+
}
|
|
11138
|
+
static CURVE() {
|
|
11139
|
+
return CURVE;
|
|
11140
|
+
}
|
|
11141
|
+
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
11142
|
+
static fromAffine(p) {
|
|
11143
|
+
const { x, y } = p || {};
|
|
11144
|
+
if (!p || !Fp.isValid(x) || !Fp.isValid(y))
|
|
11145
|
+
throw new Error("invalid affine point");
|
|
11146
|
+
if (p instanceof Point)
|
|
11147
|
+
throw new Error("projective point not allowed");
|
|
11148
|
+
if (Fp.is0(x) && Fp.is0(y))
|
|
11149
|
+
return Point.ZERO;
|
|
11150
|
+
return new Point(x, y, Fp.ONE);
|
|
11151
|
+
}
|
|
11152
|
+
static fromBytes(bytes) {
|
|
11153
|
+
const P = Point.fromAffine(decodePoint(abytes(bytes, void 0, "point")));
|
|
11154
|
+
P.assertValidity();
|
|
11155
|
+
return P;
|
|
11156
|
+
}
|
|
11157
|
+
static fromHex(hex) {
|
|
11158
|
+
return Point.fromBytes(hexToBytes2(hex));
|
|
11159
|
+
}
|
|
11160
|
+
get x() {
|
|
11161
|
+
return this.toAffine().x;
|
|
11162
|
+
}
|
|
11163
|
+
get y() {
|
|
11164
|
+
return this.toAffine().y;
|
|
11165
|
+
}
|
|
11166
|
+
/**
|
|
11167
|
+
*
|
|
11168
|
+
* @param windowSize
|
|
11169
|
+
* @param isLazy true will defer table computation until the first multiplication
|
|
11170
|
+
* @returns
|
|
11171
|
+
*/
|
|
11172
|
+
precompute(windowSize = 8, isLazy = true) {
|
|
11173
|
+
wnaf.createCache(this, windowSize);
|
|
11174
|
+
if (!isLazy)
|
|
11175
|
+
this.multiply(_3n2);
|
|
11176
|
+
return this;
|
|
11177
|
+
}
|
|
11178
|
+
// TODO: return `this`
|
|
11179
|
+
/** A point on curve is valid if it conforms to equation. */
|
|
11180
|
+
assertValidity() {
|
|
11181
|
+
assertValidMemo(this);
|
|
11182
|
+
}
|
|
11183
|
+
hasEvenY() {
|
|
11184
|
+
const { y } = this.toAffine();
|
|
11185
|
+
if (!Fp.isOdd)
|
|
11186
|
+
throw new Error("Field doesn't support isOdd");
|
|
11187
|
+
return !Fp.isOdd(y);
|
|
11188
|
+
}
|
|
11189
|
+
/** Compare one point to another. */
|
|
11190
|
+
equals(other) {
|
|
11191
|
+
aprjpoint(other);
|
|
11192
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
11193
|
+
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
11194
|
+
const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
|
|
11195
|
+
const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
|
|
11196
|
+
return U1 && U2;
|
|
11197
|
+
}
|
|
11198
|
+
/** Flips point to one corresponding to (x, -y) in Affine coordinates. */
|
|
11199
|
+
negate() {
|
|
11200
|
+
return new Point(this.X, Fp.neg(this.Y), this.Z);
|
|
11201
|
+
}
|
|
11202
|
+
// Renes-Costello-Batina exception-free doubling formula.
|
|
11203
|
+
// There is 30% faster Jacobian formula, but it is not complete.
|
|
11204
|
+
// https://eprint.iacr.org/2015/1060, algorithm 3
|
|
11205
|
+
// Cost: 8M + 3S + 3*a + 2*b3 + 15add.
|
|
11206
|
+
double() {
|
|
11207
|
+
const { a, b } = CURVE;
|
|
11208
|
+
const b3 = Fp.mul(b, _3n2);
|
|
11209
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
11210
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
|
|
11211
|
+
let t0 = Fp.mul(X1, X1);
|
|
11212
|
+
let t1 = Fp.mul(Y1, Y1);
|
|
11213
|
+
let t2 = Fp.mul(Z1, Z1);
|
|
11214
|
+
let t3 = Fp.mul(X1, Y1);
|
|
11215
|
+
t3 = Fp.add(t3, t3);
|
|
11216
|
+
Z3 = Fp.mul(X1, Z1);
|
|
11217
|
+
Z3 = Fp.add(Z3, Z3);
|
|
11218
|
+
X3 = Fp.mul(a, Z3);
|
|
11219
|
+
Y3 = Fp.mul(b3, t2);
|
|
11220
|
+
Y3 = Fp.add(X3, Y3);
|
|
11221
|
+
X3 = Fp.sub(t1, Y3);
|
|
11222
|
+
Y3 = Fp.add(t1, Y3);
|
|
11223
|
+
Y3 = Fp.mul(X3, Y3);
|
|
11224
|
+
X3 = Fp.mul(t3, X3);
|
|
11225
|
+
Z3 = Fp.mul(b3, Z3);
|
|
11226
|
+
t2 = Fp.mul(a, t2);
|
|
11227
|
+
t3 = Fp.sub(t0, t2);
|
|
11228
|
+
t3 = Fp.mul(a, t3);
|
|
11229
|
+
t3 = Fp.add(t3, Z3);
|
|
11230
|
+
Z3 = Fp.add(t0, t0);
|
|
11231
|
+
t0 = Fp.add(Z3, t0);
|
|
11232
|
+
t0 = Fp.add(t0, t2);
|
|
11233
|
+
t0 = Fp.mul(t0, t3);
|
|
11234
|
+
Y3 = Fp.add(Y3, t0);
|
|
11235
|
+
t2 = Fp.mul(Y1, Z1);
|
|
11236
|
+
t2 = Fp.add(t2, t2);
|
|
11237
|
+
t0 = Fp.mul(t2, t3);
|
|
11238
|
+
X3 = Fp.sub(X3, t0);
|
|
11239
|
+
Z3 = Fp.mul(t2, t1);
|
|
11240
|
+
Z3 = Fp.add(Z3, Z3);
|
|
11241
|
+
Z3 = Fp.add(Z3, Z3);
|
|
11242
|
+
return new Point(X3, Y3, Z3);
|
|
11243
|
+
}
|
|
11244
|
+
// Renes-Costello-Batina exception-free addition formula.
|
|
11245
|
+
// There is 30% faster Jacobian formula, but it is not complete.
|
|
11246
|
+
// https://eprint.iacr.org/2015/1060, algorithm 1
|
|
11247
|
+
// Cost: 12M + 0S + 3*a + 3*b3 + 23add.
|
|
11248
|
+
add(other) {
|
|
11249
|
+
aprjpoint(other);
|
|
11250
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
11251
|
+
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
11252
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
|
|
11253
|
+
const a = CURVE.a;
|
|
11254
|
+
const b3 = Fp.mul(CURVE.b, _3n2);
|
|
11255
|
+
let t0 = Fp.mul(X1, X2);
|
|
11256
|
+
let t1 = Fp.mul(Y1, Y2);
|
|
11257
|
+
let t2 = Fp.mul(Z1, Z2);
|
|
11258
|
+
let t3 = Fp.add(X1, Y1);
|
|
11259
|
+
let t4 = Fp.add(X2, Y2);
|
|
11260
|
+
t3 = Fp.mul(t3, t4);
|
|
11261
|
+
t4 = Fp.add(t0, t1);
|
|
11262
|
+
t3 = Fp.sub(t3, t4);
|
|
11263
|
+
t4 = Fp.add(X1, Z1);
|
|
11264
|
+
let t5 = Fp.add(X2, Z2);
|
|
11265
|
+
t4 = Fp.mul(t4, t5);
|
|
11266
|
+
t5 = Fp.add(t0, t2);
|
|
11267
|
+
t4 = Fp.sub(t4, t5);
|
|
11268
|
+
t5 = Fp.add(Y1, Z1);
|
|
11269
|
+
X3 = Fp.add(Y2, Z2);
|
|
11270
|
+
t5 = Fp.mul(t5, X3);
|
|
11271
|
+
X3 = Fp.add(t1, t2);
|
|
11272
|
+
t5 = Fp.sub(t5, X3);
|
|
11273
|
+
Z3 = Fp.mul(a, t4);
|
|
11274
|
+
X3 = Fp.mul(b3, t2);
|
|
11275
|
+
Z3 = Fp.add(X3, Z3);
|
|
11276
|
+
X3 = Fp.sub(t1, Z3);
|
|
11277
|
+
Z3 = Fp.add(t1, Z3);
|
|
11278
|
+
Y3 = Fp.mul(X3, Z3);
|
|
11279
|
+
t1 = Fp.add(t0, t0);
|
|
11280
|
+
t1 = Fp.add(t1, t0);
|
|
11281
|
+
t2 = Fp.mul(a, t2);
|
|
11282
|
+
t4 = Fp.mul(b3, t4);
|
|
11283
|
+
t1 = Fp.add(t1, t2);
|
|
11284
|
+
t2 = Fp.sub(t0, t2);
|
|
11285
|
+
t2 = Fp.mul(a, t2);
|
|
11286
|
+
t4 = Fp.add(t4, t2);
|
|
11287
|
+
t0 = Fp.mul(t1, t4);
|
|
11288
|
+
Y3 = Fp.add(Y3, t0);
|
|
11289
|
+
t0 = Fp.mul(t5, t4);
|
|
11290
|
+
X3 = Fp.mul(t3, X3);
|
|
11291
|
+
X3 = Fp.sub(X3, t0);
|
|
11292
|
+
t0 = Fp.mul(t3, t1);
|
|
11293
|
+
Z3 = Fp.mul(t5, Z3);
|
|
11294
|
+
Z3 = Fp.add(Z3, t0);
|
|
11295
|
+
return new Point(X3, Y3, Z3);
|
|
11296
|
+
}
|
|
11297
|
+
subtract(other) {
|
|
11298
|
+
return this.add(other.negate());
|
|
11299
|
+
}
|
|
11300
|
+
is0() {
|
|
11301
|
+
return this.equals(Point.ZERO);
|
|
11302
|
+
}
|
|
11303
|
+
/**
|
|
11304
|
+
* Constant time multiplication.
|
|
11305
|
+
* Uses wNAF method. Windowed method may be 10% faster,
|
|
11306
|
+
* but takes 2x longer to generate and consumes 2x memory.
|
|
11307
|
+
* Uses precomputes when available.
|
|
11308
|
+
* Uses endomorphism for Koblitz curves.
|
|
11309
|
+
* @param scalar by which the point would be multiplied
|
|
11310
|
+
* @returns New point
|
|
11311
|
+
*/
|
|
11312
|
+
multiply(scalar) {
|
|
11313
|
+
const { endo: endo2 } = extraOpts;
|
|
11314
|
+
if (!Fn.isValidNot0(scalar))
|
|
11315
|
+
throw new Error("invalid scalar: out of range");
|
|
11316
|
+
let point, fake;
|
|
11317
|
+
const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
|
|
11318
|
+
if (endo2) {
|
|
11319
|
+
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
|
|
11320
|
+
const { p: k1p, f: k1f } = mul(k1);
|
|
11321
|
+
const { p: k2p, f: k2f } = mul(k2);
|
|
11322
|
+
fake = k1f.add(k2f);
|
|
11323
|
+
point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
|
|
11324
|
+
} else {
|
|
11325
|
+
const { p, f } = mul(scalar);
|
|
11326
|
+
point = p;
|
|
11327
|
+
fake = f;
|
|
11328
|
+
}
|
|
11329
|
+
return normalizeZ(Point, [point, fake])[0];
|
|
11330
|
+
}
|
|
11331
|
+
/**
|
|
11332
|
+
* Non-constant-time multiplication. Uses double-and-add algorithm.
|
|
11333
|
+
* It's faster, but should only be used when you don't care about
|
|
11334
|
+
* an exposed secret key e.g. sig verification, which works over *public* keys.
|
|
11335
|
+
*/
|
|
11336
|
+
multiplyUnsafe(sc) {
|
|
11337
|
+
const { endo: endo2 } = extraOpts;
|
|
11338
|
+
const p = this;
|
|
11339
|
+
if (!Fn.isValid(sc))
|
|
11340
|
+
throw new Error("invalid scalar: out of range");
|
|
11341
|
+
if (sc === _0n4 || p.is0())
|
|
11342
|
+
return Point.ZERO;
|
|
11343
|
+
if (sc === _1n4)
|
|
11344
|
+
return p;
|
|
11345
|
+
if (wnaf.hasCache(this))
|
|
11346
|
+
return this.multiply(sc);
|
|
11347
|
+
if (endo2) {
|
|
11348
|
+
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
|
|
11349
|
+
const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
|
|
11350
|
+
return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
|
|
11351
|
+
} else {
|
|
11352
|
+
return wnaf.unsafe(p, sc);
|
|
11353
|
+
}
|
|
11354
|
+
}
|
|
11355
|
+
/**
|
|
11356
|
+
* Converts Projective point to affine (x, y) coordinates.
|
|
11357
|
+
* @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
|
|
11358
|
+
*/
|
|
11359
|
+
toAffine(invertedZ) {
|
|
11360
|
+
return toAffineMemo(this, invertedZ);
|
|
11361
|
+
}
|
|
11362
|
+
/**
|
|
11363
|
+
* Checks whether Point is free of torsion elements (is in prime subgroup).
|
|
11364
|
+
* Always torsion-free for cofactor=1 curves.
|
|
11365
|
+
*/
|
|
11366
|
+
isTorsionFree() {
|
|
11367
|
+
const { isTorsionFree } = extraOpts;
|
|
11368
|
+
if (cofactor === _1n4)
|
|
11369
|
+
return true;
|
|
11370
|
+
if (isTorsionFree)
|
|
11371
|
+
return isTorsionFree(Point, this);
|
|
11372
|
+
return wnaf.unsafe(this, CURVE_ORDER2).is0();
|
|
11373
|
+
}
|
|
11374
|
+
clearCofactor() {
|
|
11375
|
+
const { clearCofactor } = extraOpts;
|
|
11376
|
+
if (cofactor === _1n4)
|
|
11377
|
+
return this;
|
|
11378
|
+
if (clearCofactor)
|
|
11379
|
+
return clearCofactor(Point, this);
|
|
11380
|
+
return this.multiplyUnsafe(cofactor);
|
|
11381
|
+
}
|
|
11382
|
+
isSmallOrder() {
|
|
11383
|
+
return this.multiplyUnsafe(cofactor).is0();
|
|
11384
|
+
}
|
|
11385
|
+
toBytes(isCompressed = true) {
|
|
11386
|
+
abool(isCompressed, "isCompressed");
|
|
11387
|
+
this.assertValidity();
|
|
11388
|
+
return encodePoint(Point, this, isCompressed);
|
|
11389
|
+
}
|
|
11390
|
+
toHex(isCompressed = true) {
|
|
11391
|
+
return bytesToHex4(this.toBytes(isCompressed));
|
|
11392
|
+
}
|
|
11393
|
+
toString() {
|
|
11394
|
+
return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
|
|
11395
|
+
}
|
|
11396
|
+
}
|
|
11397
|
+
const bits = Fn.BITS;
|
|
11398
|
+
const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
|
|
11399
|
+
Point.BASE.precompute(8);
|
|
11400
|
+
return Point;
|
|
11401
|
+
}
|
|
11402
|
+
function pprefix(hasEvenY) {
|
|
11403
|
+
return Uint8Array.of(hasEvenY ? 2 : 3);
|
|
11404
|
+
}
|
|
11405
|
+
function getWLengths(Fp, Fn) {
|
|
11406
|
+
return {
|
|
11407
|
+
secretKey: Fn.BYTES,
|
|
11408
|
+
publicKey: 1 + Fp.BYTES,
|
|
11409
|
+
publicKeyUncompressed: 1 + 2 * Fp.BYTES,
|
|
11410
|
+
publicKeyHasPrefix: true,
|
|
11411
|
+
signature: 2 * Fn.BYTES
|
|
11412
|
+
};
|
|
11413
|
+
}
|
|
11414
|
+
function ecdh(Point, ecdhOpts = {}) {
|
|
11415
|
+
const { Fn } = Point;
|
|
11416
|
+
const randomBytes_ = ecdhOpts.randomBytes || randomBytes2;
|
|
11417
|
+
const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
|
|
11418
|
+
function isValidSecretKey(secretKey) {
|
|
11419
|
+
try {
|
|
11420
|
+
const num = Fn.fromBytes(secretKey);
|
|
11421
|
+
return Fn.isValidNot0(num);
|
|
11422
|
+
} catch (error) {
|
|
11423
|
+
return false;
|
|
11424
|
+
}
|
|
11425
|
+
}
|
|
11426
|
+
function isValidPublicKey(publicKey, isCompressed) {
|
|
11427
|
+
const { publicKey: comp, publicKeyUncompressed } = lengths;
|
|
11428
|
+
try {
|
|
11429
|
+
const l = publicKey.length;
|
|
11430
|
+
if (isCompressed === true && l !== comp)
|
|
11431
|
+
return false;
|
|
11432
|
+
if (isCompressed === false && l !== publicKeyUncompressed)
|
|
11433
|
+
return false;
|
|
11434
|
+
return !!Point.fromBytes(publicKey);
|
|
11435
|
+
} catch (error) {
|
|
11436
|
+
return false;
|
|
11437
|
+
}
|
|
11438
|
+
}
|
|
11439
|
+
function randomSecretKey(seed = randomBytes_(lengths.seed)) {
|
|
11440
|
+
return mapHashToField(abytes(seed, lengths.seed, "seed"), Fn.ORDER);
|
|
11441
|
+
}
|
|
11442
|
+
function getPublicKey2(secretKey, isCompressed = true) {
|
|
11443
|
+
return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
|
|
11444
|
+
}
|
|
11445
|
+
function isProbPub(item) {
|
|
11446
|
+
const { secretKey, publicKey, publicKeyUncompressed } = lengths;
|
|
11447
|
+
if (!isBytes(item))
|
|
11448
|
+
return void 0;
|
|
11449
|
+
if ("_lengths" in Fn && Fn._lengths || secretKey === publicKey)
|
|
11450
|
+
return void 0;
|
|
11451
|
+
const l = abytes(item, void 0, "key").length;
|
|
11452
|
+
return l === publicKey || l === publicKeyUncompressed;
|
|
11453
|
+
}
|
|
11454
|
+
function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
|
|
11455
|
+
if (isProbPub(secretKeyA) === true)
|
|
11456
|
+
throw new Error("first arg must be private key");
|
|
11457
|
+
if (isProbPub(publicKeyB) === false)
|
|
11458
|
+
throw new Error("second arg must be public key");
|
|
11459
|
+
const s = Fn.fromBytes(secretKeyA);
|
|
11460
|
+
const b = Point.fromBytes(publicKeyB);
|
|
11461
|
+
return b.multiply(s).toBytes(isCompressed);
|
|
11462
|
+
}
|
|
11463
|
+
const utils = {
|
|
11464
|
+
isValidSecretKey,
|
|
11465
|
+
isValidPublicKey,
|
|
11466
|
+
randomSecretKey
|
|
11467
|
+
};
|
|
11468
|
+
const keygen = createKeygen(randomSecretKey, getPublicKey2);
|
|
11469
|
+
return Object.freeze({ getPublicKey: getPublicKey2, getSharedSecret, keygen, Point, utils, lengths });
|
|
11470
|
+
}
|
|
11471
|
+
function ecdsa(Point, hash, ecdsaOpts = {}) {
|
|
11472
|
+
ahash(hash);
|
|
11473
|
+
validateObject(ecdsaOpts, {}, {
|
|
11474
|
+
hmac: "function",
|
|
11475
|
+
lowS: "boolean",
|
|
11476
|
+
randomBytes: "function",
|
|
11477
|
+
bits2int: "function",
|
|
11478
|
+
bits2int_modN: "function"
|
|
11479
|
+
});
|
|
11480
|
+
ecdsaOpts = Object.assign({}, ecdsaOpts);
|
|
11481
|
+
const randomBytes3 = ecdsaOpts.randomBytes || randomBytes2;
|
|
11482
|
+
const hmac2 = ecdsaOpts.hmac || ((key, msg) => hmac(hash, key, msg));
|
|
11483
|
+
const { Fp, Fn } = Point;
|
|
11484
|
+
const { ORDER: CURVE_ORDER2, BITS: fnBits } = Fn;
|
|
11485
|
+
const { keygen, getPublicKey: getPublicKey2, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
|
|
11486
|
+
const defaultSigOpts = {
|
|
11487
|
+
prehash: true,
|
|
11488
|
+
lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
|
|
11489
|
+
format: "compact",
|
|
11490
|
+
extraEntropy: false
|
|
11491
|
+
};
|
|
11492
|
+
const hasLargeCofactor = CURVE_ORDER2 * _2n2 < Fp.ORDER;
|
|
11493
|
+
function isBiggerThanHalfOrder(number) {
|
|
11494
|
+
const HALF = CURVE_ORDER2 >> _1n4;
|
|
11495
|
+
return number > HALF;
|
|
11496
|
+
}
|
|
11497
|
+
function validateRS(title, num) {
|
|
11498
|
+
if (!Fn.isValidNot0(num))
|
|
11499
|
+
throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
|
|
11500
|
+
return num;
|
|
11501
|
+
}
|
|
11502
|
+
function assertSmallCofactor() {
|
|
11503
|
+
if (hasLargeCofactor)
|
|
11504
|
+
throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
|
|
11505
|
+
}
|
|
11506
|
+
function validateSigLength(bytes, format) {
|
|
11507
|
+
validateSigFormat(format);
|
|
11508
|
+
const size = lengths.signature;
|
|
11509
|
+
const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
|
|
11510
|
+
return abytes(bytes, sizer);
|
|
11511
|
+
}
|
|
11512
|
+
class Signature {
|
|
11513
|
+
r;
|
|
11514
|
+
s;
|
|
11515
|
+
recovery;
|
|
11516
|
+
constructor(r, s, recovery) {
|
|
11517
|
+
this.r = validateRS("r", r);
|
|
11518
|
+
this.s = validateRS("s", s);
|
|
11519
|
+
if (recovery != null) {
|
|
11520
|
+
assertSmallCofactor();
|
|
11521
|
+
if (![0, 1, 2, 3].includes(recovery))
|
|
11522
|
+
throw new Error("invalid recovery id");
|
|
11523
|
+
this.recovery = recovery;
|
|
11524
|
+
}
|
|
11525
|
+
Object.freeze(this);
|
|
11526
|
+
}
|
|
11527
|
+
static fromBytes(bytes, format = defaultSigOpts.format) {
|
|
11528
|
+
validateSigLength(bytes, format);
|
|
11529
|
+
let recid;
|
|
11530
|
+
if (format === "der") {
|
|
11531
|
+
const { r: r2, s: s2 } = DER.toSig(abytes(bytes));
|
|
11532
|
+
return new Signature(r2, s2);
|
|
11533
|
+
}
|
|
11534
|
+
if (format === "recovered") {
|
|
11535
|
+
recid = bytes[0];
|
|
11536
|
+
format = "compact";
|
|
11537
|
+
bytes = bytes.subarray(1);
|
|
11538
|
+
}
|
|
11539
|
+
const L = lengths.signature / 2;
|
|
11540
|
+
const r = bytes.subarray(0, L);
|
|
11541
|
+
const s = bytes.subarray(L, L * 2);
|
|
11542
|
+
return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
|
|
11543
|
+
}
|
|
11544
|
+
static fromHex(hex, format) {
|
|
11545
|
+
return this.fromBytes(hexToBytes2(hex), format);
|
|
11546
|
+
}
|
|
11547
|
+
assertRecovery() {
|
|
11548
|
+
const { recovery } = this;
|
|
11549
|
+
if (recovery == null)
|
|
11550
|
+
throw new Error("invalid recovery id: must be present");
|
|
11551
|
+
return recovery;
|
|
11552
|
+
}
|
|
11553
|
+
addRecoveryBit(recovery) {
|
|
11554
|
+
return new Signature(this.r, this.s, recovery);
|
|
11555
|
+
}
|
|
11556
|
+
recoverPublicKey(messageHash) {
|
|
11557
|
+
const { r, s } = this;
|
|
11558
|
+
const recovery = this.assertRecovery();
|
|
11559
|
+
const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER2 : r;
|
|
11560
|
+
if (!Fp.isValid(radj))
|
|
11561
|
+
throw new Error("invalid recovery id: sig.r+curve.n != R.x");
|
|
11562
|
+
const x = Fp.toBytes(radj);
|
|
11563
|
+
const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));
|
|
11564
|
+
const ir = Fn.inv(radj);
|
|
11565
|
+
const h = bits2int_modN(abytes(messageHash, void 0, "msgHash"));
|
|
11566
|
+
const u1 = Fn.create(-h * ir);
|
|
11567
|
+
const u2 = Fn.create(s * ir);
|
|
11568
|
+
const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
|
|
11569
|
+
if (Q.is0())
|
|
11570
|
+
throw new Error("invalid recovery: point at infinify");
|
|
11571
|
+
Q.assertValidity();
|
|
11572
|
+
return Q;
|
|
11573
|
+
}
|
|
11574
|
+
// Signatures should be low-s, to prevent malleability.
|
|
11575
|
+
hasHighS() {
|
|
11576
|
+
return isBiggerThanHalfOrder(this.s);
|
|
11577
|
+
}
|
|
11578
|
+
toBytes(format = defaultSigOpts.format) {
|
|
11579
|
+
validateSigFormat(format);
|
|
11580
|
+
if (format === "der")
|
|
11581
|
+
return hexToBytes2(DER.hexFromSig(this));
|
|
11582
|
+
const { r, s } = this;
|
|
11583
|
+
const rb = Fn.toBytes(r);
|
|
11584
|
+
const sb = Fn.toBytes(s);
|
|
11585
|
+
if (format === "recovered") {
|
|
11586
|
+
assertSmallCofactor();
|
|
11587
|
+
return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);
|
|
11588
|
+
}
|
|
11589
|
+
return concatBytes(rb, sb);
|
|
11590
|
+
}
|
|
11591
|
+
toHex(format) {
|
|
11592
|
+
return bytesToHex4(this.toBytes(format));
|
|
11593
|
+
}
|
|
11594
|
+
}
|
|
11595
|
+
const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
|
|
11596
|
+
if (bytes.length > 8192)
|
|
11597
|
+
throw new Error("input is too large");
|
|
11598
|
+
const num = bytesToNumberBE(bytes);
|
|
11599
|
+
const delta = bytes.length * 8 - fnBits;
|
|
11600
|
+
return delta > 0 ? num >> BigInt(delta) : num;
|
|
11601
|
+
};
|
|
11602
|
+
const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
|
|
11603
|
+
return Fn.create(bits2int(bytes));
|
|
11604
|
+
};
|
|
11605
|
+
const ORDER_MASK = bitMask(fnBits);
|
|
11606
|
+
function int2octets(num) {
|
|
11607
|
+
aInRange("num < 2^" + fnBits, num, _0n4, ORDER_MASK);
|
|
11608
|
+
return Fn.toBytes(num);
|
|
11609
|
+
}
|
|
11610
|
+
function validateMsgAndHash(message, prehash) {
|
|
11611
|
+
abytes(message, void 0, "message");
|
|
11612
|
+
return prehash ? abytes(hash(message), void 0, "prehashed message") : message;
|
|
11613
|
+
}
|
|
11614
|
+
function prepSig(message, secretKey, opts) {
|
|
11615
|
+
const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
|
|
11616
|
+
message = validateMsgAndHash(message, prehash);
|
|
11617
|
+
const h1int = bits2int_modN(message);
|
|
11618
|
+
const d = Fn.fromBytes(secretKey);
|
|
11619
|
+
if (!Fn.isValidNot0(d))
|
|
11620
|
+
throw new Error("invalid private key");
|
|
11621
|
+
const seedArgs = [int2octets(d), int2octets(h1int)];
|
|
11622
|
+
if (extraEntropy != null && extraEntropy !== false) {
|
|
11623
|
+
const e = extraEntropy === true ? randomBytes3(lengths.secretKey) : extraEntropy;
|
|
11624
|
+
seedArgs.push(abytes(e, void 0, "extraEntropy"));
|
|
11625
|
+
}
|
|
11626
|
+
const seed = concatBytes(...seedArgs);
|
|
11627
|
+
const m = h1int;
|
|
11628
|
+
function k2sig(kBytes) {
|
|
11629
|
+
const k = bits2int(kBytes);
|
|
11630
|
+
if (!Fn.isValidNot0(k))
|
|
11631
|
+
return;
|
|
11632
|
+
const ik = Fn.inv(k);
|
|
11633
|
+
const q = Point.BASE.multiply(k).toAffine();
|
|
11634
|
+
const r = Fn.create(q.x);
|
|
11635
|
+
if (r === _0n4)
|
|
11636
|
+
return;
|
|
11637
|
+
const s = Fn.create(ik * Fn.create(m + r * d));
|
|
11638
|
+
if (s === _0n4)
|
|
11639
|
+
return;
|
|
11640
|
+
let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
|
|
11641
|
+
let normS = s;
|
|
11642
|
+
if (lowS && isBiggerThanHalfOrder(s)) {
|
|
11643
|
+
normS = Fn.neg(s);
|
|
11644
|
+
recovery ^= 1;
|
|
11645
|
+
}
|
|
11646
|
+
return new Signature(r, normS, hasLargeCofactor ? void 0 : recovery);
|
|
11647
|
+
}
|
|
11648
|
+
return { seed, k2sig };
|
|
11649
|
+
}
|
|
11650
|
+
function sign(message, secretKey, opts = {}) {
|
|
11651
|
+
const { seed, k2sig } = prepSig(message, secretKey, opts);
|
|
11652
|
+
const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac2);
|
|
11653
|
+
const sig = drbg(seed, k2sig);
|
|
11654
|
+
return sig.toBytes(opts.format);
|
|
11655
|
+
}
|
|
11656
|
+
function verify(signature, message, publicKey, opts = {}) {
|
|
11657
|
+
const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
|
|
11658
|
+
publicKey = abytes(publicKey, void 0, "publicKey");
|
|
11659
|
+
message = validateMsgAndHash(message, prehash);
|
|
11660
|
+
if (!isBytes(signature)) {
|
|
11661
|
+
const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
|
|
11662
|
+
throw new Error("verify expects Uint8Array signature" + end);
|
|
11663
|
+
}
|
|
11664
|
+
validateSigLength(signature, format);
|
|
11665
|
+
try {
|
|
11666
|
+
const sig = Signature.fromBytes(signature, format);
|
|
11667
|
+
const P = Point.fromBytes(publicKey);
|
|
11668
|
+
if (lowS && sig.hasHighS())
|
|
11669
|
+
return false;
|
|
11670
|
+
const { r, s } = sig;
|
|
11671
|
+
const h = bits2int_modN(message);
|
|
11672
|
+
const is = Fn.inv(s);
|
|
11673
|
+
const u1 = Fn.create(h * is);
|
|
11674
|
+
const u2 = Fn.create(r * is);
|
|
11675
|
+
const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
|
|
11676
|
+
if (R.is0())
|
|
11677
|
+
return false;
|
|
11678
|
+
const v = Fn.create(R.x);
|
|
11679
|
+
return v === r;
|
|
11680
|
+
} catch (e) {
|
|
11681
|
+
return false;
|
|
11682
|
+
}
|
|
11683
|
+
}
|
|
11684
|
+
function recoverPublicKey(signature, message, opts = {}) {
|
|
11685
|
+
const { prehash } = validateSigOpts(opts, defaultSigOpts);
|
|
11686
|
+
message = validateMsgAndHash(message, prehash);
|
|
11687
|
+
return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
|
|
11688
|
+
}
|
|
11689
|
+
return Object.freeze({
|
|
11690
|
+
keygen,
|
|
11691
|
+
getPublicKey: getPublicKey2,
|
|
11692
|
+
getSharedSecret,
|
|
11693
|
+
utils,
|
|
11694
|
+
lengths,
|
|
11695
|
+
Point,
|
|
11696
|
+
sign,
|
|
11697
|
+
verify,
|
|
11698
|
+
recoverPublicKey,
|
|
11699
|
+
Signature,
|
|
11700
|
+
hash
|
|
11701
|
+
});
|
|
11702
|
+
}
|
|
11703
|
+
|
|
11704
|
+
// node_modules/@noble/curves/secp256k1.js
|
|
11705
|
+
var secp256k1_CURVE = {
|
|
11706
|
+
p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
|
|
11707
|
+
n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
|
|
11708
|
+
h: BigInt(1),
|
|
11709
|
+
a: BigInt(0),
|
|
11710
|
+
b: BigInt(7),
|
|
11711
|
+
Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
|
|
11712
|
+
Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
|
|
11713
|
+
};
|
|
11714
|
+
var secp256k1_ENDO = {
|
|
11715
|
+
beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
|
|
11716
|
+
basises: [
|
|
11717
|
+
[BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
|
|
11718
|
+
[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
|
|
11719
|
+
]
|
|
11720
|
+
};
|
|
11721
|
+
var _2n3 = /* @__PURE__ */ BigInt(2);
|
|
11722
|
+
function sqrtMod(y) {
|
|
11723
|
+
const P = secp256k1_CURVE.p;
|
|
11724
|
+
const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
|
|
11725
|
+
const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
|
|
11726
|
+
const b2 = y * y * y % P;
|
|
11727
|
+
const b3 = b2 * b2 * y % P;
|
|
11728
|
+
const b6 = pow2(b3, _3n3, P) * b3 % P;
|
|
11729
|
+
const b9 = pow2(b6, _3n3, P) * b3 % P;
|
|
11730
|
+
const b11 = pow2(b9, _2n3, P) * b2 % P;
|
|
11731
|
+
const b22 = pow2(b11, _11n, P) * b11 % P;
|
|
11732
|
+
const b44 = pow2(b22, _22n, P) * b22 % P;
|
|
11733
|
+
const b88 = pow2(b44, _44n, P) * b44 % P;
|
|
11734
|
+
const b176 = pow2(b88, _88n, P) * b88 % P;
|
|
11735
|
+
const b220 = pow2(b176, _44n, P) * b44 % P;
|
|
11736
|
+
const b223 = pow2(b220, _3n3, P) * b3 % P;
|
|
11737
|
+
const t1 = pow2(b223, _23n, P) * b22 % P;
|
|
11738
|
+
const t2 = pow2(t1, _6n, P) * b2 % P;
|
|
11739
|
+
const root = pow2(t2, _2n3, P);
|
|
11740
|
+
if (!Fpk1.eql(Fpk1.sqr(root), y))
|
|
11741
|
+
throw new Error("Cannot find square root");
|
|
11742
|
+
return root;
|
|
11743
|
+
}
|
|
11744
|
+
var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
|
|
11745
|
+
var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
|
|
11746
|
+
Fp: Fpk1,
|
|
11747
|
+
endo: secp256k1_ENDO
|
|
11748
|
+
});
|
|
11749
|
+
var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha2564);
|
|
11750
|
+
|
|
11751
|
+
// modules/market/MarketModule.ts
|
|
11752
|
+
var DEFAULT_MARKET_API_URL = "https://market-api.unicity.network";
|
|
11753
|
+
function hexToBytes3(hex) {
|
|
11754
|
+
const len = hex.length >> 1;
|
|
11755
|
+
const bytes = new Uint8Array(len);
|
|
11756
|
+
for (let i = 0; i < len; i++) {
|
|
11757
|
+
bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
11758
|
+
}
|
|
11759
|
+
return bytes;
|
|
11760
|
+
}
|
|
11761
|
+
function signRequest(body, privateKeyHex) {
|
|
11762
|
+
const timestamp = Date.now();
|
|
11763
|
+
const payload = JSON.stringify({ body, timestamp });
|
|
11764
|
+
const messageHash = sha2564(new TextEncoder().encode(payload));
|
|
11765
|
+
const privateKeyBytes = hexToBytes3(privateKeyHex);
|
|
11766
|
+
const signature = secp256k1.sign(messageHash, privateKeyBytes);
|
|
11767
|
+
const publicKey = bytesToHex4(secp256k1.getPublicKey(privateKeyBytes, true));
|
|
11768
|
+
return {
|
|
11769
|
+
body: JSON.stringify(body),
|
|
11770
|
+
headers: {
|
|
11771
|
+
"x-signature": bytesToHex4(signature),
|
|
11772
|
+
"x-public-key": publicKey,
|
|
11773
|
+
"x-timestamp": String(timestamp),
|
|
11774
|
+
"content-type": "application/json"
|
|
11775
|
+
}
|
|
11776
|
+
};
|
|
11777
|
+
}
|
|
11778
|
+
function toSnakeCaseIntent(req) {
|
|
11779
|
+
const result = {
|
|
11780
|
+
description: req.description,
|
|
11781
|
+
intent_type: req.intentType
|
|
11782
|
+
};
|
|
11783
|
+
if (req.category !== void 0) result.category = req.category;
|
|
11784
|
+
if (req.price !== void 0) result.price = req.price;
|
|
11785
|
+
if (req.currency !== void 0) result.currency = req.currency;
|
|
11786
|
+
if (req.location !== void 0) result.location = req.location;
|
|
11787
|
+
if (req.contactHandle !== void 0) result.contact_handle = req.contactHandle;
|
|
11788
|
+
if (req.expiresInDays !== void 0) result.expires_in_days = req.expiresInDays;
|
|
11789
|
+
return result;
|
|
11790
|
+
}
|
|
11791
|
+
function toSnakeCaseFilters(opts) {
|
|
11792
|
+
const result = {};
|
|
11793
|
+
if (opts?.filters) {
|
|
11794
|
+
const f = opts.filters;
|
|
11795
|
+
if (f.intentType !== void 0) result.intent_type = f.intentType;
|
|
11796
|
+
if (f.category !== void 0) result.category = f.category;
|
|
11797
|
+
if (f.minPrice !== void 0) result.min_price = f.minPrice;
|
|
11798
|
+
if (f.maxPrice !== void 0) result.max_price = f.maxPrice;
|
|
11799
|
+
if (f.location !== void 0) result.location = f.location;
|
|
11800
|
+
}
|
|
11801
|
+
if (opts?.limit !== void 0) result.limit = opts.limit;
|
|
11802
|
+
return result;
|
|
11803
|
+
}
|
|
11804
|
+
function mapSearchResult(raw) {
|
|
11805
|
+
return {
|
|
11806
|
+
id: raw.id,
|
|
11807
|
+
score: raw.score,
|
|
11808
|
+
agentNametag: raw.agent_nametag ?? void 0,
|
|
11809
|
+
agentPublicKey: raw.agent_public_key,
|
|
11810
|
+
description: raw.description,
|
|
11811
|
+
intentType: raw.intent_type,
|
|
11812
|
+
category: raw.category ?? void 0,
|
|
11813
|
+
price: raw.price ?? void 0,
|
|
11814
|
+
currency: raw.currency,
|
|
11815
|
+
location: raw.location ?? void 0,
|
|
11816
|
+
contactMethod: raw.contact_method,
|
|
11817
|
+
contactHandle: raw.contact_handle ?? void 0,
|
|
11818
|
+
createdAt: raw.created_at,
|
|
11819
|
+
expiresAt: raw.expires_at
|
|
11820
|
+
};
|
|
11821
|
+
}
|
|
11822
|
+
function mapMyIntent(raw) {
|
|
11823
|
+
return {
|
|
11824
|
+
id: raw.id,
|
|
11825
|
+
intentType: raw.intent_type,
|
|
11826
|
+
category: raw.category ?? void 0,
|
|
11827
|
+
price: raw.price ?? void 0,
|
|
11828
|
+
currency: raw.currency,
|
|
11829
|
+
location: raw.location ?? void 0,
|
|
11830
|
+
status: raw.status,
|
|
11831
|
+
createdAt: raw.created_at,
|
|
11832
|
+
expiresAt: raw.expires_at
|
|
11833
|
+
};
|
|
11834
|
+
}
|
|
11835
|
+
function mapFeedListing(raw) {
|
|
11836
|
+
return {
|
|
11837
|
+
id: raw.id,
|
|
11838
|
+
title: raw.title,
|
|
11839
|
+
descriptionPreview: raw.description_preview,
|
|
11840
|
+
agentName: raw.agent_name,
|
|
11841
|
+
agentId: raw.agent_id,
|
|
11842
|
+
type: raw.type,
|
|
11843
|
+
createdAt: raw.created_at
|
|
11844
|
+
};
|
|
11845
|
+
}
|
|
11846
|
+
function mapFeedMessage(raw) {
|
|
11847
|
+
if (raw.type === "initial") {
|
|
11848
|
+
return { type: "initial", listings: (raw.listings ?? []).map(mapFeedListing) };
|
|
11849
|
+
}
|
|
11850
|
+
return { type: "new", listing: mapFeedListing(raw.listing) };
|
|
11851
|
+
}
|
|
11852
|
+
var MarketModule = class {
|
|
11853
|
+
apiUrl;
|
|
11854
|
+
timeout;
|
|
11855
|
+
identity = null;
|
|
11856
|
+
registered = false;
|
|
11857
|
+
constructor(config) {
|
|
11858
|
+
this.apiUrl = (config?.apiUrl ?? DEFAULT_MARKET_API_URL).replace(/\/+$/, "");
|
|
11859
|
+
this.timeout = config?.timeout ?? 3e4;
|
|
11860
|
+
}
|
|
11861
|
+
/** Called by Sphere after construction */
|
|
11862
|
+
initialize(deps) {
|
|
11863
|
+
this.identity = deps.identity;
|
|
11864
|
+
}
|
|
11865
|
+
/** No-op — stateless module */
|
|
11866
|
+
async load() {
|
|
11867
|
+
}
|
|
11868
|
+
/** No-op — stateless module */
|
|
11869
|
+
destroy() {
|
|
11870
|
+
}
|
|
11871
|
+
// ---------------------------------------------------------------------------
|
|
11872
|
+
// Public API
|
|
11873
|
+
// ---------------------------------------------------------------------------
|
|
11874
|
+
/** Post a new intent (agent is auto-registered on first post) */
|
|
11875
|
+
async postIntent(intent) {
|
|
11876
|
+
const body = toSnakeCaseIntent(intent);
|
|
11877
|
+
const data = await this.apiPost("/api/intents", body);
|
|
11878
|
+
return {
|
|
11879
|
+
intentId: data.intent_id ?? data.intentId,
|
|
11880
|
+
message: data.message,
|
|
11881
|
+
expiresAt: data.expires_at ?? data.expiresAt
|
|
11882
|
+
};
|
|
11883
|
+
}
|
|
11884
|
+
/** Semantic search for intents (public — no auth required) */
|
|
11885
|
+
async search(query, opts) {
|
|
11886
|
+
const body = {
|
|
11887
|
+
query,
|
|
11888
|
+
...toSnakeCaseFilters(opts)
|
|
11889
|
+
};
|
|
11890
|
+
const data = await this.apiPublicPost("/api/search", body);
|
|
11891
|
+
let results = (data.intents ?? []).map(mapSearchResult);
|
|
11892
|
+
const minScore = opts?.filters?.minScore;
|
|
11893
|
+
if (minScore != null) {
|
|
11894
|
+
results = results.filter((r) => Math.round(r.score * 100) >= Math.round(minScore * 100));
|
|
11895
|
+
}
|
|
11896
|
+
return { intents: results, count: results.length };
|
|
11897
|
+
}
|
|
11898
|
+
/** List own intents (authenticated) */
|
|
11899
|
+
async getMyIntents() {
|
|
11900
|
+
const data = await this.apiGet("/api/intents");
|
|
11901
|
+
return (data.intents ?? []).map(mapMyIntent);
|
|
11902
|
+
}
|
|
11903
|
+
/** Close (delete) an intent */
|
|
11904
|
+
async closeIntent(intentId) {
|
|
11905
|
+
await this.apiDelete(`/api/intents/${encodeURIComponent(intentId)}`);
|
|
11906
|
+
}
|
|
11907
|
+
/** Fetch the most recent listings via REST (public — no auth required) */
|
|
11908
|
+
async getRecentListings() {
|
|
11909
|
+
const res = await fetch(`${this.apiUrl}/api/feed/recent`, {
|
|
11910
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
11911
|
+
});
|
|
11912
|
+
const data = await this.parseResponse(res);
|
|
11913
|
+
return (data.listings ?? []).map(mapFeedListing);
|
|
11914
|
+
}
|
|
11915
|
+
/**
|
|
11916
|
+
* Subscribe to the live listing feed via WebSocket.
|
|
11917
|
+
* Returns an unsubscribe function that closes the connection.
|
|
11918
|
+
*
|
|
11919
|
+
* Requires a WebSocket implementation — works natively in browsers
|
|
11920
|
+
* and in Node.js 21+ (or with the `ws` package).
|
|
11921
|
+
*/
|
|
11922
|
+
subscribeFeed(listener) {
|
|
11923
|
+
const wsUrl = this.apiUrl.replace(/^http/, "ws") + "/ws/feed";
|
|
11924
|
+
const ws2 = new WebSocket(wsUrl);
|
|
11925
|
+
ws2.onmessage = (event) => {
|
|
11926
|
+
try {
|
|
11927
|
+
const raw = JSON.parse(typeof event.data === "string" ? event.data : event.data.toString());
|
|
11928
|
+
listener(mapFeedMessage(raw));
|
|
11929
|
+
} catch {
|
|
11930
|
+
}
|
|
11931
|
+
};
|
|
11932
|
+
return () => {
|
|
11933
|
+
ws2.close();
|
|
11934
|
+
};
|
|
11935
|
+
}
|
|
11936
|
+
// ---------------------------------------------------------------------------
|
|
11937
|
+
// Private: HTTP helpers
|
|
11938
|
+
// ---------------------------------------------------------------------------
|
|
11939
|
+
ensureIdentity() {
|
|
11940
|
+
if (!this.identity) {
|
|
11941
|
+
throw new Error("MarketModule not initialized \u2014 call initialize() first");
|
|
11942
|
+
}
|
|
11943
|
+
}
|
|
11944
|
+
/** Register the agent's public key with the server (idempotent) */
|
|
11945
|
+
async ensureRegistered() {
|
|
11946
|
+
if (this.registered) return;
|
|
11947
|
+
this.ensureIdentity();
|
|
11948
|
+
const publicKey = bytesToHex4(secp256k1.getPublicKey(hexToBytes3(this.identity.privateKey), true));
|
|
11949
|
+
const body = { public_key: publicKey };
|
|
11950
|
+
if (this.identity.nametag) body.nametag = this.identity.nametag;
|
|
11951
|
+
const res = await fetch(`${this.apiUrl}/api/agent/register`, {
|
|
11952
|
+
method: "POST",
|
|
11953
|
+
headers: { "content-type": "application/json" },
|
|
11954
|
+
body: JSON.stringify(body),
|
|
11955
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
11956
|
+
});
|
|
11957
|
+
if (res.ok || res.status === 409) {
|
|
11958
|
+
this.registered = true;
|
|
11959
|
+
return;
|
|
11960
|
+
}
|
|
11961
|
+
const text = await res.text();
|
|
11962
|
+
let data;
|
|
11963
|
+
try {
|
|
11964
|
+
data = JSON.parse(text);
|
|
11965
|
+
} catch {
|
|
11966
|
+
}
|
|
11967
|
+
throw new Error(data?.error ?? `Agent registration failed: HTTP ${res.status}`);
|
|
11968
|
+
}
|
|
11969
|
+
async parseResponse(res) {
|
|
11970
|
+
const text = await res.text();
|
|
11971
|
+
let data;
|
|
11972
|
+
try {
|
|
11973
|
+
data = JSON.parse(text);
|
|
11974
|
+
} catch {
|
|
11975
|
+
throw new Error(`Market API error: HTTP ${res.status} \u2014 unexpected response (not JSON)`);
|
|
11976
|
+
}
|
|
11977
|
+
if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
|
|
11978
|
+
return data;
|
|
11979
|
+
}
|
|
11980
|
+
async apiPost(path, body) {
|
|
11981
|
+
this.ensureIdentity();
|
|
11982
|
+
await this.ensureRegistered();
|
|
11983
|
+
const signed = signRequest(body, this.identity.privateKey);
|
|
11984
|
+
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11985
|
+
method: "POST",
|
|
11986
|
+
headers: signed.headers,
|
|
11987
|
+
body: signed.body,
|
|
11988
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
11989
|
+
});
|
|
11990
|
+
return this.parseResponse(res);
|
|
11991
|
+
}
|
|
11992
|
+
async apiGet(path) {
|
|
11993
|
+
this.ensureIdentity();
|
|
11994
|
+
await this.ensureRegistered();
|
|
11995
|
+
const signed = signRequest({}, this.identity.privateKey);
|
|
11996
|
+
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11997
|
+
method: "GET",
|
|
11998
|
+
headers: signed.headers,
|
|
11999
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
12000
|
+
});
|
|
12001
|
+
return this.parseResponse(res);
|
|
12002
|
+
}
|
|
12003
|
+
async apiDelete(path) {
|
|
12004
|
+
this.ensureIdentity();
|
|
12005
|
+
await this.ensureRegistered();
|
|
12006
|
+
const signed = signRequest({}, this.identity.privateKey);
|
|
12007
|
+
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
12008
|
+
method: "DELETE",
|
|
12009
|
+
headers: signed.headers,
|
|
12010
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
12011
|
+
});
|
|
12012
|
+
return this.parseResponse(res);
|
|
12013
|
+
}
|
|
12014
|
+
async apiPublicPost(path, body) {
|
|
12015
|
+
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
12016
|
+
method: "POST",
|
|
12017
|
+
headers: { "content-type": "application/json" },
|
|
12018
|
+
body: JSON.stringify(body),
|
|
12019
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
12020
|
+
});
|
|
12021
|
+
return this.parseResponse(res);
|
|
12022
|
+
}
|
|
12023
|
+
};
|
|
12024
|
+
function createMarketModule(config) {
|
|
12025
|
+
return new MarketModule(config);
|
|
12026
|
+
}
|
|
12027
|
+
|
|
9441
12028
|
// core/encryption.ts
|
|
9442
12029
|
var import_crypto_js6 = __toESM(require("crypto-js"), 1);
|
|
9443
12030
|
function encryptSimple(plaintext, password) {
|
|
@@ -10273,6 +12860,7 @@ var Sphere = class _Sphere {
|
|
|
10273
12860
|
_payments;
|
|
10274
12861
|
_communications;
|
|
10275
12862
|
_groupChat = null;
|
|
12863
|
+
_market = null;
|
|
10276
12864
|
// Events
|
|
10277
12865
|
eventHandlers = /* @__PURE__ */ new Map();
|
|
10278
12866
|
// Provider management
|
|
@@ -10282,7 +12870,7 @@ var Sphere = class _Sphere {
|
|
|
10282
12870
|
// ===========================================================================
|
|
10283
12871
|
// Constructor (private)
|
|
10284
12872
|
// ===========================================================================
|
|
10285
|
-
constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig) {
|
|
12873
|
+
constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig, marketConfig) {
|
|
10286
12874
|
this._storage = storage;
|
|
10287
12875
|
this._transport = transport;
|
|
10288
12876
|
this._oracle = oracle;
|
|
@@ -10293,6 +12881,7 @@ var Sphere = class _Sphere {
|
|
|
10293
12881
|
this._payments = createPaymentsModule({ l1: l1Config });
|
|
10294
12882
|
this._communications = createCommunicationsModule();
|
|
10295
12883
|
this._groupChat = groupChatConfig ? createGroupChatModule(groupChatConfig) : null;
|
|
12884
|
+
this._market = marketConfig ? createMarketModule(marketConfig) : null;
|
|
10296
12885
|
}
|
|
10297
12886
|
// ===========================================================================
|
|
10298
12887
|
// Static Methods - Wallet Management
|
|
@@ -10302,13 +12891,17 @@ var Sphere = class _Sphere {
|
|
|
10302
12891
|
*/
|
|
10303
12892
|
static async exists(storage) {
|
|
10304
12893
|
try {
|
|
10305
|
-
|
|
12894
|
+
const wasConnected = storage.isConnected();
|
|
12895
|
+
if (!wasConnected) {
|
|
10306
12896
|
await storage.connect();
|
|
10307
12897
|
}
|
|
10308
12898
|
const mnemonic = await storage.get(STORAGE_KEYS_GLOBAL.MNEMONIC);
|
|
10309
12899
|
if (mnemonic) return true;
|
|
10310
12900
|
const masterKey = await storage.get(STORAGE_KEYS_GLOBAL.MASTER_KEY);
|
|
10311
12901
|
if (masterKey) return true;
|
|
12902
|
+
if (!wasConnected) {
|
|
12903
|
+
await storage.disconnect();
|
|
12904
|
+
}
|
|
10312
12905
|
return false;
|
|
10313
12906
|
} catch {
|
|
10314
12907
|
return false;
|
|
@@ -10342,6 +12935,7 @@ var Sphere = class _Sphere {
|
|
|
10342
12935
|
static async init(options) {
|
|
10343
12936
|
_Sphere.configureTokenRegistry(options.storage, options.network);
|
|
10344
12937
|
const groupChat = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
|
|
12938
|
+
const market = _Sphere.resolveMarketConfig(options.market);
|
|
10345
12939
|
const walletExists = await _Sphere.exists(options.storage);
|
|
10346
12940
|
if (walletExists) {
|
|
10347
12941
|
const sphere2 = await _Sphere.load({
|
|
@@ -10352,6 +12946,7 @@ var Sphere = class _Sphere {
|
|
|
10352
12946
|
l1: options.l1,
|
|
10353
12947
|
price: options.price,
|
|
10354
12948
|
groupChat,
|
|
12949
|
+
market,
|
|
10355
12950
|
password: options.password
|
|
10356
12951
|
});
|
|
10357
12952
|
return { sphere: sphere2, created: false };
|
|
@@ -10379,6 +12974,7 @@ var Sphere = class _Sphere {
|
|
|
10379
12974
|
l1: options.l1,
|
|
10380
12975
|
price: options.price,
|
|
10381
12976
|
groupChat,
|
|
12977
|
+
market,
|
|
10382
12978
|
password: options.password
|
|
10383
12979
|
});
|
|
10384
12980
|
return { sphere, created: true, generatedMnemonic };
|
|
@@ -10406,6 +13002,17 @@ var Sphere = class _Sphere {
|
|
|
10406
13002
|
}
|
|
10407
13003
|
return config;
|
|
10408
13004
|
}
|
|
13005
|
+
/**
|
|
13006
|
+
* Resolve market module config from Sphere.init() options.
|
|
13007
|
+
* - `true` → enable with default API URL
|
|
13008
|
+
* - `MarketModuleConfig` → pass through
|
|
13009
|
+
* - `undefined` → no market module
|
|
13010
|
+
*/
|
|
13011
|
+
static resolveMarketConfig(config) {
|
|
13012
|
+
if (!config) return void 0;
|
|
13013
|
+
if (config === true) return {};
|
|
13014
|
+
return config;
|
|
13015
|
+
}
|
|
10409
13016
|
/**
|
|
10410
13017
|
* Configure TokenRegistry in the main bundle context.
|
|
10411
13018
|
*
|
|
@@ -10431,6 +13038,7 @@ var Sphere = class _Sphere {
|
|
|
10431
13038
|
}
|
|
10432
13039
|
_Sphere.configureTokenRegistry(options.storage, options.network);
|
|
10433
13040
|
const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
|
|
13041
|
+
const marketConfig = _Sphere.resolveMarketConfig(options.market);
|
|
10434
13042
|
const sphere = new _Sphere(
|
|
10435
13043
|
options.storage,
|
|
10436
13044
|
options.transport,
|
|
@@ -10438,7 +13046,8 @@ var Sphere = class _Sphere {
|
|
|
10438
13046
|
options.tokenStorage,
|
|
10439
13047
|
options.l1,
|
|
10440
13048
|
options.price,
|
|
10441
|
-
groupChatConfig
|
|
13049
|
+
groupChatConfig,
|
|
13050
|
+
marketConfig
|
|
10442
13051
|
);
|
|
10443
13052
|
sphere._password = options.password ?? null;
|
|
10444
13053
|
await sphere.storeMnemonic(options.mnemonic, options.derivationPath);
|
|
@@ -10466,6 +13075,7 @@ var Sphere = class _Sphere {
|
|
|
10466
13075
|
}
|
|
10467
13076
|
_Sphere.configureTokenRegistry(options.storage, options.network);
|
|
10468
13077
|
const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
|
|
13078
|
+
const marketConfig = _Sphere.resolveMarketConfig(options.market);
|
|
10469
13079
|
const sphere = new _Sphere(
|
|
10470
13080
|
options.storage,
|
|
10471
13081
|
options.transport,
|
|
@@ -10473,7 +13083,8 @@ var Sphere = class _Sphere {
|
|
|
10473
13083
|
options.tokenStorage,
|
|
10474
13084
|
options.l1,
|
|
10475
13085
|
options.price,
|
|
10476
|
-
groupChatConfig
|
|
13086
|
+
groupChatConfig,
|
|
13087
|
+
marketConfig
|
|
10477
13088
|
);
|
|
10478
13089
|
sphere._password = options.password ?? null;
|
|
10479
13090
|
await sphere.loadIdentityFromStorage();
|
|
@@ -10519,6 +13130,7 @@ var Sphere = class _Sphere {
|
|
|
10519
13130
|
console.log("[Sphere.import] Storage reconnected");
|
|
10520
13131
|
}
|
|
10521
13132
|
const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat);
|
|
13133
|
+
const marketConfig = _Sphere.resolveMarketConfig(options.market);
|
|
10522
13134
|
const sphere = new _Sphere(
|
|
10523
13135
|
options.storage,
|
|
10524
13136
|
options.transport,
|
|
@@ -10526,7 +13138,8 @@ var Sphere = class _Sphere {
|
|
|
10526
13138
|
options.tokenStorage,
|
|
10527
13139
|
options.l1,
|
|
10528
13140
|
options.price,
|
|
10529
|
-
groupChatConfig
|
|
13141
|
+
groupChatConfig,
|
|
13142
|
+
marketConfig
|
|
10530
13143
|
);
|
|
10531
13144
|
sphere._password = options.password ?? null;
|
|
10532
13145
|
if (options.mnemonic) {
|
|
@@ -10607,47 +13220,40 @@ var Sphere = class _Sphere {
|
|
|
10607
13220
|
static async clear(storageOrOptions) {
|
|
10608
13221
|
const storage = "get" in storageOrOptions ? storageOrOptions : storageOrOptions.storage;
|
|
10609
13222
|
const tokenStorage = "get" in storageOrOptions ? void 0 : storageOrOptions.tokenStorage;
|
|
10610
|
-
if (
|
|
10611
|
-
|
|
10612
|
-
|
|
10613
|
-
|
|
10614
|
-
|
|
10615
|
-
|
|
10616
|
-
await
|
|
10617
|
-
|
|
10618
|
-
await
|
|
10619
|
-
await storage.remove(STORAGE_KEYS_GLOBAL.DERIVATION_MODE);
|
|
10620
|
-
await storage.remove(STORAGE_KEYS_GLOBAL.WALLET_SOURCE);
|
|
10621
|
-
await storage.remove(STORAGE_KEYS_GLOBAL.WALLET_EXISTS);
|
|
10622
|
-
await storage.remove(STORAGE_KEYS_GLOBAL.TRACKED_ADDRESSES);
|
|
10623
|
-
await storage.remove(STORAGE_KEYS_GLOBAL.ADDRESS_NAMETAGS);
|
|
10624
|
-
await storage.remove(STORAGE_KEYS_ADDRESS.PENDING_TRANSFERS);
|
|
10625
|
-
await storage.remove(STORAGE_KEYS_ADDRESS.OUTBOX);
|
|
10626
|
-
console.log("[Sphere.clear] Storage keys removed");
|
|
13223
|
+
if (_Sphere.instance) {
|
|
13224
|
+
console.log("[Sphere.clear] Destroying Sphere instance...");
|
|
13225
|
+
await _Sphere.instance.destroy();
|
|
13226
|
+
console.log("[Sphere.clear] Sphere instance destroyed");
|
|
13227
|
+
}
|
|
13228
|
+
console.log("[Sphere.clear] Clearing L1 vesting cache...");
|
|
13229
|
+
await vestingClassifier.destroy();
|
|
13230
|
+
console.log("[Sphere.clear] Yielding 50ms for IDB transaction settlement...");
|
|
13231
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
10627
13232
|
if (tokenStorage?.clear) {
|
|
10628
13233
|
console.log("[Sphere.clear] Clearing token storage...");
|
|
10629
13234
|
try {
|
|
10630
|
-
await
|
|
10631
|
-
tokenStorage.clear(),
|
|
10632
|
-
new Promise(
|
|
10633
|
-
(_, reject) => setTimeout(() => reject(new Error("tokenStorage.clear() timed out after 2s")), 2e3)
|
|
10634
|
-
)
|
|
10635
|
-
]);
|
|
13235
|
+
await tokenStorage.clear();
|
|
10636
13236
|
console.log("[Sphere.clear] Token storage cleared");
|
|
10637
13237
|
} catch (err) {
|
|
10638
|
-
console.warn("[Sphere.clear] Token storage clear failed
|
|
13238
|
+
console.warn("[Sphere.clear] Token storage clear failed:", err);
|
|
10639
13239
|
}
|
|
13240
|
+
} else {
|
|
13241
|
+
console.log("[Sphere.clear] No token storage provider to clear");
|
|
10640
13242
|
}
|
|
10641
|
-
console.log("[Sphere.clear]
|
|
10642
|
-
|
|
10643
|
-
|
|
10644
|
-
|
|
10645
|
-
|
|
10646
|
-
|
|
10647
|
-
|
|
13243
|
+
console.log("[Sphere.clear] Clearing KV storage...");
|
|
13244
|
+
if (!storage.isConnected()) {
|
|
13245
|
+
try {
|
|
13246
|
+
await storage.connect();
|
|
13247
|
+
} catch {
|
|
13248
|
+
}
|
|
13249
|
+
}
|
|
13250
|
+
if (storage.isConnected()) {
|
|
13251
|
+
await storage.clear();
|
|
13252
|
+
console.log("[Sphere.clear] KV storage cleared");
|
|
10648
13253
|
} else {
|
|
10649
|
-
console.log("[Sphere.clear]
|
|
13254
|
+
console.log("[Sphere.clear] KV storage not connected, skipping");
|
|
10650
13255
|
}
|
|
13256
|
+
console.log("[Sphere.clear] Done");
|
|
10651
13257
|
}
|
|
10652
13258
|
/**
|
|
10653
13259
|
* Get current instance
|
|
@@ -10691,6 +13297,10 @@ var Sphere = class _Sphere {
|
|
|
10691
13297
|
get groupChat() {
|
|
10692
13298
|
return this._groupChat;
|
|
10693
13299
|
}
|
|
13300
|
+
/** Market module (intent bulletin board). Null if not configured. */
|
|
13301
|
+
get market() {
|
|
13302
|
+
return this._market;
|
|
13303
|
+
}
|
|
10694
13304
|
// ===========================================================================
|
|
10695
13305
|
// Public Properties - State
|
|
10696
13306
|
// ===========================================================================
|
|
@@ -11491,8 +14101,12 @@ var Sphere = class _Sphere {
|
|
|
11491
14101
|
await this._storage.set(STORAGE_KEYS_GLOBAL.CURRENT_ADDRESS_INDEX, index.toString());
|
|
11492
14102
|
this._storage.setIdentity(this._identity);
|
|
11493
14103
|
await this._transport.setIdentity(this._identity);
|
|
11494
|
-
|
|
14104
|
+
console.log(`[Sphere] switchToAddress(${index}): re-initializing ${this._tokenStorageProviders.size} token storage provider(s)`);
|
|
14105
|
+
for (const [providerId, provider] of this._tokenStorageProviders.entries()) {
|
|
14106
|
+
console.log(`[Sphere] switchToAddress(${index}): shutdown provider=${providerId}`);
|
|
14107
|
+
await provider.shutdown();
|
|
11495
14108
|
provider.setIdentity(this._identity);
|
|
14109
|
+
console.log(`[Sphere] switchToAddress(${index}): initialize provider=${providerId}`);
|
|
11496
14110
|
await provider.initialize();
|
|
11497
14111
|
}
|
|
11498
14112
|
await this.reinitializeModulesForNewAddress();
|
|
@@ -11566,9 +14180,17 @@ var Sphere = class _Sphere {
|
|
|
11566
14180
|
storage: this._storage,
|
|
11567
14181
|
emitEvent
|
|
11568
14182
|
});
|
|
14183
|
+
this._market?.initialize({
|
|
14184
|
+
identity: this._identity,
|
|
14185
|
+
emitEvent
|
|
14186
|
+
});
|
|
11569
14187
|
await this._payments.load();
|
|
11570
14188
|
await this._communications.load();
|
|
11571
14189
|
await this._groupChat?.load();
|
|
14190
|
+
await this._market?.load();
|
|
14191
|
+
this._payments.sync().catch((err) => {
|
|
14192
|
+
console.warn("[Sphere] Post-switch sync failed:", err);
|
|
14193
|
+
});
|
|
11572
14194
|
}
|
|
11573
14195
|
/**
|
|
11574
14196
|
* Derive address at a specific index
|
|
@@ -12393,6 +15015,7 @@ var Sphere = class _Sphere {
|
|
|
12393
15015
|
this._payments.destroy();
|
|
12394
15016
|
this._communications.destroy();
|
|
12395
15017
|
this._groupChat?.destroy();
|
|
15018
|
+
this._market?.destroy();
|
|
12396
15019
|
await this._transport.disconnect();
|
|
12397
15020
|
await this._storage.disconnect();
|
|
12398
15021
|
await this._oracle.disconnect();
|
|
@@ -12700,9 +15323,14 @@ var Sphere = class _Sphere {
|
|
|
12700
15323
|
storage: this._storage,
|
|
12701
15324
|
emitEvent
|
|
12702
15325
|
});
|
|
15326
|
+
this._market?.initialize({
|
|
15327
|
+
identity: this._identity,
|
|
15328
|
+
emitEvent
|
|
15329
|
+
});
|
|
12703
15330
|
await this._payments.load();
|
|
12704
15331
|
await this._communications.load();
|
|
12705
15332
|
await this._groupChat?.load();
|
|
15333
|
+
await this._market?.load();
|
|
12706
15334
|
}
|
|
12707
15335
|
// ===========================================================================
|
|
12708
15336
|
// Private: Helpers
|
|
@@ -13628,6 +16256,7 @@ function createPriceProvider(config) {
|
|
|
13628
16256
|
DEFAULT_GROUP_RELAYS,
|
|
13629
16257
|
DEFAULT_IPFS_BOOTSTRAP_PEERS,
|
|
13630
16258
|
DEFAULT_IPFS_GATEWAYS,
|
|
16259
|
+
DEFAULT_MARKET_API_URL,
|
|
13631
16260
|
DEFAULT_NOSTR_RELAYS,
|
|
13632
16261
|
DEV_AGGREGATOR_URL,
|
|
13633
16262
|
GroupChatModule,
|
|
@@ -13636,11 +16265,14 @@ function createPriceProvider(config) {
|
|
|
13636
16265
|
L1,
|
|
13637
16266
|
L1PaymentsModule,
|
|
13638
16267
|
LIMITS,
|
|
16268
|
+
MarketModule,
|
|
13639
16269
|
NETWORKS,
|
|
13640
16270
|
NIP29_KINDS,
|
|
13641
16271
|
NOSTR_EVENT_KINDS,
|
|
13642
16272
|
PaymentsModule,
|
|
13643
16273
|
STORAGE_KEYS,
|
|
16274
|
+
STORAGE_KEYS_ADDRESS,
|
|
16275
|
+
STORAGE_KEYS_GLOBAL,
|
|
13644
16276
|
STORAGE_PREFIX,
|
|
13645
16277
|
Sphere,
|
|
13646
16278
|
SphereError,
|
|
@@ -13663,6 +16295,7 @@ function createPriceProvider(config) {
|
|
|
13663
16295
|
createGroupChatModule,
|
|
13664
16296
|
createKeyPair,
|
|
13665
16297
|
createL1PaymentsModule,
|
|
16298
|
+
createMarketModule,
|
|
13666
16299
|
createPaymentSession,
|
|
13667
16300
|
createPaymentSessionError,
|
|
13668
16301
|
createPaymentsModule,
|
|
@@ -13686,6 +16319,8 @@ function createPriceProvider(config) {
|
|
|
13686
16319
|
generateMasterKey,
|
|
13687
16320
|
generateMnemonic,
|
|
13688
16321
|
getAddressHrp,
|
|
16322
|
+
getAddressId,
|
|
16323
|
+
getAddressStorageKey,
|
|
13689
16324
|
getCoinIdByName,
|
|
13690
16325
|
getCoinIdBySymbol,
|
|
13691
16326
|
getCurrentStateHash,
|
|
@@ -13750,4 +16385,16 @@ function createPriceProvider(config) {
|
|
|
13750
16385
|
txfToToken,
|
|
13751
16386
|
validateMnemonic
|
|
13752
16387
|
});
|
|
16388
|
+
/*! Bundled license information:
|
|
16389
|
+
|
|
16390
|
+
@noble/hashes/utils.js:
|
|
16391
|
+
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
16392
|
+
|
|
16393
|
+
@noble/curves/utils.js:
|
|
16394
|
+
@noble/curves/abstract/modular.js:
|
|
16395
|
+
@noble/curves/abstract/curve.js:
|
|
16396
|
+
@noble/curves/abstract/weierstrass.js:
|
|
16397
|
+
@noble/curves/secp256k1.js:
|
|
16398
|
+
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
16399
|
+
*/
|
|
13753
16400
|
//# sourceMappingURL=index.cjs.map
|