@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.js
CHANGED
|
@@ -59,10 +59,10 @@ function bech32Polymod(values) {
|
|
|
59
59
|
}
|
|
60
60
|
function bech32Checksum(hrp, data) {
|
|
61
61
|
const values = hrpExpand(hrp).concat(data).concat([0, 0, 0, 0, 0, 0]);
|
|
62
|
-
const
|
|
62
|
+
const mod2 = bech32Polymod(values) ^ 1;
|
|
63
63
|
const ret = [];
|
|
64
64
|
for (let p = 0; p < 6; p++) {
|
|
65
|
-
ret.push(
|
|
65
|
+
ret.push(mod2 >> 5 * (5 - p) & 31);
|
|
66
66
|
}
|
|
67
67
|
return ret;
|
|
68
68
|
}
|
|
@@ -833,9 +833,13 @@ var VestingClassifier = class {
|
|
|
833
833
|
storeName = "vestingCache";
|
|
834
834
|
db = null;
|
|
835
835
|
/**
|
|
836
|
-
* Initialize IndexedDB for persistent caching
|
|
836
|
+
* Initialize IndexedDB for persistent caching.
|
|
837
|
+
* In Node.js (no IndexedDB), silently falls back to memory-only caching.
|
|
837
838
|
*/
|
|
838
839
|
async initDB() {
|
|
840
|
+
if (typeof indexedDB === "undefined") {
|
|
841
|
+
return;
|
|
842
|
+
}
|
|
839
843
|
return new Promise((resolve, reject) => {
|
|
840
844
|
const request = indexedDB.open(this.dbName, 1);
|
|
841
845
|
request.onupgradeneeded = (event) => {
|
|
@@ -2518,6 +2522,9 @@ var STORAGE_KEYS = {
|
|
|
2518
2522
|
...STORAGE_KEYS_GLOBAL,
|
|
2519
2523
|
...STORAGE_KEYS_ADDRESS
|
|
2520
2524
|
};
|
|
2525
|
+
function getAddressStorageKey(addressId, key) {
|
|
2526
|
+
return `${addressId}_${key}`;
|
|
2527
|
+
}
|
|
2521
2528
|
function getAddressId(directAddress) {
|
|
2522
2529
|
let hash = directAddress;
|
|
2523
2530
|
if (hash.startsWith("DIRECT://")) {
|
|
@@ -6568,6 +6575,29 @@ var PaymentsModule = class _PaymentsModule {
|
|
|
6568
6575
|
this.nametags = [];
|
|
6569
6576
|
await this.save();
|
|
6570
6577
|
}
|
|
6578
|
+
/**
|
|
6579
|
+
* Reload nametag data from storage providers into memory.
|
|
6580
|
+
*
|
|
6581
|
+
* Used as a recovery mechanism when `this.nametags` is unexpectedly empty
|
|
6582
|
+
* (e.g., wiped by sync or race condition) but nametag data exists in storage.
|
|
6583
|
+
*/
|
|
6584
|
+
async reloadNametagsFromStorage() {
|
|
6585
|
+
const providers = this.getTokenStorageProviders();
|
|
6586
|
+
for (const [, provider] of providers) {
|
|
6587
|
+
try {
|
|
6588
|
+
const result = await provider.load();
|
|
6589
|
+
if (result.success && result.data) {
|
|
6590
|
+
const parsed = parseTxfStorageData(result.data);
|
|
6591
|
+
if (parsed.nametags.length > 0) {
|
|
6592
|
+
this.nametags = parsed.nametags;
|
|
6593
|
+
this.log(`Reloaded ${parsed.nametags.length} nametag(s) from storage`);
|
|
6594
|
+
return;
|
|
6595
|
+
}
|
|
6596
|
+
}
|
|
6597
|
+
} catch {
|
|
6598
|
+
}
|
|
6599
|
+
}
|
|
6600
|
+
}
|
|
6571
6601
|
/**
|
|
6572
6602
|
* Mint a nametag token on-chain (like Sphere wallet and lottery)
|
|
6573
6603
|
* This creates the nametag token required for receiving tokens via PROXY addresses
|
|
@@ -6692,11 +6722,15 @@ var PaymentsModule = class _PaymentsModule {
|
|
|
6692
6722
|
const localData = await this.createStorageData();
|
|
6693
6723
|
let totalAdded = 0;
|
|
6694
6724
|
let totalRemoved = 0;
|
|
6725
|
+
const savedNametags = [...this.nametags];
|
|
6695
6726
|
for (const [providerId, provider] of providers) {
|
|
6696
6727
|
try {
|
|
6697
6728
|
const result = await provider.sync(localData);
|
|
6698
6729
|
if (result.success && result.merged) {
|
|
6699
6730
|
this.loadFromStorageData(result.merged);
|
|
6731
|
+
if (this.nametags.length === 0 && savedNametags.length > 0) {
|
|
6732
|
+
this.nametags = savedNametags;
|
|
6733
|
+
}
|
|
6700
6734
|
totalAdded += result.added;
|
|
6701
6735
|
totalRemoved += result.removed;
|
|
6702
6736
|
}
|
|
@@ -6925,6 +6959,15 @@ var PaymentsModule = class _PaymentsModule {
|
|
|
6925
6959
|
);
|
|
6926
6960
|
return SigningService.createFromSecret(privateKeyBytes);
|
|
6927
6961
|
}
|
|
6962
|
+
/**
|
|
6963
|
+
* Get the wallet's signing public key (used for token ownership predicates).
|
|
6964
|
+
* This is the key that token state predicates are checked against.
|
|
6965
|
+
*/
|
|
6966
|
+
async getSigningPublicKey() {
|
|
6967
|
+
this.ensureInitialized();
|
|
6968
|
+
const signer = await this.createSigningService();
|
|
6969
|
+
return signer.publicKey;
|
|
6970
|
+
}
|
|
6928
6971
|
/**
|
|
6929
6972
|
* Create DirectAddress from a public key using UnmaskedPredicateReference
|
|
6930
6973
|
*/
|
|
@@ -7075,7 +7118,12 @@ var PaymentsModule = class _PaymentsModule {
|
|
|
7075
7118
|
let nametagTokens = [];
|
|
7076
7119
|
if (addressScheme === AddressScheme.PROXY) {
|
|
7077
7120
|
const { ProxyAddress } = await import("@unicitylabs/state-transition-sdk/lib/address/ProxyAddress");
|
|
7078
|
-
|
|
7121
|
+
let proxyNametag = this.getNametag();
|
|
7122
|
+
if (!proxyNametag?.token) {
|
|
7123
|
+
this.log("Nametag missing in memory, attempting reload from storage...");
|
|
7124
|
+
await this.reloadNametagsFromStorage();
|
|
7125
|
+
proxyNametag = this.getNametag();
|
|
7126
|
+
}
|
|
7079
7127
|
if (!proxyNametag?.token) {
|
|
7080
7128
|
throw new Error("Cannot finalize PROXY transfer - no nametag token");
|
|
7081
7129
|
}
|
|
@@ -7573,14 +7621,17 @@ var CommunicationsModule = class {
|
|
|
7573
7621
|
broadcasts = /* @__PURE__ */ new Map();
|
|
7574
7622
|
// Subscriptions
|
|
7575
7623
|
unsubscribeMessages = null;
|
|
7624
|
+
unsubscribeComposing = null;
|
|
7576
7625
|
broadcastSubscriptions = /* @__PURE__ */ new Map();
|
|
7577
7626
|
// Handlers
|
|
7578
7627
|
dmHandlers = /* @__PURE__ */ new Set();
|
|
7628
|
+
composingHandlers = /* @__PURE__ */ new Set();
|
|
7579
7629
|
broadcastHandlers = /* @__PURE__ */ new Set();
|
|
7580
7630
|
constructor(config) {
|
|
7581
7631
|
this.config = {
|
|
7582
7632
|
autoSave: config?.autoSave ?? true,
|
|
7583
7633
|
maxMessages: config?.maxMessages ?? 1e3,
|
|
7634
|
+
maxPerConversation: config?.maxPerConversation ?? 200,
|
|
7584
7635
|
readReceipts: config?.readReceipts ?? true
|
|
7585
7636
|
};
|
|
7586
7637
|
}
|
|
@@ -7591,6 +7642,8 @@ var CommunicationsModule = class {
|
|
|
7591
7642
|
* Initialize module with dependencies
|
|
7592
7643
|
*/
|
|
7593
7644
|
initialize(deps) {
|
|
7645
|
+
this.unsubscribeMessages?.();
|
|
7646
|
+
this.unsubscribeComposing?.();
|
|
7594
7647
|
this.deps = deps;
|
|
7595
7648
|
this.unsubscribeMessages = deps.transport.onMessage((msg) => {
|
|
7596
7649
|
this.handleIncomingMessage(msg);
|
|
@@ -7617,19 +7670,41 @@ var CommunicationsModule = class {
|
|
|
7617
7670
|
});
|
|
7618
7671
|
});
|
|
7619
7672
|
}
|
|
7673
|
+
this.unsubscribeComposing = deps.transport.onComposing?.((indicator) => {
|
|
7674
|
+
this.handleComposingIndicator(indicator);
|
|
7675
|
+
}) ?? null;
|
|
7620
7676
|
}
|
|
7621
7677
|
/**
|
|
7622
|
-
* Load messages from storage
|
|
7678
|
+
* Load messages from storage.
|
|
7679
|
+
* Uses per-address key (STORAGE_KEYS_ADDRESS.MESSAGES) which is automatically
|
|
7680
|
+
* scoped by LocalStorageProvider to sphere_DIRECT_xxx_yyy_messages.
|
|
7681
|
+
* Falls back to legacy global 'direct_messages' key for migration.
|
|
7623
7682
|
*/
|
|
7624
7683
|
async load() {
|
|
7625
7684
|
this.ensureInitialized();
|
|
7626
|
-
|
|
7685
|
+
this.messages.clear();
|
|
7686
|
+
let data = await this.deps.storage.get(STORAGE_KEYS_ADDRESS.MESSAGES);
|
|
7627
7687
|
if (data) {
|
|
7628
7688
|
const messages = JSON.parse(data);
|
|
7629
|
-
this.messages.clear();
|
|
7630
7689
|
for (const msg of messages) {
|
|
7631
7690
|
this.messages.set(msg.id, msg);
|
|
7632
7691
|
}
|
|
7692
|
+
return;
|
|
7693
|
+
}
|
|
7694
|
+
data = await this.deps.storage.get("direct_messages");
|
|
7695
|
+
if (data) {
|
|
7696
|
+
const allMessages = JSON.parse(data);
|
|
7697
|
+
const myPubkey = this.deps.identity.chainPubkey;
|
|
7698
|
+
const myMessages = allMessages.filter(
|
|
7699
|
+
(m) => m.senderPubkey === myPubkey || m.recipientPubkey === myPubkey
|
|
7700
|
+
);
|
|
7701
|
+
for (const msg of myMessages) {
|
|
7702
|
+
this.messages.set(msg.id, msg);
|
|
7703
|
+
}
|
|
7704
|
+
if (myMessages.length > 0) {
|
|
7705
|
+
await this.save();
|
|
7706
|
+
console.log(`[Communications] Migrated ${myMessages.length} messages to per-address storage`);
|
|
7707
|
+
}
|
|
7633
7708
|
}
|
|
7634
7709
|
}
|
|
7635
7710
|
/**
|
|
@@ -7638,6 +7713,8 @@ var CommunicationsModule = class {
|
|
|
7638
7713
|
destroy() {
|
|
7639
7714
|
this.unsubscribeMessages?.();
|
|
7640
7715
|
this.unsubscribeMessages = null;
|
|
7716
|
+
this.unsubscribeComposing?.();
|
|
7717
|
+
this.unsubscribeComposing = null;
|
|
7641
7718
|
for (const unsub of this.broadcastSubscriptions.values()) {
|
|
7642
7719
|
unsub();
|
|
7643
7720
|
}
|
|
@@ -7651,13 +7728,14 @@ var CommunicationsModule = class {
|
|
|
7651
7728
|
*/
|
|
7652
7729
|
async sendDM(recipient, content) {
|
|
7653
7730
|
this.ensureInitialized();
|
|
7654
|
-
const
|
|
7655
|
-
const eventId = await this.deps.transport.sendMessage(
|
|
7731
|
+
const resolved = await this.resolveRecipient(recipient);
|
|
7732
|
+
const eventId = await this.deps.transport.sendMessage(resolved.pubkey, content);
|
|
7656
7733
|
const message = {
|
|
7657
7734
|
id: eventId,
|
|
7658
7735
|
senderPubkey: this.deps.identity.chainPubkey,
|
|
7659
7736
|
senderNametag: this.deps.identity.nametag,
|
|
7660
|
-
recipientPubkey,
|
|
7737
|
+
recipientPubkey: resolved.pubkey,
|
|
7738
|
+
...resolved.nametag ? { recipientNametag: resolved.nametag } : {},
|
|
7661
7739
|
content,
|
|
7662
7740
|
timestamp: Date.now(),
|
|
7663
7741
|
isRead: false
|
|
@@ -7729,6 +7807,37 @@ var CommunicationsModule = class {
|
|
|
7729
7807
|
}
|
|
7730
7808
|
return messages.length;
|
|
7731
7809
|
}
|
|
7810
|
+
/**
|
|
7811
|
+
* Get a page of messages from a conversation (for lazy loading).
|
|
7812
|
+
* Returns messages in chronological order with a cursor for loading older messages.
|
|
7813
|
+
*/
|
|
7814
|
+
getConversationPage(peerPubkey, options) {
|
|
7815
|
+
const limit = options?.limit ?? 20;
|
|
7816
|
+
const before = options?.before ?? Infinity;
|
|
7817
|
+
const all = Array.from(this.messages.values()).filter(
|
|
7818
|
+
(m) => (m.senderPubkey === peerPubkey || m.recipientPubkey === peerPubkey) && m.timestamp < before
|
|
7819
|
+
).sort((a, b) => b.timestamp - a.timestamp);
|
|
7820
|
+
const page = all.slice(0, limit);
|
|
7821
|
+
return {
|
|
7822
|
+
messages: page.reverse(),
|
|
7823
|
+
// chronological order for display
|
|
7824
|
+
hasMore: all.length > limit,
|
|
7825
|
+
oldestTimestamp: page.length > 0 ? page[0].timestamp : null
|
|
7826
|
+
};
|
|
7827
|
+
}
|
|
7828
|
+
/**
|
|
7829
|
+
* Delete all messages in a conversation with a peer
|
|
7830
|
+
*/
|
|
7831
|
+
async deleteConversation(peerPubkey) {
|
|
7832
|
+
for (const [id, msg] of this.messages) {
|
|
7833
|
+
if (msg.senderPubkey === peerPubkey || msg.recipientPubkey === peerPubkey) {
|
|
7834
|
+
this.messages.delete(id);
|
|
7835
|
+
}
|
|
7836
|
+
}
|
|
7837
|
+
if (this.config.autoSave) {
|
|
7838
|
+
await this.save();
|
|
7839
|
+
}
|
|
7840
|
+
}
|
|
7732
7841
|
/**
|
|
7733
7842
|
* Send typing indicator to a peer
|
|
7734
7843
|
*/
|
|
@@ -7738,6 +7847,26 @@ var CommunicationsModule = class {
|
|
|
7738
7847
|
await this.deps.transport.sendTypingIndicator(peerPubkey);
|
|
7739
7848
|
}
|
|
7740
7849
|
}
|
|
7850
|
+
/**
|
|
7851
|
+
* Send a composing indicator to a peer.
|
|
7852
|
+
* Fire-and-forget — does not save to message history.
|
|
7853
|
+
*/
|
|
7854
|
+
async sendComposingIndicator(recipientPubkeyOrNametag) {
|
|
7855
|
+
this.ensureInitialized();
|
|
7856
|
+
const resolved = await this.resolveRecipient(recipientPubkeyOrNametag);
|
|
7857
|
+
const content = JSON.stringify({
|
|
7858
|
+
senderNametag: this.deps.identity.nametag,
|
|
7859
|
+
expiresIn: 3e4
|
|
7860
|
+
});
|
|
7861
|
+
await this.deps.transport.sendComposingIndicator?.(resolved.pubkey, content);
|
|
7862
|
+
}
|
|
7863
|
+
/**
|
|
7864
|
+
* Subscribe to incoming composing indicators
|
|
7865
|
+
*/
|
|
7866
|
+
onComposingIndicator(handler) {
|
|
7867
|
+
this.composingHandlers.add(handler);
|
|
7868
|
+
return () => this.composingHandlers.delete(handler);
|
|
7869
|
+
}
|
|
7741
7870
|
/**
|
|
7742
7871
|
* Subscribe to incoming DMs
|
|
7743
7872
|
*/
|
|
@@ -7850,6 +7979,21 @@ var CommunicationsModule = class {
|
|
|
7850
7979
|
}
|
|
7851
7980
|
this.pruneIfNeeded();
|
|
7852
7981
|
}
|
|
7982
|
+
handleComposingIndicator(indicator) {
|
|
7983
|
+
const composing = {
|
|
7984
|
+
senderPubkey: indicator.senderPubkey,
|
|
7985
|
+
senderNametag: indicator.senderNametag,
|
|
7986
|
+
expiresIn: indicator.expiresIn
|
|
7987
|
+
};
|
|
7988
|
+
this.deps.emitEvent("composing:started", composing);
|
|
7989
|
+
for (const handler of this.composingHandlers) {
|
|
7990
|
+
try {
|
|
7991
|
+
handler(composing);
|
|
7992
|
+
} catch (error) {
|
|
7993
|
+
console.error("[Communications] Composing handler error:", error);
|
|
7994
|
+
}
|
|
7995
|
+
}
|
|
7996
|
+
}
|
|
7853
7997
|
handleIncomingBroadcast(incoming) {
|
|
7854
7998
|
const message = {
|
|
7855
7999
|
id: incoming.id,
|
|
@@ -7873,9 +8017,23 @@ var CommunicationsModule = class {
|
|
|
7873
8017
|
// ===========================================================================
|
|
7874
8018
|
async save() {
|
|
7875
8019
|
const messages = Array.from(this.messages.values());
|
|
7876
|
-
await this.deps.storage.set(
|
|
8020
|
+
await this.deps.storage.set(STORAGE_KEYS_ADDRESS.MESSAGES, JSON.stringify(messages));
|
|
7877
8021
|
}
|
|
7878
8022
|
pruneIfNeeded() {
|
|
8023
|
+
const byPeer = /* @__PURE__ */ new Map();
|
|
8024
|
+
for (const msg of this.messages.values()) {
|
|
8025
|
+
const peer = msg.senderPubkey === this.deps?.identity.chainPubkey ? msg.recipientPubkey : msg.senderPubkey;
|
|
8026
|
+
if (!byPeer.has(peer)) byPeer.set(peer, []);
|
|
8027
|
+
byPeer.get(peer).push(msg);
|
|
8028
|
+
}
|
|
8029
|
+
for (const [, msgs] of byPeer) {
|
|
8030
|
+
if (msgs.length <= this.config.maxPerConversation) continue;
|
|
8031
|
+
msgs.sort((a, b) => a.timestamp - b.timestamp);
|
|
8032
|
+
const toRemove2 = msgs.slice(0, msgs.length - this.config.maxPerConversation);
|
|
8033
|
+
for (const msg of toRemove2) {
|
|
8034
|
+
this.messages.delete(msg.id);
|
|
8035
|
+
}
|
|
8036
|
+
}
|
|
7879
8037
|
if (this.messages.size <= this.config.maxMessages) return;
|
|
7880
8038
|
const sorted = Array.from(this.messages.entries()).sort(([, a], [, b]) => a.timestamp - b.timestamp);
|
|
7881
8039
|
const toRemove = sorted.slice(0, sorted.length - this.config.maxMessages);
|
|
@@ -7888,13 +8046,14 @@ var CommunicationsModule = class {
|
|
|
7888
8046
|
// ===========================================================================
|
|
7889
8047
|
async resolveRecipient(recipient) {
|
|
7890
8048
|
if (recipient.startsWith("@")) {
|
|
7891
|
-
const
|
|
8049
|
+
const nametag = recipient.slice(1);
|
|
8050
|
+
const pubkey = await this.deps.transport.resolveNametag?.(nametag);
|
|
7892
8051
|
if (!pubkey) {
|
|
7893
8052
|
throw new Error(`Nametag not found: ${recipient}`);
|
|
7894
8053
|
}
|
|
7895
|
-
return pubkey;
|
|
8054
|
+
return { pubkey, nametag };
|
|
7896
8055
|
}
|
|
7897
|
-
return recipient;
|
|
8056
|
+
return { pubkey: recipient };
|
|
7898
8057
|
}
|
|
7899
8058
|
ensureInitialized() {
|
|
7900
8059
|
if (!this.deps) {
|
|
@@ -9288,6 +9447,2427 @@ function createGroupChatModule(config) {
|
|
|
9288
9447
|
return new GroupChatModule(config);
|
|
9289
9448
|
}
|
|
9290
9449
|
|
|
9450
|
+
// node_modules/@noble/hashes/utils.js
|
|
9451
|
+
function isBytes(a) {
|
|
9452
|
+
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
|
|
9453
|
+
}
|
|
9454
|
+
function anumber(n, title = "") {
|
|
9455
|
+
if (!Number.isSafeInteger(n) || n < 0) {
|
|
9456
|
+
const prefix = title && `"${title}" `;
|
|
9457
|
+
throw new Error(`${prefix}expected integer >= 0, got ${n}`);
|
|
9458
|
+
}
|
|
9459
|
+
}
|
|
9460
|
+
function abytes(value, length, title = "") {
|
|
9461
|
+
const bytes = isBytes(value);
|
|
9462
|
+
const len = value?.length;
|
|
9463
|
+
const needsLen = length !== void 0;
|
|
9464
|
+
if (!bytes || needsLen && len !== length) {
|
|
9465
|
+
const prefix = title && `"${title}" `;
|
|
9466
|
+
const ofLen = needsLen ? ` of length ${length}` : "";
|
|
9467
|
+
const got = bytes ? `length=${len}` : `type=${typeof value}`;
|
|
9468
|
+
throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
|
|
9469
|
+
}
|
|
9470
|
+
return value;
|
|
9471
|
+
}
|
|
9472
|
+
function ahash(h) {
|
|
9473
|
+
if (typeof h !== "function" || typeof h.create !== "function")
|
|
9474
|
+
throw new Error("Hash must wrapped by utils.createHasher");
|
|
9475
|
+
anumber(h.outputLen);
|
|
9476
|
+
anumber(h.blockLen);
|
|
9477
|
+
}
|
|
9478
|
+
function aexists(instance, checkFinished = true) {
|
|
9479
|
+
if (instance.destroyed)
|
|
9480
|
+
throw new Error("Hash instance has been destroyed");
|
|
9481
|
+
if (checkFinished && instance.finished)
|
|
9482
|
+
throw new Error("Hash#digest() has already been called");
|
|
9483
|
+
}
|
|
9484
|
+
function aoutput(out, instance) {
|
|
9485
|
+
abytes(out, void 0, "digestInto() output");
|
|
9486
|
+
const min = instance.outputLen;
|
|
9487
|
+
if (out.length < min) {
|
|
9488
|
+
throw new Error('"digestInto() output" expected to be of length >=' + min);
|
|
9489
|
+
}
|
|
9490
|
+
}
|
|
9491
|
+
function clean(...arrays) {
|
|
9492
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
9493
|
+
arrays[i].fill(0);
|
|
9494
|
+
}
|
|
9495
|
+
}
|
|
9496
|
+
function createView(arr) {
|
|
9497
|
+
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
9498
|
+
}
|
|
9499
|
+
function rotr(word, shift) {
|
|
9500
|
+
return word << 32 - shift | word >>> shift;
|
|
9501
|
+
}
|
|
9502
|
+
var hasHexBuiltin = /* @__PURE__ */ (() => (
|
|
9503
|
+
// @ts-ignore
|
|
9504
|
+
typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
|
|
9505
|
+
))();
|
|
9506
|
+
var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
|
|
9507
|
+
function bytesToHex4(bytes) {
|
|
9508
|
+
abytes(bytes);
|
|
9509
|
+
if (hasHexBuiltin)
|
|
9510
|
+
return bytes.toHex();
|
|
9511
|
+
let hex = "";
|
|
9512
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
9513
|
+
hex += hexes[bytes[i]];
|
|
9514
|
+
}
|
|
9515
|
+
return hex;
|
|
9516
|
+
}
|
|
9517
|
+
var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
|
|
9518
|
+
function asciiToBase16(ch) {
|
|
9519
|
+
if (ch >= asciis._0 && ch <= asciis._9)
|
|
9520
|
+
return ch - asciis._0;
|
|
9521
|
+
if (ch >= asciis.A && ch <= asciis.F)
|
|
9522
|
+
return ch - (asciis.A - 10);
|
|
9523
|
+
if (ch >= asciis.a && ch <= asciis.f)
|
|
9524
|
+
return ch - (asciis.a - 10);
|
|
9525
|
+
return;
|
|
9526
|
+
}
|
|
9527
|
+
function hexToBytes2(hex) {
|
|
9528
|
+
if (typeof hex !== "string")
|
|
9529
|
+
throw new Error("hex string expected, got " + typeof hex);
|
|
9530
|
+
if (hasHexBuiltin)
|
|
9531
|
+
return Uint8Array.fromHex(hex);
|
|
9532
|
+
const hl = hex.length;
|
|
9533
|
+
const al = hl / 2;
|
|
9534
|
+
if (hl % 2)
|
|
9535
|
+
throw new Error("hex string expected, got unpadded hex of length " + hl);
|
|
9536
|
+
const array = new Uint8Array(al);
|
|
9537
|
+
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
9538
|
+
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
|
9539
|
+
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
|
9540
|
+
if (n1 === void 0 || n2 === void 0) {
|
|
9541
|
+
const char = hex[hi] + hex[hi + 1];
|
|
9542
|
+
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
9543
|
+
}
|
|
9544
|
+
array[ai] = n1 * 16 + n2;
|
|
9545
|
+
}
|
|
9546
|
+
return array;
|
|
9547
|
+
}
|
|
9548
|
+
function concatBytes(...arrays) {
|
|
9549
|
+
let sum = 0;
|
|
9550
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
9551
|
+
const a = arrays[i];
|
|
9552
|
+
abytes(a);
|
|
9553
|
+
sum += a.length;
|
|
9554
|
+
}
|
|
9555
|
+
const res = new Uint8Array(sum);
|
|
9556
|
+
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
9557
|
+
const a = arrays[i];
|
|
9558
|
+
res.set(a, pad);
|
|
9559
|
+
pad += a.length;
|
|
9560
|
+
}
|
|
9561
|
+
return res;
|
|
9562
|
+
}
|
|
9563
|
+
function createHasher(hashCons, info = {}) {
|
|
9564
|
+
const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
|
|
9565
|
+
const tmp = hashCons(void 0);
|
|
9566
|
+
hashC.outputLen = tmp.outputLen;
|
|
9567
|
+
hashC.blockLen = tmp.blockLen;
|
|
9568
|
+
hashC.create = (opts) => hashCons(opts);
|
|
9569
|
+
Object.assign(hashC, info);
|
|
9570
|
+
return Object.freeze(hashC);
|
|
9571
|
+
}
|
|
9572
|
+
function randomBytes2(bytesLength = 32) {
|
|
9573
|
+
const cr = typeof globalThis === "object" ? globalThis.crypto : null;
|
|
9574
|
+
if (typeof cr?.getRandomValues !== "function")
|
|
9575
|
+
throw new Error("crypto.getRandomValues must be defined");
|
|
9576
|
+
return cr.getRandomValues(new Uint8Array(bytesLength));
|
|
9577
|
+
}
|
|
9578
|
+
var oidNist = (suffix) => ({
|
|
9579
|
+
oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
|
|
9580
|
+
});
|
|
9581
|
+
|
|
9582
|
+
// node_modules/@noble/hashes/_md.js
|
|
9583
|
+
function Chi(a, b, c) {
|
|
9584
|
+
return a & b ^ ~a & c;
|
|
9585
|
+
}
|
|
9586
|
+
function Maj(a, b, c) {
|
|
9587
|
+
return a & b ^ a & c ^ b & c;
|
|
9588
|
+
}
|
|
9589
|
+
var HashMD = class {
|
|
9590
|
+
blockLen;
|
|
9591
|
+
outputLen;
|
|
9592
|
+
padOffset;
|
|
9593
|
+
isLE;
|
|
9594
|
+
// For partial updates less than block size
|
|
9595
|
+
buffer;
|
|
9596
|
+
view;
|
|
9597
|
+
finished = false;
|
|
9598
|
+
length = 0;
|
|
9599
|
+
pos = 0;
|
|
9600
|
+
destroyed = false;
|
|
9601
|
+
constructor(blockLen, outputLen, padOffset, isLE) {
|
|
9602
|
+
this.blockLen = blockLen;
|
|
9603
|
+
this.outputLen = outputLen;
|
|
9604
|
+
this.padOffset = padOffset;
|
|
9605
|
+
this.isLE = isLE;
|
|
9606
|
+
this.buffer = new Uint8Array(blockLen);
|
|
9607
|
+
this.view = createView(this.buffer);
|
|
9608
|
+
}
|
|
9609
|
+
update(data) {
|
|
9610
|
+
aexists(this);
|
|
9611
|
+
abytes(data);
|
|
9612
|
+
const { view, buffer, blockLen } = this;
|
|
9613
|
+
const len = data.length;
|
|
9614
|
+
for (let pos = 0; pos < len; ) {
|
|
9615
|
+
const take = Math.min(blockLen - this.pos, len - pos);
|
|
9616
|
+
if (take === blockLen) {
|
|
9617
|
+
const dataView = createView(data);
|
|
9618
|
+
for (; blockLen <= len - pos; pos += blockLen)
|
|
9619
|
+
this.process(dataView, pos);
|
|
9620
|
+
continue;
|
|
9621
|
+
}
|
|
9622
|
+
buffer.set(data.subarray(pos, pos + take), this.pos);
|
|
9623
|
+
this.pos += take;
|
|
9624
|
+
pos += take;
|
|
9625
|
+
if (this.pos === blockLen) {
|
|
9626
|
+
this.process(view, 0);
|
|
9627
|
+
this.pos = 0;
|
|
9628
|
+
}
|
|
9629
|
+
}
|
|
9630
|
+
this.length += data.length;
|
|
9631
|
+
this.roundClean();
|
|
9632
|
+
return this;
|
|
9633
|
+
}
|
|
9634
|
+
digestInto(out) {
|
|
9635
|
+
aexists(this);
|
|
9636
|
+
aoutput(out, this);
|
|
9637
|
+
this.finished = true;
|
|
9638
|
+
const { buffer, view, blockLen, isLE } = this;
|
|
9639
|
+
let { pos } = this;
|
|
9640
|
+
buffer[pos++] = 128;
|
|
9641
|
+
clean(this.buffer.subarray(pos));
|
|
9642
|
+
if (this.padOffset > blockLen - pos) {
|
|
9643
|
+
this.process(view, 0);
|
|
9644
|
+
pos = 0;
|
|
9645
|
+
}
|
|
9646
|
+
for (let i = pos; i < blockLen; i++)
|
|
9647
|
+
buffer[i] = 0;
|
|
9648
|
+
view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
|
|
9649
|
+
this.process(view, 0);
|
|
9650
|
+
const oview = createView(out);
|
|
9651
|
+
const len = this.outputLen;
|
|
9652
|
+
if (len % 4)
|
|
9653
|
+
throw new Error("_sha2: outputLen must be aligned to 32bit");
|
|
9654
|
+
const outLen = len / 4;
|
|
9655
|
+
const state = this.get();
|
|
9656
|
+
if (outLen > state.length)
|
|
9657
|
+
throw new Error("_sha2: outputLen bigger than state");
|
|
9658
|
+
for (let i = 0; i < outLen; i++)
|
|
9659
|
+
oview.setUint32(4 * i, state[i], isLE);
|
|
9660
|
+
}
|
|
9661
|
+
digest() {
|
|
9662
|
+
const { buffer, outputLen } = this;
|
|
9663
|
+
this.digestInto(buffer);
|
|
9664
|
+
const res = buffer.slice(0, outputLen);
|
|
9665
|
+
this.destroy();
|
|
9666
|
+
return res;
|
|
9667
|
+
}
|
|
9668
|
+
_cloneInto(to) {
|
|
9669
|
+
to ||= new this.constructor();
|
|
9670
|
+
to.set(...this.get());
|
|
9671
|
+
const { blockLen, buffer, length, finished, destroyed, pos } = this;
|
|
9672
|
+
to.destroyed = destroyed;
|
|
9673
|
+
to.finished = finished;
|
|
9674
|
+
to.length = length;
|
|
9675
|
+
to.pos = pos;
|
|
9676
|
+
if (length % blockLen)
|
|
9677
|
+
to.buffer.set(buffer);
|
|
9678
|
+
return to;
|
|
9679
|
+
}
|
|
9680
|
+
clone() {
|
|
9681
|
+
return this._cloneInto();
|
|
9682
|
+
}
|
|
9683
|
+
};
|
|
9684
|
+
var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
|
|
9685
|
+
1779033703,
|
|
9686
|
+
3144134277,
|
|
9687
|
+
1013904242,
|
|
9688
|
+
2773480762,
|
|
9689
|
+
1359893119,
|
|
9690
|
+
2600822924,
|
|
9691
|
+
528734635,
|
|
9692
|
+
1541459225
|
|
9693
|
+
]);
|
|
9694
|
+
|
|
9695
|
+
// node_modules/@noble/hashes/sha2.js
|
|
9696
|
+
var SHA256_K = /* @__PURE__ */ Uint32Array.from([
|
|
9697
|
+
1116352408,
|
|
9698
|
+
1899447441,
|
|
9699
|
+
3049323471,
|
|
9700
|
+
3921009573,
|
|
9701
|
+
961987163,
|
|
9702
|
+
1508970993,
|
|
9703
|
+
2453635748,
|
|
9704
|
+
2870763221,
|
|
9705
|
+
3624381080,
|
|
9706
|
+
310598401,
|
|
9707
|
+
607225278,
|
|
9708
|
+
1426881987,
|
|
9709
|
+
1925078388,
|
|
9710
|
+
2162078206,
|
|
9711
|
+
2614888103,
|
|
9712
|
+
3248222580,
|
|
9713
|
+
3835390401,
|
|
9714
|
+
4022224774,
|
|
9715
|
+
264347078,
|
|
9716
|
+
604807628,
|
|
9717
|
+
770255983,
|
|
9718
|
+
1249150122,
|
|
9719
|
+
1555081692,
|
|
9720
|
+
1996064986,
|
|
9721
|
+
2554220882,
|
|
9722
|
+
2821834349,
|
|
9723
|
+
2952996808,
|
|
9724
|
+
3210313671,
|
|
9725
|
+
3336571891,
|
|
9726
|
+
3584528711,
|
|
9727
|
+
113926993,
|
|
9728
|
+
338241895,
|
|
9729
|
+
666307205,
|
|
9730
|
+
773529912,
|
|
9731
|
+
1294757372,
|
|
9732
|
+
1396182291,
|
|
9733
|
+
1695183700,
|
|
9734
|
+
1986661051,
|
|
9735
|
+
2177026350,
|
|
9736
|
+
2456956037,
|
|
9737
|
+
2730485921,
|
|
9738
|
+
2820302411,
|
|
9739
|
+
3259730800,
|
|
9740
|
+
3345764771,
|
|
9741
|
+
3516065817,
|
|
9742
|
+
3600352804,
|
|
9743
|
+
4094571909,
|
|
9744
|
+
275423344,
|
|
9745
|
+
430227734,
|
|
9746
|
+
506948616,
|
|
9747
|
+
659060556,
|
|
9748
|
+
883997877,
|
|
9749
|
+
958139571,
|
|
9750
|
+
1322822218,
|
|
9751
|
+
1537002063,
|
|
9752
|
+
1747873779,
|
|
9753
|
+
1955562222,
|
|
9754
|
+
2024104815,
|
|
9755
|
+
2227730452,
|
|
9756
|
+
2361852424,
|
|
9757
|
+
2428436474,
|
|
9758
|
+
2756734187,
|
|
9759
|
+
3204031479,
|
|
9760
|
+
3329325298
|
|
9761
|
+
]);
|
|
9762
|
+
var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
|
|
9763
|
+
var SHA2_32B = class extends HashMD {
|
|
9764
|
+
constructor(outputLen) {
|
|
9765
|
+
super(64, outputLen, 8, false);
|
|
9766
|
+
}
|
|
9767
|
+
get() {
|
|
9768
|
+
const { A, B, C, D, E, F, G, H } = this;
|
|
9769
|
+
return [A, B, C, D, E, F, G, H];
|
|
9770
|
+
}
|
|
9771
|
+
// prettier-ignore
|
|
9772
|
+
set(A, B, C, D, E, F, G, H) {
|
|
9773
|
+
this.A = A | 0;
|
|
9774
|
+
this.B = B | 0;
|
|
9775
|
+
this.C = C | 0;
|
|
9776
|
+
this.D = D | 0;
|
|
9777
|
+
this.E = E | 0;
|
|
9778
|
+
this.F = F | 0;
|
|
9779
|
+
this.G = G | 0;
|
|
9780
|
+
this.H = H | 0;
|
|
9781
|
+
}
|
|
9782
|
+
process(view, offset) {
|
|
9783
|
+
for (let i = 0; i < 16; i++, offset += 4)
|
|
9784
|
+
SHA256_W[i] = view.getUint32(offset, false);
|
|
9785
|
+
for (let i = 16; i < 64; i++) {
|
|
9786
|
+
const W15 = SHA256_W[i - 15];
|
|
9787
|
+
const W2 = SHA256_W[i - 2];
|
|
9788
|
+
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
|
|
9789
|
+
const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
|
|
9790
|
+
SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
|
|
9791
|
+
}
|
|
9792
|
+
let { A, B, C, D, E, F, G, H } = this;
|
|
9793
|
+
for (let i = 0; i < 64; i++) {
|
|
9794
|
+
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
|
|
9795
|
+
const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
|
|
9796
|
+
const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
|
|
9797
|
+
const T2 = sigma0 + Maj(A, B, C) | 0;
|
|
9798
|
+
H = G;
|
|
9799
|
+
G = F;
|
|
9800
|
+
F = E;
|
|
9801
|
+
E = D + T1 | 0;
|
|
9802
|
+
D = C;
|
|
9803
|
+
C = B;
|
|
9804
|
+
B = A;
|
|
9805
|
+
A = T1 + T2 | 0;
|
|
9806
|
+
}
|
|
9807
|
+
A = A + this.A | 0;
|
|
9808
|
+
B = B + this.B | 0;
|
|
9809
|
+
C = C + this.C | 0;
|
|
9810
|
+
D = D + this.D | 0;
|
|
9811
|
+
E = E + this.E | 0;
|
|
9812
|
+
F = F + this.F | 0;
|
|
9813
|
+
G = G + this.G | 0;
|
|
9814
|
+
H = H + this.H | 0;
|
|
9815
|
+
this.set(A, B, C, D, E, F, G, H);
|
|
9816
|
+
}
|
|
9817
|
+
roundClean() {
|
|
9818
|
+
clean(SHA256_W);
|
|
9819
|
+
}
|
|
9820
|
+
destroy() {
|
|
9821
|
+
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
|
9822
|
+
clean(this.buffer);
|
|
9823
|
+
}
|
|
9824
|
+
};
|
|
9825
|
+
var _SHA256 = class extends SHA2_32B {
|
|
9826
|
+
// We cannot use array here since array allows indexing by variable
|
|
9827
|
+
// which means optimizer/compiler cannot use registers.
|
|
9828
|
+
A = SHA256_IV[0] | 0;
|
|
9829
|
+
B = SHA256_IV[1] | 0;
|
|
9830
|
+
C = SHA256_IV[2] | 0;
|
|
9831
|
+
D = SHA256_IV[3] | 0;
|
|
9832
|
+
E = SHA256_IV[4] | 0;
|
|
9833
|
+
F = SHA256_IV[5] | 0;
|
|
9834
|
+
G = SHA256_IV[6] | 0;
|
|
9835
|
+
H = SHA256_IV[7] | 0;
|
|
9836
|
+
constructor() {
|
|
9837
|
+
super(32);
|
|
9838
|
+
}
|
|
9839
|
+
};
|
|
9840
|
+
var sha2564 = /* @__PURE__ */ createHasher(
|
|
9841
|
+
() => new _SHA256(),
|
|
9842
|
+
/* @__PURE__ */ oidNist(1)
|
|
9843
|
+
);
|
|
9844
|
+
|
|
9845
|
+
// node_modules/@noble/curves/utils.js
|
|
9846
|
+
var _0n = /* @__PURE__ */ BigInt(0);
|
|
9847
|
+
var _1n = /* @__PURE__ */ BigInt(1);
|
|
9848
|
+
function abool(value, title = "") {
|
|
9849
|
+
if (typeof value !== "boolean") {
|
|
9850
|
+
const prefix = title && `"${title}" `;
|
|
9851
|
+
throw new Error(prefix + "expected boolean, got type=" + typeof value);
|
|
9852
|
+
}
|
|
9853
|
+
return value;
|
|
9854
|
+
}
|
|
9855
|
+
function abignumber(n) {
|
|
9856
|
+
if (typeof n === "bigint") {
|
|
9857
|
+
if (!isPosBig(n))
|
|
9858
|
+
throw new Error("positive bigint expected, got " + n);
|
|
9859
|
+
} else
|
|
9860
|
+
anumber(n);
|
|
9861
|
+
return n;
|
|
9862
|
+
}
|
|
9863
|
+
function numberToHexUnpadded(num) {
|
|
9864
|
+
const hex = abignumber(num).toString(16);
|
|
9865
|
+
return hex.length & 1 ? "0" + hex : hex;
|
|
9866
|
+
}
|
|
9867
|
+
function hexToNumber(hex) {
|
|
9868
|
+
if (typeof hex !== "string")
|
|
9869
|
+
throw new Error("hex string expected, got " + typeof hex);
|
|
9870
|
+
return hex === "" ? _0n : BigInt("0x" + hex);
|
|
9871
|
+
}
|
|
9872
|
+
function bytesToNumberBE(bytes) {
|
|
9873
|
+
return hexToNumber(bytesToHex4(bytes));
|
|
9874
|
+
}
|
|
9875
|
+
function bytesToNumberLE(bytes) {
|
|
9876
|
+
return hexToNumber(bytesToHex4(copyBytes(abytes(bytes)).reverse()));
|
|
9877
|
+
}
|
|
9878
|
+
function numberToBytesBE(n, len) {
|
|
9879
|
+
anumber(len);
|
|
9880
|
+
n = abignumber(n);
|
|
9881
|
+
const res = hexToBytes2(n.toString(16).padStart(len * 2, "0"));
|
|
9882
|
+
if (res.length !== len)
|
|
9883
|
+
throw new Error("number too large");
|
|
9884
|
+
return res;
|
|
9885
|
+
}
|
|
9886
|
+
function numberToBytesLE(n, len) {
|
|
9887
|
+
return numberToBytesBE(n, len).reverse();
|
|
9888
|
+
}
|
|
9889
|
+
function copyBytes(bytes) {
|
|
9890
|
+
return Uint8Array.from(bytes);
|
|
9891
|
+
}
|
|
9892
|
+
var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
|
|
9893
|
+
function inRange(n, min, max) {
|
|
9894
|
+
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
|
|
9895
|
+
}
|
|
9896
|
+
function aInRange(title, n, min, max) {
|
|
9897
|
+
if (!inRange(n, min, max))
|
|
9898
|
+
throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
|
|
9899
|
+
}
|
|
9900
|
+
function bitLen(n) {
|
|
9901
|
+
let len;
|
|
9902
|
+
for (len = 0; n > _0n; n >>= _1n, len += 1)
|
|
9903
|
+
;
|
|
9904
|
+
return len;
|
|
9905
|
+
}
|
|
9906
|
+
var bitMask = (n) => (_1n << BigInt(n)) - _1n;
|
|
9907
|
+
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
9908
|
+
anumber(hashLen, "hashLen");
|
|
9909
|
+
anumber(qByteLen, "qByteLen");
|
|
9910
|
+
if (typeof hmacFn !== "function")
|
|
9911
|
+
throw new Error("hmacFn must be a function");
|
|
9912
|
+
const u8n = (len) => new Uint8Array(len);
|
|
9913
|
+
const NULL = Uint8Array.of();
|
|
9914
|
+
const byte0 = Uint8Array.of(0);
|
|
9915
|
+
const byte1 = Uint8Array.of(1);
|
|
9916
|
+
const _maxDrbgIters = 1e3;
|
|
9917
|
+
let v = u8n(hashLen);
|
|
9918
|
+
let k = u8n(hashLen);
|
|
9919
|
+
let i = 0;
|
|
9920
|
+
const reset = () => {
|
|
9921
|
+
v.fill(1);
|
|
9922
|
+
k.fill(0);
|
|
9923
|
+
i = 0;
|
|
9924
|
+
};
|
|
9925
|
+
const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));
|
|
9926
|
+
const reseed = (seed = NULL) => {
|
|
9927
|
+
k = h(byte0, seed);
|
|
9928
|
+
v = h();
|
|
9929
|
+
if (seed.length === 0)
|
|
9930
|
+
return;
|
|
9931
|
+
k = h(byte1, seed);
|
|
9932
|
+
v = h();
|
|
9933
|
+
};
|
|
9934
|
+
const gen = () => {
|
|
9935
|
+
if (i++ >= _maxDrbgIters)
|
|
9936
|
+
throw new Error("drbg: tried max amount of iterations");
|
|
9937
|
+
let len = 0;
|
|
9938
|
+
const out = [];
|
|
9939
|
+
while (len < qByteLen) {
|
|
9940
|
+
v = h();
|
|
9941
|
+
const sl = v.slice();
|
|
9942
|
+
out.push(sl);
|
|
9943
|
+
len += v.length;
|
|
9944
|
+
}
|
|
9945
|
+
return concatBytes(...out);
|
|
9946
|
+
};
|
|
9947
|
+
const genUntil = (seed, pred) => {
|
|
9948
|
+
reset();
|
|
9949
|
+
reseed(seed);
|
|
9950
|
+
let res = void 0;
|
|
9951
|
+
while (!(res = pred(gen())))
|
|
9952
|
+
reseed();
|
|
9953
|
+
reset();
|
|
9954
|
+
return res;
|
|
9955
|
+
};
|
|
9956
|
+
return genUntil;
|
|
9957
|
+
}
|
|
9958
|
+
function validateObject(object, fields = {}, optFields = {}) {
|
|
9959
|
+
if (!object || typeof object !== "object")
|
|
9960
|
+
throw new Error("expected valid options object");
|
|
9961
|
+
function checkField(fieldName, expectedType, isOpt) {
|
|
9962
|
+
const val = object[fieldName];
|
|
9963
|
+
if (isOpt && val === void 0)
|
|
9964
|
+
return;
|
|
9965
|
+
const current = typeof val;
|
|
9966
|
+
if (current !== expectedType || val === null)
|
|
9967
|
+
throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
|
|
9968
|
+
}
|
|
9969
|
+
const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
|
|
9970
|
+
iter(fields, false);
|
|
9971
|
+
iter(optFields, true);
|
|
9972
|
+
}
|
|
9973
|
+
function memoized(fn) {
|
|
9974
|
+
const map = /* @__PURE__ */ new WeakMap();
|
|
9975
|
+
return (arg, ...args) => {
|
|
9976
|
+
const val = map.get(arg);
|
|
9977
|
+
if (val !== void 0)
|
|
9978
|
+
return val;
|
|
9979
|
+
const computed = fn(arg, ...args);
|
|
9980
|
+
map.set(arg, computed);
|
|
9981
|
+
return computed;
|
|
9982
|
+
};
|
|
9983
|
+
}
|
|
9984
|
+
|
|
9985
|
+
// node_modules/@noble/curves/abstract/modular.js
|
|
9986
|
+
var _0n2 = /* @__PURE__ */ BigInt(0);
|
|
9987
|
+
var _1n2 = /* @__PURE__ */ BigInt(1);
|
|
9988
|
+
var _2n = /* @__PURE__ */ BigInt(2);
|
|
9989
|
+
var _3n = /* @__PURE__ */ BigInt(3);
|
|
9990
|
+
var _4n = /* @__PURE__ */ BigInt(4);
|
|
9991
|
+
var _5n = /* @__PURE__ */ BigInt(5);
|
|
9992
|
+
var _7n = /* @__PURE__ */ BigInt(7);
|
|
9993
|
+
var _8n = /* @__PURE__ */ BigInt(8);
|
|
9994
|
+
var _9n = /* @__PURE__ */ BigInt(9);
|
|
9995
|
+
var _16n = /* @__PURE__ */ BigInt(16);
|
|
9996
|
+
function mod(a, b) {
|
|
9997
|
+
const result = a % b;
|
|
9998
|
+
return result >= _0n2 ? result : b + result;
|
|
9999
|
+
}
|
|
10000
|
+
function pow2(x, power, modulo) {
|
|
10001
|
+
let res = x;
|
|
10002
|
+
while (power-- > _0n2) {
|
|
10003
|
+
res *= res;
|
|
10004
|
+
res %= modulo;
|
|
10005
|
+
}
|
|
10006
|
+
return res;
|
|
10007
|
+
}
|
|
10008
|
+
function invert(number, modulo) {
|
|
10009
|
+
if (number === _0n2)
|
|
10010
|
+
throw new Error("invert: expected non-zero number");
|
|
10011
|
+
if (modulo <= _0n2)
|
|
10012
|
+
throw new Error("invert: expected positive modulus, got " + modulo);
|
|
10013
|
+
let a = mod(number, modulo);
|
|
10014
|
+
let b = modulo;
|
|
10015
|
+
let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
|
|
10016
|
+
while (a !== _0n2) {
|
|
10017
|
+
const q = b / a;
|
|
10018
|
+
const r = b % a;
|
|
10019
|
+
const m = x - u * q;
|
|
10020
|
+
const n = y - v * q;
|
|
10021
|
+
b = a, a = r, x = u, y = v, u = m, v = n;
|
|
10022
|
+
}
|
|
10023
|
+
const gcd = b;
|
|
10024
|
+
if (gcd !== _1n2)
|
|
10025
|
+
throw new Error("invert: does not exist");
|
|
10026
|
+
return mod(x, modulo);
|
|
10027
|
+
}
|
|
10028
|
+
function assertIsSquare(Fp, root, n) {
|
|
10029
|
+
if (!Fp.eql(Fp.sqr(root), n))
|
|
10030
|
+
throw new Error("Cannot find square root");
|
|
10031
|
+
}
|
|
10032
|
+
function sqrt3mod4(Fp, n) {
|
|
10033
|
+
const p1div4 = (Fp.ORDER + _1n2) / _4n;
|
|
10034
|
+
const root = Fp.pow(n, p1div4);
|
|
10035
|
+
assertIsSquare(Fp, root, n);
|
|
10036
|
+
return root;
|
|
10037
|
+
}
|
|
10038
|
+
function sqrt5mod8(Fp, n) {
|
|
10039
|
+
const p5div8 = (Fp.ORDER - _5n) / _8n;
|
|
10040
|
+
const n2 = Fp.mul(n, _2n);
|
|
10041
|
+
const v = Fp.pow(n2, p5div8);
|
|
10042
|
+
const nv = Fp.mul(n, v);
|
|
10043
|
+
const i = Fp.mul(Fp.mul(nv, _2n), v);
|
|
10044
|
+
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
|
|
10045
|
+
assertIsSquare(Fp, root, n);
|
|
10046
|
+
return root;
|
|
10047
|
+
}
|
|
10048
|
+
function sqrt9mod16(P) {
|
|
10049
|
+
const Fp_ = Field(P);
|
|
10050
|
+
const tn = tonelliShanks(P);
|
|
10051
|
+
const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
|
|
10052
|
+
const c2 = tn(Fp_, c1);
|
|
10053
|
+
const c3 = tn(Fp_, Fp_.neg(c1));
|
|
10054
|
+
const c4 = (P + _7n) / _16n;
|
|
10055
|
+
return (Fp, n) => {
|
|
10056
|
+
let tv1 = Fp.pow(n, c4);
|
|
10057
|
+
let tv2 = Fp.mul(tv1, c1);
|
|
10058
|
+
const tv3 = Fp.mul(tv1, c2);
|
|
10059
|
+
const tv4 = Fp.mul(tv1, c3);
|
|
10060
|
+
const e1 = Fp.eql(Fp.sqr(tv2), n);
|
|
10061
|
+
const e2 = Fp.eql(Fp.sqr(tv3), n);
|
|
10062
|
+
tv1 = Fp.cmov(tv1, tv2, e1);
|
|
10063
|
+
tv2 = Fp.cmov(tv4, tv3, e2);
|
|
10064
|
+
const e3 = Fp.eql(Fp.sqr(tv2), n);
|
|
10065
|
+
const root = Fp.cmov(tv1, tv2, e3);
|
|
10066
|
+
assertIsSquare(Fp, root, n);
|
|
10067
|
+
return root;
|
|
10068
|
+
};
|
|
10069
|
+
}
|
|
10070
|
+
function tonelliShanks(P) {
|
|
10071
|
+
if (P < _3n)
|
|
10072
|
+
throw new Error("sqrt is not defined for small field");
|
|
10073
|
+
let Q = P - _1n2;
|
|
10074
|
+
let S = 0;
|
|
10075
|
+
while (Q % _2n === _0n2) {
|
|
10076
|
+
Q /= _2n;
|
|
10077
|
+
S++;
|
|
10078
|
+
}
|
|
10079
|
+
let Z = _2n;
|
|
10080
|
+
const _Fp = Field(P);
|
|
10081
|
+
while (FpLegendre(_Fp, Z) === 1) {
|
|
10082
|
+
if (Z++ > 1e3)
|
|
10083
|
+
throw new Error("Cannot find square root: probably non-prime P");
|
|
10084
|
+
}
|
|
10085
|
+
if (S === 1)
|
|
10086
|
+
return sqrt3mod4;
|
|
10087
|
+
let cc = _Fp.pow(Z, Q);
|
|
10088
|
+
const Q1div2 = (Q + _1n2) / _2n;
|
|
10089
|
+
return function tonelliSlow(Fp, n) {
|
|
10090
|
+
if (Fp.is0(n))
|
|
10091
|
+
return n;
|
|
10092
|
+
if (FpLegendre(Fp, n) !== 1)
|
|
10093
|
+
throw new Error("Cannot find square root");
|
|
10094
|
+
let M = S;
|
|
10095
|
+
let c = Fp.mul(Fp.ONE, cc);
|
|
10096
|
+
let t = Fp.pow(n, Q);
|
|
10097
|
+
let R = Fp.pow(n, Q1div2);
|
|
10098
|
+
while (!Fp.eql(t, Fp.ONE)) {
|
|
10099
|
+
if (Fp.is0(t))
|
|
10100
|
+
return Fp.ZERO;
|
|
10101
|
+
let i = 1;
|
|
10102
|
+
let t_tmp = Fp.sqr(t);
|
|
10103
|
+
while (!Fp.eql(t_tmp, Fp.ONE)) {
|
|
10104
|
+
i++;
|
|
10105
|
+
t_tmp = Fp.sqr(t_tmp);
|
|
10106
|
+
if (i === M)
|
|
10107
|
+
throw new Error("Cannot find square root");
|
|
10108
|
+
}
|
|
10109
|
+
const exponent = _1n2 << BigInt(M - i - 1);
|
|
10110
|
+
const b = Fp.pow(c, exponent);
|
|
10111
|
+
M = i;
|
|
10112
|
+
c = Fp.sqr(b);
|
|
10113
|
+
t = Fp.mul(t, c);
|
|
10114
|
+
R = Fp.mul(R, b);
|
|
10115
|
+
}
|
|
10116
|
+
return R;
|
|
10117
|
+
};
|
|
10118
|
+
}
|
|
10119
|
+
function FpSqrt(P) {
|
|
10120
|
+
if (P % _4n === _3n)
|
|
10121
|
+
return sqrt3mod4;
|
|
10122
|
+
if (P % _8n === _5n)
|
|
10123
|
+
return sqrt5mod8;
|
|
10124
|
+
if (P % _16n === _9n)
|
|
10125
|
+
return sqrt9mod16(P);
|
|
10126
|
+
return tonelliShanks(P);
|
|
10127
|
+
}
|
|
10128
|
+
var FIELD_FIELDS = [
|
|
10129
|
+
"create",
|
|
10130
|
+
"isValid",
|
|
10131
|
+
"is0",
|
|
10132
|
+
"neg",
|
|
10133
|
+
"inv",
|
|
10134
|
+
"sqrt",
|
|
10135
|
+
"sqr",
|
|
10136
|
+
"eql",
|
|
10137
|
+
"add",
|
|
10138
|
+
"sub",
|
|
10139
|
+
"mul",
|
|
10140
|
+
"pow",
|
|
10141
|
+
"div",
|
|
10142
|
+
"addN",
|
|
10143
|
+
"subN",
|
|
10144
|
+
"mulN",
|
|
10145
|
+
"sqrN"
|
|
10146
|
+
];
|
|
10147
|
+
function validateField(field) {
|
|
10148
|
+
const initial = {
|
|
10149
|
+
ORDER: "bigint",
|
|
10150
|
+
BYTES: "number",
|
|
10151
|
+
BITS: "number"
|
|
10152
|
+
};
|
|
10153
|
+
const opts = FIELD_FIELDS.reduce((map, val) => {
|
|
10154
|
+
map[val] = "function";
|
|
10155
|
+
return map;
|
|
10156
|
+
}, initial);
|
|
10157
|
+
validateObject(field, opts);
|
|
10158
|
+
return field;
|
|
10159
|
+
}
|
|
10160
|
+
function FpPow(Fp, num, power) {
|
|
10161
|
+
if (power < _0n2)
|
|
10162
|
+
throw new Error("invalid exponent, negatives unsupported");
|
|
10163
|
+
if (power === _0n2)
|
|
10164
|
+
return Fp.ONE;
|
|
10165
|
+
if (power === _1n2)
|
|
10166
|
+
return num;
|
|
10167
|
+
let p = Fp.ONE;
|
|
10168
|
+
let d = num;
|
|
10169
|
+
while (power > _0n2) {
|
|
10170
|
+
if (power & _1n2)
|
|
10171
|
+
p = Fp.mul(p, d);
|
|
10172
|
+
d = Fp.sqr(d);
|
|
10173
|
+
power >>= _1n2;
|
|
10174
|
+
}
|
|
10175
|
+
return p;
|
|
10176
|
+
}
|
|
10177
|
+
function FpInvertBatch(Fp, nums, passZero = false) {
|
|
10178
|
+
const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
|
|
10179
|
+
const multipliedAcc = nums.reduce((acc, num, i) => {
|
|
10180
|
+
if (Fp.is0(num))
|
|
10181
|
+
return acc;
|
|
10182
|
+
inverted[i] = acc;
|
|
10183
|
+
return Fp.mul(acc, num);
|
|
10184
|
+
}, Fp.ONE);
|
|
10185
|
+
const invertedAcc = Fp.inv(multipliedAcc);
|
|
10186
|
+
nums.reduceRight((acc, num, i) => {
|
|
10187
|
+
if (Fp.is0(num))
|
|
10188
|
+
return acc;
|
|
10189
|
+
inverted[i] = Fp.mul(acc, inverted[i]);
|
|
10190
|
+
return Fp.mul(acc, num);
|
|
10191
|
+
}, invertedAcc);
|
|
10192
|
+
return inverted;
|
|
10193
|
+
}
|
|
10194
|
+
function FpLegendre(Fp, n) {
|
|
10195
|
+
const p1mod2 = (Fp.ORDER - _1n2) / _2n;
|
|
10196
|
+
const powered = Fp.pow(n, p1mod2);
|
|
10197
|
+
const yes = Fp.eql(powered, Fp.ONE);
|
|
10198
|
+
const zero = Fp.eql(powered, Fp.ZERO);
|
|
10199
|
+
const no = Fp.eql(powered, Fp.neg(Fp.ONE));
|
|
10200
|
+
if (!yes && !zero && !no)
|
|
10201
|
+
throw new Error("invalid Legendre symbol result");
|
|
10202
|
+
return yes ? 1 : zero ? 0 : -1;
|
|
10203
|
+
}
|
|
10204
|
+
function nLength(n, nBitLength) {
|
|
10205
|
+
if (nBitLength !== void 0)
|
|
10206
|
+
anumber(nBitLength);
|
|
10207
|
+
const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
|
|
10208
|
+
const nByteLength = Math.ceil(_nBitLength / 8);
|
|
10209
|
+
return { nBitLength: _nBitLength, nByteLength };
|
|
10210
|
+
}
|
|
10211
|
+
var _Field = class {
|
|
10212
|
+
ORDER;
|
|
10213
|
+
BITS;
|
|
10214
|
+
BYTES;
|
|
10215
|
+
isLE;
|
|
10216
|
+
ZERO = _0n2;
|
|
10217
|
+
ONE = _1n2;
|
|
10218
|
+
_lengths;
|
|
10219
|
+
_sqrt;
|
|
10220
|
+
// cached sqrt
|
|
10221
|
+
_mod;
|
|
10222
|
+
constructor(ORDER, opts = {}) {
|
|
10223
|
+
if (ORDER <= _0n2)
|
|
10224
|
+
throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
|
|
10225
|
+
let _nbitLength = void 0;
|
|
10226
|
+
this.isLE = false;
|
|
10227
|
+
if (opts != null && typeof opts === "object") {
|
|
10228
|
+
if (typeof opts.BITS === "number")
|
|
10229
|
+
_nbitLength = opts.BITS;
|
|
10230
|
+
if (typeof opts.sqrt === "function")
|
|
10231
|
+
this.sqrt = opts.sqrt;
|
|
10232
|
+
if (typeof opts.isLE === "boolean")
|
|
10233
|
+
this.isLE = opts.isLE;
|
|
10234
|
+
if (opts.allowedLengths)
|
|
10235
|
+
this._lengths = opts.allowedLengths?.slice();
|
|
10236
|
+
if (typeof opts.modFromBytes === "boolean")
|
|
10237
|
+
this._mod = opts.modFromBytes;
|
|
10238
|
+
}
|
|
10239
|
+
const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
|
|
10240
|
+
if (nByteLength > 2048)
|
|
10241
|
+
throw new Error("invalid field: expected ORDER of <= 2048 bytes");
|
|
10242
|
+
this.ORDER = ORDER;
|
|
10243
|
+
this.BITS = nBitLength;
|
|
10244
|
+
this.BYTES = nByteLength;
|
|
10245
|
+
this._sqrt = void 0;
|
|
10246
|
+
Object.preventExtensions(this);
|
|
10247
|
+
}
|
|
10248
|
+
create(num) {
|
|
10249
|
+
return mod(num, this.ORDER);
|
|
10250
|
+
}
|
|
10251
|
+
isValid(num) {
|
|
10252
|
+
if (typeof num !== "bigint")
|
|
10253
|
+
throw new Error("invalid field element: expected bigint, got " + typeof num);
|
|
10254
|
+
return _0n2 <= num && num < this.ORDER;
|
|
10255
|
+
}
|
|
10256
|
+
is0(num) {
|
|
10257
|
+
return num === _0n2;
|
|
10258
|
+
}
|
|
10259
|
+
// is valid and invertible
|
|
10260
|
+
isValidNot0(num) {
|
|
10261
|
+
return !this.is0(num) && this.isValid(num);
|
|
10262
|
+
}
|
|
10263
|
+
isOdd(num) {
|
|
10264
|
+
return (num & _1n2) === _1n2;
|
|
10265
|
+
}
|
|
10266
|
+
neg(num) {
|
|
10267
|
+
return mod(-num, this.ORDER);
|
|
10268
|
+
}
|
|
10269
|
+
eql(lhs, rhs) {
|
|
10270
|
+
return lhs === rhs;
|
|
10271
|
+
}
|
|
10272
|
+
sqr(num) {
|
|
10273
|
+
return mod(num * num, this.ORDER);
|
|
10274
|
+
}
|
|
10275
|
+
add(lhs, rhs) {
|
|
10276
|
+
return mod(lhs + rhs, this.ORDER);
|
|
10277
|
+
}
|
|
10278
|
+
sub(lhs, rhs) {
|
|
10279
|
+
return mod(lhs - rhs, this.ORDER);
|
|
10280
|
+
}
|
|
10281
|
+
mul(lhs, rhs) {
|
|
10282
|
+
return mod(lhs * rhs, this.ORDER);
|
|
10283
|
+
}
|
|
10284
|
+
pow(num, power) {
|
|
10285
|
+
return FpPow(this, num, power);
|
|
10286
|
+
}
|
|
10287
|
+
div(lhs, rhs) {
|
|
10288
|
+
return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
|
|
10289
|
+
}
|
|
10290
|
+
// Same as above, but doesn't normalize
|
|
10291
|
+
sqrN(num) {
|
|
10292
|
+
return num * num;
|
|
10293
|
+
}
|
|
10294
|
+
addN(lhs, rhs) {
|
|
10295
|
+
return lhs + rhs;
|
|
10296
|
+
}
|
|
10297
|
+
subN(lhs, rhs) {
|
|
10298
|
+
return lhs - rhs;
|
|
10299
|
+
}
|
|
10300
|
+
mulN(lhs, rhs) {
|
|
10301
|
+
return lhs * rhs;
|
|
10302
|
+
}
|
|
10303
|
+
inv(num) {
|
|
10304
|
+
return invert(num, this.ORDER);
|
|
10305
|
+
}
|
|
10306
|
+
sqrt(num) {
|
|
10307
|
+
if (!this._sqrt)
|
|
10308
|
+
this._sqrt = FpSqrt(this.ORDER);
|
|
10309
|
+
return this._sqrt(this, num);
|
|
10310
|
+
}
|
|
10311
|
+
toBytes(num) {
|
|
10312
|
+
return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
|
|
10313
|
+
}
|
|
10314
|
+
fromBytes(bytes, skipValidation = false) {
|
|
10315
|
+
abytes(bytes);
|
|
10316
|
+
const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
|
|
10317
|
+
if (allowedLengths) {
|
|
10318
|
+
if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
|
|
10319
|
+
throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
|
|
10320
|
+
}
|
|
10321
|
+
const padded = new Uint8Array(BYTES);
|
|
10322
|
+
padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
|
|
10323
|
+
bytes = padded;
|
|
10324
|
+
}
|
|
10325
|
+
if (bytes.length !== BYTES)
|
|
10326
|
+
throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
|
|
10327
|
+
let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
|
|
10328
|
+
if (modFromBytes)
|
|
10329
|
+
scalar = mod(scalar, ORDER);
|
|
10330
|
+
if (!skipValidation) {
|
|
10331
|
+
if (!this.isValid(scalar))
|
|
10332
|
+
throw new Error("invalid field element: outside of range 0..ORDER");
|
|
10333
|
+
}
|
|
10334
|
+
return scalar;
|
|
10335
|
+
}
|
|
10336
|
+
// TODO: we don't need it here, move out to separate fn
|
|
10337
|
+
invertBatch(lst) {
|
|
10338
|
+
return FpInvertBatch(this, lst);
|
|
10339
|
+
}
|
|
10340
|
+
// We can't move this out because Fp6, Fp12 implement it
|
|
10341
|
+
// and it's unclear what to return in there.
|
|
10342
|
+
cmov(a, b, condition) {
|
|
10343
|
+
return condition ? b : a;
|
|
10344
|
+
}
|
|
10345
|
+
};
|
|
10346
|
+
function Field(ORDER, opts = {}) {
|
|
10347
|
+
return new _Field(ORDER, opts);
|
|
10348
|
+
}
|
|
10349
|
+
function getFieldBytesLength(fieldOrder) {
|
|
10350
|
+
if (typeof fieldOrder !== "bigint")
|
|
10351
|
+
throw new Error("field order must be bigint");
|
|
10352
|
+
const bitLength = fieldOrder.toString(2).length;
|
|
10353
|
+
return Math.ceil(bitLength / 8);
|
|
10354
|
+
}
|
|
10355
|
+
function getMinHashLength(fieldOrder) {
|
|
10356
|
+
const length = getFieldBytesLength(fieldOrder);
|
|
10357
|
+
return length + Math.ceil(length / 2);
|
|
10358
|
+
}
|
|
10359
|
+
function mapHashToField(key, fieldOrder, isLE = false) {
|
|
10360
|
+
abytes(key);
|
|
10361
|
+
const len = key.length;
|
|
10362
|
+
const fieldLen = getFieldBytesLength(fieldOrder);
|
|
10363
|
+
const minLen = getMinHashLength(fieldOrder);
|
|
10364
|
+
if (len < 16 || len < minLen || len > 1024)
|
|
10365
|
+
throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
|
|
10366
|
+
const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
|
|
10367
|
+
const reduced = mod(num, fieldOrder - _1n2) + _1n2;
|
|
10368
|
+
return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
|
|
10369
|
+
}
|
|
10370
|
+
|
|
10371
|
+
// node_modules/@noble/curves/abstract/curve.js
|
|
10372
|
+
var _0n3 = /* @__PURE__ */ BigInt(0);
|
|
10373
|
+
var _1n3 = /* @__PURE__ */ BigInt(1);
|
|
10374
|
+
function negateCt(condition, item) {
|
|
10375
|
+
const neg = item.negate();
|
|
10376
|
+
return condition ? neg : item;
|
|
10377
|
+
}
|
|
10378
|
+
function normalizeZ(c, points) {
|
|
10379
|
+
const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
|
|
10380
|
+
return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
|
|
10381
|
+
}
|
|
10382
|
+
function validateW(W, bits) {
|
|
10383
|
+
if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
|
|
10384
|
+
throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
|
|
10385
|
+
}
|
|
10386
|
+
function calcWOpts(W, scalarBits) {
|
|
10387
|
+
validateW(W, scalarBits);
|
|
10388
|
+
const windows = Math.ceil(scalarBits / W) + 1;
|
|
10389
|
+
const windowSize = 2 ** (W - 1);
|
|
10390
|
+
const maxNumber = 2 ** W;
|
|
10391
|
+
const mask = bitMask(W);
|
|
10392
|
+
const shiftBy = BigInt(W);
|
|
10393
|
+
return { windows, windowSize, mask, maxNumber, shiftBy };
|
|
10394
|
+
}
|
|
10395
|
+
function calcOffsets(n, window, wOpts) {
|
|
10396
|
+
const { windowSize, mask, maxNumber, shiftBy } = wOpts;
|
|
10397
|
+
let wbits = Number(n & mask);
|
|
10398
|
+
let nextN = n >> shiftBy;
|
|
10399
|
+
if (wbits > windowSize) {
|
|
10400
|
+
wbits -= maxNumber;
|
|
10401
|
+
nextN += _1n3;
|
|
10402
|
+
}
|
|
10403
|
+
const offsetStart = window * windowSize;
|
|
10404
|
+
const offset = offsetStart + Math.abs(wbits) - 1;
|
|
10405
|
+
const isZero = wbits === 0;
|
|
10406
|
+
const isNeg = wbits < 0;
|
|
10407
|
+
const isNegF = window % 2 !== 0;
|
|
10408
|
+
const offsetF = offsetStart;
|
|
10409
|
+
return { nextN, offset, isZero, isNeg, isNegF, offsetF };
|
|
10410
|
+
}
|
|
10411
|
+
var pointPrecomputes = /* @__PURE__ */ new WeakMap();
|
|
10412
|
+
var pointWindowSizes = /* @__PURE__ */ new WeakMap();
|
|
10413
|
+
function getW(P) {
|
|
10414
|
+
return pointWindowSizes.get(P) || 1;
|
|
10415
|
+
}
|
|
10416
|
+
function assert0(n) {
|
|
10417
|
+
if (n !== _0n3)
|
|
10418
|
+
throw new Error("invalid wNAF");
|
|
10419
|
+
}
|
|
10420
|
+
var wNAF = class {
|
|
10421
|
+
BASE;
|
|
10422
|
+
ZERO;
|
|
10423
|
+
Fn;
|
|
10424
|
+
bits;
|
|
10425
|
+
// Parametrized with a given Point class (not individual point)
|
|
10426
|
+
constructor(Point, bits) {
|
|
10427
|
+
this.BASE = Point.BASE;
|
|
10428
|
+
this.ZERO = Point.ZERO;
|
|
10429
|
+
this.Fn = Point.Fn;
|
|
10430
|
+
this.bits = bits;
|
|
10431
|
+
}
|
|
10432
|
+
// non-const time multiplication ladder
|
|
10433
|
+
_unsafeLadder(elm, n, p = this.ZERO) {
|
|
10434
|
+
let d = elm;
|
|
10435
|
+
while (n > _0n3) {
|
|
10436
|
+
if (n & _1n3)
|
|
10437
|
+
p = p.add(d);
|
|
10438
|
+
d = d.double();
|
|
10439
|
+
n >>= _1n3;
|
|
10440
|
+
}
|
|
10441
|
+
return p;
|
|
10442
|
+
}
|
|
10443
|
+
/**
|
|
10444
|
+
* Creates a wNAF precomputation window. Used for caching.
|
|
10445
|
+
* Default window size is set by `utils.precompute()` and is equal to 8.
|
|
10446
|
+
* Number of precomputed points depends on the curve size:
|
|
10447
|
+
* 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
|
|
10448
|
+
* - 𝑊 is the window size
|
|
10449
|
+
* - 𝑛 is the bitlength of the curve order.
|
|
10450
|
+
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
|
|
10451
|
+
* @param point Point instance
|
|
10452
|
+
* @param W window size
|
|
10453
|
+
* @returns precomputed point tables flattened to a single array
|
|
10454
|
+
*/
|
|
10455
|
+
precomputeWindow(point, W) {
|
|
10456
|
+
const { windows, windowSize } = calcWOpts(W, this.bits);
|
|
10457
|
+
const points = [];
|
|
10458
|
+
let p = point;
|
|
10459
|
+
let base = p;
|
|
10460
|
+
for (let window = 0; window < windows; window++) {
|
|
10461
|
+
base = p;
|
|
10462
|
+
points.push(base);
|
|
10463
|
+
for (let i = 1; i < windowSize; i++) {
|
|
10464
|
+
base = base.add(p);
|
|
10465
|
+
points.push(base);
|
|
10466
|
+
}
|
|
10467
|
+
p = base.double();
|
|
10468
|
+
}
|
|
10469
|
+
return points;
|
|
10470
|
+
}
|
|
10471
|
+
/**
|
|
10472
|
+
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
|
|
10473
|
+
* More compact implementation:
|
|
10474
|
+
* https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
|
|
10475
|
+
* @returns real and fake (for const-time) points
|
|
10476
|
+
*/
|
|
10477
|
+
wNAF(W, precomputes, n) {
|
|
10478
|
+
if (!this.Fn.isValid(n))
|
|
10479
|
+
throw new Error("invalid scalar");
|
|
10480
|
+
let p = this.ZERO;
|
|
10481
|
+
let f = this.BASE;
|
|
10482
|
+
const wo = calcWOpts(W, this.bits);
|
|
10483
|
+
for (let window = 0; window < wo.windows; window++) {
|
|
10484
|
+
const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
|
|
10485
|
+
n = nextN;
|
|
10486
|
+
if (isZero) {
|
|
10487
|
+
f = f.add(negateCt(isNegF, precomputes[offsetF]));
|
|
10488
|
+
} else {
|
|
10489
|
+
p = p.add(negateCt(isNeg, precomputes[offset]));
|
|
10490
|
+
}
|
|
10491
|
+
}
|
|
10492
|
+
assert0(n);
|
|
10493
|
+
return { p, f };
|
|
10494
|
+
}
|
|
10495
|
+
/**
|
|
10496
|
+
* Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
|
|
10497
|
+
* @param acc accumulator point to add result of multiplication
|
|
10498
|
+
* @returns point
|
|
10499
|
+
*/
|
|
10500
|
+
wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
|
|
10501
|
+
const wo = calcWOpts(W, this.bits);
|
|
10502
|
+
for (let window = 0; window < wo.windows; window++) {
|
|
10503
|
+
if (n === _0n3)
|
|
10504
|
+
break;
|
|
10505
|
+
const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
|
|
10506
|
+
n = nextN;
|
|
10507
|
+
if (isZero) {
|
|
10508
|
+
continue;
|
|
10509
|
+
} else {
|
|
10510
|
+
const item = precomputes[offset];
|
|
10511
|
+
acc = acc.add(isNeg ? item.negate() : item);
|
|
10512
|
+
}
|
|
10513
|
+
}
|
|
10514
|
+
assert0(n);
|
|
10515
|
+
return acc;
|
|
10516
|
+
}
|
|
10517
|
+
getPrecomputes(W, point, transform) {
|
|
10518
|
+
let comp = pointPrecomputes.get(point);
|
|
10519
|
+
if (!comp) {
|
|
10520
|
+
comp = this.precomputeWindow(point, W);
|
|
10521
|
+
if (W !== 1) {
|
|
10522
|
+
if (typeof transform === "function")
|
|
10523
|
+
comp = transform(comp);
|
|
10524
|
+
pointPrecomputes.set(point, comp);
|
|
10525
|
+
}
|
|
10526
|
+
}
|
|
10527
|
+
return comp;
|
|
10528
|
+
}
|
|
10529
|
+
cached(point, scalar, transform) {
|
|
10530
|
+
const W = getW(point);
|
|
10531
|
+
return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
|
|
10532
|
+
}
|
|
10533
|
+
unsafe(point, scalar, transform, prev) {
|
|
10534
|
+
const W = getW(point);
|
|
10535
|
+
if (W === 1)
|
|
10536
|
+
return this._unsafeLadder(point, scalar, prev);
|
|
10537
|
+
return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
|
|
10538
|
+
}
|
|
10539
|
+
// We calculate precomputes for elliptic curve point multiplication
|
|
10540
|
+
// using windowed method. This specifies window size and
|
|
10541
|
+
// stores precomputed values. Usually only base point would be precomputed.
|
|
10542
|
+
createCache(P, W) {
|
|
10543
|
+
validateW(W, this.bits);
|
|
10544
|
+
pointWindowSizes.set(P, W);
|
|
10545
|
+
pointPrecomputes.delete(P);
|
|
10546
|
+
}
|
|
10547
|
+
hasCache(elm) {
|
|
10548
|
+
return getW(elm) !== 1;
|
|
10549
|
+
}
|
|
10550
|
+
};
|
|
10551
|
+
function mulEndoUnsafe(Point, point, k1, k2) {
|
|
10552
|
+
let acc = point;
|
|
10553
|
+
let p1 = Point.ZERO;
|
|
10554
|
+
let p2 = Point.ZERO;
|
|
10555
|
+
while (k1 > _0n3 || k2 > _0n3) {
|
|
10556
|
+
if (k1 & _1n3)
|
|
10557
|
+
p1 = p1.add(acc);
|
|
10558
|
+
if (k2 & _1n3)
|
|
10559
|
+
p2 = p2.add(acc);
|
|
10560
|
+
acc = acc.double();
|
|
10561
|
+
k1 >>= _1n3;
|
|
10562
|
+
k2 >>= _1n3;
|
|
10563
|
+
}
|
|
10564
|
+
return { p1, p2 };
|
|
10565
|
+
}
|
|
10566
|
+
function createField(order, field, isLE) {
|
|
10567
|
+
if (field) {
|
|
10568
|
+
if (field.ORDER !== order)
|
|
10569
|
+
throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
|
|
10570
|
+
validateField(field);
|
|
10571
|
+
return field;
|
|
10572
|
+
} else {
|
|
10573
|
+
return Field(order, { isLE });
|
|
10574
|
+
}
|
|
10575
|
+
}
|
|
10576
|
+
function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
|
|
10577
|
+
if (FpFnLE === void 0)
|
|
10578
|
+
FpFnLE = type === "edwards";
|
|
10579
|
+
if (!CURVE || typeof CURVE !== "object")
|
|
10580
|
+
throw new Error(`expected valid ${type} CURVE object`);
|
|
10581
|
+
for (const p of ["p", "n", "h"]) {
|
|
10582
|
+
const val = CURVE[p];
|
|
10583
|
+
if (!(typeof val === "bigint" && val > _0n3))
|
|
10584
|
+
throw new Error(`CURVE.${p} must be positive bigint`);
|
|
10585
|
+
}
|
|
10586
|
+
const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
|
|
10587
|
+
const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
|
|
10588
|
+
const _b = type === "weierstrass" ? "b" : "d";
|
|
10589
|
+
const params = ["Gx", "Gy", "a", _b];
|
|
10590
|
+
for (const p of params) {
|
|
10591
|
+
if (!Fp.isValid(CURVE[p]))
|
|
10592
|
+
throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
|
|
10593
|
+
}
|
|
10594
|
+
CURVE = Object.freeze(Object.assign({}, CURVE));
|
|
10595
|
+
return { CURVE, Fp, Fn };
|
|
10596
|
+
}
|
|
10597
|
+
function createKeygen(randomSecretKey, getPublicKey2) {
|
|
10598
|
+
return function keygen(seed) {
|
|
10599
|
+
const secretKey = randomSecretKey(seed);
|
|
10600
|
+
return { secretKey, publicKey: getPublicKey2(secretKey) };
|
|
10601
|
+
};
|
|
10602
|
+
}
|
|
10603
|
+
|
|
10604
|
+
// node_modules/@noble/hashes/hmac.js
|
|
10605
|
+
var _HMAC = class {
|
|
10606
|
+
oHash;
|
|
10607
|
+
iHash;
|
|
10608
|
+
blockLen;
|
|
10609
|
+
outputLen;
|
|
10610
|
+
finished = false;
|
|
10611
|
+
destroyed = false;
|
|
10612
|
+
constructor(hash, key) {
|
|
10613
|
+
ahash(hash);
|
|
10614
|
+
abytes(key, void 0, "key");
|
|
10615
|
+
this.iHash = hash.create();
|
|
10616
|
+
if (typeof this.iHash.update !== "function")
|
|
10617
|
+
throw new Error("Expected instance of class which extends utils.Hash");
|
|
10618
|
+
this.blockLen = this.iHash.blockLen;
|
|
10619
|
+
this.outputLen = this.iHash.outputLen;
|
|
10620
|
+
const blockLen = this.blockLen;
|
|
10621
|
+
const pad = new Uint8Array(blockLen);
|
|
10622
|
+
pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
|
|
10623
|
+
for (let i = 0; i < pad.length; i++)
|
|
10624
|
+
pad[i] ^= 54;
|
|
10625
|
+
this.iHash.update(pad);
|
|
10626
|
+
this.oHash = hash.create();
|
|
10627
|
+
for (let i = 0; i < pad.length; i++)
|
|
10628
|
+
pad[i] ^= 54 ^ 92;
|
|
10629
|
+
this.oHash.update(pad);
|
|
10630
|
+
clean(pad);
|
|
10631
|
+
}
|
|
10632
|
+
update(buf) {
|
|
10633
|
+
aexists(this);
|
|
10634
|
+
this.iHash.update(buf);
|
|
10635
|
+
return this;
|
|
10636
|
+
}
|
|
10637
|
+
digestInto(out) {
|
|
10638
|
+
aexists(this);
|
|
10639
|
+
abytes(out, this.outputLen, "output");
|
|
10640
|
+
this.finished = true;
|
|
10641
|
+
this.iHash.digestInto(out);
|
|
10642
|
+
this.oHash.update(out);
|
|
10643
|
+
this.oHash.digestInto(out);
|
|
10644
|
+
this.destroy();
|
|
10645
|
+
}
|
|
10646
|
+
digest() {
|
|
10647
|
+
const out = new Uint8Array(this.oHash.outputLen);
|
|
10648
|
+
this.digestInto(out);
|
|
10649
|
+
return out;
|
|
10650
|
+
}
|
|
10651
|
+
_cloneInto(to) {
|
|
10652
|
+
to ||= Object.create(Object.getPrototypeOf(this), {});
|
|
10653
|
+
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
|
|
10654
|
+
to = to;
|
|
10655
|
+
to.finished = finished;
|
|
10656
|
+
to.destroyed = destroyed;
|
|
10657
|
+
to.blockLen = blockLen;
|
|
10658
|
+
to.outputLen = outputLen;
|
|
10659
|
+
to.oHash = oHash._cloneInto(to.oHash);
|
|
10660
|
+
to.iHash = iHash._cloneInto(to.iHash);
|
|
10661
|
+
return to;
|
|
10662
|
+
}
|
|
10663
|
+
clone() {
|
|
10664
|
+
return this._cloneInto();
|
|
10665
|
+
}
|
|
10666
|
+
destroy() {
|
|
10667
|
+
this.destroyed = true;
|
|
10668
|
+
this.oHash.destroy();
|
|
10669
|
+
this.iHash.destroy();
|
|
10670
|
+
}
|
|
10671
|
+
};
|
|
10672
|
+
var hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();
|
|
10673
|
+
hmac.create = (hash, key) => new _HMAC(hash, key);
|
|
10674
|
+
|
|
10675
|
+
// node_modules/@noble/curves/abstract/weierstrass.js
|
|
10676
|
+
var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den;
|
|
10677
|
+
function _splitEndoScalar(k, basis, n) {
|
|
10678
|
+
const [[a1, b1], [a2, b2]] = basis;
|
|
10679
|
+
const c1 = divNearest(b2 * k, n);
|
|
10680
|
+
const c2 = divNearest(-b1 * k, n);
|
|
10681
|
+
let k1 = k - c1 * a1 - c2 * a2;
|
|
10682
|
+
let k2 = -c1 * b1 - c2 * b2;
|
|
10683
|
+
const k1neg = k1 < _0n4;
|
|
10684
|
+
const k2neg = k2 < _0n4;
|
|
10685
|
+
if (k1neg)
|
|
10686
|
+
k1 = -k1;
|
|
10687
|
+
if (k2neg)
|
|
10688
|
+
k2 = -k2;
|
|
10689
|
+
const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
|
|
10690
|
+
if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) {
|
|
10691
|
+
throw new Error("splitScalar (endomorphism): failed, k=" + k);
|
|
10692
|
+
}
|
|
10693
|
+
return { k1neg, k1, k2neg, k2 };
|
|
10694
|
+
}
|
|
10695
|
+
function validateSigFormat(format) {
|
|
10696
|
+
if (!["compact", "recovered", "der"].includes(format))
|
|
10697
|
+
throw new Error('Signature format must be "compact", "recovered", or "der"');
|
|
10698
|
+
return format;
|
|
10699
|
+
}
|
|
10700
|
+
function validateSigOpts(opts, def) {
|
|
10701
|
+
const optsn = {};
|
|
10702
|
+
for (let optName of Object.keys(def)) {
|
|
10703
|
+
optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
|
|
10704
|
+
}
|
|
10705
|
+
abool(optsn.lowS, "lowS");
|
|
10706
|
+
abool(optsn.prehash, "prehash");
|
|
10707
|
+
if (optsn.format !== void 0)
|
|
10708
|
+
validateSigFormat(optsn.format);
|
|
10709
|
+
return optsn;
|
|
10710
|
+
}
|
|
10711
|
+
var DERErr = class extends Error {
|
|
10712
|
+
constructor(m = "") {
|
|
10713
|
+
super(m);
|
|
10714
|
+
}
|
|
10715
|
+
};
|
|
10716
|
+
var DER = {
|
|
10717
|
+
// asn.1 DER encoding utils
|
|
10718
|
+
Err: DERErr,
|
|
10719
|
+
// Basic building block is TLV (Tag-Length-Value)
|
|
10720
|
+
_tlv: {
|
|
10721
|
+
encode: (tag, data) => {
|
|
10722
|
+
const { Err: E } = DER;
|
|
10723
|
+
if (tag < 0 || tag > 256)
|
|
10724
|
+
throw new E("tlv.encode: wrong tag");
|
|
10725
|
+
if (data.length & 1)
|
|
10726
|
+
throw new E("tlv.encode: unpadded data");
|
|
10727
|
+
const dataLen = data.length / 2;
|
|
10728
|
+
const len = numberToHexUnpadded(dataLen);
|
|
10729
|
+
if (len.length / 2 & 128)
|
|
10730
|
+
throw new E("tlv.encode: long form length too big");
|
|
10731
|
+
const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
|
|
10732
|
+
const t = numberToHexUnpadded(tag);
|
|
10733
|
+
return t + lenLen + len + data;
|
|
10734
|
+
},
|
|
10735
|
+
// v - value, l - left bytes (unparsed)
|
|
10736
|
+
decode(tag, data) {
|
|
10737
|
+
const { Err: E } = DER;
|
|
10738
|
+
let pos = 0;
|
|
10739
|
+
if (tag < 0 || tag > 256)
|
|
10740
|
+
throw new E("tlv.encode: wrong tag");
|
|
10741
|
+
if (data.length < 2 || data[pos++] !== tag)
|
|
10742
|
+
throw new E("tlv.decode: wrong tlv");
|
|
10743
|
+
const first = data[pos++];
|
|
10744
|
+
const isLong = !!(first & 128);
|
|
10745
|
+
let length = 0;
|
|
10746
|
+
if (!isLong)
|
|
10747
|
+
length = first;
|
|
10748
|
+
else {
|
|
10749
|
+
const lenLen = first & 127;
|
|
10750
|
+
if (!lenLen)
|
|
10751
|
+
throw new E("tlv.decode(long): indefinite length not supported");
|
|
10752
|
+
if (lenLen > 4)
|
|
10753
|
+
throw new E("tlv.decode(long): byte length is too big");
|
|
10754
|
+
const lengthBytes = data.subarray(pos, pos + lenLen);
|
|
10755
|
+
if (lengthBytes.length !== lenLen)
|
|
10756
|
+
throw new E("tlv.decode: length bytes not complete");
|
|
10757
|
+
if (lengthBytes[0] === 0)
|
|
10758
|
+
throw new E("tlv.decode(long): zero leftmost byte");
|
|
10759
|
+
for (const b of lengthBytes)
|
|
10760
|
+
length = length << 8 | b;
|
|
10761
|
+
pos += lenLen;
|
|
10762
|
+
if (length < 128)
|
|
10763
|
+
throw new E("tlv.decode(long): not minimal encoding");
|
|
10764
|
+
}
|
|
10765
|
+
const v = data.subarray(pos, pos + length);
|
|
10766
|
+
if (v.length !== length)
|
|
10767
|
+
throw new E("tlv.decode: wrong value length");
|
|
10768
|
+
return { v, l: data.subarray(pos + length) };
|
|
10769
|
+
}
|
|
10770
|
+
},
|
|
10771
|
+
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
|
|
10772
|
+
// since we always use positive integers here. It must always be empty:
|
|
10773
|
+
// - add zero byte if exists
|
|
10774
|
+
// - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
|
|
10775
|
+
_int: {
|
|
10776
|
+
encode(num) {
|
|
10777
|
+
const { Err: E } = DER;
|
|
10778
|
+
if (num < _0n4)
|
|
10779
|
+
throw new E("integer: negative integers are not allowed");
|
|
10780
|
+
let hex = numberToHexUnpadded(num);
|
|
10781
|
+
if (Number.parseInt(hex[0], 16) & 8)
|
|
10782
|
+
hex = "00" + hex;
|
|
10783
|
+
if (hex.length & 1)
|
|
10784
|
+
throw new E("unexpected DER parsing assertion: unpadded hex");
|
|
10785
|
+
return hex;
|
|
10786
|
+
},
|
|
10787
|
+
decode(data) {
|
|
10788
|
+
const { Err: E } = DER;
|
|
10789
|
+
if (data[0] & 128)
|
|
10790
|
+
throw new E("invalid signature integer: negative");
|
|
10791
|
+
if (data[0] === 0 && !(data[1] & 128))
|
|
10792
|
+
throw new E("invalid signature integer: unnecessary leading zero");
|
|
10793
|
+
return bytesToNumberBE(data);
|
|
10794
|
+
}
|
|
10795
|
+
},
|
|
10796
|
+
toSig(bytes) {
|
|
10797
|
+
const { Err: E, _int: int, _tlv: tlv } = DER;
|
|
10798
|
+
const data = abytes(bytes, void 0, "signature");
|
|
10799
|
+
const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
|
|
10800
|
+
if (seqLeftBytes.length)
|
|
10801
|
+
throw new E("invalid signature: left bytes after parsing");
|
|
10802
|
+
const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
|
|
10803
|
+
const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
|
|
10804
|
+
if (sLeftBytes.length)
|
|
10805
|
+
throw new E("invalid signature: left bytes after parsing");
|
|
10806
|
+
return { r: int.decode(rBytes), s: int.decode(sBytes) };
|
|
10807
|
+
},
|
|
10808
|
+
hexFromSig(sig) {
|
|
10809
|
+
const { _tlv: tlv, _int: int } = DER;
|
|
10810
|
+
const rs = tlv.encode(2, int.encode(sig.r));
|
|
10811
|
+
const ss = tlv.encode(2, int.encode(sig.s));
|
|
10812
|
+
const seq = rs + ss;
|
|
10813
|
+
return tlv.encode(48, seq);
|
|
10814
|
+
}
|
|
10815
|
+
};
|
|
10816
|
+
var _0n4 = BigInt(0);
|
|
10817
|
+
var _1n4 = BigInt(1);
|
|
10818
|
+
var _2n2 = BigInt(2);
|
|
10819
|
+
var _3n2 = BigInt(3);
|
|
10820
|
+
var _4n2 = BigInt(4);
|
|
10821
|
+
function weierstrass(params, extraOpts = {}) {
|
|
10822
|
+
const validated = createCurveFields("weierstrass", params, extraOpts);
|
|
10823
|
+
const { Fp, Fn } = validated;
|
|
10824
|
+
let CURVE = validated.CURVE;
|
|
10825
|
+
const { h: cofactor, n: CURVE_ORDER2 } = CURVE;
|
|
10826
|
+
validateObject(extraOpts, {}, {
|
|
10827
|
+
allowInfinityPoint: "boolean",
|
|
10828
|
+
clearCofactor: "function",
|
|
10829
|
+
isTorsionFree: "function",
|
|
10830
|
+
fromBytes: "function",
|
|
10831
|
+
toBytes: "function",
|
|
10832
|
+
endo: "object"
|
|
10833
|
+
});
|
|
10834
|
+
const { endo } = extraOpts;
|
|
10835
|
+
if (endo) {
|
|
10836
|
+
if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
|
|
10837
|
+
throw new Error('invalid endo: expected "beta": bigint and "basises": array');
|
|
10838
|
+
}
|
|
10839
|
+
}
|
|
10840
|
+
const lengths = getWLengths(Fp, Fn);
|
|
10841
|
+
function assertCompressionIsSupported() {
|
|
10842
|
+
if (!Fp.isOdd)
|
|
10843
|
+
throw new Error("compression is not supported: Field does not have .isOdd()");
|
|
10844
|
+
}
|
|
10845
|
+
function pointToBytes(_c, point, isCompressed) {
|
|
10846
|
+
const { x, y } = point.toAffine();
|
|
10847
|
+
const bx = Fp.toBytes(x);
|
|
10848
|
+
abool(isCompressed, "isCompressed");
|
|
10849
|
+
if (isCompressed) {
|
|
10850
|
+
assertCompressionIsSupported();
|
|
10851
|
+
const hasEvenY = !Fp.isOdd(y);
|
|
10852
|
+
return concatBytes(pprefix(hasEvenY), bx);
|
|
10853
|
+
} else {
|
|
10854
|
+
return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
|
|
10855
|
+
}
|
|
10856
|
+
}
|
|
10857
|
+
function pointFromBytes(bytes) {
|
|
10858
|
+
abytes(bytes, void 0, "Point");
|
|
10859
|
+
const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
|
|
10860
|
+
const length = bytes.length;
|
|
10861
|
+
const head = bytes[0];
|
|
10862
|
+
const tail = bytes.subarray(1);
|
|
10863
|
+
if (length === comp && (head === 2 || head === 3)) {
|
|
10864
|
+
const x = Fp.fromBytes(tail);
|
|
10865
|
+
if (!Fp.isValid(x))
|
|
10866
|
+
throw new Error("bad point: is not on curve, wrong x");
|
|
10867
|
+
const y2 = weierstrassEquation(x);
|
|
10868
|
+
let y;
|
|
10869
|
+
try {
|
|
10870
|
+
y = Fp.sqrt(y2);
|
|
10871
|
+
} catch (sqrtError) {
|
|
10872
|
+
const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
|
|
10873
|
+
throw new Error("bad point: is not on curve, sqrt error" + err);
|
|
10874
|
+
}
|
|
10875
|
+
assertCompressionIsSupported();
|
|
10876
|
+
const evenY = Fp.isOdd(y);
|
|
10877
|
+
const evenH = (head & 1) === 1;
|
|
10878
|
+
if (evenH !== evenY)
|
|
10879
|
+
y = Fp.neg(y);
|
|
10880
|
+
return { x, y };
|
|
10881
|
+
} else if (length === uncomp && head === 4) {
|
|
10882
|
+
const L = Fp.BYTES;
|
|
10883
|
+
const x = Fp.fromBytes(tail.subarray(0, L));
|
|
10884
|
+
const y = Fp.fromBytes(tail.subarray(L, L * 2));
|
|
10885
|
+
if (!isValidXY(x, y))
|
|
10886
|
+
throw new Error("bad point: is not on curve");
|
|
10887
|
+
return { x, y };
|
|
10888
|
+
} else {
|
|
10889
|
+
throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
|
|
10890
|
+
}
|
|
10891
|
+
}
|
|
10892
|
+
const encodePoint = extraOpts.toBytes || pointToBytes;
|
|
10893
|
+
const decodePoint = extraOpts.fromBytes || pointFromBytes;
|
|
10894
|
+
function weierstrassEquation(x) {
|
|
10895
|
+
const x2 = Fp.sqr(x);
|
|
10896
|
+
const x3 = Fp.mul(x2, x);
|
|
10897
|
+
return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
|
|
10898
|
+
}
|
|
10899
|
+
function isValidXY(x, y) {
|
|
10900
|
+
const left = Fp.sqr(y);
|
|
10901
|
+
const right = weierstrassEquation(x);
|
|
10902
|
+
return Fp.eql(left, right);
|
|
10903
|
+
}
|
|
10904
|
+
if (!isValidXY(CURVE.Gx, CURVE.Gy))
|
|
10905
|
+
throw new Error("bad curve params: generator point");
|
|
10906
|
+
const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
|
|
10907
|
+
const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
|
|
10908
|
+
if (Fp.is0(Fp.add(_4a3, _27b2)))
|
|
10909
|
+
throw new Error("bad curve params: a or b");
|
|
10910
|
+
function acoord(title, n, banZero = false) {
|
|
10911
|
+
if (!Fp.isValid(n) || banZero && Fp.is0(n))
|
|
10912
|
+
throw new Error(`bad point coordinate ${title}`);
|
|
10913
|
+
return n;
|
|
10914
|
+
}
|
|
10915
|
+
function aprjpoint(other) {
|
|
10916
|
+
if (!(other instanceof Point))
|
|
10917
|
+
throw new Error("Weierstrass Point expected");
|
|
10918
|
+
}
|
|
10919
|
+
function splitEndoScalarN(k) {
|
|
10920
|
+
if (!endo || !endo.basises)
|
|
10921
|
+
throw new Error("no endo");
|
|
10922
|
+
return _splitEndoScalar(k, endo.basises, Fn.ORDER);
|
|
10923
|
+
}
|
|
10924
|
+
const toAffineMemo = memoized((p, iz) => {
|
|
10925
|
+
const { X, Y, Z } = p;
|
|
10926
|
+
if (Fp.eql(Z, Fp.ONE))
|
|
10927
|
+
return { x: X, y: Y };
|
|
10928
|
+
const is0 = p.is0();
|
|
10929
|
+
if (iz == null)
|
|
10930
|
+
iz = is0 ? Fp.ONE : Fp.inv(Z);
|
|
10931
|
+
const x = Fp.mul(X, iz);
|
|
10932
|
+
const y = Fp.mul(Y, iz);
|
|
10933
|
+
const zz = Fp.mul(Z, iz);
|
|
10934
|
+
if (is0)
|
|
10935
|
+
return { x: Fp.ZERO, y: Fp.ZERO };
|
|
10936
|
+
if (!Fp.eql(zz, Fp.ONE))
|
|
10937
|
+
throw new Error("invZ was invalid");
|
|
10938
|
+
return { x, y };
|
|
10939
|
+
});
|
|
10940
|
+
const assertValidMemo = memoized((p) => {
|
|
10941
|
+
if (p.is0()) {
|
|
10942
|
+
if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
|
|
10943
|
+
return;
|
|
10944
|
+
throw new Error("bad point: ZERO");
|
|
10945
|
+
}
|
|
10946
|
+
const { x, y } = p.toAffine();
|
|
10947
|
+
if (!Fp.isValid(x) || !Fp.isValid(y))
|
|
10948
|
+
throw new Error("bad point: x or y not field elements");
|
|
10949
|
+
if (!isValidXY(x, y))
|
|
10950
|
+
throw new Error("bad point: equation left != right");
|
|
10951
|
+
if (!p.isTorsionFree())
|
|
10952
|
+
throw new Error("bad point: not in prime-order subgroup");
|
|
10953
|
+
return true;
|
|
10954
|
+
});
|
|
10955
|
+
function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
|
|
10956
|
+
k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
|
|
10957
|
+
k1p = negateCt(k1neg, k1p);
|
|
10958
|
+
k2p = negateCt(k2neg, k2p);
|
|
10959
|
+
return k1p.add(k2p);
|
|
10960
|
+
}
|
|
10961
|
+
class Point {
|
|
10962
|
+
// base / generator point
|
|
10963
|
+
static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
|
|
10964
|
+
// zero / infinity / identity point
|
|
10965
|
+
static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
|
|
10966
|
+
// 0, 1, 0
|
|
10967
|
+
// math field
|
|
10968
|
+
static Fp = Fp;
|
|
10969
|
+
// scalar field
|
|
10970
|
+
static Fn = Fn;
|
|
10971
|
+
X;
|
|
10972
|
+
Y;
|
|
10973
|
+
Z;
|
|
10974
|
+
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
10975
|
+
constructor(X, Y, Z) {
|
|
10976
|
+
this.X = acoord("x", X);
|
|
10977
|
+
this.Y = acoord("y", Y, true);
|
|
10978
|
+
this.Z = acoord("z", Z);
|
|
10979
|
+
Object.freeze(this);
|
|
10980
|
+
}
|
|
10981
|
+
static CURVE() {
|
|
10982
|
+
return CURVE;
|
|
10983
|
+
}
|
|
10984
|
+
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
10985
|
+
static fromAffine(p) {
|
|
10986
|
+
const { x, y } = p || {};
|
|
10987
|
+
if (!p || !Fp.isValid(x) || !Fp.isValid(y))
|
|
10988
|
+
throw new Error("invalid affine point");
|
|
10989
|
+
if (p instanceof Point)
|
|
10990
|
+
throw new Error("projective point not allowed");
|
|
10991
|
+
if (Fp.is0(x) && Fp.is0(y))
|
|
10992
|
+
return Point.ZERO;
|
|
10993
|
+
return new Point(x, y, Fp.ONE);
|
|
10994
|
+
}
|
|
10995
|
+
static fromBytes(bytes) {
|
|
10996
|
+
const P = Point.fromAffine(decodePoint(abytes(bytes, void 0, "point")));
|
|
10997
|
+
P.assertValidity();
|
|
10998
|
+
return P;
|
|
10999
|
+
}
|
|
11000
|
+
static fromHex(hex) {
|
|
11001
|
+
return Point.fromBytes(hexToBytes2(hex));
|
|
11002
|
+
}
|
|
11003
|
+
get x() {
|
|
11004
|
+
return this.toAffine().x;
|
|
11005
|
+
}
|
|
11006
|
+
get y() {
|
|
11007
|
+
return this.toAffine().y;
|
|
11008
|
+
}
|
|
11009
|
+
/**
|
|
11010
|
+
*
|
|
11011
|
+
* @param windowSize
|
|
11012
|
+
* @param isLazy true will defer table computation until the first multiplication
|
|
11013
|
+
* @returns
|
|
11014
|
+
*/
|
|
11015
|
+
precompute(windowSize = 8, isLazy = true) {
|
|
11016
|
+
wnaf.createCache(this, windowSize);
|
|
11017
|
+
if (!isLazy)
|
|
11018
|
+
this.multiply(_3n2);
|
|
11019
|
+
return this;
|
|
11020
|
+
}
|
|
11021
|
+
// TODO: return `this`
|
|
11022
|
+
/** A point on curve is valid if it conforms to equation. */
|
|
11023
|
+
assertValidity() {
|
|
11024
|
+
assertValidMemo(this);
|
|
11025
|
+
}
|
|
11026
|
+
hasEvenY() {
|
|
11027
|
+
const { y } = this.toAffine();
|
|
11028
|
+
if (!Fp.isOdd)
|
|
11029
|
+
throw new Error("Field doesn't support isOdd");
|
|
11030
|
+
return !Fp.isOdd(y);
|
|
11031
|
+
}
|
|
11032
|
+
/** Compare one point to another. */
|
|
11033
|
+
equals(other) {
|
|
11034
|
+
aprjpoint(other);
|
|
11035
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
11036
|
+
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
11037
|
+
const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
|
|
11038
|
+
const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
|
|
11039
|
+
return U1 && U2;
|
|
11040
|
+
}
|
|
11041
|
+
/** Flips point to one corresponding to (x, -y) in Affine coordinates. */
|
|
11042
|
+
negate() {
|
|
11043
|
+
return new Point(this.X, Fp.neg(this.Y), this.Z);
|
|
11044
|
+
}
|
|
11045
|
+
// Renes-Costello-Batina exception-free doubling formula.
|
|
11046
|
+
// There is 30% faster Jacobian formula, but it is not complete.
|
|
11047
|
+
// https://eprint.iacr.org/2015/1060, algorithm 3
|
|
11048
|
+
// Cost: 8M + 3S + 3*a + 2*b3 + 15add.
|
|
11049
|
+
double() {
|
|
11050
|
+
const { a, b } = CURVE;
|
|
11051
|
+
const b3 = Fp.mul(b, _3n2);
|
|
11052
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
11053
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
|
|
11054
|
+
let t0 = Fp.mul(X1, X1);
|
|
11055
|
+
let t1 = Fp.mul(Y1, Y1);
|
|
11056
|
+
let t2 = Fp.mul(Z1, Z1);
|
|
11057
|
+
let t3 = Fp.mul(X1, Y1);
|
|
11058
|
+
t3 = Fp.add(t3, t3);
|
|
11059
|
+
Z3 = Fp.mul(X1, Z1);
|
|
11060
|
+
Z3 = Fp.add(Z3, Z3);
|
|
11061
|
+
X3 = Fp.mul(a, Z3);
|
|
11062
|
+
Y3 = Fp.mul(b3, t2);
|
|
11063
|
+
Y3 = Fp.add(X3, Y3);
|
|
11064
|
+
X3 = Fp.sub(t1, Y3);
|
|
11065
|
+
Y3 = Fp.add(t1, Y3);
|
|
11066
|
+
Y3 = Fp.mul(X3, Y3);
|
|
11067
|
+
X3 = Fp.mul(t3, X3);
|
|
11068
|
+
Z3 = Fp.mul(b3, Z3);
|
|
11069
|
+
t2 = Fp.mul(a, t2);
|
|
11070
|
+
t3 = Fp.sub(t0, t2);
|
|
11071
|
+
t3 = Fp.mul(a, t3);
|
|
11072
|
+
t3 = Fp.add(t3, Z3);
|
|
11073
|
+
Z3 = Fp.add(t0, t0);
|
|
11074
|
+
t0 = Fp.add(Z3, t0);
|
|
11075
|
+
t0 = Fp.add(t0, t2);
|
|
11076
|
+
t0 = Fp.mul(t0, t3);
|
|
11077
|
+
Y3 = Fp.add(Y3, t0);
|
|
11078
|
+
t2 = Fp.mul(Y1, Z1);
|
|
11079
|
+
t2 = Fp.add(t2, t2);
|
|
11080
|
+
t0 = Fp.mul(t2, t3);
|
|
11081
|
+
X3 = Fp.sub(X3, t0);
|
|
11082
|
+
Z3 = Fp.mul(t2, t1);
|
|
11083
|
+
Z3 = Fp.add(Z3, Z3);
|
|
11084
|
+
Z3 = Fp.add(Z3, Z3);
|
|
11085
|
+
return new Point(X3, Y3, Z3);
|
|
11086
|
+
}
|
|
11087
|
+
// Renes-Costello-Batina exception-free addition formula.
|
|
11088
|
+
// There is 30% faster Jacobian formula, but it is not complete.
|
|
11089
|
+
// https://eprint.iacr.org/2015/1060, algorithm 1
|
|
11090
|
+
// Cost: 12M + 0S + 3*a + 3*b3 + 23add.
|
|
11091
|
+
add(other) {
|
|
11092
|
+
aprjpoint(other);
|
|
11093
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
11094
|
+
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
11095
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
|
|
11096
|
+
const a = CURVE.a;
|
|
11097
|
+
const b3 = Fp.mul(CURVE.b, _3n2);
|
|
11098
|
+
let t0 = Fp.mul(X1, X2);
|
|
11099
|
+
let t1 = Fp.mul(Y1, Y2);
|
|
11100
|
+
let t2 = Fp.mul(Z1, Z2);
|
|
11101
|
+
let t3 = Fp.add(X1, Y1);
|
|
11102
|
+
let t4 = Fp.add(X2, Y2);
|
|
11103
|
+
t3 = Fp.mul(t3, t4);
|
|
11104
|
+
t4 = Fp.add(t0, t1);
|
|
11105
|
+
t3 = Fp.sub(t3, t4);
|
|
11106
|
+
t4 = Fp.add(X1, Z1);
|
|
11107
|
+
let t5 = Fp.add(X2, Z2);
|
|
11108
|
+
t4 = Fp.mul(t4, t5);
|
|
11109
|
+
t5 = Fp.add(t0, t2);
|
|
11110
|
+
t4 = Fp.sub(t4, t5);
|
|
11111
|
+
t5 = Fp.add(Y1, Z1);
|
|
11112
|
+
X3 = Fp.add(Y2, Z2);
|
|
11113
|
+
t5 = Fp.mul(t5, X3);
|
|
11114
|
+
X3 = Fp.add(t1, t2);
|
|
11115
|
+
t5 = Fp.sub(t5, X3);
|
|
11116
|
+
Z3 = Fp.mul(a, t4);
|
|
11117
|
+
X3 = Fp.mul(b3, t2);
|
|
11118
|
+
Z3 = Fp.add(X3, Z3);
|
|
11119
|
+
X3 = Fp.sub(t1, Z3);
|
|
11120
|
+
Z3 = Fp.add(t1, Z3);
|
|
11121
|
+
Y3 = Fp.mul(X3, Z3);
|
|
11122
|
+
t1 = Fp.add(t0, t0);
|
|
11123
|
+
t1 = Fp.add(t1, t0);
|
|
11124
|
+
t2 = Fp.mul(a, t2);
|
|
11125
|
+
t4 = Fp.mul(b3, t4);
|
|
11126
|
+
t1 = Fp.add(t1, t2);
|
|
11127
|
+
t2 = Fp.sub(t0, t2);
|
|
11128
|
+
t2 = Fp.mul(a, t2);
|
|
11129
|
+
t4 = Fp.add(t4, t2);
|
|
11130
|
+
t0 = Fp.mul(t1, t4);
|
|
11131
|
+
Y3 = Fp.add(Y3, t0);
|
|
11132
|
+
t0 = Fp.mul(t5, t4);
|
|
11133
|
+
X3 = Fp.mul(t3, X3);
|
|
11134
|
+
X3 = Fp.sub(X3, t0);
|
|
11135
|
+
t0 = Fp.mul(t3, t1);
|
|
11136
|
+
Z3 = Fp.mul(t5, Z3);
|
|
11137
|
+
Z3 = Fp.add(Z3, t0);
|
|
11138
|
+
return new Point(X3, Y3, Z3);
|
|
11139
|
+
}
|
|
11140
|
+
subtract(other) {
|
|
11141
|
+
return this.add(other.negate());
|
|
11142
|
+
}
|
|
11143
|
+
is0() {
|
|
11144
|
+
return this.equals(Point.ZERO);
|
|
11145
|
+
}
|
|
11146
|
+
/**
|
|
11147
|
+
* Constant time multiplication.
|
|
11148
|
+
* Uses wNAF method. Windowed method may be 10% faster,
|
|
11149
|
+
* but takes 2x longer to generate and consumes 2x memory.
|
|
11150
|
+
* Uses precomputes when available.
|
|
11151
|
+
* Uses endomorphism for Koblitz curves.
|
|
11152
|
+
* @param scalar by which the point would be multiplied
|
|
11153
|
+
* @returns New point
|
|
11154
|
+
*/
|
|
11155
|
+
multiply(scalar) {
|
|
11156
|
+
const { endo: endo2 } = extraOpts;
|
|
11157
|
+
if (!Fn.isValidNot0(scalar))
|
|
11158
|
+
throw new Error("invalid scalar: out of range");
|
|
11159
|
+
let point, fake;
|
|
11160
|
+
const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
|
|
11161
|
+
if (endo2) {
|
|
11162
|
+
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
|
|
11163
|
+
const { p: k1p, f: k1f } = mul(k1);
|
|
11164
|
+
const { p: k2p, f: k2f } = mul(k2);
|
|
11165
|
+
fake = k1f.add(k2f);
|
|
11166
|
+
point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
|
|
11167
|
+
} else {
|
|
11168
|
+
const { p, f } = mul(scalar);
|
|
11169
|
+
point = p;
|
|
11170
|
+
fake = f;
|
|
11171
|
+
}
|
|
11172
|
+
return normalizeZ(Point, [point, fake])[0];
|
|
11173
|
+
}
|
|
11174
|
+
/**
|
|
11175
|
+
* Non-constant-time multiplication. Uses double-and-add algorithm.
|
|
11176
|
+
* It's faster, but should only be used when you don't care about
|
|
11177
|
+
* an exposed secret key e.g. sig verification, which works over *public* keys.
|
|
11178
|
+
*/
|
|
11179
|
+
multiplyUnsafe(sc) {
|
|
11180
|
+
const { endo: endo2 } = extraOpts;
|
|
11181
|
+
const p = this;
|
|
11182
|
+
if (!Fn.isValid(sc))
|
|
11183
|
+
throw new Error("invalid scalar: out of range");
|
|
11184
|
+
if (sc === _0n4 || p.is0())
|
|
11185
|
+
return Point.ZERO;
|
|
11186
|
+
if (sc === _1n4)
|
|
11187
|
+
return p;
|
|
11188
|
+
if (wnaf.hasCache(this))
|
|
11189
|
+
return this.multiply(sc);
|
|
11190
|
+
if (endo2) {
|
|
11191
|
+
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
|
|
11192
|
+
const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
|
|
11193
|
+
return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
|
|
11194
|
+
} else {
|
|
11195
|
+
return wnaf.unsafe(p, sc);
|
|
11196
|
+
}
|
|
11197
|
+
}
|
|
11198
|
+
/**
|
|
11199
|
+
* Converts Projective point to affine (x, y) coordinates.
|
|
11200
|
+
* @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
|
|
11201
|
+
*/
|
|
11202
|
+
toAffine(invertedZ) {
|
|
11203
|
+
return toAffineMemo(this, invertedZ);
|
|
11204
|
+
}
|
|
11205
|
+
/**
|
|
11206
|
+
* Checks whether Point is free of torsion elements (is in prime subgroup).
|
|
11207
|
+
* Always torsion-free for cofactor=1 curves.
|
|
11208
|
+
*/
|
|
11209
|
+
isTorsionFree() {
|
|
11210
|
+
const { isTorsionFree } = extraOpts;
|
|
11211
|
+
if (cofactor === _1n4)
|
|
11212
|
+
return true;
|
|
11213
|
+
if (isTorsionFree)
|
|
11214
|
+
return isTorsionFree(Point, this);
|
|
11215
|
+
return wnaf.unsafe(this, CURVE_ORDER2).is0();
|
|
11216
|
+
}
|
|
11217
|
+
clearCofactor() {
|
|
11218
|
+
const { clearCofactor } = extraOpts;
|
|
11219
|
+
if (cofactor === _1n4)
|
|
11220
|
+
return this;
|
|
11221
|
+
if (clearCofactor)
|
|
11222
|
+
return clearCofactor(Point, this);
|
|
11223
|
+
return this.multiplyUnsafe(cofactor);
|
|
11224
|
+
}
|
|
11225
|
+
isSmallOrder() {
|
|
11226
|
+
return this.multiplyUnsafe(cofactor).is0();
|
|
11227
|
+
}
|
|
11228
|
+
toBytes(isCompressed = true) {
|
|
11229
|
+
abool(isCompressed, "isCompressed");
|
|
11230
|
+
this.assertValidity();
|
|
11231
|
+
return encodePoint(Point, this, isCompressed);
|
|
11232
|
+
}
|
|
11233
|
+
toHex(isCompressed = true) {
|
|
11234
|
+
return bytesToHex4(this.toBytes(isCompressed));
|
|
11235
|
+
}
|
|
11236
|
+
toString() {
|
|
11237
|
+
return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
|
|
11238
|
+
}
|
|
11239
|
+
}
|
|
11240
|
+
const bits = Fn.BITS;
|
|
11241
|
+
const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
|
|
11242
|
+
Point.BASE.precompute(8);
|
|
11243
|
+
return Point;
|
|
11244
|
+
}
|
|
11245
|
+
function pprefix(hasEvenY) {
|
|
11246
|
+
return Uint8Array.of(hasEvenY ? 2 : 3);
|
|
11247
|
+
}
|
|
11248
|
+
function getWLengths(Fp, Fn) {
|
|
11249
|
+
return {
|
|
11250
|
+
secretKey: Fn.BYTES,
|
|
11251
|
+
publicKey: 1 + Fp.BYTES,
|
|
11252
|
+
publicKeyUncompressed: 1 + 2 * Fp.BYTES,
|
|
11253
|
+
publicKeyHasPrefix: true,
|
|
11254
|
+
signature: 2 * Fn.BYTES
|
|
11255
|
+
};
|
|
11256
|
+
}
|
|
11257
|
+
function ecdh(Point, ecdhOpts = {}) {
|
|
11258
|
+
const { Fn } = Point;
|
|
11259
|
+
const randomBytes_ = ecdhOpts.randomBytes || randomBytes2;
|
|
11260
|
+
const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
|
|
11261
|
+
function isValidSecretKey(secretKey) {
|
|
11262
|
+
try {
|
|
11263
|
+
const num = Fn.fromBytes(secretKey);
|
|
11264
|
+
return Fn.isValidNot0(num);
|
|
11265
|
+
} catch (error) {
|
|
11266
|
+
return false;
|
|
11267
|
+
}
|
|
11268
|
+
}
|
|
11269
|
+
function isValidPublicKey(publicKey, isCompressed) {
|
|
11270
|
+
const { publicKey: comp, publicKeyUncompressed } = lengths;
|
|
11271
|
+
try {
|
|
11272
|
+
const l = publicKey.length;
|
|
11273
|
+
if (isCompressed === true && l !== comp)
|
|
11274
|
+
return false;
|
|
11275
|
+
if (isCompressed === false && l !== publicKeyUncompressed)
|
|
11276
|
+
return false;
|
|
11277
|
+
return !!Point.fromBytes(publicKey);
|
|
11278
|
+
} catch (error) {
|
|
11279
|
+
return false;
|
|
11280
|
+
}
|
|
11281
|
+
}
|
|
11282
|
+
function randomSecretKey(seed = randomBytes_(lengths.seed)) {
|
|
11283
|
+
return mapHashToField(abytes(seed, lengths.seed, "seed"), Fn.ORDER);
|
|
11284
|
+
}
|
|
11285
|
+
function getPublicKey2(secretKey, isCompressed = true) {
|
|
11286
|
+
return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
|
|
11287
|
+
}
|
|
11288
|
+
function isProbPub(item) {
|
|
11289
|
+
const { secretKey, publicKey, publicKeyUncompressed } = lengths;
|
|
11290
|
+
if (!isBytes(item))
|
|
11291
|
+
return void 0;
|
|
11292
|
+
if ("_lengths" in Fn && Fn._lengths || secretKey === publicKey)
|
|
11293
|
+
return void 0;
|
|
11294
|
+
const l = abytes(item, void 0, "key").length;
|
|
11295
|
+
return l === publicKey || l === publicKeyUncompressed;
|
|
11296
|
+
}
|
|
11297
|
+
function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
|
|
11298
|
+
if (isProbPub(secretKeyA) === true)
|
|
11299
|
+
throw new Error("first arg must be private key");
|
|
11300
|
+
if (isProbPub(publicKeyB) === false)
|
|
11301
|
+
throw new Error("second arg must be public key");
|
|
11302
|
+
const s = Fn.fromBytes(secretKeyA);
|
|
11303
|
+
const b = Point.fromBytes(publicKeyB);
|
|
11304
|
+
return b.multiply(s).toBytes(isCompressed);
|
|
11305
|
+
}
|
|
11306
|
+
const utils = {
|
|
11307
|
+
isValidSecretKey,
|
|
11308
|
+
isValidPublicKey,
|
|
11309
|
+
randomSecretKey
|
|
11310
|
+
};
|
|
11311
|
+
const keygen = createKeygen(randomSecretKey, getPublicKey2);
|
|
11312
|
+
return Object.freeze({ getPublicKey: getPublicKey2, getSharedSecret, keygen, Point, utils, lengths });
|
|
11313
|
+
}
|
|
11314
|
+
function ecdsa(Point, hash, ecdsaOpts = {}) {
|
|
11315
|
+
ahash(hash);
|
|
11316
|
+
validateObject(ecdsaOpts, {}, {
|
|
11317
|
+
hmac: "function",
|
|
11318
|
+
lowS: "boolean",
|
|
11319
|
+
randomBytes: "function",
|
|
11320
|
+
bits2int: "function",
|
|
11321
|
+
bits2int_modN: "function"
|
|
11322
|
+
});
|
|
11323
|
+
ecdsaOpts = Object.assign({}, ecdsaOpts);
|
|
11324
|
+
const randomBytes3 = ecdsaOpts.randomBytes || randomBytes2;
|
|
11325
|
+
const hmac2 = ecdsaOpts.hmac || ((key, msg) => hmac(hash, key, msg));
|
|
11326
|
+
const { Fp, Fn } = Point;
|
|
11327
|
+
const { ORDER: CURVE_ORDER2, BITS: fnBits } = Fn;
|
|
11328
|
+
const { keygen, getPublicKey: getPublicKey2, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
|
|
11329
|
+
const defaultSigOpts = {
|
|
11330
|
+
prehash: true,
|
|
11331
|
+
lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
|
|
11332
|
+
format: "compact",
|
|
11333
|
+
extraEntropy: false
|
|
11334
|
+
};
|
|
11335
|
+
const hasLargeCofactor = CURVE_ORDER2 * _2n2 < Fp.ORDER;
|
|
11336
|
+
function isBiggerThanHalfOrder(number) {
|
|
11337
|
+
const HALF = CURVE_ORDER2 >> _1n4;
|
|
11338
|
+
return number > HALF;
|
|
11339
|
+
}
|
|
11340
|
+
function validateRS(title, num) {
|
|
11341
|
+
if (!Fn.isValidNot0(num))
|
|
11342
|
+
throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
|
|
11343
|
+
return num;
|
|
11344
|
+
}
|
|
11345
|
+
function assertSmallCofactor() {
|
|
11346
|
+
if (hasLargeCofactor)
|
|
11347
|
+
throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
|
|
11348
|
+
}
|
|
11349
|
+
function validateSigLength(bytes, format) {
|
|
11350
|
+
validateSigFormat(format);
|
|
11351
|
+
const size = lengths.signature;
|
|
11352
|
+
const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
|
|
11353
|
+
return abytes(bytes, sizer);
|
|
11354
|
+
}
|
|
11355
|
+
class Signature {
|
|
11356
|
+
r;
|
|
11357
|
+
s;
|
|
11358
|
+
recovery;
|
|
11359
|
+
constructor(r, s, recovery) {
|
|
11360
|
+
this.r = validateRS("r", r);
|
|
11361
|
+
this.s = validateRS("s", s);
|
|
11362
|
+
if (recovery != null) {
|
|
11363
|
+
assertSmallCofactor();
|
|
11364
|
+
if (![0, 1, 2, 3].includes(recovery))
|
|
11365
|
+
throw new Error("invalid recovery id");
|
|
11366
|
+
this.recovery = recovery;
|
|
11367
|
+
}
|
|
11368
|
+
Object.freeze(this);
|
|
11369
|
+
}
|
|
11370
|
+
static fromBytes(bytes, format = defaultSigOpts.format) {
|
|
11371
|
+
validateSigLength(bytes, format);
|
|
11372
|
+
let recid;
|
|
11373
|
+
if (format === "der") {
|
|
11374
|
+
const { r: r2, s: s2 } = DER.toSig(abytes(bytes));
|
|
11375
|
+
return new Signature(r2, s2);
|
|
11376
|
+
}
|
|
11377
|
+
if (format === "recovered") {
|
|
11378
|
+
recid = bytes[0];
|
|
11379
|
+
format = "compact";
|
|
11380
|
+
bytes = bytes.subarray(1);
|
|
11381
|
+
}
|
|
11382
|
+
const L = lengths.signature / 2;
|
|
11383
|
+
const r = bytes.subarray(0, L);
|
|
11384
|
+
const s = bytes.subarray(L, L * 2);
|
|
11385
|
+
return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
|
|
11386
|
+
}
|
|
11387
|
+
static fromHex(hex, format) {
|
|
11388
|
+
return this.fromBytes(hexToBytes2(hex), format);
|
|
11389
|
+
}
|
|
11390
|
+
assertRecovery() {
|
|
11391
|
+
const { recovery } = this;
|
|
11392
|
+
if (recovery == null)
|
|
11393
|
+
throw new Error("invalid recovery id: must be present");
|
|
11394
|
+
return recovery;
|
|
11395
|
+
}
|
|
11396
|
+
addRecoveryBit(recovery) {
|
|
11397
|
+
return new Signature(this.r, this.s, recovery);
|
|
11398
|
+
}
|
|
11399
|
+
recoverPublicKey(messageHash) {
|
|
11400
|
+
const { r, s } = this;
|
|
11401
|
+
const recovery = this.assertRecovery();
|
|
11402
|
+
const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER2 : r;
|
|
11403
|
+
if (!Fp.isValid(radj))
|
|
11404
|
+
throw new Error("invalid recovery id: sig.r+curve.n != R.x");
|
|
11405
|
+
const x = Fp.toBytes(radj);
|
|
11406
|
+
const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));
|
|
11407
|
+
const ir = Fn.inv(radj);
|
|
11408
|
+
const h = bits2int_modN(abytes(messageHash, void 0, "msgHash"));
|
|
11409
|
+
const u1 = Fn.create(-h * ir);
|
|
11410
|
+
const u2 = Fn.create(s * ir);
|
|
11411
|
+
const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
|
|
11412
|
+
if (Q.is0())
|
|
11413
|
+
throw new Error("invalid recovery: point at infinify");
|
|
11414
|
+
Q.assertValidity();
|
|
11415
|
+
return Q;
|
|
11416
|
+
}
|
|
11417
|
+
// Signatures should be low-s, to prevent malleability.
|
|
11418
|
+
hasHighS() {
|
|
11419
|
+
return isBiggerThanHalfOrder(this.s);
|
|
11420
|
+
}
|
|
11421
|
+
toBytes(format = defaultSigOpts.format) {
|
|
11422
|
+
validateSigFormat(format);
|
|
11423
|
+
if (format === "der")
|
|
11424
|
+
return hexToBytes2(DER.hexFromSig(this));
|
|
11425
|
+
const { r, s } = this;
|
|
11426
|
+
const rb = Fn.toBytes(r);
|
|
11427
|
+
const sb = Fn.toBytes(s);
|
|
11428
|
+
if (format === "recovered") {
|
|
11429
|
+
assertSmallCofactor();
|
|
11430
|
+
return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);
|
|
11431
|
+
}
|
|
11432
|
+
return concatBytes(rb, sb);
|
|
11433
|
+
}
|
|
11434
|
+
toHex(format) {
|
|
11435
|
+
return bytesToHex4(this.toBytes(format));
|
|
11436
|
+
}
|
|
11437
|
+
}
|
|
11438
|
+
const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
|
|
11439
|
+
if (bytes.length > 8192)
|
|
11440
|
+
throw new Error("input is too large");
|
|
11441
|
+
const num = bytesToNumberBE(bytes);
|
|
11442
|
+
const delta = bytes.length * 8 - fnBits;
|
|
11443
|
+
return delta > 0 ? num >> BigInt(delta) : num;
|
|
11444
|
+
};
|
|
11445
|
+
const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
|
|
11446
|
+
return Fn.create(bits2int(bytes));
|
|
11447
|
+
};
|
|
11448
|
+
const ORDER_MASK = bitMask(fnBits);
|
|
11449
|
+
function int2octets(num) {
|
|
11450
|
+
aInRange("num < 2^" + fnBits, num, _0n4, ORDER_MASK);
|
|
11451
|
+
return Fn.toBytes(num);
|
|
11452
|
+
}
|
|
11453
|
+
function validateMsgAndHash(message, prehash) {
|
|
11454
|
+
abytes(message, void 0, "message");
|
|
11455
|
+
return prehash ? abytes(hash(message), void 0, "prehashed message") : message;
|
|
11456
|
+
}
|
|
11457
|
+
function prepSig(message, secretKey, opts) {
|
|
11458
|
+
const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
|
|
11459
|
+
message = validateMsgAndHash(message, prehash);
|
|
11460
|
+
const h1int = bits2int_modN(message);
|
|
11461
|
+
const d = Fn.fromBytes(secretKey);
|
|
11462
|
+
if (!Fn.isValidNot0(d))
|
|
11463
|
+
throw new Error("invalid private key");
|
|
11464
|
+
const seedArgs = [int2octets(d), int2octets(h1int)];
|
|
11465
|
+
if (extraEntropy != null && extraEntropy !== false) {
|
|
11466
|
+
const e = extraEntropy === true ? randomBytes3(lengths.secretKey) : extraEntropy;
|
|
11467
|
+
seedArgs.push(abytes(e, void 0, "extraEntropy"));
|
|
11468
|
+
}
|
|
11469
|
+
const seed = concatBytes(...seedArgs);
|
|
11470
|
+
const m = h1int;
|
|
11471
|
+
function k2sig(kBytes) {
|
|
11472
|
+
const k = bits2int(kBytes);
|
|
11473
|
+
if (!Fn.isValidNot0(k))
|
|
11474
|
+
return;
|
|
11475
|
+
const ik = Fn.inv(k);
|
|
11476
|
+
const q = Point.BASE.multiply(k).toAffine();
|
|
11477
|
+
const r = Fn.create(q.x);
|
|
11478
|
+
if (r === _0n4)
|
|
11479
|
+
return;
|
|
11480
|
+
const s = Fn.create(ik * Fn.create(m + r * d));
|
|
11481
|
+
if (s === _0n4)
|
|
11482
|
+
return;
|
|
11483
|
+
let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
|
|
11484
|
+
let normS = s;
|
|
11485
|
+
if (lowS && isBiggerThanHalfOrder(s)) {
|
|
11486
|
+
normS = Fn.neg(s);
|
|
11487
|
+
recovery ^= 1;
|
|
11488
|
+
}
|
|
11489
|
+
return new Signature(r, normS, hasLargeCofactor ? void 0 : recovery);
|
|
11490
|
+
}
|
|
11491
|
+
return { seed, k2sig };
|
|
11492
|
+
}
|
|
11493
|
+
function sign(message, secretKey, opts = {}) {
|
|
11494
|
+
const { seed, k2sig } = prepSig(message, secretKey, opts);
|
|
11495
|
+
const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac2);
|
|
11496
|
+
const sig = drbg(seed, k2sig);
|
|
11497
|
+
return sig.toBytes(opts.format);
|
|
11498
|
+
}
|
|
11499
|
+
function verify(signature, message, publicKey, opts = {}) {
|
|
11500
|
+
const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
|
|
11501
|
+
publicKey = abytes(publicKey, void 0, "publicKey");
|
|
11502
|
+
message = validateMsgAndHash(message, prehash);
|
|
11503
|
+
if (!isBytes(signature)) {
|
|
11504
|
+
const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
|
|
11505
|
+
throw new Error("verify expects Uint8Array signature" + end);
|
|
11506
|
+
}
|
|
11507
|
+
validateSigLength(signature, format);
|
|
11508
|
+
try {
|
|
11509
|
+
const sig = Signature.fromBytes(signature, format);
|
|
11510
|
+
const P = Point.fromBytes(publicKey);
|
|
11511
|
+
if (lowS && sig.hasHighS())
|
|
11512
|
+
return false;
|
|
11513
|
+
const { r, s } = sig;
|
|
11514
|
+
const h = bits2int_modN(message);
|
|
11515
|
+
const is = Fn.inv(s);
|
|
11516
|
+
const u1 = Fn.create(h * is);
|
|
11517
|
+
const u2 = Fn.create(r * is);
|
|
11518
|
+
const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
|
|
11519
|
+
if (R.is0())
|
|
11520
|
+
return false;
|
|
11521
|
+
const v = Fn.create(R.x);
|
|
11522
|
+
return v === r;
|
|
11523
|
+
} catch (e) {
|
|
11524
|
+
return false;
|
|
11525
|
+
}
|
|
11526
|
+
}
|
|
11527
|
+
function recoverPublicKey(signature, message, opts = {}) {
|
|
11528
|
+
const { prehash } = validateSigOpts(opts, defaultSigOpts);
|
|
11529
|
+
message = validateMsgAndHash(message, prehash);
|
|
11530
|
+
return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
|
|
11531
|
+
}
|
|
11532
|
+
return Object.freeze({
|
|
11533
|
+
keygen,
|
|
11534
|
+
getPublicKey: getPublicKey2,
|
|
11535
|
+
getSharedSecret,
|
|
11536
|
+
utils,
|
|
11537
|
+
lengths,
|
|
11538
|
+
Point,
|
|
11539
|
+
sign,
|
|
11540
|
+
verify,
|
|
11541
|
+
recoverPublicKey,
|
|
11542
|
+
Signature,
|
|
11543
|
+
hash
|
|
11544
|
+
});
|
|
11545
|
+
}
|
|
11546
|
+
|
|
11547
|
+
// node_modules/@noble/curves/secp256k1.js
|
|
11548
|
+
var secp256k1_CURVE = {
|
|
11549
|
+
p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
|
|
11550
|
+
n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
|
|
11551
|
+
h: BigInt(1),
|
|
11552
|
+
a: BigInt(0),
|
|
11553
|
+
b: BigInt(7),
|
|
11554
|
+
Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
|
|
11555
|
+
Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
|
|
11556
|
+
};
|
|
11557
|
+
var secp256k1_ENDO = {
|
|
11558
|
+
beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
|
|
11559
|
+
basises: [
|
|
11560
|
+
[BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
|
|
11561
|
+
[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
|
|
11562
|
+
]
|
|
11563
|
+
};
|
|
11564
|
+
var _2n3 = /* @__PURE__ */ BigInt(2);
|
|
11565
|
+
function sqrtMod(y) {
|
|
11566
|
+
const P = secp256k1_CURVE.p;
|
|
11567
|
+
const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
|
|
11568
|
+
const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
|
|
11569
|
+
const b2 = y * y * y % P;
|
|
11570
|
+
const b3 = b2 * b2 * y % P;
|
|
11571
|
+
const b6 = pow2(b3, _3n3, P) * b3 % P;
|
|
11572
|
+
const b9 = pow2(b6, _3n3, P) * b3 % P;
|
|
11573
|
+
const b11 = pow2(b9, _2n3, P) * b2 % P;
|
|
11574
|
+
const b22 = pow2(b11, _11n, P) * b11 % P;
|
|
11575
|
+
const b44 = pow2(b22, _22n, P) * b22 % P;
|
|
11576
|
+
const b88 = pow2(b44, _44n, P) * b44 % P;
|
|
11577
|
+
const b176 = pow2(b88, _88n, P) * b88 % P;
|
|
11578
|
+
const b220 = pow2(b176, _44n, P) * b44 % P;
|
|
11579
|
+
const b223 = pow2(b220, _3n3, P) * b3 % P;
|
|
11580
|
+
const t1 = pow2(b223, _23n, P) * b22 % P;
|
|
11581
|
+
const t2 = pow2(t1, _6n, P) * b2 % P;
|
|
11582
|
+
const root = pow2(t2, _2n3, P);
|
|
11583
|
+
if (!Fpk1.eql(Fpk1.sqr(root), y))
|
|
11584
|
+
throw new Error("Cannot find square root");
|
|
11585
|
+
return root;
|
|
11586
|
+
}
|
|
11587
|
+
var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
|
|
11588
|
+
var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
|
|
11589
|
+
Fp: Fpk1,
|
|
11590
|
+
endo: secp256k1_ENDO
|
|
11591
|
+
});
|
|
11592
|
+
var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha2564);
|
|
11593
|
+
|
|
11594
|
+
// modules/market/MarketModule.ts
|
|
11595
|
+
var DEFAULT_MARKET_API_URL = "https://market-api.unicity.network";
|
|
11596
|
+
function hexToBytes3(hex) {
|
|
11597
|
+
const len = hex.length >> 1;
|
|
11598
|
+
const bytes = new Uint8Array(len);
|
|
11599
|
+
for (let i = 0; i < len; i++) {
|
|
11600
|
+
bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
11601
|
+
}
|
|
11602
|
+
return bytes;
|
|
11603
|
+
}
|
|
11604
|
+
function signRequest(body, privateKeyHex) {
|
|
11605
|
+
const timestamp = Date.now();
|
|
11606
|
+
const payload = JSON.stringify({ body, timestamp });
|
|
11607
|
+
const messageHash = sha2564(new TextEncoder().encode(payload));
|
|
11608
|
+
const privateKeyBytes = hexToBytes3(privateKeyHex);
|
|
11609
|
+
const signature = secp256k1.sign(messageHash, privateKeyBytes);
|
|
11610
|
+
const publicKey = bytesToHex4(secp256k1.getPublicKey(privateKeyBytes, true));
|
|
11611
|
+
return {
|
|
11612
|
+
body: JSON.stringify(body),
|
|
11613
|
+
headers: {
|
|
11614
|
+
"x-signature": bytesToHex4(signature),
|
|
11615
|
+
"x-public-key": publicKey,
|
|
11616
|
+
"x-timestamp": String(timestamp),
|
|
11617
|
+
"content-type": "application/json"
|
|
11618
|
+
}
|
|
11619
|
+
};
|
|
11620
|
+
}
|
|
11621
|
+
function toSnakeCaseIntent(req) {
|
|
11622
|
+
const result = {
|
|
11623
|
+
description: req.description,
|
|
11624
|
+
intent_type: req.intentType
|
|
11625
|
+
};
|
|
11626
|
+
if (req.category !== void 0) result.category = req.category;
|
|
11627
|
+
if (req.price !== void 0) result.price = req.price;
|
|
11628
|
+
if (req.currency !== void 0) result.currency = req.currency;
|
|
11629
|
+
if (req.location !== void 0) result.location = req.location;
|
|
11630
|
+
if (req.contactHandle !== void 0) result.contact_handle = req.contactHandle;
|
|
11631
|
+
if (req.expiresInDays !== void 0) result.expires_in_days = req.expiresInDays;
|
|
11632
|
+
return result;
|
|
11633
|
+
}
|
|
11634
|
+
function toSnakeCaseFilters(opts) {
|
|
11635
|
+
const result = {};
|
|
11636
|
+
if (opts?.filters) {
|
|
11637
|
+
const f = opts.filters;
|
|
11638
|
+
if (f.intentType !== void 0) result.intent_type = f.intentType;
|
|
11639
|
+
if (f.category !== void 0) result.category = f.category;
|
|
11640
|
+
if (f.minPrice !== void 0) result.min_price = f.minPrice;
|
|
11641
|
+
if (f.maxPrice !== void 0) result.max_price = f.maxPrice;
|
|
11642
|
+
if (f.location !== void 0) result.location = f.location;
|
|
11643
|
+
}
|
|
11644
|
+
if (opts?.limit !== void 0) result.limit = opts.limit;
|
|
11645
|
+
return result;
|
|
11646
|
+
}
|
|
11647
|
+
function mapSearchResult(raw) {
|
|
11648
|
+
return {
|
|
11649
|
+
id: raw.id,
|
|
11650
|
+
score: raw.score,
|
|
11651
|
+
agentNametag: raw.agent_nametag ?? void 0,
|
|
11652
|
+
agentPublicKey: raw.agent_public_key,
|
|
11653
|
+
description: raw.description,
|
|
11654
|
+
intentType: raw.intent_type,
|
|
11655
|
+
category: raw.category ?? void 0,
|
|
11656
|
+
price: raw.price ?? void 0,
|
|
11657
|
+
currency: raw.currency,
|
|
11658
|
+
location: raw.location ?? void 0,
|
|
11659
|
+
contactMethod: raw.contact_method,
|
|
11660
|
+
contactHandle: raw.contact_handle ?? void 0,
|
|
11661
|
+
createdAt: raw.created_at,
|
|
11662
|
+
expiresAt: raw.expires_at
|
|
11663
|
+
};
|
|
11664
|
+
}
|
|
11665
|
+
function mapMyIntent(raw) {
|
|
11666
|
+
return {
|
|
11667
|
+
id: raw.id,
|
|
11668
|
+
intentType: raw.intent_type,
|
|
11669
|
+
category: raw.category ?? void 0,
|
|
11670
|
+
price: raw.price ?? void 0,
|
|
11671
|
+
currency: raw.currency,
|
|
11672
|
+
location: raw.location ?? void 0,
|
|
11673
|
+
status: raw.status,
|
|
11674
|
+
createdAt: raw.created_at,
|
|
11675
|
+
expiresAt: raw.expires_at
|
|
11676
|
+
};
|
|
11677
|
+
}
|
|
11678
|
+
function mapFeedListing(raw) {
|
|
11679
|
+
return {
|
|
11680
|
+
id: raw.id,
|
|
11681
|
+
title: raw.title,
|
|
11682
|
+
descriptionPreview: raw.description_preview,
|
|
11683
|
+
agentName: raw.agent_name,
|
|
11684
|
+
agentId: raw.agent_id,
|
|
11685
|
+
type: raw.type,
|
|
11686
|
+
createdAt: raw.created_at
|
|
11687
|
+
};
|
|
11688
|
+
}
|
|
11689
|
+
function mapFeedMessage(raw) {
|
|
11690
|
+
if (raw.type === "initial") {
|
|
11691
|
+
return { type: "initial", listings: (raw.listings ?? []).map(mapFeedListing) };
|
|
11692
|
+
}
|
|
11693
|
+
return { type: "new", listing: mapFeedListing(raw.listing) };
|
|
11694
|
+
}
|
|
11695
|
+
var MarketModule = class {
|
|
11696
|
+
apiUrl;
|
|
11697
|
+
timeout;
|
|
11698
|
+
identity = null;
|
|
11699
|
+
registered = false;
|
|
11700
|
+
constructor(config) {
|
|
11701
|
+
this.apiUrl = (config?.apiUrl ?? DEFAULT_MARKET_API_URL).replace(/\/+$/, "");
|
|
11702
|
+
this.timeout = config?.timeout ?? 3e4;
|
|
11703
|
+
}
|
|
11704
|
+
/** Called by Sphere after construction */
|
|
11705
|
+
initialize(deps) {
|
|
11706
|
+
this.identity = deps.identity;
|
|
11707
|
+
}
|
|
11708
|
+
/** No-op — stateless module */
|
|
11709
|
+
async load() {
|
|
11710
|
+
}
|
|
11711
|
+
/** No-op — stateless module */
|
|
11712
|
+
destroy() {
|
|
11713
|
+
}
|
|
11714
|
+
// ---------------------------------------------------------------------------
|
|
11715
|
+
// Public API
|
|
11716
|
+
// ---------------------------------------------------------------------------
|
|
11717
|
+
/** Post a new intent (agent is auto-registered on first post) */
|
|
11718
|
+
async postIntent(intent) {
|
|
11719
|
+
const body = toSnakeCaseIntent(intent);
|
|
11720
|
+
const data = await this.apiPost("/api/intents", body);
|
|
11721
|
+
return {
|
|
11722
|
+
intentId: data.intent_id ?? data.intentId,
|
|
11723
|
+
message: data.message,
|
|
11724
|
+
expiresAt: data.expires_at ?? data.expiresAt
|
|
11725
|
+
};
|
|
11726
|
+
}
|
|
11727
|
+
/** Semantic search for intents (public — no auth required) */
|
|
11728
|
+
async search(query, opts) {
|
|
11729
|
+
const body = {
|
|
11730
|
+
query,
|
|
11731
|
+
...toSnakeCaseFilters(opts)
|
|
11732
|
+
};
|
|
11733
|
+
const data = await this.apiPublicPost("/api/search", body);
|
|
11734
|
+
let results = (data.intents ?? []).map(mapSearchResult);
|
|
11735
|
+
const minScore = opts?.filters?.minScore;
|
|
11736
|
+
if (minScore != null) {
|
|
11737
|
+
results = results.filter((r) => Math.round(r.score * 100) >= Math.round(minScore * 100));
|
|
11738
|
+
}
|
|
11739
|
+
return { intents: results, count: results.length };
|
|
11740
|
+
}
|
|
11741
|
+
/** List own intents (authenticated) */
|
|
11742
|
+
async getMyIntents() {
|
|
11743
|
+
const data = await this.apiGet("/api/intents");
|
|
11744
|
+
return (data.intents ?? []).map(mapMyIntent);
|
|
11745
|
+
}
|
|
11746
|
+
/** Close (delete) an intent */
|
|
11747
|
+
async closeIntent(intentId) {
|
|
11748
|
+
await this.apiDelete(`/api/intents/${encodeURIComponent(intentId)}`);
|
|
11749
|
+
}
|
|
11750
|
+
/** Fetch the most recent listings via REST (public — no auth required) */
|
|
11751
|
+
async getRecentListings() {
|
|
11752
|
+
const res = await fetch(`${this.apiUrl}/api/feed/recent`, {
|
|
11753
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
11754
|
+
});
|
|
11755
|
+
const data = await this.parseResponse(res);
|
|
11756
|
+
return (data.listings ?? []).map(mapFeedListing);
|
|
11757
|
+
}
|
|
11758
|
+
/**
|
|
11759
|
+
* Subscribe to the live listing feed via WebSocket.
|
|
11760
|
+
* Returns an unsubscribe function that closes the connection.
|
|
11761
|
+
*
|
|
11762
|
+
* Requires a WebSocket implementation — works natively in browsers
|
|
11763
|
+
* and in Node.js 21+ (or with the `ws` package).
|
|
11764
|
+
*/
|
|
11765
|
+
subscribeFeed(listener) {
|
|
11766
|
+
const wsUrl = this.apiUrl.replace(/^http/, "ws") + "/ws/feed";
|
|
11767
|
+
const ws2 = new WebSocket(wsUrl);
|
|
11768
|
+
ws2.onmessage = (event) => {
|
|
11769
|
+
try {
|
|
11770
|
+
const raw = JSON.parse(typeof event.data === "string" ? event.data : event.data.toString());
|
|
11771
|
+
listener(mapFeedMessage(raw));
|
|
11772
|
+
} catch {
|
|
11773
|
+
}
|
|
11774
|
+
};
|
|
11775
|
+
return () => {
|
|
11776
|
+
ws2.close();
|
|
11777
|
+
};
|
|
11778
|
+
}
|
|
11779
|
+
// ---------------------------------------------------------------------------
|
|
11780
|
+
// Private: HTTP helpers
|
|
11781
|
+
// ---------------------------------------------------------------------------
|
|
11782
|
+
ensureIdentity() {
|
|
11783
|
+
if (!this.identity) {
|
|
11784
|
+
throw new Error("MarketModule not initialized \u2014 call initialize() first");
|
|
11785
|
+
}
|
|
11786
|
+
}
|
|
11787
|
+
/** Register the agent's public key with the server (idempotent) */
|
|
11788
|
+
async ensureRegistered() {
|
|
11789
|
+
if (this.registered) return;
|
|
11790
|
+
this.ensureIdentity();
|
|
11791
|
+
const publicKey = bytesToHex4(secp256k1.getPublicKey(hexToBytes3(this.identity.privateKey), true));
|
|
11792
|
+
const body = { public_key: publicKey };
|
|
11793
|
+
if (this.identity.nametag) body.nametag = this.identity.nametag;
|
|
11794
|
+
const res = await fetch(`${this.apiUrl}/api/agent/register`, {
|
|
11795
|
+
method: "POST",
|
|
11796
|
+
headers: { "content-type": "application/json" },
|
|
11797
|
+
body: JSON.stringify(body),
|
|
11798
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
11799
|
+
});
|
|
11800
|
+
if (res.ok || res.status === 409) {
|
|
11801
|
+
this.registered = true;
|
|
11802
|
+
return;
|
|
11803
|
+
}
|
|
11804
|
+
const text = await res.text();
|
|
11805
|
+
let data;
|
|
11806
|
+
try {
|
|
11807
|
+
data = JSON.parse(text);
|
|
11808
|
+
} catch {
|
|
11809
|
+
}
|
|
11810
|
+
throw new Error(data?.error ?? `Agent registration failed: HTTP ${res.status}`);
|
|
11811
|
+
}
|
|
11812
|
+
async parseResponse(res) {
|
|
11813
|
+
const text = await res.text();
|
|
11814
|
+
let data;
|
|
11815
|
+
try {
|
|
11816
|
+
data = JSON.parse(text);
|
|
11817
|
+
} catch {
|
|
11818
|
+
throw new Error(`Market API error: HTTP ${res.status} \u2014 unexpected response (not JSON)`);
|
|
11819
|
+
}
|
|
11820
|
+
if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
|
|
11821
|
+
return data;
|
|
11822
|
+
}
|
|
11823
|
+
async apiPost(path, body) {
|
|
11824
|
+
this.ensureIdentity();
|
|
11825
|
+
await this.ensureRegistered();
|
|
11826
|
+
const signed = signRequest(body, this.identity.privateKey);
|
|
11827
|
+
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11828
|
+
method: "POST",
|
|
11829
|
+
headers: signed.headers,
|
|
11830
|
+
body: signed.body,
|
|
11831
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
11832
|
+
});
|
|
11833
|
+
return this.parseResponse(res);
|
|
11834
|
+
}
|
|
11835
|
+
async apiGet(path) {
|
|
11836
|
+
this.ensureIdentity();
|
|
11837
|
+
await this.ensureRegistered();
|
|
11838
|
+
const signed = signRequest({}, this.identity.privateKey);
|
|
11839
|
+
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11840
|
+
method: "GET",
|
|
11841
|
+
headers: signed.headers,
|
|
11842
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
11843
|
+
});
|
|
11844
|
+
return this.parseResponse(res);
|
|
11845
|
+
}
|
|
11846
|
+
async apiDelete(path) {
|
|
11847
|
+
this.ensureIdentity();
|
|
11848
|
+
await this.ensureRegistered();
|
|
11849
|
+
const signed = signRequest({}, this.identity.privateKey);
|
|
11850
|
+
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11851
|
+
method: "DELETE",
|
|
11852
|
+
headers: signed.headers,
|
|
11853
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
11854
|
+
});
|
|
11855
|
+
return this.parseResponse(res);
|
|
11856
|
+
}
|
|
11857
|
+
async apiPublicPost(path, body) {
|
|
11858
|
+
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11859
|
+
method: "POST",
|
|
11860
|
+
headers: { "content-type": "application/json" },
|
|
11861
|
+
body: JSON.stringify(body),
|
|
11862
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
11863
|
+
});
|
|
11864
|
+
return this.parseResponse(res);
|
|
11865
|
+
}
|
|
11866
|
+
};
|
|
11867
|
+
function createMarketModule(config) {
|
|
11868
|
+
return new MarketModule(config);
|
|
11869
|
+
}
|
|
11870
|
+
|
|
9291
11871
|
// core/encryption.ts
|
|
9292
11872
|
import CryptoJS6 from "crypto-js";
|
|
9293
11873
|
function encryptSimple(plaintext, password) {
|
|
@@ -10123,6 +12703,7 @@ var Sphere = class _Sphere {
|
|
|
10123
12703
|
_payments;
|
|
10124
12704
|
_communications;
|
|
10125
12705
|
_groupChat = null;
|
|
12706
|
+
_market = null;
|
|
10126
12707
|
// Events
|
|
10127
12708
|
eventHandlers = /* @__PURE__ */ new Map();
|
|
10128
12709
|
// Provider management
|
|
@@ -10132,7 +12713,7 @@ var Sphere = class _Sphere {
|
|
|
10132
12713
|
// ===========================================================================
|
|
10133
12714
|
// Constructor (private)
|
|
10134
12715
|
// ===========================================================================
|
|
10135
|
-
constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig) {
|
|
12716
|
+
constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig, marketConfig) {
|
|
10136
12717
|
this._storage = storage;
|
|
10137
12718
|
this._transport = transport;
|
|
10138
12719
|
this._oracle = oracle;
|
|
@@ -10143,6 +12724,7 @@ var Sphere = class _Sphere {
|
|
|
10143
12724
|
this._payments = createPaymentsModule({ l1: l1Config });
|
|
10144
12725
|
this._communications = createCommunicationsModule();
|
|
10145
12726
|
this._groupChat = groupChatConfig ? createGroupChatModule(groupChatConfig) : null;
|
|
12727
|
+
this._market = marketConfig ? createMarketModule(marketConfig) : null;
|
|
10146
12728
|
}
|
|
10147
12729
|
// ===========================================================================
|
|
10148
12730
|
// Static Methods - Wallet Management
|
|
@@ -10152,13 +12734,17 @@ var Sphere = class _Sphere {
|
|
|
10152
12734
|
*/
|
|
10153
12735
|
static async exists(storage) {
|
|
10154
12736
|
try {
|
|
10155
|
-
|
|
12737
|
+
const wasConnected = storage.isConnected();
|
|
12738
|
+
if (!wasConnected) {
|
|
10156
12739
|
await storage.connect();
|
|
10157
12740
|
}
|
|
10158
12741
|
const mnemonic = await storage.get(STORAGE_KEYS_GLOBAL.MNEMONIC);
|
|
10159
12742
|
if (mnemonic) return true;
|
|
10160
12743
|
const masterKey = await storage.get(STORAGE_KEYS_GLOBAL.MASTER_KEY);
|
|
10161
12744
|
if (masterKey) return true;
|
|
12745
|
+
if (!wasConnected) {
|
|
12746
|
+
await storage.disconnect();
|
|
12747
|
+
}
|
|
10162
12748
|
return false;
|
|
10163
12749
|
} catch {
|
|
10164
12750
|
return false;
|
|
@@ -10192,6 +12778,7 @@ var Sphere = class _Sphere {
|
|
|
10192
12778
|
static async init(options) {
|
|
10193
12779
|
_Sphere.configureTokenRegistry(options.storage, options.network);
|
|
10194
12780
|
const groupChat = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
|
|
12781
|
+
const market = _Sphere.resolveMarketConfig(options.market);
|
|
10195
12782
|
const walletExists = await _Sphere.exists(options.storage);
|
|
10196
12783
|
if (walletExists) {
|
|
10197
12784
|
const sphere2 = await _Sphere.load({
|
|
@@ -10202,6 +12789,7 @@ var Sphere = class _Sphere {
|
|
|
10202
12789
|
l1: options.l1,
|
|
10203
12790
|
price: options.price,
|
|
10204
12791
|
groupChat,
|
|
12792
|
+
market,
|
|
10205
12793
|
password: options.password
|
|
10206
12794
|
});
|
|
10207
12795
|
return { sphere: sphere2, created: false };
|
|
@@ -10229,6 +12817,7 @@ var Sphere = class _Sphere {
|
|
|
10229
12817
|
l1: options.l1,
|
|
10230
12818
|
price: options.price,
|
|
10231
12819
|
groupChat,
|
|
12820
|
+
market,
|
|
10232
12821
|
password: options.password
|
|
10233
12822
|
});
|
|
10234
12823
|
return { sphere, created: true, generatedMnemonic };
|
|
@@ -10256,6 +12845,17 @@ var Sphere = class _Sphere {
|
|
|
10256
12845
|
}
|
|
10257
12846
|
return config;
|
|
10258
12847
|
}
|
|
12848
|
+
/**
|
|
12849
|
+
* Resolve market module config from Sphere.init() options.
|
|
12850
|
+
* - `true` → enable with default API URL
|
|
12851
|
+
* - `MarketModuleConfig` → pass through
|
|
12852
|
+
* - `undefined` → no market module
|
|
12853
|
+
*/
|
|
12854
|
+
static resolveMarketConfig(config) {
|
|
12855
|
+
if (!config) return void 0;
|
|
12856
|
+
if (config === true) return {};
|
|
12857
|
+
return config;
|
|
12858
|
+
}
|
|
10259
12859
|
/**
|
|
10260
12860
|
* Configure TokenRegistry in the main bundle context.
|
|
10261
12861
|
*
|
|
@@ -10281,6 +12881,7 @@ var Sphere = class _Sphere {
|
|
|
10281
12881
|
}
|
|
10282
12882
|
_Sphere.configureTokenRegistry(options.storage, options.network);
|
|
10283
12883
|
const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
|
|
12884
|
+
const marketConfig = _Sphere.resolveMarketConfig(options.market);
|
|
10284
12885
|
const sphere = new _Sphere(
|
|
10285
12886
|
options.storage,
|
|
10286
12887
|
options.transport,
|
|
@@ -10288,7 +12889,8 @@ var Sphere = class _Sphere {
|
|
|
10288
12889
|
options.tokenStorage,
|
|
10289
12890
|
options.l1,
|
|
10290
12891
|
options.price,
|
|
10291
|
-
groupChatConfig
|
|
12892
|
+
groupChatConfig,
|
|
12893
|
+
marketConfig
|
|
10292
12894
|
);
|
|
10293
12895
|
sphere._password = options.password ?? null;
|
|
10294
12896
|
await sphere.storeMnemonic(options.mnemonic, options.derivationPath);
|
|
@@ -10316,6 +12918,7 @@ var Sphere = class _Sphere {
|
|
|
10316
12918
|
}
|
|
10317
12919
|
_Sphere.configureTokenRegistry(options.storage, options.network);
|
|
10318
12920
|
const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
|
|
12921
|
+
const marketConfig = _Sphere.resolveMarketConfig(options.market);
|
|
10319
12922
|
const sphere = new _Sphere(
|
|
10320
12923
|
options.storage,
|
|
10321
12924
|
options.transport,
|
|
@@ -10323,7 +12926,8 @@ var Sphere = class _Sphere {
|
|
|
10323
12926
|
options.tokenStorage,
|
|
10324
12927
|
options.l1,
|
|
10325
12928
|
options.price,
|
|
10326
|
-
groupChatConfig
|
|
12929
|
+
groupChatConfig,
|
|
12930
|
+
marketConfig
|
|
10327
12931
|
);
|
|
10328
12932
|
sphere._password = options.password ?? null;
|
|
10329
12933
|
await sphere.loadIdentityFromStorage();
|
|
@@ -10369,6 +12973,7 @@ var Sphere = class _Sphere {
|
|
|
10369
12973
|
console.log("[Sphere.import] Storage reconnected");
|
|
10370
12974
|
}
|
|
10371
12975
|
const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat);
|
|
12976
|
+
const marketConfig = _Sphere.resolveMarketConfig(options.market);
|
|
10372
12977
|
const sphere = new _Sphere(
|
|
10373
12978
|
options.storage,
|
|
10374
12979
|
options.transport,
|
|
@@ -10376,7 +12981,8 @@ var Sphere = class _Sphere {
|
|
|
10376
12981
|
options.tokenStorage,
|
|
10377
12982
|
options.l1,
|
|
10378
12983
|
options.price,
|
|
10379
|
-
groupChatConfig
|
|
12984
|
+
groupChatConfig,
|
|
12985
|
+
marketConfig
|
|
10380
12986
|
);
|
|
10381
12987
|
sphere._password = options.password ?? null;
|
|
10382
12988
|
if (options.mnemonic) {
|
|
@@ -10457,47 +13063,40 @@ var Sphere = class _Sphere {
|
|
|
10457
13063
|
static async clear(storageOrOptions) {
|
|
10458
13064
|
const storage = "get" in storageOrOptions ? storageOrOptions : storageOrOptions.storage;
|
|
10459
13065
|
const tokenStorage = "get" in storageOrOptions ? void 0 : storageOrOptions.tokenStorage;
|
|
10460
|
-
if (
|
|
10461
|
-
|
|
10462
|
-
|
|
10463
|
-
|
|
10464
|
-
|
|
10465
|
-
|
|
10466
|
-
await
|
|
10467
|
-
|
|
10468
|
-
await
|
|
10469
|
-
await storage.remove(STORAGE_KEYS_GLOBAL.DERIVATION_MODE);
|
|
10470
|
-
await storage.remove(STORAGE_KEYS_GLOBAL.WALLET_SOURCE);
|
|
10471
|
-
await storage.remove(STORAGE_KEYS_GLOBAL.WALLET_EXISTS);
|
|
10472
|
-
await storage.remove(STORAGE_KEYS_GLOBAL.TRACKED_ADDRESSES);
|
|
10473
|
-
await storage.remove(STORAGE_KEYS_GLOBAL.ADDRESS_NAMETAGS);
|
|
10474
|
-
await storage.remove(STORAGE_KEYS_ADDRESS.PENDING_TRANSFERS);
|
|
10475
|
-
await storage.remove(STORAGE_KEYS_ADDRESS.OUTBOX);
|
|
10476
|
-
console.log("[Sphere.clear] Storage keys removed");
|
|
13066
|
+
if (_Sphere.instance) {
|
|
13067
|
+
console.log("[Sphere.clear] Destroying Sphere instance...");
|
|
13068
|
+
await _Sphere.instance.destroy();
|
|
13069
|
+
console.log("[Sphere.clear] Sphere instance destroyed");
|
|
13070
|
+
}
|
|
13071
|
+
console.log("[Sphere.clear] Clearing L1 vesting cache...");
|
|
13072
|
+
await vestingClassifier.destroy();
|
|
13073
|
+
console.log("[Sphere.clear] Yielding 50ms for IDB transaction settlement...");
|
|
13074
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
10477
13075
|
if (tokenStorage?.clear) {
|
|
10478
13076
|
console.log("[Sphere.clear] Clearing token storage...");
|
|
10479
13077
|
try {
|
|
10480
|
-
await
|
|
10481
|
-
tokenStorage.clear(),
|
|
10482
|
-
new Promise(
|
|
10483
|
-
(_, reject) => setTimeout(() => reject(new Error("tokenStorage.clear() timed out after 2s")), 2e3)
|
|
10484
|
-
)
|
|
10485
|
-
]);
|
|
13078
|
+
await tokenStorage.clear();
|
|
10486
13079
|
console.log("[Sphere.clear] Token storage cleared");
|
|
10487
13080
|
} catch (err) {
|
|
10488
|
-
console.warn("[Sphere.clear] Token storage clear failed
|
|
13081
|
+
console.warn("[Sphere.clear] Token storage clear failed:", err);
|
|
10489
13082
|
}
|
|
13083
|
+
} else {
|
|
13084
|
+
console.log("[Sphere.clear] No token storage provider to clear");
|
|
10490
13085
|
}
|
|
10491
|
-
console.log("[Sphere.clear]
|
|
10492
|
-
|
|
10493
|
-
|
|
10494
|
-
|
|
10495
|
-
|
|
10496
|
-
|
|
10497
|
-
|
|
13086
|
+
console.log("[Sphere.clear] Clearing KV storage...");
|
|
13087
|
+
if (!storage.isConnected()) {
|
|
13088
|
+
try {
|
|
13089
|
+
await storage.connect();
|
|
13090
|
+
} catch {
|
|
13091
|
+
}
|
|
13092
|
+
}
|
|
13093
|
+
if (storage.isConnected()) {
|
|
13094
|
+
await storage.clear();
|
|
13095
|
+
console.log("[Sphere.clear] KV storage cleared");
|
|
10498
13096
|
} else {
|
|
10499
|
-
console.log("[Sphere.clear]
|
|
13097
|
+
console.log("[Sphere.clear] KV storage not connected, skipping");
|
|
10500
13098
|
}
|
|
13099
|
+
console.log("[Sphere.clear] Done");
|
|
10501
13100
|
}
|
|
10502
13101
|
/**
|
|
10503
13102
|
* Get current instance
|
|
@@ -10541,6 +13140,10 @@ var Sphere = class _Sphere {
|
|
|
10541
13140
|
get groupChat() {
|
|
10542
13141
|
return this._groupChat;
|
|
10543
13142
|
}
|
|
13143
|
+
/** Market module (intent bulletin board). Null if not configured. */
|
|
13144
|
+
get market() {
|
|
13145
|
+
return this._market;
|
|
13146
|
+
}
|
|
10544
13147
|
// ===========================================================================
|
|
10545
13148
|
// Public Properties - State
|
|
10546
13149
|
// ===========================================================================
|
|
@@ -11341,8 +13944,12 @@ var Sphere = class _Sphere {
|
|
|
11341
13944
|
await this._storage.set(STORAGE_KEYS_GLOBAL.CURRENT_ADDRESS_INDEX, index.toString());
|
|
11342
13945
|
this._storage.setIdentity(this._identity);
|
|
11343
13946
|
await this._transport.setIdentity(this._identity);
|
|
11344
|
-
|
|
13947
|
+
console.log(`[Sphere] switchToAddress(${index}): re-initializing ${this._tokenStorageProviders.size} token storage provider(s)`);
|
|
13948
|
+
for (const [providerId, provider] of this._tokenStorageProviders.entries()) {
|
|
13949
|
+
console.log(`[Sphere] switchToAddress(${index}): shutdown provider=${providerId}`);
|
|
13950
|
+
await provider.shutdown();
|
|
11345
13951
|
provider.setIdentity(this._identity);
|
|
13952
|
+
console.log(`[Sphere] switchToAddress(${index}): initialize provider=${providerId}`);
|
|
11346
13953
|
await provider.initialize();
|
|
11347
13954
|
}
|
|
11348
13955
|
await this.reinitializeModulesForNewAddress();
|
|
@@ -11416,9 +14023,17 @@ var Sphere = class _Sphere {
|
|
|
11416
14023
|
storage: this._storage,
|
|
11417
14024
|
emitEvent
|
|
11418
14025
|
});
|
|
14026
|
+
this._market?.initialize({
|
|
14027
|
+
identity: this._identity,
|
|
14028
|
+
emitEvent
|
|
14029
|
+
});
|
|
11419
14030
|
await this._payments.load();
|
|
11420
14031
|
await this._communications.load();
|
|
11421
14032
|
await this._groupChat?.load();
|
|
14033
|
+
await this._market?.load();
|
|
14034
|
+
this._payments.sync().catch((err) => {
|
|
14035
|
+
console.warn("[Sphere] Post-switch sync failed:", err);
|
|
14036
|
+
});
|
|
11422
14037
|
}
|
|
11423
14038
|
/**
|
|
11424
14039
|
* Derive address at a specific index
|
|
@@ -12243,6 +14858,7 @@ var Sphere = class _Sphere {
|
|
|
12243
14858
|
this._payments.destroy();
|
|
12244
14859
|
this._communications.destroy();
|
|
12245
14860
|
this._groupChat?.destroy();
|
|
14861
|
+
this._market?.destroy();
|
|
12246
14862
|
await this._transport.disconnect();
|
|
12247
14863
|
await this._storage.disconnect();
|
|
12248
14864
|
await this._oracle.disconnect();
|
|
@@ -12550,9 +15166,14 @@ var Sphere = class _Sphere {
|
|
|
12550
15166
|
storage: this._storage,
|
|
12551
15167
|
emitEvent
|
|
12552
15168
|
});
|
|
15169
|
+
this._market?.initialize({
|
|
15170
|
+
identity: this._identity,
|
|
15171
|
+
emitEvent
|
|
15172
|
+
});
|
|
12553
15173
|
await this._payments.load();
|
|
12554
15174
|
await this._communications.load();
|
|
12555
15175
|
await this._groupChat?.load();
|
|
15176
|
+
await this._market?.load();
|
|
12556
15177
|
}
|
|
12557
15178
|
// ===========================================================================
|
|
12558
15179
|
// Private: Helpers
|
|
@@ -13482,6 +16103,7 @@ export {
|
|
|
13482
16103
|
DEFAULT_GROUP_RELAYS,
|
|
13483
16104
|
DEFAULT_IPFS_BOOTSTRAP_PEERS,
|
|
13484
16105
|
DEFAULT_IPFS_GATEWAYS,
|
|
16106
|
+
DEFAULT_MARKET_API_URL,
|
|
13485
16107
|
DEFAULT_NOSTR_RELAYS,
|
|
13486
16108
|
DEV_AGGREGATOR_URL,
|
|
13487
16109
|
GroupChatModule,
|
|
@@ -13490,11 +16112,14 @@ export {
|
|
|
13490
16112
|
l1_exports as L1,
|
|
13491
16113
|
L1PaymentsModule,
|
|
13492
16114
|
LIMITS,
|
|
16115
|
+
MarketModule,
|
|
13493
16116
|
NETWORKS,
|
|
13494
16117
|
NIP29_KINDS,
|
|
13495
16118
|
NOSTR_EVENT_KINDS,
|
|
13496
16119
|
PaymentsModule,
|
|
13497
16120
|
STORAGE_KEYS,
|
|
16121
|
+
STORAGE_KEYS_ADDRESS,
|
|
16122
|
+
STORAGE_KEYS_GLOBAL,
|
|
13498
16123
|
STORAGE_PREFIX,
|
|
13499
16124
|
Sphere,
|
|
13500
16125
|
SphereError,
|
|
@@ -13517,6 +16142,7 @@ export {
|
|
|
13517
16142
|
createGroupChatModule,
|
|
13518
16143
|
createKeyPair,
|
|
13519
16144
|
createL1PaymentsModule,
|
|
16145
|
+
createMarketModule,
|
|
13520
16146
|
createPaymentSession,
|
|
13521
16147
|
createPaymentSessionError,
|
|
13522
16148
|
createPaymentsModule,
|
|
@@ -13540,6 +16166,8 @@ export {
|
|
|
13540
16166
|
generateMasterKey,
|
|
13541
16167
|
generateMnemonic2 as generateMnemonic,
|
|
13542
16168
|
getAddressHrp,
|
|
16169
|
+
getAddressId,
|
|
16170
|
+
getAddressStorageKey,
|
|
13543
16171
|
getCoinIdByName,
|
|
13544
16172
|
getCoinIdBySymbol,
|
|
13545
16173
|
getCurrentStateHash,
|
|
@@ -13604,4 +16232,16 @@ export {
|
|
|
13604
16232
|
txfToToken,
|
|
13605
16233
|
validateMnemonic2 as validateMnemonic
|
|
13606
16234
|
};
|
|
16235
|
+
/*! Bundled license information:
|
|
16236
|
+
|
|
16237
|
+
@noble/hashes/utils.js:
|
|
16238
|
+
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
16239
|
+
|
|
16240
|
+
@noble/curves/utils.js:
|
|
16241
|
+
@noble/curves/abstract/modular.js:
|
|
16242
|
+
@noble/curves/abstract/curve.js:
|
|
16243
|
+
@noble/curves/abstract/weierstrass.js:
|
|
16244
|
+
@noble/curves/secp256k1.js:
|
|
16245
|
+
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
16246
|
+
*/
|
|
13607
16247
|
//# sourceMappingURL=index.js.map
|