@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/core/index.cjs
CHANGED
|
@@ -20,15 +20,15 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
20
20
|
}
|
|
21
21
|
return to;
|
|
22
22
|
};
|
|
23
|
-
var __toESM = (
|
|
23
|
+
var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
|
|
24
24
|
// If the importer is in node compatibility mode or this is not an ESM
|
|
25
25
|
// file that has been converted to a CommonJS file using a Babel-
|
|
26
26
|
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
27
27
|
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
28
|
-
isNodeMode || !
|
|
29
|
-
|
|
28
|
+
isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
|
|
29
|
+
mod2
|
|
30
30
|
));
|
|
31
|
-
var __toCommonJS = (
|
|
31
|
+
var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
|
|
32
32
|
|
|
33
33
|
// core/bech32.ts
|
|
34
34
|
function convertBits(data, fromBits, toBits, pad) {
|
|
@@ -75,10 +75,10 @@ function bech32Polymod(values) {
|
|
|
75
75
|
}
|
|
76
76
|
function bech32Checksum(hrp, data) {
|
|
77
77
|
const values = hrpExpand(hrp).concat(data).concat([0, 0, 0, 0, 0, 0]);
|
|
78
|
-
const
|
|
78
|
+
const mod2 = bech32Polymod(values) ^ 1;
|
|
79
79
|
const ret = [];
|
|
80
80
|
for (let p = 0; p < 6; p++) {
|
|
81
|
-
ret.push(
|
|
81
|
+
ret.push(mod2 >> 5 * (5 - p) & 31);
|
|
82
82
|
}
|
|
83
83
|
return ret;
|
|
84
84
|
}
|
|
@@ -776,9 +776,13 @@ var VestingClassifier = class {
|
|
|
776
776
|
storeName = "vestingCache";
|
|
777
777
|
db = null;
|
|
778
778
|
/**
|
|
779
|
-
* Initialize IndexedDB for persistent caching
|
|
779
|
+
* Initialize IndexedDB for persistent caching.
|
|
780
|
+
* In Node.js (no IndexedDB), silently falls back to memory-only caching.
|
|
780
781
|
*/
|
|
781
782
|
async initDB() {
|
|
783
|
+
if (typeof indexedDB === "undefined") {
|
|
784
|
+
return;
|
|
785
|
+
}
|
|
782
786
|
return new Promise((resolve, reject) => {
|
|
783
787
|
const request = indexedDB.open(this.dbName, 1);
|
|
784
788
|
request.onupgradeneeded = (event) => {
|
|
@@ -6370,6 +6374,29 @@ var PaymentsModule = class _PaymentsModule {
|
|
|
6370
6374
|
this.nametags = [];
|
|
6371
6375
|
await this.save();
|
|
6372
6376
|
}
|
|
6377
|
+
/**
|
|
6378
|
+
* Reload nametag data from storage providers into memory.
|
|
6379
|
+
*
|
|
6380
|
+
* Used as a recovery mechanism when `this.nametags` is unexpectedly empty
|
|
6381
|
+
* (e.g., wiped by sync or race condition) but nametag data exists in storage.
|
|
6382
|
+
*/
|
|
6383
|
+
async reloadNametagsFromStorage() {
|
|
6384
|
+
const providers = this.getTokenStorageProviders();
|
|
6385
|
+
for (const [, provider] of providers) {
|
|
6386
|
+
try {
|
|
6387
|
+
const result = await provider.load();
|
|
6388
|
+
if (result.success && result.data) {
|
|
6389
|
+
const parsed = parseTxfStorageData(result.data);
|
|
6390
|
+
if (parsed.nametags.length > 0) {
|
|
6391
|
+
this.nametags = parsed.nametags;
|
|
6392
|
+
this.log(`Reloaded ${parsed.nametags.length} nametag(s) from storage`);
|
|
6393
|
+
return;
|
|
6394
|
+
}
|
|
6395
|
+
}
|
|
6396
|
+
} catch {
|
|
6397
|
+
}
|
|
6398
|
+
}
|
|
6399
|
+
}
|
|
6373
6400
|
/**
|
|
6374
6401
|
* Mint a nametag token on-chain (like Sphere wallet and lottery)
|
|
6375
6402
|
* This creates the nametag token required for receiving tokens via PROXY addresses
|
|
@@ -6494,11 +6521,15 @@ var PaymentsModule = class _PaymentsModule {
|
|
|
6494
6521
|
const localData = await this.createStorageData();
|
|
6495
6522
|
let totalAdded = 0;
|
|
6496
6523
|
let totalRemoved = 0;
|
|
6524
|
+
const savedNametags = [...this.nametags];
|
|
6497
6525
|
for (const [providerId, provider] of providers) {
|
|
6498
6526
|
try {
|
|
6499
6527
|
const result = await provider.sync(localData);
|
|
6500
6528
|
if (result.success && result.merged) {
|
|
6501
6529
|
this.loadFromStorageData(result.merged);
|
|
6530
|
+
if (this.nametags.length === 0 && savedNametags.length > 0) {
|
|
6531
|
+
this.nametags = savedNametags;
|
|
6532
|
+
}
|
|
6502
6533
|
totalAdded += result.added;
|
|
6503
6534
|
totalRemoved += result.removed;
|
|
6504
6535
|
}
|
|
@@ -6727,6 +6758,15 @@ var PaymentsModule = class _PaymentsModule {
|
|
|
6727
6758
|
);
|
|
6728
6759
|
return import_SigningService.SigningService.createFromSecret(privateKeyBytes);
|
|
6729
6760
|
}
|
|
6761
|
+
/**
|
|
6762
|
+
* Get the wallet's signing public key (used for token ownership predicates).
|
|
6763
|
+
* This is the key that token state predicates are checked against.
|
|
6764
|
+
*/
|
|
6765
|
+
async getSigningPublicKey() {
|
|
6766
|
+
this.ensureInitialized();
|
|
6767
|
+
const signer = await this.createSigningService();
|
|
6768
|
+
return signer.publicKey;
|
|
6769
|
+
}
|
|
6730
6770
|
/**
|
|
6731
6771
|
* Create DirectAddress from a public key using UnmaskedPredicateReference
|
|
6732
6772
|
*/
|
|
@@ -6877,7 +6917,12 @@ var PaymentsModule = class _PaymentsModule {
|
|
|
6877
6917
|
let nametagTokens = [];
|
|
6878
6918
|
if (addressScheme === import_AddressScheme.AddressScheme.PROXY) {
|
|
6879
6919
|
const { ProxyAddress } = await import("@unicitylabs/state-transition-sdk/lib/address/ProxyAddress");
|
|
6880
|
-
|
|
6920
|
+
let proxyNametag = this.getNametag();
|
|
6921
|
+
if (!proxyNametag?.token) {
|
|
6922
|
+
this.log("Nametag missing in memory, attempting reload from storage...");
|
|
6923
|
+
await this.reloadNametagsFromStorage();
|
|
6924
|
+
proxyNametag = this.getNametag();
|
|
6925
|
+
}
|
|
6881
6926
|
if (!proxyNametag?.token) {
|
|
6882
6927
|
throw new Error("Cannot finalize PROXY transfer - no nametag token");
|
|
6883
6928
|
}
|
|
@@ -7375,14 +7420,17 @@ var CommunicationsModule = class {
|
|
|
7375
7420
|
broadcasts = /* @__PURE__ */ new Map();
|
|
7376
7421
|
// Subscriptions
|
|
7377
7422
|
unsubscribeMessages = null;
|
|
7423
|
+
unsubscribeComposing = null;
|
|
7378
7424
|
broadcastSubscriptions = /* @__PURE__ */ new Map();
|
|
7379
7425
|
// Handlers
|
|
7380
7426
|
dmHandlers = /* @__PURE__ */ new Set();
|
|
7427
|
+
composingHandlers = /* @__PURE__ */ new Set();
|
|
7381
7428
|
broadcastHandlers = /* @__PURE__ */ new Set();
|
|
7382
7429
|
constructor(config) {
|
|
7383
7430
|
this.config = {
|
|
7384
7431
|
autoSave: config?.autoSave ?? true,
|
|
7385
7432
|
maxMessages: config?.maxMessages ?? 1e3,
|
|
7433
|
+
maxPerConversation: config?.maxPerConversation ?? 200,
|
|
7386
7434
|
readReceipts: config?.readReceipts ?? true
|
|
7387
7435
|
};
|
|
7388
7436
|
}
|
|
@@ -7393,6 +7441,8 @@ var CommunicationsModule = class {
|
|
|
7393
7441
|
* Initialize module with dependencies
|
|
7394
7442
|
*/
|
|
7395
7443
|
initialize(deps) {
|
|
7444
|
+
this.unsubscribeMessages?.();
|
|
7445
|
+
this.unsubscribeComposing?.();
|
|
7396
7446
|
this.deps = deps;
|
|
7397
7447
|
this.unsubscribeMessages = deps.transport.onMessage((msg) => {
|
|
7398
7448
|
this.handleIncomingMessage(msg);
|
|
@@ -7419,19 +7469,41 @@ var CommunicationsModule = class {
|
|
|
7419
7469
|
});
|
|
7420
7470
|
});
|
|
7421
7471
|
}
|
|
7472
|
+
this.unsubscribeComposing = deps.transport.onComposing?.((indicator) => {
|
|
7473
|
+
this.handleComposingIndicator(indicator);
|
|
7474
|
+
}) ?? null;
|
|
7422
7475
|
}
|
|
7423
7476
|
/**
|
|
7424
|
-
* Load messages from storage
|
|
7477
|
+
* Load messages from storage.
|
|
7478
|
+
* Uses per-address key (STORAGE_KEYS_ADDRESS.MESSAGES) which is automatically
|
|
7479
|
+
* scoped by LocalStorageProvider to sphere_DIRECT_xxx_yyy_messages.
|
|
7480
|
+
* Falls back to legacy global 'direct_messages' key for migration.
|
|
7425
7481
|
*/
|
|
7426
7482
|
async load() {
|
|
7427
7483
|
this.ensureInitialized();
|
|
7428
|
-
|
|
7484
|
+
this.messages.clear();
|
|
7485
|
+
let data = await this.deps.storage.get(STORAGE_KEYS_ADDRESS.MESSAGES);
|
|
7429
7486
|
if (data) {
|
|
7430
7487
|
const messages = JSON.parse(data);
|
|
7431
|
-
this.messages.clear();
|
|
7432
7488
|
for (const msg of messages) {
|
|
7433
7489
|
this.messages.set(msg.id, msg);
|
|
7434
7490
|
}
|
|
7491
|
+
return;
|
|
7492
|
+
}
|
|
7493
|
+
data = await this.deps.storage.get("direct_messages");
|
|
7494
|
+
if (data) {
|
|
7495
|
+
const allMessages = JSON.parse(data);
|
|
7496
|
+
const myPubkey = this.deps.identity.chainPubkey;
|
|
7497
|
+
const myMessages = allMessages.filter(
|
|
7498
|
+
(m) => m.senderPubkey === myPubkey || m.recipientPubkey === myPubkey
|
|
7499
|
+
);
|
|
7500
|
+
for (const msg of myMessages) {
|
|
7501
|
+
this.messages.set(msg.id, msg);
|
|
7502
|
+
}
|
|
7503
|
+
if (myMessages.length > 0) {
|
|
7504
|
+
await this.save();
|
|
7505
|
+
console.log(`[Communications] Migrated ${myMessages.length} messages to per-address storage`);
|
|
7506
|
+
}
|
|
7435
7507
|
}
|
|
7436
7508
|
}
|
|
7437
7509
|
/**
|
|
@@ -7440,6 +7512,8 @@ var CommunicationsModule = class {
|
|
|
7440
7512
|
destroy() {
|
|
7441
7513
|
this.unsubscribeMessages?.();
|
|
7442
7514
|
this.unsubscribeMessages = null;
|
|
7515
|
+
this.unsubscribeComposing?.();
|
|
7516
|
+
this.unsubscribeComposing = null;
|
|
7443
7517
|
for (const unsub of this.broadcastSubscriptions.values()) {
|
|
7444
7518
|
unsub();
|
|
7445
7519
|
}
|
|
@@ -7453,13 +7527,14 @@ var CommunicationsModule = class {
|
|
|
7453
7527
|
*/
|
|
7454
7528
|
async sendDM(recipient, content) {
|
|
7455
7529
|
this.ensureInitialized();
|
|
7456
|
-
const
|
|
7457
|
-
const eventId = await this.deps.transport.sendMessage(
|
|
7530
|
+
const resolved = await this.resolveRecipient(recipient);
|
|
7531
|
+
const eventId = await this.deps.transport.sendMessage(resolved.pubkey, content);
|
|
7458
7532
|
const message = {
|
|
7459
7533
|
id: eventId,
|
|
7460
7534
|
senderPubkey: this.deps.identity.chainPubkey,
|
|
7461
7535
|
senderNametag: this.deps.identity.nametag,
|
|
7462
|
-
recipientPubkey,
|
|
7536
|
+
recipientPubkey: resolved.pubkey,
|
|
7537
|
+
...resolved.nametag ? { recipientNametag: resolved.nametag } : {},
|
|
7463
7538
|
content,
|
|
7464
7539
|
timestamp: Date.now(),
|
|
7465
7540
|
isRead: false
|
|
@@ -7531,6 +7606,37 @@ var CommunicationsModule = class {
|
|
|
7531
7606
|
}
|
|
7532
7607
|
return messages.length;
|
|
7533
7608
|
}
|
|
7609
|
+
/**
|
|
7610
|
+
* Get a page of messages from a conversation (for lazy loading).
|
|
7611
|
+
* Returns messages in chronological order with a cursor for loading older messages.
|
|
7612
|
+
*/
|
|
7613
|
+
getConversationPage(peerPubkey, options) {
|
|
7614
|
+
const limit = options?.limit ?? 20;
|
|
7615
|
+
const before = options?.before ?? Infinity;
|
|
7616
|
+
const all = Array.from(this.messages.values()).filter(
|
|
7617
|
+
(m) => (m.senderPubkey === peerPubkey || m.recipientPubkey === peerPubkey) && m.timestamp < before
|
|
7618
|
+
).sort((a, b) => b.timestamp - a.timestamp);
|
|
7619
|
+
const page = all.slice(0, limit);
|
|
7620
|
+
return {
|
|
7621
|
+
messages: page.reverse(),
|
|
7622
|
+
// chronological order for display
|
|
7623
|
+
hasMore: all.length > limit,
|
|
7624
|
+
oldestTimestamp: page.length > 0 ? page[0].timestamp : null
|
|
7625
|
+
};
|
|
7626
|
+
}
|
|
7627
|
+
/**
|
|
7628
|
+
* Delete all messages in a conversation with a peer
|
|
7629
|
+
*/
|
|
7630
|
+
async deleteConversation(peerPubkey) {
|
|
7631
|
+
for (const [id, msg] of this.messages) {
|
|
7632
|
+
if (msg.senderPubkey === peerPubkey || msg.recipientPubkey === peerPubkey) {
|
|
7633
|
+
this.messages.delete(id);
|
|
7634
|
+
}
|
|
7635
|
+
}
|
|
7636
|
+
if (this.config.autoSave) {
|
|
7637
|
+
await this.save();
|
|
7638
|
+
}
|
|
7639
|
+
}
|
|
7534
7640
|
/**
|
|
7535
7641
|
* Send typing indicator to a peer
|
|
7536
7642
|
*/
|
|
@@ -7540,6 +7646,26 @@ var CommunicationsModule = class {
|
|
|
7540
7646
|
await this.deps.transport.sendTypingIndicator(peerPubkey);
|
|
7541
7647
|
}
|
|
7542
7648
|
}
|
|
7649
|
+
/**
|
|
7650
|
+
* Send a composing indicator to a peer.
|
|
7651
|
+
* Fire-and-forget — does not save to message history.
|
|
7652
|
+
*/
|
|
7653
|
+
async sendComposingIndicator(recipientPubkeyOrNametag) {
|
|
7654
|
+
this.ensureInitialized();
|
|
7655
|
+
const resolved = await this.resolveRecipient(recipientPubkeyOrNametag);
|
|
7656
|
+
const content = JSON.stringify({
|
|
7657
|
+
senderNametag: this.deps.identity.nametag,
|
|
7658
|
+
expiresIn: 3e4
|
|
7659
|
+
});
|
|
7660
|
+
await this.deps.transport.sendComposingIndicator?.(resolved.pubkey, content);
|
|
7661
|
+
}
|
|
7662
|
+
/**
|
|
7663
|
+
* Subscribe to incoming composing indicators
|
|
7664
|
+
*/
|
|
7665
|
+
onComposingIndicator(handler) {
|
|
7666
|
+
this.composingHandlers.add(handler);
|
|
7667
|
+
return () => this.composingHandlers.delete(handler);
|
|
7668
|
+
}
|
|
7543
7669
|
/**
|
|
7544
7670
|
* Subscribe to incoming DMs
|
|
7545
7671
|
*/
|
|
@@ -7652,6 +7778,21 @@ var CommunicationsModule = class {
|
|
|
7652
7778
|
}
|
|
7653
7779
|
this.pruneIfNeeded();
|
|
7654
7780
|
}
|
|
7781
|
+
handleComposingIndicator(indicator) {
|
|
7782
|
+
const composing = {
|
|
7783
|
+
senderPubkey: indicator.senderPubkey,
|
|
7784
|
+
senderNametag: indicator.senderNametag,
|
|
7785
|
+
expiresIn: indicator.expiresIn
|
|
7786
|
+
};
|
|
7787
|
+
this.deps.emitEvent("composing:started", composing);
|
|
7788
|
+
for (const handler of this.composingHandlers) {
|
|
7789
|
+
try {
|
|
7790
|
+
handler(composing);
|
|
7791
|
+
} catch (error) {
|
|
7792
|
+
console.error("[Communications] Composing handler error:", error);
|
|
7793
|
+
}
|
|
7794
|
+
}
|
|
7795
|
+
}
|
|
7655
7796
|
handleIncomingBroadcast(incoming) {
|
|
7656
7797
|
const message = {
|
|
7657
7798
|
id: incoming.id,
|
|
@@ -7675,9 +7816,23 @@ var CommunicationsModule = class {
|
|
|
7675
7816
|
// ===========================================================================
|
|
7676
7817
|
async save() {
|
|
7677
7818
|
const messages = Array.from(this.messages.values());
|
|
7678
|
-
await this.deps.storage.set(
|
|
7819
|
+
await this.deps.storage.set(STORAGE_KEYS_ADDRESS.MESSAGES, JSON.stringify(messages));
|
|
7679
7820
|
}
|
|
7680
7821
|
pruneIfNeeded() {
|
|
7822
|
+
const byPeer = /* @__PURE__ */ new Map();
|
|
7823
|
+
for (const msg of this.messages.values()) {
|
|
7824
|
+
const peer = msg.senderPubkey === this.deps?.identity.chainPubkey ? msg.recipientPubkey : msg.senderPubkey;
|
|
7825
|
+
if (!byPeer.has(peer)) byPeer.set(peer, []);
|
|
7826
|
+
byPeer.get(peer).push(msg);
|
|
7827
|
+
}
|
|
7828
|
+
for (const [, msgs] of byPeer) {
|
|
7829
|
+
if (msgs.length <= this.config.maxPerConversation) continue;
|
|
7830
|
+
msgs.sort((a, b) => a.timestamp - b.timestamp);
|
|
7831
|
+
const toRemove2 = msgs.slice(0, msgs.length - this.config.maxPerConversation);
|
|
7832
|
+
for (const msg of toRemove2) {
|
|
7833
|
+
this.messages.delete(msg.id);
|
|
7834
|
+
}
|
|
7835
|
+
}
|
|
7681
7836
|
if (this.messages.size <= this.config.maxMessages) return;
|
|
7682
7837
|
const sorted = Array.from(this.messages.entries()).sort(([, a], [, b]) => a.timestamp - b.timestamp);
|
|
7683
7838
|
const toRemove = sorted.slice(0, sorted.length - this.config.maxMessages);
|
|
@@ -7690,13 +7845,14 @@ var CommunicationsModule = class {
|
|
|
7690
7845
|
// ===========================================================================
|
|
7691
7846
|
async resolveRecipient(recipient) {
|
|
7692
7847
|
if (recipient.startsWith("@")) {
|
|
7693
|
-
const
|
|
7848
|
+
const nametag = recipient.slice(1);
|
|
7849
|
+
const pubkey = await this.deps.transport.resolveNametag?.(nametag);
|
|
7694
7850
|
if (!pubkey) {
|
|
7695
7851
|
throw new Error(`Nametag not found: ${recipient}`);
|
|
7696
7852
|
}
|
|
7697
|
-
return pubkey;
|
|
7853
|
+
return { pubkey, nametag };
|
|
7698
7854
|
}
|
|
7699
|
-
return recipient;
|
|
7855
|
+
return { pubkey: recipient };
|
|
7700
7856
|
}
|
|
7701
7857
|
ensureInitialized() {
|
|
7702
7858
|
if (!this.deps) {
|
|
@@ -9086,6 +9242,2427 @@ function createGroupChatModule(config) {
|
|
|
9086
9242
|
return new GroupChatModule(config);
|
|
9087
9243
|
}
|
|
9088
9244
|
|
|
9245
|
+
// node_modules/@noble/hashes/utils.js
|
|
9246
|
+
function isBytes(a) {
|
|
9247
|
+
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
|
|
9248
|
+
}
|
|
9249
|
+
function anumber(n, title = "") {
|
|
9250
|
+
if (!Number.isSafeInteger(n) || n < 0) {
|
|
9251
|
+
const prefix = title && `"${title}" `;
|
|
9252
|
+
throw new Error(`${prefix}expected integer >= 0, got ${n}`);
|
|
9253
|
+
}
|
|
9254
|
+
}
|
|
9255
|
+
function abytes(value, length, title = "") {
|
|
9256
|
+
const bytes = isBytes(value);
|
|
9257
|
+
const len = value?.length;
|
|
9258
|
+
const needsLen = length !== void 0;
|
|
9259
|
+
if (!bytes || needsLen && len !== length) {
|
|
9260
|
+
const prefix = title && `"${title}" `;
|
|
9261
|
+
const ofLen = needsLen ? ` of length ${length}` : "";
|
|
9262
|
+
const got = bytes ? `length=${len}` : `type=${typeof value}`;
|
|
9263
|
+
throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
|
|
9264
|
+
}
|
|
9265
|
+
return value;
|
|
9266
|
+
}
|
|
9267
|
+
function ahash(h) {
|
|
9268
|
+
if (typeof h !== "function" || typeof h.create !== "function")
|
|
9269
|
+
throw new Error("Hash must wrapped by utils.createHasher");
|
|
9270
|
+
anumber(h.outputLen);
|
|
9271
|
+
anumber(h.blockLen);
|
|
9272
|
+
}
|
|
9273
|
+
function aexists(instance, checkFinished = true) {
|
|
9274
|
+
if (instance.destroyed)
|
|
9275
|
+
throw new Error("Hash instance has been destroyed");
|
|
9276
|
+
if (checkFinished && instance.finished)
|
|
9277
|
+
throw new Error("Hash#digest() has already been called");
|
|
9278
|
+
}
|
|
9279
|
+
function aoutput(out, instance) {
|
|
9280
|
+
abytes(out, void 0, "digestInto() output");
|
|
9281
|
+
const min = instance.outputLen;
|
|
9282
|
+
if (out.length < min) {
|
|
9283
|
+
throw new Error('"digestInto() output" expected to be of length >=' + min);
|
|
9284
|
+
}
|
|
9285
|
+
}
|
|
9286
|
+
function clean(...arrays) {
|
|
9287
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
9288
|
+
arrays[i].fill(0);
|
|
9289
|
+
}
|
|
9290
|
+
}
|
|
9291
|
+
function createView(arr) {
|
|
9292
|
+
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
9293
|
+
}
|
|
9294
|
+
function rotr(word, shift) {
|
|
9295
|
+
return word << 32 - shift | word >>> shift;
|
|
9296
|
+
}
|
|
9297
|
+
var hasHexBuiltin = /* @__PURE__ */ (() => (
|
|
9298
|
+
// @ts-ignore
|
|
9299
|
+
typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
|
|
9300
|
+
))();
|
|
9301
|
+
var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
|
|
9302
|
+
function bytesToHex4(bytes) {
|
|
9303
|
+
abytes(bytes);
|
|
9304
|
+
if (hasHexBuiltin)
|
|
9305
|
+
return bytes.toHex();
|
|
9306
|
+
let hex = "";
|
|
9307
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
9308
|
+
hex += hexes[bytes[i]];
|
|
9309
|
+
}
|
|
9310
|
+
return hex;
|
|
9311
|
+
}
|
|
9312
|
+
var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
|
|
9313
|
+
function asciiToBase16(ch) {
|
|
9314
|
+
if (ch >= asciis._0 && ch <= asciis._9)
|
|
9315
|
+
return ch - asciis._0;
|
|
9316
|
+
if (ch >= asciis.A && ch <= asciis.F)
|
|
9317
|
+
return ch - (asciis.A - 10);
|
|
9318
|
+
if (ch >= asciis.a && ch <= asciis.f)
|
|
9319
|
+
return ch - (asciis.a - 10);
|
|
9320
|
+
return;
|
|
9321
|
+
}
|
|
9322
|
+
function hexToBytes2(hex) {
|
|
9323
|
+
if (typeof hex !== "string")
|
|
9324
|
+
throw new Error("hex string expected, got " + typeof hex);
|
|
9325
|
+
if (hasHexBuiltin)
|
|
9326
|
+
return Uint8Array.fromHex(hex);
|
|
9327
|
+
const hl = hex.length;
|
|
9328
|
+
const al = hl / 2;
|
|
9329
|
+
if (hl % 2)
|
|
9330
|
+
throw new Error("hex string expected, got unpadded hex of length " + hl);
|
|
9331
|
+
const array = new Uint8Array(al);
|
|
9332
|
+
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
9333
|
+
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
|
9334
|
+
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
|
9335
|
+
if (n1 === void 0 || n2 === void 0) {
|
|
9336
|
+
const char = hex[hi] + hex[hi + 1];
|
|
9337
|
+
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
9338
|
+
}
|
|
9339
|
+
array[ai] = n1 * 16 + n2;
|
|
9340
|
+
}
|
|
9341
|
+
return array;
|
|
9342
|
+
}
|
|
9343
|
+
function concatBytes(...arrays) {
|
|
9344
|
+
let sum = 0;
|
|
9345
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
9346
|
+
const a = arrays[i];
|
|
9347
|
+
abytes(a);
|
|
9348
|
+
sum += a.length;
|
|
9349
|
+
}
|
|
9350
|
+
const res = new Uint8Array(sum);
|
|
9351
|
+
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
9352
|
+
const a = arrays[i];
|
|
9353
|
+
res.set(a, pad);
|
|
9354
|
+
pad += a.length;
|
|
9355
|
+
}
|
|
9356
|
+
return res;
|
|
9357
|
+
}
|
|
9358
|
+
function createHasher(hashCons, info = {}) {
|
|
9359
|
+
const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
|
|
9360
|
+
const tmp = hashCons(void 0);
|
|
9361
|
+
hashC.outputLen = tmp.outputLen;
|
|
9362
|
+
hashC.blockLen = tmp.blockLen;
|
|
9363
|
+
hashC.create = (opts) => hashCons(opts);
|
|
9364
|
+
Object.assign(hashC, info);
|
|
9365
|
+
return Object.freeze(hashC);
|
|
9366
|
+
}
|
|
9367
|
+
function randomBytes2(bytesLength = 32) {
|
|
9368
|
+
const cr = typeof globalThis === "object" ? globalThis.crypto : null;
|
|
9369
|
+
if (typeof cr?.getRandomValues !== "function")
|
|
9370
|
+
throw new Error("crypto.getRandomValues must be defined");
|
|
9371
|
+
return cr.getRandomValues(new Uint8Array(bytesLength));
|
|
9372
|
+
}
|
|
9373
|
+
var oidNist = (suffix) => ({
|
|
9374
|
+
oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
|
|
9375
|
+
});
|
|
9376
|
+
|
|
9377
|
+
// node_modules/@noble/hashes/_md.js
|
|
9378
|
+
function Chi(a, b, c) {
|
|
9379
|
+
return a & b ^ ~a & c;
|
|
9380
|
+
}
|
|
9381
|
+
function Maj(a, b, c) {
|
|
9382
|
+
return a & b ^ a & c ^ b & c;
|
|
9383
|
+
}
|
|
9384
|
+
var HashMD = class {
|
|
9385
|
+
blockLen;
|
|
9386
|
+
outputLen;
|
|
9387
|
+
padOffset;
|
|
9388
|
+
isLE;
|
|
9389
|
+
// For partial updates less than block size
|
|
9390
|
+
buffer;
|
|
9391
|
+
view;
|
|
9392
|
+
finished = false;
|
|
9393
|
+
length = 0;
|
|
9394
|
+
pos = 0;
|
|
9395
|
+
destroyed = false;
|
|
9396
|
+
constructor(blockLen, outputLen, padOffset, isLE) {
|
|
9397
|
+
this.blockLen = blockLen;
|
|
9398
|
+
this.outputLen = outputLen;
|
|
9399
|
+
this.padOffset = padOffset;
|
|
9400
|
+
this.isLE = isLE;
|
|
9401
|
+
this.buffer = new Uint8Array(blockLen);
|
|
9402
|
+
this.view = createView(this.buffer);
|
|
9403
|
+
}
|
|
9404
|
+
update(data) {
|
|
9405
|
+
aexists(this);
|
|
9406
|
+
abytes(data);
|
|
9407
|
+
const { view, buffer, blockLen } = this;
|
|
9408
|
+
const len = data.length;
|
|
9409
|
+
for (let pos = 0; pos < len; ) {
|
|
9410
|
+
const take = Math.min(blockLen - this.pos, len - pos);
|
|
9411
|
+
if (take === blockLen) {
|
|
9412
|
+
const dataView = createView(data);
|
|
9413
|
+
for (; blockLen <= len - pos; pos += blockLen)
|
|
9414
|
+
this.process(dataView, pos);
|
|
9415
|
+
continue;
|
|
9416
|
+
}
|
|
9417
|
+
buffer.set(data.subarray(pos, pos + take), this.pos);
|
|
9418
|
+
this.pos += take;
|
|
9419
|
+
pos += take;
|
|
9420
|
+
if (this.pos === blockLen) {
|
|
9421
|
+
this.process(view, 0);
|
|
9422
|
+
this.pos = 0;
|
|
9423
|
+
}
|
|
9424
|
+
}
|
|
9425
|
+
this.length += data.length;
|
|
9426
|
+
this.roundClean();
|
|
9427
|
+
return this;
|
|
9428
|
+
}
|
|
9429
|
+
digestInto(out) {
|
|
9430
|
+
aexists(this);
|
|
9431
|
+
aoutput(out, this);
|
|
9432
|
+
this.finished = true;
|
|
9433
|
+
const { buffer, view, blockLen, isLE } = this;
|
|
9434
|
+
let { pos } = this;
|
|
9435
|
+
buffer[pos++] = 128;
|
|
9436
|
+
clean(this.buffer.subarray(pos));
|
|
9437
|
+
if (this.padOffset > blockLen - pos) {
|
|
9438
|
+
this.process(view, 0);
|
|
9439
|
+
pos = 0;
|
|
9440
|
+
}
|
|
9441
|
+
for (let i = pos; i < blockLen; i++)
|
|
9442
|
+
buffer[i] = 0;
|
|
9443
|
+
view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
|
|
9444
|
+
this.process(view, 0);
|
|
9445
|
+
const oview = createView(out);
|
|
9446
|
+
const len = this.outputLen;
|
|
9447
|
+
if (len % 4)
|
|
9448
|
+
throw new Error("_sha2: outputLen must be aligned to 32bit");
|
|
9449
|
+
const outLen = len / 4;
|
|
9450
|
+
const state = this.get();
|
|
9451
|
+
if (outLen > state.length)
|
|
9452
|
+
throw new Error("_sha2: outputLen bigger than state");
|
|
9453
|
+
for (let i = 0; i < outLen; i++)
|
|
9454
|
+
oview.setUint32(4 * i, state[i], isLE);
|
|
9455
|
+
}
|
|
9456
|
+
digest() {
|
|
9457
|
+
const { buffer, outputLen } = this;
|
|
9458
|
+
this.digestInto(buffer);
|
|
9459
|
+
const res = buffer.slice(0, outputLen);
|
|
9460
|
+
this.destroy();
|
|
9461
|
+
return res;
|
|
9462
|
+
}
|
|
9463
|
+
_cloneInto(to) {
|
|
9464
|
+
to ||= new this.constructor();
|
|
9465
|
+
to.set(...this.get());
|
|
9466
|
+
const { blockLen, buffer, length, finished, destroyed, pos } = this;
|
|
9467
|
+
to.destroyed = destroyed;
|
|
9468
|
+
to.finished = finished;
|
|
9469
|
+
to.length = length;
|
|
9470
|
+
to.pos = pos;
|
|
9471
|
+
if (length % blockLen)
|
|
9472
|
+
to.buffer.set(buffer);
|
|
9473
|
+
return to;
|
|
9474
|
+
}
|
|
9475
|
+
clone() {
|
|
9476
|
+
return this._cloneInto();
|
|
9477
|
+
}
|
|
9478
|
+
};
|
|
9479
|
+
var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
|
|
9480
|
+
1779033703,
|
|
9481
|
+
3144134277,
|
|
9482
|
+
1013904242,
|
|
9483
|
+
2773480762,
|
|
9484
|
+
1359893119,
|
|
9485
|
+
2600822924,
|
|
9486
|
+
528734635,
|
|
9487
|
+
1541459225
|
|
9488
|
+
]);
|
|
9489
|
+
|
|
9490
|
+
// node_modules/@noble/hashes/sha2.js
|
|
9491
|
+
var SHA256_K = /* @__PURE__ */ Uint32Array.from([
|
|
9492
|
+
1116352408,
|
|
9493
|
+
1899447441,
|
|
9494
|
+
3049323471,
|
|
9495
|
+
3921009573,
|
|
9496
|
+
961987163,
|
|
9497
|
+
1508970993,
|
|
9498
|
+
2453635748,
|
|
9499
|
+
2870763221,
|
|
9500
|
+
3624381080,
|
|
9501
|
+
310598401,
|
|
9502
|
+
607225278,
|
|
9503
|
+
1426881987,
|
|
9504
|
+
1925078388,
|
|
9505
|
+
2162078206,
|
|
9506
|
+
2614888103,
|
|
9507
|
+
3248222580,
|
|
9508
|
+
3835390401,
|
|
9509
|
+
4022224774,
|
|
9510
|
+
264347078,
|
|
9511
|
+
604807628,
|
|
9512
|
+
770255983,
|
|
9513
|
+
1249150122,
|
|
9514
|
+
1555081692,
|
|
9515
|
+
1996064986,
|
|
9516
|
+
2554220882,
|
|
9517
|
+
2821834349,
|
|
9518
|
+
2952996808,
|
|
9519
|
+
3210313671,
|
|
9520
|
+
3336571891,
|
|
9521
|
+
3584528711,
|
|
9522
|
+
113926993,
|
|
9523
|
+
338241895,
|
|
9524
|
+
666307205,
|
|
9525
|
+
773529912,
|
|
9526
|
+
1294757372,
|
|
9527
|
+
1396182291,
|
|
9528
|
+
1695183700,
|
|
9529
|
+
1986661051,
|
|
9530
|
+
2177026350,
|
|
9531
|
+
2456956037,
|
|
9532
|
+
2730485921,
|
|
9533
|
+
2820302411,
|
|
9534
|
+
3259730800,
|
|
9535
|
+
3345764771,
|
|
9536
|
+
3516065817,
|
|
9537
|
+
3600352804,
|
|
9538
|
+
4094571909,
|
|
9539
|
+
275423344,
|
|
9540
|
+
430227734,
|
|
9541
|
+
506948616,
|
|
9542
|
+
659060556,
|
|
9543
|
+
883997877,
|
|
9544
|
+
958139571,
|
|
9545
|
+
1322822218,
|
|
9546
|
+
1537002063,
|
|
9547
|
+
1747873779,
|
|
9548
|
+
1955562222,
|
|
9549
|
+
2024104815,
|
|
9550
|
+
2227730452,
|
|
9551
|
+
2361852424,
|
|
9552
|
+
2428436474,
|
|
9553
|
+
2756734187,
|
|
9554
|
+
3204031479,
|
|
9555
|
+
3329325298
|
|
9556
|
+
]);
|
|
9557
|
+
var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
|
|
9558
|
+
var SHA2_32B = class extends HashMD {
|
|
9559
|
+
constructor(outputLen) {
|
|
9560
|
+
super(64, outputLen, 8, false);
|
|
9561
|
+
}
|
|
9562
|
+
get() {
|
|
9563
|
+
const { A, B, C, D, E, F, G, H } = this;
|
|
9564
|
+
return [A, B, C, D, E, F, G, H];
|
|
9565
|
+
}
|
|
9566
|
+
// prettier-ignore
|
|
9567
|
+
set(A, B, C, D, E, F, G, H) {
|
|
9568
|
+
this.A = A | 0;
|
|
9569
|
+
this.B = B | 0;
|
|
9570
|
+
this.C = C | 0;
|
|
9571
|
+
this.D = D | 0;
|
|
9572
|
+
this.E = E | 0;
|
|
9573
|
+
this.F = F | 0;
|
|
9574
|
+
this.G = G | 0;
|
|
9575
|
+
this.H = H | 0;
|
|
9576
|
+
}
|
|
9577
|
+
process(view, offset) {
|
|
9578
|
+
for (let i = 0; i < 16; i++, offset += 4)
|
|
9579
|
+
SHA256_W[i] = view.getUint32(offset, false);
|
|
9580
|
+
for (let i = 16; i < 64; i++) {
|
|
9581
|
+
const W15 = SHA256_W[i - 15];
|
|
9582
|
+
const W2 = SHA256_W[i - 2];
|
|
9583
|
+
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
|
|
9584
|
+
const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
|
|
9585
|
+
SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
|
|
9586
|
+
}
|
|
9587
|
+
let { A, B, C, D, E, F, G, H } = this;
|
|
9588
|
+
for (let i = 0; i < 64; i++) {
|
|
9589
|
+
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
|
|
9590
|
+
const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
|
|
9591
|
+
const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
|
|
9592
|
+
const T2 = sigma0 + Maj(A, B, C) | 0;
|
|
9593
|
+
H = G;
|
|
9594
|
+
G = F;
|
|
9595
|
+
F = E;
|
|
9596
|
+
E = D + T1 | 0;
|
|
9597
|
+
D = C;
|
|
9598
|
+
C = B;
|
|
9599
|
+
B = A;
|
|
9600
|
+
A = T1 + T2 | 0;
|
|
9601
|
+
}
|
|
9602
|
+
A = A + this.A | 0;
|
|
9603
|
+
B = B + this.B | 0;
|
|
9604
|
+
C = C + this.C | 0;
|
|
9605
|
+
D = D + this.D | 0;
|
|
9606
|
+
E = E + this.E | 0;
|
|
9607
|
+
F = F + this.F | 0;
|
|
9608
|
+
G = G + this.G | 0;
|
|
9609
|
+
H = H + this.H | 0;
|
|
9610
|
+
this.set(A, B, C, D, E, F, G, H);
|
|
9611
|
+
}
|
|
9612
|
+
roundClean() {
|
|
9613
|
+
clean(SHA256_W);
|
|
9614
|
+
}
|
|
9615
|
+
destroy() {
|
|
9616
|
+
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
|
9617
|
+
clean(this.buffer);
|
|
9618
|
+
}
|
|
9619
|
+
};
|
|
9620
|
+
var _SHA256 = class extends SHA2_32B {
|
|
9621
|
+
// We cannot use array here since array allows indexing by variable
|
|
9622
|
+
// which means optimizer/compiler cannot use registers.
|
|
9623
|
+
A = SHA256_IV[0] | 0;
|
|
9624
|
+
B = SHA256_IV[1] | 0;
|
|
9625
|
+
C = SHA256_IV[2] | 0;
|
|
9626
|
+
D = SHA256_IV[3] | 0;
|
|
9627
|
+
E = SHA256_IV[4] | 0;
|
|
9628
|
+
F = SHA256_IV[5] | 0;
|
|
9629
|
+
G = SHA256_IV[6] | 0;
|
|
9630
|
+
H = SHA256_IV[7] | 0;
|
|
9631
|
+
constructor() {
|
|
9632
|
+
super(32);
|
|
9633
|
+
}
|
|
9634
|
+
};
|
|
9635
|
+
var sha2564 = /* @__PURE__ */ createHasher(
|
|
9636
|
+
() => new _SHA256(),
|
|
9637
|
+
/* @__PURE__ */ oidNist(1)
|
|
9638
|
+
);
|
|
9639
|
+
|
|
9640
|
+
// node_modules/@noble/curves/utils.js
|
|
9641
|
+
var _0n = /* @__PURE__ */ BigInt(0);
|
|
9642
|
+
var _1n = /* @__PURE__ */ BigInt(1);
|
|
9643
|
+
function abool(value, title = "") {
|
|
9644
|
+
if (typeof value !== "boolean") {
|
|
9645
|
+
const prefix = title && `"${title}" `;
|
|
9646
|
+
throw new Error(prefix + "expected boolean, got type=" + typeof value);
|
|
9647
|
+
}
|
|
9648
|
+
return value;
|
|
9649
|
+
}
|
|
9650
|
+
function abignumber(n) {
|
|
9651
|
+
if (typeof n === "bigint") {
|
|
9652
|
+
if (!isPosBig(n))
|
|
9653
|
+
throw new Error("positive bigint expected, got " + n);
|
|
9654
|
+
} else
|
|
9655
|
+
anumber(n);
|
|
9656
|
+
return n;
|
|
9657
|
+
}
|
|
9658
|
+
function numberToHexUnpadded(num) {
|
|
9659
|
+
const hex = abignumber(num).toString(16);
|
|
9660
|
+
return hex.length & 1 ? "0" + hex : hex;
|
|
9661
|
+
}
|
|
9662
|
+
function hexToNumber(hex) {
|
|
9663
|
+
if (typeof hex !== "string")
|
|
9664
|
+
throw new Error("hex string expected, got " + typeof hex);
|
|
9665
|
+
return hex === "" ? _0n : BigInt("0x" + hex);
|
|
9666
|
+
}
|
|
9667
|
+
function bytesToNumberBE(bytes) {
|
|
9668
|
+
return hexToNumber(bytesToHex4(bytes));
|
|
9669
|
+
}
|
|
9670
|
+
function bytesToNumberLE(bytes) {
|
|
9671
|
+
return hexToNumber(bytesToHex4(copyBytes(abytes(bytes)).reverse()));
|
|
9672
|
+
}
|
|
9673
|
+
function numberToBytesBE(n, len) {
|
|
9674
|
+
anumber(len);
|
|
9675
|
+
n = abignumber(n);
|
|
9676
|
+
const res = hexToBytes2(n.toString(16).padStart(len * 2, "0"));
|
|
9677
|
+
if (res.length !== len)
|
|
9678
|
+
throw new Error("number too large");
|
|
9679
|
+
return res;
|
|
9680
|
+
}
|
|
9681
|
+
function numberToBytesLE(n, len) {
|
|
9682
|
+
return numberToBytesBE(n, len).reverse();
|
|
9683
|
+
}
|
|
9684
|
+
function copyBytes(bytes) {
|
|
9685
|
+
return Uint8Array.from(bytes);
|
|
9686
|
+
}
|
|
9687
|
+
var isPosBig = (n) => typeof n === "bigint" && _0n <= n;
|
|
9688
|
+
function inRange(n, min, max) {
|
|
9689
|
+
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
|
|
9690
|
+
}
|
|
9691
|
+
function aInRange(title, n, min, max) {
|
|
9692
|
+
if (!inRange(n, min, max))
|
|
9693
|
+
throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
|
|
9694
|
+
}
|
|
9695
|
+
function bitLen(n) {
|
|
9696
|
+
let len;
|
|
9697
|
+
for (len = 0; n > _0n; n >>= _1n, len += 1)
|
|
9698
|
+
;
|
|
9699
|
+
return len;
|
|
9700
|
+
}
|
|
9701
|
+
var bitMask = (n) => (_1n << BigInt(n)) - _1n;
|
|
9702
|
+
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
|
|
9703
|
+
anumber(hashLen, "hashLen");
|
|
9704
|
+
anumber(qByteLen, "qByteLen");
|
|
9705
|
+
if (typeof hmacFn !== "function")
|
|
9706
|
+
throw new Error("hmacFn must be a function");
|
|
9707
|
+
const u8n = (len) => new Uint8Array(len);
|
|
9708
|
+
const NULL = Uint8Array.of();
|
|
9709
|
+
const byte0 = Uint8Array.of(0);
|
|
9710
|
+
const byte1 = Uint8Array.of(1);
|
|
9711
|
+
const _maxDrbgIters = 1e3;
|
|
9712
|
+
let v = u8n(hashLen);
|
|
9713
|
+
let k = u8n(hashLen);
|
|
9714
|
+
let i = 0;
|
|
9715
|
+
const reset = () => {
|
|
9716
|
+
v.fill(1);
|
|
9717
|
+
k.fill(0);
|
|
9718
|
+
i = 0;
|
|
9719
|
+
};
|
|
9720
|
+
const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));
|
|
9721
|
+
const reseed = (seed = NULL) => {
|
|
9722
|
+
k = h(byte0, seed);
|
|
9723
|
+
v = h();
|
|
9724
|
+
if (seed.length === 0)
|
|
9725
|
+
return;
|
|
9726
|
+
k = h(byte1, seed);
|
|
9727
|
+
v = h();
|
|
9728
|
+
};
|
|
9729
|
+
const gen = () => {
|
|
9730
|
+
if (i++ >= _maxDrbgIters)
|
|
9731
|
+
throw new Error("drbg: tried max amount of iterations");
|
|
9732
|
+
let len = 0;
|
|
9733
|
+
const out = [];
|
|
9734
|
+
while (len < qByteLen) {
|
|
9735
|
+
v = h();
|
|
9736
|
+
const sl = v.slice();
|
|
9737
|
+
out.push(sl);
|
|
9738
|
+
len += v.length;
|
|
9739
|
+
}
|
|
9740
|
+
return concatBytes(...out);
|
|
9741
|
+
};
|
|
9742
|
+
const genUntil = (seed, pred) => {
|
|
9743
|
+
reset();
|
|
9744
|
+
reseed(seed);
|
|
9745
|
+
let res = void 0;
|
|
9746
|
+
while (!(res = pred(gen())))
|
|
9747
|
+
reseed();
|
|
9748
|
+
reset();
|
|
9749
|
+
return res;
|
|
9750
|
+
};
|
|
9751
|
+
return genUntil;
|
|
9752
|
+
}
|
|
9753
|
+
function validateObject(object, fields = {}, optFields = {}) {
|
|
9754
|
+
if (!object || typeof object !== "object")
|
|
9755
|
+
throw new Error("expected valid options object");
|
|
9756
|
+
function checkField(fieldName, expectedType, isOpt) {
|
|
9757
|
+
const val = object[fieldName];
|
|
9758
|
+
if (isOpt && val === void 0)
|
|
9759
|
+
return;
|
|
9760
|
+
const current = typeof val;
|
|
9761
|
+
if (current !== expectedType || val === null)
|
|
9762
|
+
throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
|
|
9763
|
+
}
|
|
9764
|
+
const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
|
|
9765
|
+
iter(fields, false);
|
|
9766
|
+
iter(optFields, true);
|
|
9767
|
+
}
|
|
9768
|
+
function memoized(fn) {
|
|
9769
|
+
const map = /* @__PURE__ */ new WeakMap();
|
|
9770
|
+
return (arg, ...args) => {
|
|
9771
|
+
const val = map.get(arg);
|
|
9772
|
+
if (val !== void 0)
|
|
9773
|
+
return val;
|
|
9774
|
+
const computed = fn(arg, ...args);
|
|
9775
|
+
map.set(arg, computed);
|
|
9776
|
+
return computed;
|
|
9777
|
+
};
|
|
9778
|
+
}
|
|
9779
|
+
|
|
9780
|
+
// node_modules/@noble/curves/abstract/modular.js
|
|
9781
|
+
var _0n2 = /* @__PURE__ */ BigInt(0);
|
|
9782
|
+
var _1n2 = /* @__PURE__ */ BigInt(1);
|
|
9783
|
+
var _2n = /* @__PURE__ */ BigInt(2);
|
|
9784
|
+
var _3n = /* @__PURE__ */ BigInt(3);
|
|
9785
|
+
var _4n = /* @__PURE__ */ BigInt(4);
|
|
9786
|
+
var _5n = /* @__PURE__ */ BigInt(5);
|
|
9787
|
+
var _7n = /* @__PURE__ */ BigInt(7);
|
|
9788
|
+
var _8n = /* @__PURE__ */ BigInt(8);
|
|
9789
|
+
var _9n = /* @__PURE__ */ BigInt(9);
|
|
9790
|
+
var _16n = /* @__PURE__ */ BigInt(16);
|
|
9791
|
+
function mod(a, b) {
|
|
9792
|
+
const result = a % b;
|
|
9793
|
+
return result >= _0n2 ? result : b + result;
|
|
9794
|
+
}
|
|
9795
|
+
function pow2(x, power, modulo) {
|
|
9796
|
+
let res = x;
|
|
9797
|
+
while (power-- > _0n2) {
|
|
9798
|
+
res *= res;
|
|
9799
|
+
res %= modulo;
|
|
9800
|
+
}
|
|
9801
|
+
return res;
|
|
9802
|
+
}
|
|
9803
|
+
function invert(number, modulo) {
|
|
9804
|
+
if (number === _0n2)
|
|
9805
|
+
throw new Error("invert: expected non-zero number");
|
|
9806
|
+
if (modulo <= _0n2)
|
|
9807
|
+
throw new Error("invert: expected positive modulus, got " + modulo);
|
|
9808
|
+
let a = mod(number, modulo);
|
|
9809
|
+
let b = modulo;
|
|
9810
|
+
let x = _0n2, y = _1n2, u = _1n2, v = _0n2;
|
|
9811
|
+
while (a !== _0n2) {
|
|
9812
|
+
const q = b / a;
|
|
9813
|
+
const r = b % a;
|
|
9814
|
+
const m = x - u * q;
|
|
9815
|
+
const n = y - v * q;
|
|
9816
|
+
b = a, a = r, x = u, y = v, u = m, v = n;
|
|
9817
|
+
}
|
|
9818
|
+
const gcd = b;
|
|
9819
|
+
if (gcd !== _1n2)
|
|
9820
|
+
throw new Error("invert: does not exist");
|
|
9821
|
+
return mod(x, modulo);
|
|
9822
|
+
}
|
|
9823
|
+
function assertIsSquare(Fp, root, n) {
|
|
9824
|
+
if (!Fp.eql(Fp.sqr(root), n))
|
|
9825
|
+
throw new Error("Cannot find square root");
|
|
9826
|
+
}
|
|
9827
|
+
function sqrt3mod4(Fp, n) {
|
|
9828
|
+
const p1div4 = (Fp.ORDER + _1n2) / _4n;
|
|
9829
|
+
const root = Fp.pow(n, p1div4);
|
|
9830
|
+
assertIsSquare(Fp, root, n);
|
|
9831
|
+
return root;
|
|
9832
|
+
}
|
|
9833
|
+
function sqrt5mod8(Fp, n) {
|
|
9834
|
+
const p5div8 = (Fp.ORDER - _5n) / _8n;
|
|
9835
|
+
const n2 = Fp.mul(n, _2n);
|
|
9836
|
+
const v = Fp.pow(n2, p5div8);
|
|
9837
|
+
const nv = Fp.mul(n, v);
|
|
9838
|
+
const i = Fp.mul(Fp.mul(nv, _2n), v);
|
|
9839
|
+
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
|
|
9840
|
+
assertIsSquare(Fp, root, n);
|
|
9841
|
+
return root;
|
|
9842
|
+
}
|
|
9843
|
+
function sqrt9mod16(P) {
|
|
9844
|
+
const Fp_ = Field(P);
|
|
9845
|
+
const tn = tonelliShanks(P);
|
|
9846
|
+
const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
|
|
9847
|
+
const c2 = tn(Fp_, c1);
|
|
9848
|
+
const c3 = tn(Fp_, Fp_.neg(c1));
|
|
9849
|
+
const c4 = (P + _7n) / _16n;
|
|
9850
|
+
return (Fp, n) => {
|
|
9851
|
+
let tv1 = Fp.pow(n, c4);
|
|
9852
|
+
let tv2 = Fp.mul(tv1, c1);
|
|
9853
|
+
const tv3 = Fp.mul(tv1, c2);
|
|
9854
|
+
const tv4 = Fp.mul(tv1, c3);
|
|
9855
|
+
const e1 = Fp.eql(Fp.sqr(tv2), n);
|
|
9856
|
+
const e2 = Fp.eql(Fp.sqr(tv3), n);
|
|
9857
|
+
tv1 = Fp.cmov(tv1, tv2, e1);
|
|
9858
|
+
tv2 = Fp.cmov(tv4, tv3, e2);
|
|
9859
|
+
const e3 = Fp.eql(Fp.sqr(tv2), n);
|
|
9860
|
+
const root = Fp.cmov(tv1, tv2, e3);
|
|
9861
|
+
assertIsSquare(Fp, root, n);
|
|
9862
|
+
return root;
|
|
9863
|
+
};
|
|
9864
|
+
}
|
|
9865
|
+
function tonelliShanks(P) {
|
|
9866
|
+
if (P < _3n)
|
|
9867
|
+
throw new Error("sqrt is not defined for small field");
|
|
9868
|
+
let Q = P - _1n2;
|
|
9869
|
+
let S = 0;
|
|
9870
|
+
while (Q % _2n === _0n2) {
|
|
9871
|
+
Q /= _2n;
|
|
9872
|
+
S++;
|
|
9873
|
+
}
|
|
9874
|
+
let Z = _2n;
|
|
9875
|
+
const _Fp = Field(P);
|
|
9876
|
+
while (FpLegendre(_Fp, Z) === 1) {
|
|
9877
|
+
if (Z++ > 1e3)
|
|
9878
|
+
throw new Error("Cannot find square root: probably non-prime P");
|
|
9879
|
+
}
|
|
9880
|
+
if (S === 1)
|
|
9881
|
+
return sqrt3mod4;
|
|
9882
|
+
let cc = _Fp.pow(Z, Q);
|
|
9883
|
+
const Q1div2 = (Q + _1n2) / _2n;
|
|
9884
|
+
return function tonelliSlow(Fp, n) {
|
|
9885
|
+
if (Fp.is0(n))
|
|
9886
|
+
return n;
|
|
9887
|
+
if (FpLegendre(Fp, n) !== 1)
|
|
9888
|
+
throw new Error("Cannot find square root");
|
|
9889
|
+
let M = S;
|
|
9890
|
+
let c = Fp.mul(Fp.ONE, cc);
|
|
9891
|
+
let t = Fp.pow(n, Q);
|
|
9892
|
+
let R = Fp.pow(n, Q1div2);
|
|
9893
|
+
while (!Fp.eql(t, Fp.ONE)) {
|
|
9894
|
+
if (Fp.is0(t))
|
|
9895
|
+
return Fp.ZERO;
|
|
9896
|
+
let i = 1;
|
|
9897
|
+
let t_tmp = Fp.sqr(t);
|
|
9898
|
+
while (!Fp.eql(t_tmp, Fp.ONE)) {
|
|
9899
|
+
i++;
|
|
9900
|
+
t_tmp = Fp.sqr(t_tmp);
|
|
9901
|
+
if (i === M)
|
|
9902
|
+
throw new Error("Cannot find square root");
|
|
9903
|
+
}
|
|
9904
|
+
const exponent = _1n2 << BigInt(M - i - 1);
|
|
9905
|
+
const b = Fp.pow(c, exponent);
|
|
9906
|
+
M = i;
|
|
9907
|
+
c = Fp.sqr(b);
|
|
9908
|
+
t = Fp.mul(t, c);
|
|
9909
|
+
R = Fp.mul(R, b);
|
|
9910
|
+
}
|
|
9911
|
+
return R;
|
|
9912
|
+
};
|
|
9913
|
+
}
|
|
9914
|
+
function FpSqrt(P) {
|
|
9915
|
+
if (P % _4n === _3n)
|
|
9916
|
+
return sqrt3mod4;
|
|
9917
|
+
if (P % _8n === _5n)
|
|
9918
|
+
return sqrt5mod8;
|
|
9919
|
+
if (P % _16n === _9n)
|
|
9920
|
+
return sqrt9mod16(P);
|
|
9921
|
+
return tonelliShanks(P);
|
|
9922
|
+
}
|
|
9923
|
+
var FIELD_FIELDS = [
|
|
9924
|
+
"create",
|
|
9925
|
+
"isValid",
|
|
9926
|
+
"is0",
|
|
9927
|
+
"neg",
|
|
9928
|
+
"inv",
|
|
9929
|
+
"sqrt",
|
|
9930
|
+
"sqr",
|
|
9931
|
+
"eql",
|
|
9932
|
+
"add",
|
|
9933
|
+
"sub",
|
|
9934
|
+
"mul",
|
|
9935
|
+
"pow",
|
|
9936
|
+
"div",
|
|
9937
|
+
"addN",
|
|
9938
|
+
"subN",
|
|
9939
|
+
"mulN",
|
|
9940
|
+
"sqrN"
|
|
9941
|
+
];
|
|
9942
|
+
function validateField(field) {
|
|
9943
|
+
const initial = {
|
|
9944
|
+
ORDER: "bigint",
|
|
9945
|
+
BYTES: "number",
|
|
9946
|
+
BITS: "number"
|
|
9947
|
+
};
|
|
9948
|
+
const opts = FIELD_FIELDS.reduce((map, val) => {
|
|
9949
|
+
map[val] = "function";
|
|
9950
|
+
return map;
|
|
9951
|
+
}, initial);
|
|
9952
|
+
validateObject(field, opts);
|
|
9953
|
+
return field;
|
|
9954
|
+
}
|
|
9955
|
+
function FpPow(Fp, num, power) {
|
|
9956
|
+
if (power < _0n2)
|
|
9957
|
+
throw new Error("invalid exponent, negatives unsupported");
|
|
9958
|
+
if (power === _0n2)
|
|
9959
|
+
return Fp.ONE;
|
|
9960
|
+
if (power === _1n2)
|
|
9961
|
+
return num;
|
|
9962
|
+
let p = Fp.ONE;
|
|
9963
|
+
let d = num;
|
|
9964
|
+
while (power > _0n2) {
|
|
9965
|
+
if (power & _1n2)
|
|
9966
|
+
p = Fp.mul(p, d);
|
|
9967
|
+
d = Fp.sqr(d);
|
|
9968
|
+
power >>= _1n2;
|
|
9969
|
+
}
|
|
9970
|
+
return p;
|
|
9971
|
+
}
|
|
9972
|
+
function FpInvertBatch(Fp, nums, passZero = false) {
|
|
9973
|
+
const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
|
|
9974
|
+
const multipliedAcc = nums.reduce((acc, num, i) => {
|
|
9975
|
+
if (Fp.is0(num))
|
|
9976
|
+
return acc;
|
|
9977
|
+
inverted[i] = acc;
|
|
9978
|
+
return Fp.mul(acc, num);
|
|
9979
|
+
}, Fp.ONE);
|
|
9980
|
+
const invertedAcc = Fp.inv(multipliedAcc);
|
|
9981
|
+
nums.reduceRight((acc, num, i) => {
|
|
9982
|
+
if (Fp.is0(num))
|
|
9983
|
+
return acc;
|
|
9984
|
+
inverted[i] = Fp.mul(acc, inverted[i]);
|
|
9985
|
+
return Fp.mul(acc, num);
|
|
9986
|
+
}, invertedAcc);
|
|
9987
|
+
return inverted;
|
|
9988
|
+
}
|
|
9989
|
+
function FpLegendre(Fp, n) {
|
|
9990
|
+
const p1mod2 = (Fp.ORDER - _1n2) / _2n;
|
|
9991
|
+
const powered = Fp.pow(n, p1mod2);
|
|
9992
|
+
const yes = Fp.eql(powered, Fp.ONE);
|
|
9993
|
+
const zero = Fp.eql(powered, Fp.ZERO);
|
|
9994
|
+
const no = Fp.eql(powered, Fp.neg(Fp.ONE));
|
|
9995
|
+
if (!yes && !zero && !no)
|
|
9996
|
+
throw new Error("invalid Legendre symbol result");
|
|
9997
|
+
return yes ? 1 : zero ? 0 : -1;
|
|
9998
|
+
}
|
|
9999
|
+
function nLength(n, nBitLength) {
|
|
10000
|
+
if (nBitLength !== void 0)
|
|
10001
|
+
anumber(nBitLength);
|
|
10002
|
+
const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
|
|
10003
|
+
const nByteLength = Math.ceil(_nBitLength / 8);
|
|
10004
|
+
return { nBitLength: _nBitLength, nByteLength };
|
|
10005
|
+
}
|
|
10006
|
+
var _Field = class {
|
|
10007
|
+
ORDER;
|
|
10008
|
+
BITS;
|
|
10009
|
+
BYTES;
|
|
10010
|
+
isLE;
|
|
10011
|
+
ZERO = _0n2;
|
|
10012
|
+
ONE = _1n2;
|
|
10013
|
+
_lengths;
|
|
10014
|
+
_sqrt;
|
|
10015
|
+
// cached sqrt
|
|
10016
|
+
_mod;
|
|
10017
|
+
constructor(ORDER, opts = {}) {
|
|
10018
|
+
if (ORDER <= _0n2)
|
|
10019
|
+
throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
|
|
10020
|
+
let _nbitLength = void 0;
|
|
10021
|
+
this.isLE = false;
|
|
10022
|
+
if (opts != null && typeof opts === "object") {
|
|
10023
|
+
if (typeof opts.BITS === "number")
|
|
10024
|
+
_nbitLength = opts.BITS;
|
|
10025
|
+
if (typeof opts.sqrt === "function")
|
|
10026
|
+
this.sqrt = opts.sqrt;
|
|
10027
|
+
if (typeof opts.isLE === "boolean")
|
|
10028
|
+
this.isLE = opts.isLE;
|
|
10029
|
+
if (opts.allowedLengths)
|
|
10030
|
+
this._lengths = opts.allowedLengths?.slice();
|
|
10031
|
+
if (typeof opts.modFromBytes === "boolean")
|
|
10032
|
+
this._mod = opts.modFromBytes;
|
|
10033
|
+
}
|
|
10034
|
+
const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
|
|
10035
|
+
if (nByteLength > 2048)
|
|
10036
|
+
throw new Error("invalid field: expected ORDER of <= 2048 bytes");
|
|
10037
|
+
this.ORDER = ORDER;
|
|
10038
|
+
this.BITS = nBitLength;
|
|
10039
|
+
this.BYTES = nByteLength;
|
|
10040
|
+
this._sqrt = void 0;
|
|
10041
|
+
Object.preventExtensions(this);
|
|
10042
|
+
}
|
|
10043
|
+
create(num) {
|
|
10044
|
+
return mod(num, this.ORDER);
|
|
10045
|
+
}
|
|
10046
|
+
isValid(num) {
|
|
10047
|
+
if (typeof num !== "bigint")
|
|
10048
|
+
throw new Error("invalid field element: expected bigint, got " + typeof num);
|
|
10049
|
+
return _0n2 <= num && num < this.ORDER;
|
|
10050
|
+
}
|
|
10051
|
+
is0(num) {
|
|
10052
|
+
return num === _0n2;
|
|
10053
|
+
}
|
|
10054
|
+
// is valid and invertible
|
|
10055
|
+
isValidNot0(num) {
|
|
10056
|
+
return !this.is0(num) && this.isValid(num);
|
|
10057
|
+
}
|
|
10058
|
+
isOdd(num) {
|
|
10059
|
+
return (num & _1n2) === _1n2;
|
|
10060
|
+
}
|
|
10061
|
+
neg(num) {
|
|
10062
|
+
return mod(-num, this.ORDER);
|
|
10063
|
+
}
|
|
10064
|
+
eql(lhs, rhs) {
|
|
10065
|
+
return lhs === rhs;
|
|
10066
|
+
}
|
|
10067
|
+
sqr(num) {
|
|
10068
|
+
return mod(num * num, this.ORDER);
|
|
10069
|
+
}
|
|
10070
|
+
add(lhs, rhs) {
|
|
10071
|
+
return mod(lhs + rhs, this.ORDER);
|
|
10072
|
+
}
|
|
10073
|
+
sub(lhs, rhs) {
|
|
10074
|
+
return mod(lhs - rhs, this.ORDER);
|
|
10075
|
+
}
|
|
10076
|
+
mul(lhs, rhs) {
|
|
10077
|
+
return mod(lhs * rhs, this.ORDER);
|
|
10078
|
+
}
|
|
10079
|
+
pow(num, power) {
|
|
10080
|
+
return FpPow(this, num, power);
|
|
10081
|
+
}
|
|
10082
|
+
div(lhs, rhs) {
|
|
10083
|
+
return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
|
|
10084
|
+
}
|
|
10085
|
+
// Same as above, but doesn't normalize
|
|
10086
|
+
sqrN(num) {
|
|
10087
|
+
return num * num;
|
|
10088
|
+
}
|
|
10089
|
+
addN(lhs, rhs) {
|
|
10090
|
+
return lhs + rhs;
|
|
10091
|
+
}
|
|
10092
|
+
subN(lhs, rhs) {
|
|
10093
|
+
return lhs - rhs;
|
|
10094
|
+
}
|
|
10095
|
+
mulN(lhs, rhs) {
|
|
10096
|
+
return lhs * rhs;
|
|
10097
|
+
}
|
|
10098
|
+
inv(num) {
|
|
10099
|
+
return invert(num, this.ORDER);
|
|
10100
|
+
}
|
|
10101
|
+
sqrt(num) {
|
|
10102
|
+
if (!this._sqrt)
|
|
10103
|
+
this._sqrt = FpSqrt(this.ORDER);
|
|
10104
|
+
return this._sqrt(this, num);
|
|
10105
|
+
}
|
|
10106
|
+
toBytes(num) {
|
|
10107
|
+
return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
|
|
10108
|
+
}
|
|
10109
|
+
fromBytes(bytes, skipValidation = false) {
|
|
10110
|
+
abytes(bytes);
|
|
10111
|
+
const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
|
|
10112
|
+
if (allowedLengths) {
|
|
10113
|
+
if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
|
|
10114
|
+
throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
|
|
10115
|
+
}
|
|
10116
|
+
const padded = new Uint8Array(BYTES);
|
|
10117
|
+
padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
|
|
10118
|
+
bytes = padded;
|
|
10119
|
+
}
|
|
10120
|
+
if (bytes.length !== BYTES)
|
|
10121
|
+
throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
|
|
10122
|
+
let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
|
|
10123
|
+
if (modFromBytes)
|
|
10124
|
+
scalar = mod(scalar, ORDER);
|
|
10125
|
+
if (!skipValidation) {
|
|
10126
|
+
if (!this.isValid(scalar))
|
|
10127
|
+
throw new Error("invalid field element: outside of range 0..ORDER");
|
|
10128
|
+
}
|
|
10129
|
+
return scalar;
|
|
10130
|
+
}
|
|
10131
|
+
// TODO: we don't need it here, move out to separate fn
|
|
10132
|
+
invertBatch(lst) {
|
|
10133
|
+
return FpInvertBatch(this, lst);
|
|
10134
|
+
}
|
|
10135
|
+
// We can't move this out because Fp6, Fp12 implement it
|
|
10136
|
+
// and it's unclear what to return in there.
|
|
10137
|
+
cmov(a, b, condition) {
|
|
10138
|
+
return condition ? b : a;
|
|
10139
|
+
}
|
|
10140
|
+
};
|
|
10141
|
+
function Field(ORDER, opts = {}) {
|
|
10142
|
+
return new _Field(ORDER, opts);
|
|
10143
|
+
}
|
|
10144
|
+
function getFieldBytesLength(fieldOrder) {
|
|
10145
|
+
if (typeof fieldOrder !== "bigint")
|
|
10146
|
+
throw new Error("field order must be bigint");
|
|
10147
|
+
const bitLength = fieldOrder.toString(2).length;
|
|
10148
|
+
return Math.ceil(bitLength / 8);
|
|
10149
|
+
}
|
|
10150
|
+
function getMinHashLength(fieldOrder) {
|
|
10151
|
+
const length = getFieldBytesLength(fieldOrder);
|
|
10152
|
+
return length + Math.ceil(length / 2);
|
|
10153
|
+
}
|
|
10154
|
+
function mapHashToField(key, fieldOrder, isLE = false) {
|
|
10155
|
+
abytes(key);
|
|
10156
|
+
const len = key.length;
|
|
10157
|
+
const fieldLen = getFieldBytesLength(fieldOrder);
|
|
10158
|
+
const minLen = getMinHashLength(fieldOrder);
|
|
10159
|
+
if (len < 16 || len < minLen || len > 1024)
|
|
10160
|
+
throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
|
|
10161
|
+
const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);
|
|
10162
|
+
const reduced = mod(num, fieldOrder - _1n2) + _1n2;
|
|
10163
|
+
return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
|
|
10164
|
+
}
|
|
10165
|
+
|
|
10166
|
+
// node_modules/@noble/curves/abstract/curve.js
|
|
10167
|
+
var _0n3 = /* @__PURE__ */ BigInt(0);
|
|
10168
|
+
var _1n3 = /* @__PURE__ */ BigInt(1);
|
|
10169
|
+
function negateCt(condition, item) {
|
|
10170
|
+
const neg = item.negate();
|
|
10171
|
+
return condition ? neg : item;
|
|
10172
|
+
}
|
|
10173
|
+
function normalizeZ(c, points) {
|
|
10174
|
+
const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
|
|
10175
|
+
return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
|
|
10176
|
+
}
|
|
10177
|
+
function validateW(W, bits) {
|
|
10178
|
+
if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
|
|
10179
|
+
throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
|
|
10180
|
+
}
|
|
10181
|
+
function calcWOpts(W, scalarBits) {
|
|
10182
|
+
validateW(W, scalarBits);
|
|
10183
|
+
const windows = Math.ceil(scalarBits / W) + 1;
|
|
10184
|
+
const windowSize = 2 ** (W - 1);
|
|
10185
|
+
const maxNumber = 2 ** W;
|
|
10186
|
+
const mask = bitMask(W);
|
|
10187
|
+
const shiftBy = BigInt(W);
|
|
10188
|
+
return { windows, windowSize, mask, maxNumber, shiftBy };
|
|
10189
|
+
}
|
|
10190
|
+
function calcOffsets(n, window, wOpts) {
|
|
10191
|
+
const { windowSize, mask, maxNumber, shiftBy } = wOpts;
|
|
10192
|
+
let wbits = Number(n & mask);
|
|
10193
|
+
let nextN = n >> shiftBy;
|
|
10194
|
+
if (wbits > windowSize) {
|
|
10195
|
+
wbits -= maxNumber;
|
|
10196
|
+
nextN += _1n3;
|
|
10197
|
+
}
|
|
10198
|
+
const offsetStart = window * windowSize;
|
|
10199
|
+
const offset = offsetStart + Math.abs(wbits) - 1;
|
|
10200
|
+
const isZero = wbits === 0;
|
|
10201
|
+
const isNeg = wbits < 0;
|
|
10202
|
+
const isNegF = window % 2 !== 0;
|
|
10203
|
+
const offsetF = offsetStart;
|
|
10204
|
+
return { nextN, offset, isZero, isNeg, isNegF, offsetF };
|
|
10205
|
+
}
|
|
10206
|
+
var pointPrecomputes = /* @__PURE__ */ new WeakMap();
|
|
10207
|
+
var pointWindowSizes = /* @__PURE__ */ new WeakMap();
|
|
10208
|
+
function getW(P) {
|
|
10209
|
+
return pointWindowSizes.get(P) || 1;
|
|
10210
|
+
}
|
|
10211
|
+
function assert0(n) {
|
|
10212
|
+
if (n !== _0n3)
|
|
10213
|
+
throw new Error("invalid wNAF");
|
|
10214
|
+
}
|
|
10215
|
+
var wNAF = class {
|
|
10216
|
+
BASE;
|
|
10217
|
+
ZERO;
|
|
10218
|
+
Fn;
|
|
10219
|
+
bits;
|
|
10220
|
+
// Parametrized with a given Point class (not individual point)
|
|
10221
|
+
constructor(Point, bits) {
|
|
10222
|
+
this.BASE = Point.BASE;
|
|
10223
|
+
this.ZERO = Point.ZERO;
|
|
10224
|
+
this.Fn = Point.Fn;
|
|
10225
|
+
this.bits = bits;
|
|
10226
|
+
}
|
|
10227
|
+
// non-const time multiplication ladder
|
|
10228
|
+
_unsafeLadder(elm, n, p = this.ZERO) {
|
|
10229
|
+
let d = elm;
|
|
10230
|
+
while (n > _0n3) {
|
|
10231
|
+
if (n & _1n3)
|
|
10232
|
+
p = p.add(d);
|
|
10233
|
+
d = d.double();
|
|
10234
|
+
n >>= _1n3;
|
|
10235
|
+
}
|
|
10236
|
+
return p;
|
|
10237
|
+
}
|
|
10238
|
+
/**
|
|
10239
|
+
* Creates a wNAF precomputation window. Used for caching.
|
|
10240
|
+
* Default window size is set by `utils.precompute()` and is equal to 8.
|
|
10241
|
+
* Number of precomputed points depends on the curve size:
|
|
10242
|
+
* 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
|
|
10243
|
+
* - 𝑊 is the window size
|
|
10244
|
+
* - 𝑛 is the bitlength of the curve order.
|
|
10245
|
+
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
|
|
10246
|
+
* @param point Point instance
|
|
10247
|
+
* @param W window size
|
|
10248
|
+
* @returns precomputed point tables flattened to a single array
|
|
10249
|
+
*/
|
|
10250
|
+
precomputeWindow(point, W) {
|
|
10251
|
+
const { windows, windowSize } = calcWOpts(W, this.bits);
|
|
10252
|
+
const points = [];
|
|
10253
|
+
let p = point;
|
|
10254
|
+
let base = p;
|
|
10255
|
+
for (let window = 0; window < windows; window++) {
|
|
10256
|
+
base = p;
|
|
10257
|
+
points.push(base);
|
|
10258
|
+
for (let i = 1; i < windowSize; i++) {
|
|
10259
|
+
base = base.add(p);
|
|
10260
|
+
points.push(base);
|
|
10261
|
+
}
|
|
10262
|
+
p = base.double();
|
|
10263
|
+
}
|
|
10264
|
+
return points;
|
|
10265
|
+
}
|
|
10266
|
+
/**
|
|
10267
|
+
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
|
|
10268
|
+
* More compact implementation:
|
|
10269
|
+
* https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
|
|
10270
|
+
* @returns real and fake (for const-time) points
|
|
10271
|
+
*/
|
|
10272
|
+
wNAF(W, precomputes, n) {
|
|
10273
|
+
if (!this.Fn.isValid(n))
|
|
10274
|
+
throw new Error("invalid scalar");
|
|
10275
|
+
let p = this.ZERO;
|
|
10276
|
+
let f = this.BASE;
|
|
10277
|
+
const wo = calcWOpts(W, this.bits);
|
|
10278
|
+
for (let window = 0; window < wo.windows; window++) {
|
|
10279
|
+
const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
|
|
10280
|
+
n = nextN;
|
|
10281
|
+
if (isZero) {
|
|
10282
|
+
f = f.add(negateCt(isNegF, precomputes[offsetF]));
|
|
10283
|
+
} else {
|
|
10284
|
+
p = p.add(negateCt(isNeg, precomputes[offset]));
|
|
10285
|
+
}
|
|
10286
|
+
}
|
|
10287
|
+
assert0(n);
|
|
10288
|
+
return { p, f };
|
|
10289
|
+
}
|
|
10290
|
+
/**
|
|
10291
|
+
* Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
|
|
10292
|
+
* @param acc accumulator point to add result of multiplication
|
|
10293
|
+
* @returns point
|
|
10294
|
+
*/
|
|
10295
|
+
wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
|
|
10296
|
+
const wo = calcWOpts(W, this.bits);
|
|
10297
|
+
for (let window = 0; window < wo.windows; window++) {
|
|
10298
|
+
if (n === _0n3)
|
|
10299
|
+
break;
|
|
10300
|
+
const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
|
|
10301
|
+
n = nextN;
|
|
10302
|
+
if (isZero) {
|
|
10303
|
+
continue;
|
|
10304
|
+
} else {
|
|
10305
|
+
const item = precomputes[offset];
|
|
10306
|
+
acc = acc.add(isNeg ? item.negate() : item);
|
|
10307
|
+
}
|
|
10308
|
+
}
|
|
10309
|
+
assert0(n);
|
|
10310
|
+
return acc;
|
|
10311
|
+
}
|
|
10312
|
+
getPrecomputes(W, point, transform) {
|
|
10313
|
+
let comp = pointPrecomputes.get(point);
|
|
10314
|
+
if (!comp) {
|
|
10315
|
+
comp = this.precomputeWindow(point, W);
|
|
10316
|
+
if (W !== 1) {
|
|
10317
|
+
if (typeof transform === "function")
|
|
10318
|
+
comp = transform(comp);
|
|
10319
|
+
pointPrecomputes.set(point, comp);
|
|
10320
|
+
}
|
|
10321
|
+
}
|
|
10322
|
+
return comp;
|
|
10323
|
+
}
|
|
10324
|
+
cached(point, scalar, transform) {
|
|
10325
|
+
const W = getW(point);
|
|
10326
|
+
return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
|
|
10327
|
+
}
|
|
10328
|
+
unsafe(point, scalar, transform, prev) {
|
|
10329
|
+
const W = getW(point);
|
|
10330
|
+
if (W === 1)
|
|
10331
|
+
return this._unsafeLadder(point, scalar, prev);
|
|
10332
|
+
return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
|
|
10333
|
+
}
|
|
10334
|
+
// We calculate precomputes for elliptic curve point multiplication
|
|
10335
|
+
// using windowed method. This specifies window size and
|
|
10336
|
+
// stores precomputed values. Usually only base point would be precomputed.
|
|
10337
|
+
createCache(P, W) {
|
|
10338
|
+
validateW(W, this.bits);
|
|
10339
|
+
pointWindowSizes.set(P, W);
|
|
10340
|
+
pointPrecomputes.delete(P);
|
|
10341
|
+
}
|
|
10342
|
+
hasCache(elm) {
|
|
10343
|
+
return getW(elm) !== 1;
|
|
10344
|
+
}
|
|
10345
|
+
};
|
|
10346
|
+
function mulEndoUnsafe(Point, point, k1, k2) {
|
|
10347
|
+
let acc = point;
|
|
10348
|
+
let p1 = Point.ZERO;
|
|
10349
|
+
let p2 = Point.ZERO;
|
|
10350
|
+
while (k1 > _0n3 || k2 > _0n3) {
|
|
10351
|
+
if (k1 & _1n3)
|
|
10352
|
+
p1 = p1.add(acc);
|
|
10353
|
+
if (k2 & _1n3)
|
|
10354
|
+
p2 = p2.add(acc);
|
|
10355
|
+
acc = acc.double();
|
|
10356
|
+
k1 >>= _1n3;
|
|
10357
|
+
k2 >>= _1n3;
|
|
10358
|
+
}
|
|
10359
|
+
return { p1, p2 };
|
|
10360
|
+
}
|
|
10361
|
+
function createField(order, field, isLE) {
|
|
10362
|
+
if (field) {
|
|
10363
|
+
if (field.ORDER !== order)
|
|
10364
|
+
throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
|
|
10365
|
+
validateField(field);
|
|
10366
|
+
return field;
|
|
10367
|
+
} else {
|
|
10368
|
+
return Field(order, { isLE });
|
|
10369
|
+
}
|
|
10370
|
+
}
|
|
10371
|
+
function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
|
|
10372
|
+
if (FpFnLE === void 0)
|
|
10373
|
+
FpFnLE = type === "edwards";
|
|
10374
|
+
if (!CURVE || typeof CURVE !== "object")
|
|
10375
|
+
throw new Error(`expected valid ${type} CURVE object`);
|
|
10376
|
+
for (const p of ["p", "n", "h"]) {
|
|
10377
|
+
const val = CURVE[p];
|
|
10378
|
+
if (!(typeof val === "bigint" && val > _0n3))
|
|
10379
|
+
throw new Error(`CURVE.${p} must be positive bigint`);
|
|
10380
|
+
}
|
|
10381
|
+
const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
|
|
10382
|
+
const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
|
|
10383
|
+
const _b = type === "weierstrass" ? "b" : "d";
|
|
10384
|
+
const params = ["Gx", "Gy", "a", _b];
|
|
10385
|
+
for (const p of params) {
|
|
10386
|
+
if (!Fp.isValid(CURVE[p]))
|
|
10387
|
+
throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
|
|
10388
|
+
}
|
|
10389
|
+
CURVE = Object.freeze(Object.assign({}, CURVE));
|
|
10390
|
+
return { CURVE, Fp, Fn };
|
|
10391
|
+
}
|
|
10392
|
+
function createKeygen(randomSecretKey, getPublicKey2) {
|
|
10393
|
+
return function keygen(seed) {
|
|
10394
|
+
const secretKey = randomSecretKey(seed);
|
|
10395
|
+
return { secretKey, publicKey: getPublicKey2(secretKey) };
|
|
10396
|
+
};
|
|
10397
|
+
}
|
|
10398
|
+
|
|
10399
|
+
// node_modules/@noble/hashes/hmac.js
|
|
10400
|
+
var _HMAC = class {
|
|
10401
|
+
oHash;
|
|
10402
|
+
iHash;
|
|
10403
|
+
blockLen;
|
|
10404
|
+
outputLen;
|
|
10405
|
+
finished = false;
|
|
10406
|
+
destroyed = false;
|
|
10407
|
+
constructor(hash, key) {
|
|
10408
|
+
ahash(hash);
|
|
10409
|
+
abytes(key, void 0, "key");
|
|
10410
|
+
this.iHash = hash.create();
|
|
10411
|
+
if (typeof this.iHash.update !== "function")
|
|
10412
|
+
throw new Error("Expected instance of class which extends utils.Hash");
|
|
10413
|
+
this.blockLen = this.iHash.blockLen;
|
|
10414
|
+
this.outputLen = this.iHash.outputLen;
|
|
10415
|
+
const blockLen = this.blockLen;
|
|
10416
|
+
const pad = new Uint8Array(blockLen);
|
|
10417
|
+
pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
|
|
10418
|
+
for (let i = 0; i < pad.length; i++)
|
|
10419
|
+
pad[i] ^= 54;
|
|
10420
|
+
this.iHash.update(pad);
|
|
10421
|
+
this.oHash = hash.create();
|
|
10422
|
+
for (let i = 0; i < pad.length; i++)
|
|
10423
|
+
pad[i] ^= 54 ^ 92;
|
|
10424
|
+
this.oHash.update(pad);
|
|
10425
|
+
clean(pad);
|
|
10426
|
+
}
|
|
10427
|
+
update(buf) {
|
|
10428
|
+
aexists(this);
|
|
10429
|
+
this.iHash.update(buf);
|
|
10430
|
+
return this;
|
|
10431
|
+
}
|
|
10432
|
+
digestInto(out) {
|
|
10433
|
+
aexists(this);
|
|
10434
|
+
abytes(out, this.outputLen, "output");
|
|
10435
|
+
this.finished = true;
|
|
10436
|
+
this.iHash.digestInto(out);
|
|
10437
|
+
this.oHash.update(out);
|
|
10438
|
+
this.oHash.digestInto(out);
|
|
10439
|
+
this.destroy();
|
|
10440
|
+
}
|
|
10441
|
+
digest() {
|
|
10442
|
+
const out = new Uint8Array(this.oHash.outputLen);
|
|
10443
|
+
this.digestInto(out);
|
|
10444
|
+
return out;
|
|
10445
|
+
}
|
|
10446
|
+
_cloneInto(to) {
|
|
10447
|
+
to ||= Object.create(Object.getPrototypeOf(this), {});
|
|
10448
|
+
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
|
|
10449
|
+
to = to;
|
|
10450
|
+
to.finished = finished;
|
|
10451
|
+
to.destroyed = destroyed;
|
|
10452
|
+
to.blockLen = blockLen;
|
|
10453
|
+
to.outputLen = outputLen;
|
|
10454
|
+
to.oHash = oHash._cloneInto(to.oHash);
|
|
10455
|
+
to.iHash = iHash._cloneInto(to.iHash);
|
|
10456
|
+
return to;
|
|
10457
|
+
}
|
|
10458
|
+
clone() {
|
|
10459
|
+
return this._cloneInto();
|
|
10460
|
+
}
|
|
10461
|
+
destroy() {
|
|
10462
|
+
this.destroyed = true;
|
|
10463
|
+
this.oHash.destroy();
|
|
10464
|
+
this.iHash.destroy();
|
|
10465
|
+
}
|
|
10466
|
+
};
|
|
10467
|
+
var hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();
|
|
10468
|
+
hmac.create = (hash, key) => new _HMAC(hash, key);
|
|
10469
|
+
|
|
10470
|
+
// node_modules/@noble/curves/abstract/weierstrass.js
|
|
10471
|
+
var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den;
|
|
10472
|
+
function _splitEndoScalar(k, basis, n) {
|
|
10473
|
+
const [[a1, b1], [a2, b2]] = basis;
|
|
10474
|
+
const c1 = divNearest(b2 * k, n);
|
|
10475
|
+
const c2 = divNearest(-b1 * k, n);
|
|
10476
|
+
let k1 = k - c1 * a1 - c2 * a2;
|
|
10477
|
+
let k2 = -c1 * b1 - c2 * b2;
|
|
10478
|
+
const k1neg = k1 < _0n4;
|
|
10479
|
+
const k2neg = k2 < _0n4;
|
|
10480
|
+
if (k1neg)
|
|
10481
|
+
k1 = -k1;
|
|
10482
|
+
if (k2neg)
|
|
10483
|
+
k2 = -k2;
|
|
10484
|
+
const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4;
|
|
10485
|
+
if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) {
|
|
10486
|
+
throw new Error("splitScalar (endomorphism): failed, k=" + k);
|
|
10487
|
+
}
|
|
10488
|
+
return { k1neg, k1, k2neg, k2 };
|
|
10489
|
+
}
|
|
10490
|
+
function validateSigFormat(format) {
|
|
10491
|
+
if (!["compact", "recovered", "der"].includes(format))
|
|
10492
|
+
throw new Error('Signature format must be "compact", "recovered", or "der"');
|
|
10493
|
+
return format;
|
|
10494
|
+
}
|
|
10495
|
+
function validateSigOpts(opts, def) {
|
|
10496
|
+
const optsn = {};
|
|
10497
|
+
for (let optName of Object.keys(def)) {
|
|
10498
|
+
optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
|
|
10499
|
+
}
|
|
10500
|
+
abool(optsn.lowS, "lowS");
|
|
10501
|
+
abool(optsn.prehash, "prehash");
|
|
10502
|
+
if (optsn.format !== void 0)
|
|
10503
|
+
validateSigFormat(optsn.format);
|
|
10504
|
+
return optsn;
|
|
10505
|
+
}
|
|
10506
|
+
var DERErr = class extends Error {
|
|
10507
|
+
constructor(m = "") {
|
|
10508
|
+
super(m);
|
|
10509
|
+
}
|
|
10510
|
+
};
|
|
10511
|
+
var DER = {
|
|
10512
|
+
// asn.1 DER encoding utils
|
|
10513
|
+
Err: DERErr,
|
|
10514
|
+
// Basic building block is TLV (Tag-Length-Value)
|
|
10515
|
+
_tlv: {
|
|
10516
|
+
encode: (tag, data) => {
|
|
10517
|
+
const { Err: E } = DER;
|
|
10518
|
+
if (tag < 0 || tag > 256)
|
|
10519
|
+
throw new E("tlv.encode: wrong tag");
|
|
10520
|
+
if (data.length & 1)
|
|
10521
|
+
throw new E("tlv.encode: unpadded data");
|
|
10522
|
+
const dataLen = data.length / 2;
|
|
10523
|
+
const len = numberToHexUnpadded(dataLen);
|
|
10524
|
+
if (len.length / 2 & 128)
|
|
10525
|
+
throw new E("tlv.encode: long form length too big");
|
|
10526
|
+
const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
|
|
10527
|
+
const t = numberToHexUnpadded(tag);
|
|
10528
|
+
return t + lenLen + len + data;
|
|
10529
|
+
},
|
|
10530
|
+
// v - value, l - left bytes (unparsed)
|
|
10531
|
+
decode(tag, data) {
|
|
10532
|
+
const { Err: E } = DER;
|
|
10533
|
+
let pos = 0;
|
|
10534
|
+
if (tag < 0 || tag > 256)
|
|
10535
|
+
throw new E("tlv.encode: wrong tag");
|
|
10536
|
+
if (data.length < 2 || data[pos++] !== tag)
|
|
10537
|
+
throw new E("tlv.decode: wrong tlv");
|
|
10538
|
+
const first = data[pos++];
|
|
10539
|
+
const isLong = !!(first & 128);
|
|
10540
|
+
let length = 0;
|
|
10541
|
+
if (!isLong)
|
|
10542
|
+
length = first;
|
|
10543
|
+
else {
|
|
10544
|
+
const lenLen = first & 127;
|
|
10545
|
+
if (!lenLen)
|
|
10546
|
+
throw new E("tlv.decode(long): indefinite length not supported");
|
|
10547
|
+
if (lenLen > 4)
|
|
10548
|
+
throw new E("tlv.decode(long): byte length is too big");
|
|
10549
|
+
const lengthBytes = data.subarray(pos, pos + lenLen);
|
|
10550
|
+
if (lengthBytes.length !== lenLen)
|
|
10551
|
+
throw new E("tlv.decode: length bytes not complete");
|
|
10552
|
+
if (lengthBytes[0] === 0)
|
|
10553
|
+
throw new E("tlv.decode(long): zero leftmost byte");
|
|
10554
|
+
for (const b of lengthBytes)
|
|
10555
|
+
length = length << 8 | b;
|
|
10556
|
+
pos += lenLen;
|
|
10557
|
+
if (length < 128)
|
|
10558
|
+
throw new E("tlv.decode(long): not minimal encoding");
|
|
10559
|
+
}
|
|
10560
|
+
const v = data.subarray(pos, pos + length);
|
|
10561
|
+
if (v.length !== length)
|
|
10562
|
+
throw new E("tlv.decode: wrong value length");
|
|
10563
|
+
return { v, l: data.subarray(pos + length) };
|
|
10564
|
+
}
|
|
10565
|
+
},
|
|
10566
|
+
// https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
|
|
10567
|
+
// since we always use positive integers here. It must always be empty:
|
|
10568
|
+
// - add zero byte if exists
|
|
10569
|
+
// - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
|
|
10570
|
+
_int: {
|
|
10571
|
+
encode(num) {
|
|
10572
|
+
const { Err: E } = DER;
|
|
10573
|
+
if (num < _0n4)
|
|
10574
|
+
throw new E("integer: negative integers are not allowed");
|
|
10575
|
+
let hex = numberToHexUnpadded(num);
|
|
10576
|
+
if (Number.parseInt(hex[0], 16) & 8)
|
|
10577
|
+
hex = "00" + hex;
|
|
10578
|
+
if (hex.length & 1)
|
|
10579
|
+
throw new E("unexpected DER parsing assertion: unpadded hex");
|
|
10580
|
+
return hex;
|
|
10581
|
+
},
|
|
10582
|
+
decode(data) {
|
|
10583
|
+
const { Err: E } = DER;
|
|
10584
|
+
if (data[0] & 128)
|
|
10585
|
+
throw new E("invalid signature integer: negative");
|
|
10586
|
+
if (data[0] === 0 && !(data[1] & 128))
|
|
10587
|
+
throw new E("invalid signature integer: unnecessary leading zero");
|
|
10588
|
+
return bytesToNumberBE(data);
|
|
10589
|
+
}
|
|
10590
|
+
},
|
|
10591
|
+
toSig(bytes) {
|
|
10592
|
+
const { Err: E, _int: int, _tlv: tlv } = DER;
|
|
10593
|
+
const data = abytes(bytes, void 0, "signature");
|
|
10594
|
+
const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
|
|
10595
|
+
if (seqLeftBytes.length)
|
|
10596
|
+
throw new E("invalid signature: left bytes after parsing");
|
|
10597
|
+
const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
|
|
10598
|
+
const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
|
|
10599
|
+
if (sLeftBytes.length)
|
|
10600
|
+
throw new E("invalid signature: left bytes after parsing");
|
|
10601
|
+
return { r: int.decode(rBytes), s: int.decode(sBytes) };
|
|
10602
|
+
},
|
|
10603
|
+
hexFromSig(sig) {
|
|
10604
|
+
const { _tlv: tlv, _int: int } = DER;
|
|
10605
|
+
const rs = tlv.encode(2, int.encode(sig.r));
|
|
10606
|
+
const ss = tlv.encode(2, int.encode(sig.s));
|
|
10607
|
+
const seq = rs + ss;
|
|
10608
|
+
return tlv.encode(48, seq);
|
|
10609
|
+
}
|
|
10610
|
+
};
|
|
10611
|
+
var _0n4 = BigInt(0);
|
|
10612
|
+
var _1n4 = BigInt(1);
|
|
10613
|
+
var _2n2 = BigInt(2);
|
|
10614
|
+
var _3n2 = BigInt(3);
|
|
10615
|
+
var _4n2 = BigInt(4);
|
|
10616
|
+
function weierstrass(params, extraOpts = {}) {
|
|
10617
|
+
const validated = createCurveFields("weierstrass", params, extraOpts);
|
|
10618
|
+
const { Fp, Fn } = validated;
|
|
10619
|
+
let CURVE = validated.CURVE;
|
|
10620
|
+
const { h: cofactor, n: CURVE_ORDER2 } = CURVE;
|
|
10621
|
+
validateObject(extraOpts, {}, {
|
|
10622
|
+
allowInfinityPoint: "boolean",
|
|
10623
|
+
clearCofactor: "function",
|
|
10624
|
+
isTorsionFree: "function",
|
|
10625
|
+
fromBytes: "function",
|
|
10626
|
+
toBytes: "function",
|
|
10627
|
+
endo: "object"
|
|
10628
|
+
});
|
|
10629
|
+
const { endo } = extraOpts;
|
|
10630
|
+
if (endo) {
|
|
10631
|
+
if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
|
|
10632
|
+
throw new Error('invalid endo: expected "beta": bigint and "basises": array');
|
|
10633
|
+
}
|
|
10634
|
+
}
|
|
10635
|
+
const lengths = getWLengths(Fp, Fn);
|
|
10636
|
+
function assertCompressionIsSupported() {
|
|
10637
|
+
if (!Fp.isOdd)
|
|
10638
|
+
throw new Error("compression is not supported: Field does not have .isOdd()");
|
|
10639
|
+
}
|
|
10640
|
+
function pointToBytes(_c, point, isCompressed) {
|
|
10641
|
+
const { x, y } = point.toAffine();
|
|
10642
|
+
const bx = Fp.toBytes(x);
|
|
10643
|
+
abool(isCompressed, "isCompressed");
|
|
10644
|
+
if (isCompressed) {
|
|
10645
|
+
assertCompressionIsSupported();
|
|
10646
|
+
const hasEvenY = !Fp.isOdd(y);
|
|
10647
|
+
return concatBytes(pprefix(hasEvenY), bx);
|
|
10648
|
+
} else {
|
|
10649
|
+
return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
|
|
10650
|
+
}
|
|
10651
|
+
}
|
|
10652
|
+
function pointFromBytes(bytes) {
|
|
10653
|
+
abytes(bytes, void 0, "Point");
|
|
10654
|
+
const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
|
|
10655
|
+
const length = bytes.length;
|
|
10656
|
+
const head = bytes[0];
|
|
10657
|
+
const tail = bytes.subarray(1);
|
|
10658
|
+
if (length === comp && (head === 2 || head === 3)) {
|
|
10659
|
+
const x = Fp.fromBytes(tail);
|
|
10660
|
+
if (!Fp.isValid(x))
|
|
10661
|
+
throw new Error("bad point: is not on curve, wrong x");
|
|
10662
|
+
const y2 = weierstrassEquation(x);
|
|
10663
|
+
let y;
|
|
10664
|
+
try {
|
|
10665
|
+
y = Fp.sqrt(y2);
|
|
10666
|
+
} catch (sqrtError) {
|
|
10667
|
+
const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
|
|
10668
|
+
throw new Error("bad point: is not on curve, sqrt error" + err);
|
|
10669
|
+
}
|
|
10670
|
+
assertCompressionIsSupported();
|
|
10671
|
+
const evenY = Fp.isOdd(y);
|
|
10672
|
+
const evenH = (head & 1) === 1;
|
|
10673
|
+
if (evenH !== evenY)
|
|
10674
|
+
y = Fp.neg(y);
|
|
10675
|
+
return { x, y };
|
|
10676
|
+
} else if (length === uncomp && head === 4) {
|
|
10677
|
+
const L = Fp.BYTES;
|
|
10678
|
+
const x = Fp.fromBytes(tail.subarray(0, L));
|
|
10679
|
+
const y = Fp.fromBytes(tail.subarray(L, L * 2));
|
|
10680
|
+
if (!isValidXY(x, y))
|
|
10681
|
+
throw new Error("bad point: is not on curve");
|
|
10682
|
+
return { x, y };
|
|
10683
|
+
} else {
|
|
10684
|
+
throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
|
|
10685
|
+
}
|
|
10686
|
+
}
|
|
10687
|
+
const encodePoint = extraOpts.toBytes || pointToBytes;
|
|
10688
|
+
const decodePoint = extraOpts.fromBytes || pointFromBytes;
|
|
10689
|
+
function weierstrassEquation(x) {
|
|
10690
|
+
const x2 = Fp.sqr(x);
|
|
10691
|
+
const x3 = Fp.mul(x2, x);
|
|
10692
|
+
return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
|
|
10693
|
+
}
|
|
10694
|
+
function isValidXY(x, y) {
|
|
10695
|
+
const left = Fp.sqr(y);
|
|
10696
|
+
const right = weierstrassEquation(x);
|
|
10697
|
+
return Fp.eql(left, right);
|
|
10698
|
+
}
|
|
10699
|
+
if (!isValidXY(CURVE.Gx, CURVE.Gy))
|
|
10700
|
+
throw new Error("bad curve params: generator point");
|
|
10701
|
+
const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
|
|
10702
|
+
const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
|
|
10703
|
+
if (Fp.is0(Fp.add(_4a3, _27b2)))
|
|
10704
|
+
throw new Error("bad curve params: a or b");
|
|
10705
|
+
function acoord(title, n, banZero = false) {
|
|
10706
|
+
if (!Fp.isValid(n) || banZero && Fp.is0(n))
|
|
10707
|
+
throw new Error(`bad point coordinate ${title}`);
|
|
10708
|
+
return n;
|
|
10709
|
+
}
|
|
10710
|
+
function aprjpoint(other) {
|
|
10711
|
+
if (!(other instanceof Point))
|
|
10712
|
+
throw new Error("Weierstrass Point expected");
|
|
10713
|
+
}
|
|
10714
|
+
function splitEndoScalarN(k) {
|
|
10715
|
+
if (!endo || !endo.basises)
|
|
10716
|
+
throw new Error("no endo");
|
|
10717
|
+
return _splitEndoScalar(k, endo.basises, Fn.ORDER);
|
|
10718
|
+
}
|
|
10719
|
+
const toAffineMemo = memoized((p, iz) => {
|
|
10720
|
+
const { X, Y, Z } = p;
|
|
10721
|
+
if (Fp.eql(Z, Fp.ONE))
|
|
10722
|
+
return { x: X, y: Y };
|
|
10723
|
+
const is0 = p.is0();
|
|
10724
|
+
if (iz == null)
|
|
10725
|
+
iz = is0 ? Fp.ONE : Fp.inv(Z);
|
|
10726
|
+
const x = Fp.mul(X, iz);
|
|
10727
|
+
const y = Fp.mul(Y, iz);
|
|
10728
|
+
const zz = Fp.mul(Z, iz);
|
|
10729
|
+
if (is0)
|
|
10730
|
+
return { x: Fp.ZERO, y: Fp.ZERO };
|
|
10731
|
+
if (!Fp.eql(zz, Fp.ONE))
|
|
10732
|
+
throw new Error("invZ was invalid");
|
|
10733
|
+
return { x, y };
|
|
10734
|
+
});
|
|
10735
|
+
const assertValidMemo = memoized((p) => {
|
|
10736
|
+
if (p.is0()) {
|
|
10737
|
+
if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y))
|
|
10738
|
+
return;
|
|
10739
|
+
throw new Error("bad point: ZERO");
|
|
10740
|
+
}
|
|
10741
|
+
const { x, y } = p.toAffine();
|
|
10742
|
+
if (!Fp.isValid(x) || !Fp.isValid(y))
|
|
10743
|
+
throw new Error("bad point: x or y not field elements");
|
|
10744
|
+
if (!isValidXY(x, y))
|
|
10745
|
+
throw new Error("bad point: equation left != right");
|
|
10746
|
+
if (!p.isTorsionFree())
|
|
10747
|
+
throw new Error("bad point: not in prime-order subgroup");
|
|
10748
|
+
return true;
|
|
10749
|
+
});
|
|
10750
|
+
function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
|
|
10751
|
+
k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
|
|
10752
|
+
k1p = negateCt(k1neg, k1p);
|
|
10753
|
+
k2p = negateCt(k2neg, k2p);
|
|
10754
|
+
return k1p.add(k2p);
|
|
10755
|
+
}
|
|
10756
|
+
class Point {
|
|
10757
|
+
// base / generator point
|
|
10758
|
+
static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
|
|
10759
|
+
// zero / infinity / identity point
|
|
10760
|
+
static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
|
|
10761
|
+
// 0, 1, 0
|
|
10762
|
+
// math field
|
|
10763
|
+
static Fp = Fp;
|
|
10764
|
+
// scalar field
|
|
10765
|
+
static Fn = Fn;
|
|
10766
|
+
X;
|
|
10767
|
+
Y;
|
|
10768
|
+
Z;
|
|
10769
|
+
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
10770
|
+
constructor(X, Y, Z) {
|
|
10771
|
+
this.X = acoord("x", X);
|
|
10772
|
+
this.Y = acoord("y", Y, true);
|
|
10773
|
+
this.Z = acoord("z", Z);
|
|
10774
|
+
Object.freeze(this);
|
|
10775
|
+
}
|
|
10776
|
+
static CURVE() {
|
|
10777
|
+
return CURVE;
|
|
10778
|
+
}
|
|
10779
|
+
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
|
|
10780
|
+
static fromAffine(p) {
|
|
10781
|
+
const { x, y } = p || {};
|
|
10782
|
+
if (!p || !Fp.isValid(x) || !Fp.isValid(y))
|
|
10783
|
+
throw new Error("invalid affine point");
|
|
10784
|
+
if (p instanceof Point)
|
|
10785
|
+
throw new Error("projective point not allowed");
|
|
10786
|
+
if (Fp.is0(x) && Fp.is0(y))
|
|
10787
|
+
return Point.ZERO;
|
|
10788
|
+
return new Point(x, y, Fp.ONE);
|
|
10789
|
+
}
|
|
10790
|
+
static fromBytes(bytes) {
|
|
10791
|
+
const P = Point.fromAffine(decodePoint(abytes(bytes, void 0, "point")));
|
|
10792
|
+
P.assertValidity();
|
|
10793
|
+
return P;
|
|
10794
|
+
}
|
|
10795
|
+
static fromHex(hex) {
|
|
10796
|
+
return Point.fromBytes(hexToBytes2(hex));
|
|
10797
|
+
}
|
|
10798
|
+
get x() {
|
|
10799
|
+
return this.toAffine().x;
|
|
10800
|
+
}
|
|
10801
|
+
get y() {
|
|
10802
|
+
return this.toAffine().y;
|
|
10803
|
+
}
|
|
10804
|
+
/**
|
|
10805
|
+
*
|
|
10806
|
+
* @param windowSize
|
|
10807
|
+
* @param isLazy true will defer table computation until the first multiplication
|
|
10808
|
+
* @returns
|
|
10809
|
+
*/
|
|
10810
|
+
precompute(windowSize = 8, isLazy = true) {
|
|
10811
|
+
wnaf.createCache(this, windowSize);
|
|
10812
|
+
if (!isLazy)
|
|
10813
|
+
this.multiply(_3n2);
|
|
10814
|
+
return this;
|
|
10815
|
+
}
|
|
10816
|
+
// TODO: return `this`
|
|
10817
|
+
/** A point on curve is valid if it conforms to equation. */
|
|
10818
|
+
assertValidity() {
|
|
10819
|
+
assertValidMemo(this);
|
|
10820
|
+
}
|
|
10821
|
+
hasEvenY() {
|
|
10822
|
+
const { y } = this.toAffine();
|
|
10823
|
+
if (!Fp.isOdd)
|
|
10824
|
+
throw new Error("Field doesn't support isOdd");
|
|
10825
|
+
return !Fp.isOdd(y);
|
|
10826
|
+
}
|
|
10827
|
+
/** Compare one point to another. */
|
|
10828
|
+
equals(other) {
|
|
10829
|
+
aprjpoint(other);
|
|
10830
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
10831
|
+
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
10832
|
+
const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
|
|
10833
|
+
const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
|
|
10834
|
+
return U1 && U2;
|
|
10835
|
+
}
|
|
10836
|
+
/** Flips point to one corresponding to (x, -y) in Affine coordinates. */
|
|
10837
|
+
negate() {
|
|
10838
|
+
return new Point(this.X, Fp.neg(this.Y), this.Z);
|
|
10839
|
+
}
|
|
10840
|
+
// Renes-Costello-Batina exception-free doubling formula.
|
|
10841
|
+
// There is 30% faster Jacobian formula, but it is not complete.
|
|
10842
|
+
// https://eprint.iacr.org/2015/1060, algorithm 3
|
|
10843
|
+
// Cost: 8M + 3S + 3*a + 2*b3 + 15add.
|
|
10844
|
+
double() {
|
|
10845
|
+
const { a, b } = CURVE;
|
|
10846
|
+
const b3 = Fp.mul(b, _3n2);
|
|
10847
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
10848
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
|
|
10849
|
+
let t0 = Fp.mul(X1, X1);
|
|
10850
|
+
let t1 = Fp.mul(Y1, Y1);
|
|
10851
|
+
let t2 = Fp.mul(Z1, Z1);
|
|
10852
|
+
let t3 = Fp.mul(X1, Y1);
|
|
10853
|
+
t3 = Fp.add(t3, t3);
|
|
10854
|
+
Z3 = Fp.mul(X1, Z1);
|
|
10855
|
+
Z3 = Fp.add(Z3, Z3);
|
|
10856
|
+
X3 = Fp.mul(a, Z3);
|
|
10857
|
+
Y3 = Fp.mul(b3, t2);
|
|
10858
|
+
Y3 = Fp.add(X3, Y3);
|
|
10859
|
+
X3 = Fp.sub(t1, Y3);
|
|
10860
|
+
Y3 = Fp.add(t1, Y3);
|
|
10861
|
+
Y3 = Fp.mul(X3, Y3);
|
|
10862
|
+
X3 = Fp.mul(t3, X3);
|
|
10863
|
+
Z3 = Fp.mul(b3, Z3);
|
|
10864
|
+
t2 = Fp.mul(a, t2);
|
|
10865
|
+
t3 = Fp.sub(t0, t2);
|
|
10866
|
+
t3 = Fp.mul(a, t3);
|
|
10867
|
+
t3 = Fp.add(t3, Z3);
|
|
10868
|
+
Z3 = Fp.add(t0, t0);
|
|
10869
|
+
t0 = Fp.add(Z3, t0);
|
|
10870
|
+
t0 = Fp.add(t0, t2);
|
|
10871
|
+
t0 = Fp.mul(t0, t3);
|
|
10872
|
+
Y3 = Fp.add(Y3, t0);
|
|
10873
|
+
t2 = Fp.mul(Y1, Z1);
|
|
10874
|
+
t2 = Fp.add(t2, t2);
|
|
10875
|
+
t0 = Fp.mul(t2, t3);
|
|
10876
|
+
X3 = Fp.sub(X3, t0);
|
|
10877
|
+
Z3 = Fp.mul(t2, t1);
|
|
10878
|
+
Z3 = Fp.add(Z3, Z3);
|
|
10879
|
+
Z3 = Fp.add(Z3, Z3);
|
|
10880
|
+
return new Point(X3, Y3, Z3);
|
|
10881
|
+
}
|
|
10882
|
+
// Renes-Costello-Batina exception-free addition formula.
|
|
10883
|
+
// There is 30% faster Jacobian formula, but it is not complete.
|
|
10884
|
+
// https://eprint.iacr.org/2015/1060, algorithm 1
|
|
10885
|
+
// Cost: 12M + 0S + 3*a + 3*b3 + 23add.
|
|
10886
|
+
add(other) {
|
|
10887
|
+
aprjpoint(other);
|
|
10888
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
10889
|
+
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
10890
|
+
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
|
|
10891
|
+
const a = CURVE.a;
|
|
10892
|
+
const b3 = Fp.mul(CURVE.b, _3n2);
|
|
10893
|
+
let t0 = Fp.mul(X1, X2);
|
|
10894
|
+
let t1 = Fp.mul(Y1, Y2);
|
|
10895
|
+
let t2 = Fp.mul(Z1, Z2);
|
|
10896
|
+
let t3 = Fp.add(X1, Y1);
|
|
10897
|
+
let t4 = Fp.add(X2, Y2);
|
|
10898
|
+
t3 = Fp.mul(t3, t4);
|
|
10899
|
+
t4 = Fp.add(t0, t1);
|
|
10900
|
+
t3 = Fp.sub(t3, t4);
|
|
10901
|
+
t4 = Fp.add(X1, Z1);
|
|
10902
|
+
let t5 = Fp.add(X2, Z2);
|
|
10903
|
+
t4 = Fp.mul(t4, t5);
|
|
10904
|
+
t5 = Fp.add(t0, t2);
|
|
10905
|
+
t4 = Fp.sub(t4, t5);
|
|
10906
|
+
t5 = Fp.add(Y1, Z1);
|
|
10907
|
+
X3 = Fp.add(Y2, Z2);
|
|
10908
|
+
t5 = Fp.mul(t5, X3);
|
|
10909
|
+
X3 = Fp.add(t1, t2);
|
|
10910
|
+
t5 = Fp.sub(t5, X3);
|
|
10911
|
+
Z3 = Fp.mul(a, t4);
|
|
10912
|
+
X3 = Fp.mul(b3, t2);
|
|
10913
|
+
Z3 = Fp.add(X3, Z3);
|
|
10914
|
+
X3 = Fp.sub(t1, Z3);
|
|
10915
|
+
Z3 = Fp.add(t1, Z3);
|
|
10916
|
+
Y3 = Fp.mul(X3, Z3);
|
|
10917
|
+
t1 = Fp.add(t0, t0);
|
|
10918
|
+
t1 = Fp.add(t1, t0);
|
|
10919
|
+
t2 = Fp.mul(a, t2);
|
|
10920
|
+
t4 = Fp.mul(b3, t4);
|
|
10921
|
+
t1 = Fp.add(t1, t2);
|
|
10922
|
+
t2 = Fp.sub(t0, t2);
|
|
10923
|
+
t2 = Fp.mul(a, t2);
|
|
10924
|
+
t4 = Fp.add(t4, t2);
|
|
10925
|
+
t0 = Fp.mul(t1, t4);
|
|
10926
|
+
Y3 = Fp.add(Y3, t0);
|
|
10927
|
+
t0 = Fp.mul(t5, t4);
|
|
10928
|
+
X3 = Fp.mul(t3, X3);
|
|
10929
|
+
X3 = Fp.sub(X3, t0);
|
|
10930
|
+
t0 = Fp.mul(t3, t1);
|
|
10931
|
+
Z3 = Fp.mul(t5, Z3);
|
|
10932
|
+
Z3 = Fp.add(Z3, t0);
|
|
10933
|
+
return new Point(X3, Y3, Z3);
|
|
10934
|
+
}
|
|
10935
|
+
subtract(other) {
|
|
10936
|
+
return this.add(other.negate());
|
|
10937
|
+
}
|
|
10938
|
+
is0() {
|
|
10939
|
+
return this.equals(Point.ZERO);
|
|
10940
|
+
}
|
|
10941
|
+
/**
|
|
10942
|
+
* Constant time multiplication.
|
|
10943
|
+
* Uses wNAF method. Windowed method may be 10% faster,
|
|
10944
|
+
* but takes 2x longer to generate and consumes 2x memory.
|
|
10945
|
+
* Uses precomputes when available.
|
|
10946
|
+
* Uses endomorphism for Koblitz curves.
|
|
10947
|
+
* @param scalar by which the point would be multiplied
|
|
10948
|
+
* @returns New point
|
|
10949
|
+
*/
|
|
10950
|
+
multiply(scalar) {
|
|
10951
|
+
const { endo: endo2 } = extraOpts;
|
|
10952
|
+
if (!Fn.isValidNot0(scalar))
|
|
10953
|
+
throw new Error("invalid scalar: out of range");
|
|
10954
|
+
let point, fake;
|
|
10955
|
+
const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
|
|
10956
|
+
if (endo2) {
|
|
10957
|
+
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
|
|
10958
|
+
const { p: k1p, f: k1f } = mul(k1);
|
|
10959
|
+
const { p: k2p, f: k2f } = mul(k2);
|
|
10960
|
+
fake = k1f.add(k2f);
|
|
10961
|
+
point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
|
|
10962
|
+
} else {
|
|
10963
|
+
const { p, f } = mul(scalar);
|
|
10964
|
+
point = p;
|
|
10965
|
+
fake = f;
|
|
10966
|
+
}
|
|
10967
|
+
return normalizeZ(Point, [point, fake])[0];
|
|
10968
|
+
}
|
|
10969
|
+
/**
|
|
10970
|
+
* Non-constant-time multiplication. Uses double-and-add algorithm.
|
|
10971
|
+
* It's faster, but should only be used when you don't care about
|
|
10972
|
+
* an exposed secret key e.g. sig verification, which works over *public* keys.
|
|
10973
|
+
*/
|
|
10974
|
+
multiplyUnsafe(sc) {
|
|
10975
|
+
const { endo: endo2 } = extraOpts;
|
|
10976
|
+
const p = this;
|
|
10977
|
+
if (!Fn.isValid(sc))
|
|
10978
|
+
throw new Error("invalid scalar: out of range");
|
|
10979
|
+
if (sc === _0n4 || p.is0())
|
|
10980
|
+
return Point.ZERO;
|
|
10981
|
+
if (sc === _1n4)
|
|
10982
|
+
return p;
|
|
10983
|
+
if (wnaf.hasCache(this))
|
|
10984
|
+
return this.multiply(sc);
|
|
10985
|
+
if (endo2) {
|
|
10986
|
+
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
|
|
10987
|
+
const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
|
|
10988
|
+
return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
|
|
10989
|
+
} else {
|
|
10990
|
+
return wnaf.unsafe(p, sc);
|
|
10991
|
+
}
|
|
10992
|
+
}
|
|
10993
|
+
/**
|
|
10994
|
+
* Converts Projective point to affine (x, y) coordinates.
|
|
10995
|
+
* @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
|
|
10996
|
+
*/
|
|
10997
|
+
toAffine(invertedZ) {
|
|
10998
|
+
return toAffineMemo(this, invertedZ);
|
|
10999
|
+
}
|
|
11000
|
+
/**
|
|
11001
|
+
* Checks whether Point is free of torsion elements (is in prime subgroup).
|
|
11002
|
+
* Always torsion-free for cofactor=1 curves.
|
|
11003
|
+
*/
|
|
11004
|
+
isTorsionFree() {
|
|
11005
|
+
const { isTorsionFree } = extraOpts;
|
|
11006
|
+
if (cofactor === _1n4)
|
|
11007
|
+
return true;
|
|
11008
|
+
if (isTorsionFree)
|
|
11009
|
+
return isTorsionFree(Point, this);
|
|
11010
|
+
return wnaf.unsafe(this, CURVE_ORDER2).is0();
|
|
11011
|
+
}
|
|
11012
|
+
clearCofactor() {
|
|
11013
|
+
const { clearCofactor } = extraOpts;
|
|
11014
|
+
if (cofactor === _1n4)
|
|
11015
|
+
return this;
|
|
11016
|
+
if (clearCofactor)
|
|
11017
|
+
return clearCofactor(Point, this);
|
|
11018
|
+
return this.multiplyUnsafe(cofactor);
|
|
11019
|
+
}
|
|
11020
|
+
isSmallOrder() {
|
|
11021
|
+
return this.multiplyUnsafe(cofactor).is0();
|
|
11022
|
+
}
|
|
11023
|
+
toBytes(isCompressed = true) {
|
|
11024
|
+
abool(isCompressed, "isCompressed");
|
|
11025
|
+
this.assertValidity();
|
|
11026
|
+
return encodePoint(Point, this, isCompressed);
|
|
11027
|
+
}
|
|
11028
|
+
toHex(isCompressed = true) {
|
|
11029
|
+
return bytesToHex4(this.toBytes(isCompressed));
|
|
11030
|
+
}
|
|
11031
|
+
toString() {
|
|
11032
|
+
return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
|
|
11033
|
+
}
|
|
11034
|
+
}
|
|
11035
|
+
const bits = Fn.BITS;
|
|
11036
|
+
const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
|
|
11037
|
+
Point.BASE.precompute(8);
|
|
11038
|
+
return Point;
|
|
11039
|
+
}
|
|
11040
|
+
function pprefix(hasEvenY) {
|
|
11041
|
+
return Uint8Array.of(hasEvenY ? 2 : 3);
|
|
11042
|
+
}
|
|
11043
|
+
function getWLengths(Fp, Fn) {
|
|
11044
|
+
return {
|
|
11045
|
+
secretKey: Fn.BYTES,
|
|
11046
|
+
publicKey: 1 + Fp.BYTES,
|
|
11047
|
+
publicKeyUncompressed: 1 + 2 * Fp.BYTES,
|
|
11048
|
+
publicKeyHasPrefix: true,
|
|
11049
|
+
signature: 2 * Fn.BYTES
|
|
11050
|
+
};
|
|
11051
|
+
}
|
|
11052
|
+
function ecdh(Point, ecdhOpts = {}) {
|
|
11053
|
+
const { Fn } = Point;
|
|
11054
|
+
const randomBytes_ = ecdhOpts.randomBytes || randomBytes2;
|
|
11055
|
+
const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
|
|
11056
|
+
function isValidSecretKey(secretKey) {
|
|
11057
|
+
try {
|
|
11058
|
+
const num = Fn.fromBytes(secretKey);
|
|
11059
|
+
return Fn.isValidNot0(num);
|
|
11060
|
+
} catch (error) {
|
|
11061
|
+
return false;
|
|
11062
|
+
}
|
|
11063
|
+
}
|
|
11064
|
+
function isValidPublicKey(publicKey, isCompressed) {
|
|
11065
|
+
const { publicKey: comp, publicKeyUncompressed } = lengths;
|
|
11066
|
+
try {
|
|
11067
|
+
const l = publicKey.length;
|
|
11068
|
+
if (isCompressed === true && l !== comp)
|
|
11069
|
+
return false;
|
|
11070
|
+
if (isCompressed === false && l !== publicKeyUncompressed)
|
|
11071
|
+
return false;
|
|
11072
|
+
return !!Point.fromBytes(publicKey);
|
|
11073
|
+
} catch (error) {
|
|
11074
|
+
return false;
|
|
11075
|
+
}
|
|
11076
|
+
}
|
|
11077
|
+
function randomSecretKey(seed = randomBytes_(lengths.seed)) {
|
|
11078
|
+
return mapHashToField(abytes(seed, lengths.seed, "seed"), Fn.ORDER);
|
|
11079
|
+
}
|
|
11080
|
+
function getPublicKey2(secretKey, isCompressed = true) {
|
|
11081
|
+
return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
|
|
11082
|
+
}
|
|
11083
|
+
function isProbPub(item) {
|
|
11084
|
+
const { secretKey, publicKey, publicKeyUncompressed } = lengths;
|
|
11085
|
+
if (!isBytes(item))
|
|
11086
|
+
return void 0;
|
|
11087
|
+
if ("_lengths" in Fn && Fn._lengths || secretKey === publicKey)
|
|
11088
|
+
return void 0;
|
|
11089
|
+
const l = abytes(item, void 0, "key").length;
|
|
11090
|
+
return l === publicKey || l === publicKeyUncompressed;
|
|
11091
|
+
}
|
|
11092
|
+
function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
|
|
11093
|
+
if (isProbPub(secretKeyA) === true)
|
|
11094
|
+
throw new Error("first arg must be private key");
|
|
11095
|
+
if (isProbPub(publicKeyB) === false)
|
|
11096
|
+
throw new Error("second arg must be public key");
|
|
11097
|
+
const s = Fn.fromBytes(secretKeyA);
|
|
11098
|
+
const b = Point.fromBytes(publicKeyB);
|
|
11099
|
+
return b.multiply(s).toBytes(isCompressed);
|
|
11100
|
+
}
|
|
11101
|
+
const utils = {
|
|
11102
|
+
isValidSecretKey,
|
|
11103
|
+
isValidPublicKey,
|
|
11104
|
+
randomSecretKey
|
|
11105
|
+
};
|
|
11106
|
+
const keygen = createKeygen(randomSecretKey, getPublicKey2);
|
|
11107
|
+
return Object.freeze({ getPublicKey: getPublicKey2, getSharedSecret, keygen, Point, utils, lengths });
|
|
11108
|
+
}
|
|
11109
|
+
function ecdsa(Point, hash, ecdsaOpts = {}) {
|
|
11110
|
+
ahash(hash);
|
|
11111
|
+
validateObject(ecdsaOpts, {}, {
|
|
11112
|
+
hmac: "function",
|
|
11113
|
+
lowS: "boolean",
|
|
11114
|
+
randomBytes: "function",
|
|
11115
|
+
bits2int: "function",
|
|
11116
|
+
bits2int_modN: "function"
|
|
11117
|
+
});
|
|
11118
|
+
ecdsaOpts = Object.assign({}, ecdsaOpts);
|
|
11119
|
+
const randomBytes3 = ecdsaOpts.randomBytes || randomBytes2;
|
|
11120
|
+
const hmac2 = ecdsaOpts.hmac || ((key, msg) => hmac(hash, key, msg));
|
|
11121
|
+
const { Fp, Fn } = Point;
|
|
11122
|
+
const { ORDER: CURVE_ORDER2, BITS: fnBits } = Fn;
|
|
11123
|
+
const { keygen, getPublicKey: getPublicKey2, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
|
|
11124
|
+
const defaultSigOpts = {
|
|
11125
|
+
prehash: true,
|
|
11126
|
+
lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
|
|
11127
|
+
format: "compact",
|
|
11128
|
+
extraEntropy: false
|
|
11129
|
+
};
|
|
11130
|
+
const hasLargeCofactor = CURVE_ORDER2 * _2n2 < Fp.ORDER;
|
|
11131
|
+
function isBiggerThanHalfOrder(number) {
|
|
11132
|
+
const HALF = CURVE_ORDER2 >> _1n4;
|
|
11133
|
+
return number > HALF;
|
|
11134
|
+
}
|
|
11135
|
+
function validateRS(title, num) {
|
|
11136
|
+
if (!Fn.isValidNot0(num))
|
|
11137
|
+
throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
|
|
11138
|
+
return num;
|
|
11139
|
+
}
|
|
11140
|
+
function assertSmallCofactor() {
|
|
11141
|
+
if (hasLargeCofactor)
|
|
11142
|
+
throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
|
|
11143
|
+
}
|
|
11144
|
+
function validateSigLength(bytes, format) {
|
|
11145
|
+
validateSigFormat(format);
|
|
11146
|
+
const size = lengths.signature;
|
|
11147
|
+
const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0;
|
|
11148
|
+
return abytes(bytes, sizer);
|
|
11149
|
+
}
|
|
11150
|
+
class Signature {
|
|
11151
|
+
r;
|
|
11152
|
+
s;
|
|
11153
|
+
recovery;
|
|
11154
|
+
constructor(r, s, recovery) {
|
|
11155
|
+
this.r = validateRS("r", r);
|
|
11156
|
+
this.s = validateRS("s", s);
|
|
11157
|
+
if (recovery != null) {
|
|
11158
|
+
assertSmallCofactor();
|
|
11159
|
+
if (![0, 1, 2, 3].includes(recovery))
|
|
11160
|
+
throw new Error("invalid recovery id");
|
|
11161
|
+
this.recovery = recovery;
|
|
11162
|
+
}
|
|
11163
|
+
Object.freeze(this);
|
|
11164
|
+
}
|
|
11165
|
+
static fromBytes(bytes, format = defaultSigOpts.format) {
|
|
11166
|
+
validateSigLength(bytes, format);
|
|
11167
|
+
let recid;
|
|
11168
|
+
if (format === "der") {
|
|
11169
|
+
const { r: r2, s: s2 } = DER.toSig(abytes(bytes));
|
|
11170
|
+
return new Signature(r2, s2);
|
|
11171
|
+
}
|
|
11172
|
+
if (format === "recovered") {
|
|
11173
|
+
recid = bytes[0];
|
|
11174
|
+
format = "compact";
|
|
11175
|
+
bytes = bytes.subarray(1);
|
|
11176
|
+
}
|
|
11177
|
+
const L = lengths.signature / 2;
|
|
11178
|
+
const r = bytes.subarray(0, L);
|
|
11179
|
+
const s = bytes.subarray(L, L * 2);
|
|
11180
|
+
return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
|
|
11181
|
+
}
|
|
11182
|
+
static fromHex(hex, format) {
|
|
11183
|
+
return this.fromBytes(hexToBytes2(hex), format);
|
|
11184
|
+
}
|
|
11185
|
+
assertRecovery() {
|
|
11186
|
+
const { recovery } = this;
|
|
11187
|
+
if (recovery == null)
|
|
11188
|
+
throw new Error("invalid recovery id: must be present");
|
|
11189
|
+
return recovery;
|
|
11190
|
+
}
|
|
11191
|
+
addRecoveryBit(recovery) {
|
|
11192
|
+
return new Signature(this.r, this.s, recovery);
|
|
11193
|
+
}
|
|
11194
|
+
recoverPublicKey(messageHash) {
|
|
11195
|
+
const { r, s } = this;
|
|
11196
|
+
const recovery = this.assertRecovery();
|
|
11197
|
+
const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER2 : r;
|
|
11198
|
+
if (!Fp.isValid(radj))
|
|
11199
|
+
throw new Error("invalid recovery id: sig.r+curve.n != R.x");
|
|
11200
|
+
const x = Fp.toBytes(radj);
|
|
11201
|
+
const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));
|
|
11202
|
+
const ir = Fn.inv(radj);
|
|
11203
|
+
const h = bits2int_modN(abytes(messageHash, void 0, "msgHash"));
|
|
11204
|
+
const u1 = Fn.create(-h * ir);
|
|
11205
|
+
const u2 = Fn.create(s * ir);
|
|
11206
|
+
const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
|
|
11207
|
+
if (Q.is0())
|
|
11208
|
+
throw new Error("invalid recovery: point at infinify");
|
|
11209
|
+
Q.assertValidity();
|
|
11210
|
+
return Q;
|
|
11211
|
+
}
|
|
11212
|
+
// Signatures should be low-s, to prevent malleability.
|
|
11213
|
+
hasHighS() {
|
|
11214
|
+
return isBiggerThanHalfOrder(this.s);
|
|
11215
|
+
}
|
|
11216
|
+
toBytes(format = defaultSigOpts.format) {
|
|
11217
|
+
validateSigFormat(format);
|
|
11218
|
+
if (format === "der")
|
|
11219
|
+
return hexToBytes2(DER.hexFromSig(this));
|
|
11220
|
+
const { r, s } = this;
|
|
11221
|
+
const rb = Fn.toBytes(r);
|
|
11222
|
+
const sb = Fn.toBytes(s);
|
|
11223
|
+
if (format === "recovered") {
|
|
11224
|
+
assertSmallCofactor();
|
|
11225
|
+
return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);
|
|
11226
|
+
}
|
|
11227
|
+
return concatBytes(rb, sb);
|
|
11228
|
+
}
|
|
11229
|
+
toHex(format) {
|
|
11230
|
+
return bytesToHex4(this.toBytes(format));
|
|
11231
|
+
}
|
|
11232
|
+
}
|
|
11233
|
+
const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
|
|
11234
|
+
if (bytes.length > 8192)
|
|
11235
|
+
throw new Error("input is too large");
|
|
11236
|
+
const num = bytesToNumberBE(bytes);
|
|
11237
|
+
const delta = bytes.length * 8 - fnBits;
|
|
11238
|
+
return delta > 0 ? num >> BigInt(delta) : num;
|
|
11239
|
+
};
|
|
11240
|
+
const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
|
|
11241
|
+
return Fn.create(bits2int(bytes));
|
|
11242
|
+
};
|
|
11243
|
+
const ORDER_MASK = bitMask(fnBits);
|
|
11244
|
+
function int2octets(num) {
|
|
11245
|
+
aInRange("num < 2^" + fnBits, num, _0n4, ORDER_MASK);
|
|
11246
|
+
return Fn.toBytes(num);
|
|
11247
|
+
}
|
|
11248
|
+
function validateMsgAndHash(message, prehash) {
|
|
11249
|
+
abytes(message, void 0, "message");
|
|
11250
|
+
return prehash ? abytes(hash(message), void 0, "prehashed message") : message;
|
|
11251
|
+
}
|
|
11252
|
+
function prepSig(message, secretKey, opts) {
|
|
11253
|
+
const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
|
|
11254
|
+
message = validateMsgAndHash(message, prehash);
|
|
11255
|
+
const h1int = bits2int_modN(message);
|
|
11256
|
+
const d = Fn.fromBytes(secretKey);
|
|
11257
|
+
if (!Fn.isValidNot0(d))
|
|
11258
|
+
throw new Error("invalid private key");
|
|
11259
|
+
const seedArgs = [int2octets(d), int2octets(h1int)];
|
|
11260
|
+
if (extraEntropy != null && extraEntropy !== false) {
|
|
11261
|
+
const e = extraEntropy === true ? randomBytes3(lengths.secretKey) : extraEntropy;
|
|
11262
|
+
seedArgs.push(abytes(e, void 0, "extraEntropy"));
|
|
11263
|
+
}
|
|
11264
|
+
const seed = concatBytes(...seedArgs);
|
|
11265
|
+
const m = h1int;
|
|
11266
|
+
function k2sig(kBytes) {
|
|
11267
|
+
const k = bits2int(kBytes);
|
|
11268
|
+
if (!Fn.isValidNot0(k))
|
|
11269
|
+
return;
|
|
11270
|
+
const ik = Fn.inv(k);
|
|
11271
|
+
const q = Point.BASE.multiply(k).toAffine();
|
|
11272
|
+
const r = Fn.create(q.x);
|
|
11273
|
+
if (r === _0n4)
|
|
11274
|
+
return;
|
|
11275
|
+
const s = Fn.create(ik * Fn.create(m + r * d));
|
|
11276
|
+
if (s === _0n4)
|
|
11277
|
+
return;
|
|
11278
|
+
let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
|
|
11279
|
+
let normS = s;
|
|
11280
|
+
if (lowS && isBiggerThanHalfOrder(s)) {
|
|
11281
|
+
normS = Fn.neg(s);
|
|
11282
|
+
recovery ^= 1;
|
|
11283
|
+
}
|
|
11284
|
+
return new Signature(r, normS, hasLargeCofactor ? void 0 : recovery);
|
|
11285
|
+
}
|
|
11286
|
+
return { seed, k2sig };
|
|
11287
|
+
}
|
|
11288
|
+
function sign(message, secretKey, opts = {}) {
|
|
11289
|
+
const { seed, k2sig } = prepSig(message, secretKey, opts);
|
|
11290
|
+
const drbg = createHmacDrbg(hash.outputLen, Fn.BYTES, hmac2);
|
|
11291
|
+
const sig = drbg(seed, k2sig);
|
|
11292
|
+
return sig.toBytes(opts.format);
|
|
11293
|
+
}
|
|
11294
|
+
function verify(signature, message, publicKey, opts = {}) {
|
|
11295
|
+
const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
|
|
11296
|
+
publicKey = abytes(publicKey, void 0, "publicKey");
|
|
11297
|
+
message = validateMsgAndHash(message, prehash);
|
|
11298
|
+
if (!isBytes(signature)) {
|
|
11299
|
+
const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
|
|
11300
|
+
throw new Error("verify expects Uint8Array signature" + end);
|
|
11301
|
+
}
|
|
11302
|
+
validateSigLength(signature, format);
|
|
11303
|
+
try {
|
|
11304
|
+
const sig = Signature.fromBytes(signature, format);
|
|
11305
|
+
const P = Point.fromBytes(publicKey);
|
|
11306
|
+
if (lowS && sig.hasHighS())
|
|
11307
|
+
return false;
|
|
11308
|
+
const { r, s } = sig;
|
|
11309
|
+
const h = bits2int_modN(message);
|
|
11310
|
+
const is = Fn.inv(s);
|
|
11311
|
+
const u1 = Fn.create(h * is);
|
|
11312
|
+
const u2 = Fn.create(r * is);
|
|
11313
|
+
const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
|
|
11314
|
+
if (R.is0())
|
|
11315
|
+
return false;
|
|
11316
|
+
const v = Fn.create(R.x);
|
|
11317
|
+
return v === r;
|
|
11318
|
+
} catch (e) {
|
|
11319
|
+
return false;
|
|
11320
|
+
}
|
|
11321
|
+
}
|
|
11322
|
+
function recoverPublicKey(signature, message, opts = {}) {
|
|
11323
|
+
const { prehash } = validateSigOpts(opts, defaultSigOpts);
|
|
11324
|
+
message = validateMsgAndHash(message, prehash);
|
|
11325
|
+
return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
|
|
11326
|
+
}
|
|
11327
|
+
return Object.freeze({
|
|
11328
|
+
keygen,
|
|
11329
|
+
getPublicKey: getPublicKey2,
|
|
11330
|
+
getSharedSecret,
|
|
11331
|
+
utils,
|
|
11332
|
+
lengths,
|
|
11333
|
+
Point,
|
|
11334
|
+
sign,
|
|
11335
|
+
verify,
|
|
11336
|
+
recoverPublicKey,
|
|
11337
|
+
Signature,
|
|
11338
|
+
hash
|
|
11339
|
+
});
|
|
11340
|
+
}
|
|
11341
|
+
|
|
11342
|
+
// node_modules/@noble/curves/secp256k1.js
|
|
11343
|
+
var secp256k1_CURVE = {
|
|
11344
|
+
p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
|
|
11345
|
+
n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
|
|
11346
|
+
h: BigInt(1),
|
|
11347
|
+
a: BigInt(0),
|
|
11348
|
+
b: BigInt(7),
|
|
11349
|
+
Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
|
|
11350
|
+
Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
|
|
11351
|
+
};
|
|
11352
|
+
var secp256k1_ENDO = {
|
|
11353
|
+
beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
|
|
11354
|
+
basises: [
|
|
11355
|
+
[BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
|
|
11356
|
+
[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
|
|
11357
|
+
]
|
|
11358
|
+
};
|
|
11359
|
+
var _2n3 = /* @__PURE__ */ BigInt(2);
|
|
11360
|
+
function sqrtMod(y) {
|
|
11361
|
+
const P = secp256k1_CURVE.p;
|
|
11362
|
+
const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
|
|
11363
|
+
const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
|
|
11364
|
+
const b2 = y * y * y % P;
|
|
11365
|
+
const b3 = b2 * b2 * y % P;
|
|
11366
|
+
const b6 = pow2(b3, _3n3, P) * b3 % P;
|
|
11367
|
+
const b9 = pow2(b6, _3n3, P) * b3 % P;
|
|
11368
|
+
const b11 = pow2(b9, _2n3, P) * b2 % P;
|
|
11369
|
+
const b22 = pow2(b11, _11n, P) * b11 % P;
|
|
11370
|
+
const b44 = pow2(b22, _22n, P) * b22 % P;
|
|
11371
|
+
const b88 = pow2(b44, _44n, P) * b44 % P;
|
|
11372
|
+
const b176 = pow2(b88, _88n, P) * b88 % P;
|
|
11373
|
+
const b220 = pow2(b176, _44n, P) * b44 % P;
|
|
11374
|
+
const b223 = pow2(b220, _3n3, P) * b3 % P;
|
|
11375
|
+
const t1 = pow2(b223, _23n, P) * b22 % P;
|
|
11376
|
+
const t2 = pow2(t1, _6n, P) * b2 % P;
|
|
11377
|
+
const root = pow2(t2, _2n3, P);
|
|
11378
|
+
if (!Fpk1.eql(Fpk1.sqr(root), y))
|
|
11379
|
+
throw new Error("Cannot find square root");
|
|
11380
|
+
return root;
|
|
11381
|
+
}
|
|
11382
|
+
var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });
|
|
11383
|
+
var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {
|
|
11384
|
+
Fp: Fpk1,
|
|
11385
|
+
endo: secp256k1_ENDO
|
|
11386
|
+
});
|
|
11387
|
+
var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha2564);
|
|
11388
|
+
|
|
11389
|
+
// modules/market/MarketModule.ts
|
|
11390
|
+
var DEFAULT_MARKET_API_URL = "https://market-api.unicity.network";
|
|
11391
|
+
function hexToBytes3(hex) {
|
|
11392
|
+
const len = hex.length >> 1;
|
|
11393
|
+
const bytes = new Uint8Array(len);
|
|
11394
|
+
for (let i = 0; i < len; i++) {
|
|
11395
|
+
bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
11396
|
+
}
|
|
11397
|
+
return bytes;
|
|
11398
|
+
}
|
|
11399
|
+
function signRequest(body, privateKeyHex) {
|
|
11400
|
+
const timestamp = Date.now();
|
|
11401
|
+
const payload = JSON.stringify({ body, timestamp });
|
|
11402
|
+
const messageHash = sha2564(new TextEncoder().encode(payload));
|
|
11403
|
+
const privateKeyBytes = hexToBytes3(privateKeyHex);
|
|
11404
|
+
const signature = secp256k1.sign(messageHash, privateKeyBytes);
|
|
11405
|
+
const publicKey = bytesToHex4(secp256k1.getPublicKey(privateKeyBytes, true));
|
|
11406
|
+
return {
|
|
11407
|
+
body: JSON.stringify(body),
|
|
11408
|
+
headers: {
|
|
11409
|
+
"x-signature": bytesToHex4(signature),
|
|
11410
|
+
"x-public-key": publicKey,
|
|
11411
|
+
"x-timestamp": String(timestamp),
|
|
11412
|
+
"content-type": "application/json"
|
|
11413
|
+
}
|
|
11414
|
+
};
|
|
11415
|
+
}
|
|
11416
|
+
function toSnakeCaseIntent(req) {
|
|
11417
|
+
const result = {
|
|
11418
|
+
description: req.description,
|
|
11419
|
+
intent_type: req.intentType
|
|
11420
|
+
};
|
|
11421
|
+
if (req.category !== void 0) result.category = req.category;
|
|
11422
|
+
if (req.price !== void 0) result.price = req.price;
|
|
11423
|
+
if (req.currency !== void 0) result.currency = req.currency;
|
|
11424
|
+
if (req.location !== void 0) result.location = req.location;
|
|
11425
|
+
if (req.contactHandle !== void 0) result.contact_handle = req.contactHandle;
|
|
11426
|
+
if (req.expiresInDays !== void 0) result.expires_in_days = req.expiresInDays;
|
|
11427
|
+
return result;
|
|
11428
|
+
}
|
|
11429
|
+
function toSnakeCaseFilters(opts) {
|
|
11430
|
+
const result = {};
|
|
11431
|
+
if (opts?.filters) {
|
|
11432
|
+
const f = opts.filters;
|
|
11433
|
+
if (f.intentType !== void 0) result.intent_type = f.intentType;
|
|
11434
|
+
if (f.category !== void 0) result.category = f.category;
|
|
11435
|
+
if (f.minPrice !== void 0) result.min_price = f.minPrice;
|
|
11436
|
+
if (f.maxPrice !== void 0) result.max_price = f.maxPrice;
|
|
11437
|
+
if (f.location !== void 0) result.location = f.location;
|
|
11438
|
+
}
|
|
11439
|
+
if (opts?.limit !== void 0) result.limit = opts.limit;
|
|
11440
|
+
return result;
|
|
11441
|
+
}
|
|
11442
|
+
function mapSearchResult(raw) {
|
|
11443
|
+
return {
|
|
11444
|
+
id: raw.id,
|
|
11445
|
+
score: raw.score,
|
|
11446
|
+
agentNametag: raw.agent_nametag ?? void 0,
|
|
11447
|
+
agentPublicKey: raw.agent_public_key,
|
|
11448
|
+
description: raw.description,
|
|
11449
|
+
intentType: raw.intent_type,
|
|
11450
|
+
category: raw.category ?? void 0,
|
|
11451
|
+
price: raw.price ?? void 0,
|
|
11452
|
+
currency: raw.currency,
|
|
11453
|
+
location: raw.location ?? void 0,
|
|
11454
|
+
contactMethod: raw.contact_method,
|
|
11455
|
+
contactHandle: raw.contact_handle ?? void 0,
|
|
11456
|
+
createdAt: raw.created_at,
|
|
11457
|
+
expiresAt: raw.expires_at
|
|
11458
|
+
};
|
|
11459
|
+
}
|
|
11460
|
+
function mapMyIntent(raw) {
|
|
11461
|
+
return {
|
|
11462
|
+
id: raw.id,
|
|
11463
|
+
intentType: raw.intent_type,
|
|
11464
|
+
category: raw.category ?? void 0,
|
|
11465
|
+
price: raw.price ?? void 0,
|
|
11466
|
+
currency: raw.currency,
|
|
11467
|
+
location: raw.location ?? void 0,
|
|
11468
|
+
status: raw.status,
|
|
11469
|
+
createdAt: raw.created_at,
|
|
11470
|
+
expiresAt: raw.expires_at
|
|
11471
|
+
};
|
|
11472
|
+
}
|
|
11473
|
+
function mapFeedListing(raw) {
|
|
11474
|
+
return {
|
|
11475
|
+
id: raw.id,
|
|
11476
|
+
title: raw.title,
|
|
11477
|
+
descriptionPreview: raw.description_preview,
|
|
11478
|
+
agentName: raw.agent_name,
|
|
11479
|
+
agentId: raw.agent_id,
|
|
11480
|
+
type: raw.type,
|
|
11481
|
+
createdAt: raw.created_at
|
|
11482
|
+
};
|
|
11483
|
+
}
|
|
11484
|
+
function mapFeedMessage(raw) {
|
|
11485
|
+
if (raw.type === "initial") {
|
|
11486
|
+
return { type: "initial", listings: (raw.listings ?? []).map(mapFeedListing) };
|
|
11487
|
+
}
|
|
11488
|
+
return { type: "new", listing: mapFeedListing(raw.listing) };
|
|
11489
|
+
}
|
|
11490
|
+
var MarketModule = class {
|
|
11491
|
+
apiUrl;
|
|
11492
|
+
timeout;
|
|
11493
|
+
identity = null;
|
|
11494
|
+
registered = false;
|
|
11495
|
+
constructor(config) {
|
|
11496
|
+
this.apiUrl = (config?.apiUrl ?? DEFAULT_MARKET_API_URL).replace(/\/+$/, "");
|
|
11497
|
+
this.timeout = config?.timeout ?? 3e4;
|
|
11498
|
+
}
|
|
11499
|
+
/** Called by Sphere after construction */
|
|
11500
|
+
initialize(deps) {
|
|
11501
|
+
this.identity = deps.identity;
|
|
11502
|
+
}
|
|
11503
|
+
/** No-op — stateless module */
|
|
11504
|
+
async load() {
|
|
11505
|
+
}
|
|
11506
|
+
/** No-op — stateless module */
|
|
11507
|
+
destroy() {
|
|
11508
|
+
}
|
|
11509
|
+
// ---------------------------------------------------------------------------
|
|
11510
|
+
// Public API
|
|
11511
|
+
// ---------------------------------------------------------------------------
|
|
11512
|
+
/** Post a new intent (agent is auto-registered on first post) */
|
|
11513
|
+
async postIntent(intent) {
|
|
11514
|
+
const body = toSnakeCaseIntent(intent);
|
|
11515
|
+
const data = await this.apiPost("/api/intents", body);
|
|
11516
|
+
return {
|
|
11517
|
+
intentId: data.intent_id ?? data.intentId,
|
|
11518
|
+
message: data.message,
|
|
11519
|
+
expiresAt: data.expires_at ?? data.expiresAt
|
|
11520
|
+
};
|
|
11521
|
+
}
|
|
11522
|
+
/** Semantic search for intents (public — no auth required) */
|
|
11523
|
+
async search(query, opts) {
|
|
11524
|
+
const body = {
|
|
11525
|
+
query,
|
|
11526
|
+
...toSnakeCaseFilters(opts)
|
|
11527
|
+
};
|
|
11528
|
+
const data = await this.apiPublicPost("/api/search", body);
|
|
11529
|
+
let results = (data.intents ?? []).map(mapSearchResult);
|
|
11530
|
+
const minScore = opts?.filters?.minScore;
|
|
11531
|
+
if (minScore != null) {
|
|
11532
|
+
results = results.filter((r) => Math.round(r.score * 100) >= Math.round(minScore * 100));
|
|
11533
|
+
}
|
|
11534
|
+
return { intents: results, count: results.length };
|
|
11535
|
+
}
|
|
11536
|
+
/** List own intents (authenticated) */
|
|
11537
|
+
async getMyIntents() {
|
|
11538
|
+
const data = await this.apiGet("/api/intents");
|
|
11539
|
+
return (data.intents ?? []).map(mapMyIntent);
|
|
11540
|
+
}
|
|
11541
|
+
/** Close (delete) an intent */
|
|
11542
|
+
async closeIntent(intentId) {
|
|
11543
|
+
await this.apiDelete(`/api/intents/${encodeURIComponent(intentId)}`);
|
|
11544
|
+
}
|
|
11545
|
+
/** Fetch the most recent listings via REST (public — no auth required) */
|
|
11546
|
+
async getRecentListings() {
|
|
11547
|
+
const res = await fetch(`${this.apiUrl}/api/feed/recent`, {
|
|
11548
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
11549
|
+
});
|
|
11550
|
+
const data = await this.parseResponse(res);
|
|
11551
|
+
return (data.listings ?? []).map(mapFeedListing);
|
|
11552
|
+
}
|
|
11553
|
+
/**
|
|
11554
|
+
* Subscribe to the live listing feed via WebSocket.
|
|
11555
|
+
* Returns an unsubscribe function that closes the connection.
|
|
11556
|
+
*
|
|
11557
|
+
* Requires a WebSocket implementation — works natively in browsers
|
|
11558
|
+
* and in Node.js 21+ (or with the `ws` package).
|
|
11559
|
+
*/
|
|
11560
|
+
subscribeFeed(listener) {
|
|
11561
|
+
const wsUrl = this.apiUrl.replace(/^http/, "ws") + "/ws/feed";
|
|
11562
|
+
const ws2 = new WebSocket(wsUrl);
|
|
11563
|
+
ws2.onmessage = (event) => {
|
|
11564
|
+
try {
|
|
11565
|
+
const raw = JSON.parse(typeof event.data === "string" ? event.data : event.data.toString());
|
|
11566
|
+
listener(mapFeedMessage(raw));
|
|
11567
|
+
} catch {
|
|
11568
|
+
}
|
|
11569
|
+
};
|
|
11570
|
+
return () => {
|
|
11571
|
+
ws2.close();
|
|
11572
|
+
};
|
|
11573
|
+
}
|
|
11574
|
+
// ---------------------------------------------------------------------------
|
|
11575
|
+
// Private: HTTP helpers
|
|
11576
|
+
// ---------------------------------------------------------------------------
|
|
11577
|
+
ensureIdentity() {
|
|
11578
|
+
if (!this.identity) {
|
|
11579
|
+
throw new Error("MarketModule not initialized \u2014 call initialize() first");
|
|
11580
|
+
}
|
|
11581
|
+
}
|
|
11582
|
+
/** Register the agent's public key with the server (idempotent) */
|
|
11583
|
+
async ensureRegistered() {
|
|
11584
|
+
if (this.registered) return;
|
|
11585
|
+
this.ensureIdentity();
|
|
11586
|
+
const publicKey = bytesToHex4(secp256k1.getPublicKey(hexToBytes3(this.identity.privateKey), true));
|
|
11587
|
+
const body = { public_key: publicKey };
|
|
11588
|
+
if (this.identity.nametag) body.nametag = this.identity.nametag;
|
|
11589
|
+
const res = await fetch(`${this.apiUrl}/api/agent/register`, {
|
|
11590
|
+
method: "POST",
|
|
11591
|
+
headers: { "content-type": "application/json" },
|
|
11592
|
+
body: JSON.stringify(body),
|
|
11593
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
11594
|
+
});
|
|
11595
|
+
if (res.ok || res.status === 409) {
|
|
11596
|
+
this.registered = true;
|
|
11597
|
+
return;
|
|
11598
|
+
}
|
|
11599
|
+
const text = await res.text();
|
|
11600
|
+
let data;
|
|
11601
|
+
try {
|
|
11602
|
+
data = JSON.parse(text);
|
|
11603
|
+
} catch {
|
|
11604
|
+
}
|
|
11605
|
+
throw new Error(data?.error ?? `Agent registration failed: HTTP ${res.status}`);
|
|
11606
|
+
}
|
|
11607
|
+
async parseResponse(res) {
|
|
11608
|
+
const text = await res.text();
|
|
11609
|
+
let data;
|
|
11610
|
+
try {
|
|
11611
|
+
data = JSON.parse(text);
|
|
11612
|
+
} catch {
|
|
11613
|
+
throw new Error(`Market API error: HTTP ${res.status} \u2014 unexpected response (not JSON)`);
|
|
11614
|
+
}
|
|
11615
|
+
if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
|
|
11616
|
+
return data;
|
|
11617
|
+
}
|
|
11618
|
+
async apiPost(path, body) {
|
|
11619
|
+
this.ensureIdentity();
|
|
11620
|
+
await this.ensureRegistered();
|
|
11621
|
+
const signed = signRequest(body, this.identity.privateKey);
|
|
11622
|
+
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11623
|
+
method: "POST",
|
|
11624
|
+
headers: signed.headers,
|
|
11625
|
+
body: signed.body,
|
|
11626
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
11627
|
+
});
|
|
11628
|
+
return this.parseResponse(res);
|
|
11629
|
+
}
|
|
11630
|
+
async apiGet(path) {
|
|
11631
|
+
this.ensureIdentity();
|
|
11632
|
+
await this.ensureRegistered();
|
|
11633
|
+
const signed = signRequest({}, this.identity.privateKey);
|
|
11634
|
+
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11635
|
+
method: "GET",
|
|
11636
|
+
headers: signed.headers,
|
|
11637
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
11638
|
+
});
|
|
11639
|
+
return this.parseResponse(res);
|
|
11640
|
+
}
|
|
11641
|
+
async apiDelete(path) {
|
|
11642
|
+
this.ensureIdentity();
|
|
11643
|
+
await this.ensureRegistered();
|
|
11644
|
+
const signed = signRequest({}, this.identity.privateKey);
|
|
11645
|
+
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11646
|
+
method: "DELETE",
|
|
11647
|
+
headers: signed.headers,
|
|
11648
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
11649
|
+
});
|
|
11650
|
+
return this.parseResponse(res);
|
|
11651
|
+
}
|
|
11652
|
+
async apiPublicPost(path, body) {
|
|
11653
|
+
const res = await fetch(`${this.apiUrl}${path}`, {
|
|
11654
|
+
method: "POST",
|
|
11655
|
+
headers: { "content-type": "application/json" },
|
|
11656
|
+
body: JSON.stringify(body),
|
|
11657
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
11658
|
+
});
|
|
11659
|
+
return this.parseResponse(res);
|
|
11660
|
+
}
|
|
11661
|
+
};
|
|
11662
|
+
function createMarketModule(config) {
|
|
11663
|
+
return new MarketModule(config);
|
|
11664
|
+
}
|
|
11665
|
+
|
|
9089
11666
|
// core/encryption.ts
|
|
9090
11667
|
var import_crypto_js6 = __toESM(require("crypto-js"), 1);
|
|
9091
11668
|
var DEFAULT_ITERATIONS = 1e5;
|
|
@@ -10006,6 +12583,7 @@ var Sphere = class _Sphere {
|
|
|
10006
12583
|
_payments;
|
|
10007
12584
|
_communications;
|
|
10008
12585
|
_groupChat = null;
|
|
12586
|
+
_market = null;
|
|
10009
12587
|
// Events
|
|
10010
12588
|
eventHandlers = /* @__PURE__ */ new Map();
|
|
10011
12589
|
// Provider management
|
|
@@ -10015,7 +12593,7 @@ var Sphere = class _Sphere {
|
|
|
10015
12593
|
// ===========================================================================
|
|
10016
12594
|
// Constructor (private)
|
|
10017
12595
|
// ===========================================================================
|
|
10018
|
-
constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig) {
|
|
12596
|
+
constructor(storage, transport, oracle, tokenStorage, l1Config, priceProvider, groupChatConfig, marketConfig) {
|
|
10019
12597
|
this._storage = storage;
|
|
10020
12598
|
this._transport = transport;
|
|
10021
12599
|
this._oracle = oracle;
|
|
@@ -10026,6 +12604,7 @@ var Sphere = class _Sphere {
|
|
|
10026
12604
|
this._payments = createPaymentsModule({ l1: l1Config });
|
|
10027
12605
|
this._communications = createCommunicationsModule();
|
|
10028
12606
|
this._groupChat = groupChatConfig ? createGroupChatModule(groupChatConfig) : null;
|
|
12607
|
+
this._market = marketConfig ? createMarketModule(marketConfig) : null;
|
|
10029
12608
|
}
|
|
10030
12609
|
// ===========================================================================
|
|
10031
12610
|
// Static Methods - Wallet Management
|
|
@@ -10035,13 +12614,17 @@ var Sphere = class _Sphere {
|
|
|
10035
12614
|
*/
|
|
10036
12615
|
static async exists(storage) {
|
|
10037
12616
|
try {
|
|
10038
|
-
|
|
12617
|
+
const wasConnected = storage.isConnected();
|
|
12618
|
+
if (!wasConnected) {
|
|
10039
12619
|
await storage.connect();
|
|
10040
12620
|
}
|
|
10041
12621
|
const mnemonic = await storage.get(STORAGE_KEYS_GLOBAL.MNEMONIC);
|
|
10042
12622
|
if (mnemonic) return true;
|
|
10043
12623
|
const masterKey = await storage.get(STORAGE_KEYS_GLOBAL.MASTER_KEY);
|
|
10044
12624
|
if (masterKey) return true;
|
|
12625
|
+
if (!wasConnected) {
|
|
12626
|
+
await storage.disconnect();
|
|
12627
|
+
}
|
|
10045
12628
|
return false;
|
|
10046
12629
|
} catch {
|
|
10047
12630
|
return false;
|
|
@@ -10075,6 +12658,7 @@ var Sphere = class _Sphere {
|
|
|
10075
12658
|
static async init(options) {
|
|
10076
12659
|
_Sphere.configureTokenRegistry(options.storage, options.network);
|
|
10077
12660
|
const groupChat = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
|
|
12661
|
+
const market = _Sphere.resolveMarketConfig(options.market);
|
|
10078
12662
|
const walletExists = await _Sphere.exists(options.storage);
|
|
10079
12663
|
if (walletExists) {
|
|
10080
12664
|
const sphere2 = await _Sphere.load({
|
|
@@ -10085,6 +12669,7 @@ var Sphere = class _Sphere {
|
|
|
10085
12669
|
l1: options.l1,
|
|
10086
12670
|
price: options.price,
|
|
10087
12671
|
groupChat,
|
|
12672
|
+
market,
|
|
10088
12673
|
password: options.password
|
|
10089
12674
|
});
|
|
10090
12675
|
return { sphere: sphere2, created: false };
|
|
@@ -10112,6 +12697,7 @@ var Sphere = class _Sphere {
|
|
|
10112
12697
|
l1: options.l1,
|
|
10113
12698
|
price: options.price,
|
|
10114
12699
|
groupChat,
|
|
12700
|
+
market,
|
|
10115
12701
|
password: options.password
|
|
10116
12702
|
});
|
|
10117
12703
|
return { sphere, created: true, generatedMnemonic };
|
|
@@ -10139,6 +12725,17 @@ var Sphere = class _Sphere {
|
|
|
10139
12725
|
}
|
|
10140
12726
|
return config;
|
|
10141
12727
|
}
|
|
12728
|
+
/**
|
|
12729
|
+
* Resolve market module config from Sphere.init() options.
|
|
12730
|
+
* - `true` → enable with default API URL
|
|
12731
|
+
* - `MarketModuleConfig` → pass through
|
|
12732
|
+
* - `undefined` → no market module
|
|
12733
|
+
*/
|
|
12734
|
+
static resolveMarketConfig(config) {
|
|
12735
|
+
if (!config) return void 0;
|
|
12736
|
+
if (config === true) return {};
|
|
12737
|
+
return config;
|
|
12738
|
+
}
|
|
10142
12739
|
/**
|
|
10143
12740
|
* Configure TokenRegistry in the main bundle context.
|
|
10144
12741
|
*
|
|
@@ -10164,6 +12761,7 @@ var Sphere = class _Sphere {
|
|
|
10164
12761
|
}
|
|
10165
12762
|
_Sphere.configureTokenRegistry(options.storage, options.network);
|
|
10166
12763
|
const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
|
|
12764
|
+
const marketConfig = _Sphere.resolveMarketConfig(options.market);
|
|
10167
12765
|
const sphere = new _Sphere(
|
|
10168
12766
|
options.storage,
|
|
10169
12767
|
options.transport,
|
|
@@ -10171,7 +12769,8 @@ var Sphere = class _Sphere {
|
|
|
10171
12769
|
options.tokenStorage,
|
|
10172
12770
|
options.l1,
|
|
10173
12771
|
options.price,
|
|
10174
|
-
groupChatConfig
|
|
12772
|
+
groupChatConfig,
|
|
12773
|
+
marketConfig
|
|
10175
12774
|
);
|
|
10176
12775
|
sphere._password = options.password ?? null;
|
|
10177
12776
|
await sphere.storeMnemonic(options.mnemonic, options.derivationPath);
|
|
@@ -10199,6 +12798,7 @@ var Sphere = class _Sphere {
|
|
|
10199
12798
|
}
|
|
10200
12799
|
_Sphere.configureTokenRegistry(options.storage, options.network);
|
|
10201
12800
|
const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat, options.network);
|
|
12801
|
+
const marketConfig = _Sphere.resolveMarketConfig(options.market);
|
|
10202
12802
|
const sphere = new _Sphere(
|
|
10203
12803
|
options.storage,
|
|
10204
12804
|
options.transport,
|
|
@@ -10206,7 +12806,8 @@ var Sphere = class _Sphere {
|
|
|
10206
12806
|
options.tokenStorage,
|
|
10207
12807
|
options.l1,
|
|
10208
12808
|
options.price,
|
|
10209
|
-
groupChatConfig
|
|
12809
|
+
groupChatConfig,
|
|
12810
|
+
marketConfig
|
|
10210
12811
|
);
|
|
10211
12812
|
sphere._password = options.password ?? null;
|
|
10212
12813
|
await sphere.loadIdentityFromStorage();
|
|
@@ -10252,6 +12853,7 @@ var Sphere = class _Sphere {
|
|
|
10252
12853
|
console.log("[Sphere.import] Storage reconnected");
|
|
10253
12854
|
}
|
|
10254
12855
|
const groupChatConfig = _Sphere.resolveGroupChatConfig(options.groupChat);
|
|
12856
|
+
const marketConfig = _Sphere.resolveMarketConfig(options.market);
|
|
10255
12857
|
const sphere = new _Sphere(
|
|
10256
12858
|
options.storage,
|
|
10257
12859
|
options.transport,
|
|
@@ -10259,7 +12861,8 @@ var Sphere = class _Sphere {
|
|
|
10259
12861
|
options.tokenStorage,
|
|
10260
12862
|
options.l1,
|
|
10261
12863
|
options.price,
|
|
10262
|
-
groupChatConfig
|
|
12864
|
+
groupChatConfig,
|
|
12865
|
+
marketConfig
|
|
10263
12866
|
);
|
|
10264
12867
|
sphere._password = options.password ?? null;
|
|
10265
12868
|
if (options.mnemonic) {
|
|
@@ -10340,47 +12943,40 @@ var Sphere = class _Sphere {
|
|
|
10340
12943
|
static async clear(storageOrOptions) {
|
|
10341
12944
|
const storage = "get" in storageOrOptions ? storageOrOptions : storageOrOptions.storage;
|
|
10342
12945
|
const tokenStorage = "get" in storageOrOptions ? void 0 : storageOrOptions.tokenStorage;
|
|
10343
|
-
if (
|
|
10344
|
-
|
|
10345
|
-
|
|
10346
|
-
|
|
10347
|
-
|
|
10348
|
-
|
|
10349
|
-
await
|
|
10350
|
-
|
|
10351
|
-
await
|
|
10352
|
-
await storage.remove(STORAGE_KEYS_GLOBAL.DERIVATION_MODE);
|
|
10353
|
-
await storage.remove(STORAGE_KEYS_GLOBAL.WALLET_SOURCE);
|
|
10354
|
-
await storage.remove(STORAGE_KEYS_GLOBAL.WALLET_EXISTS);
|
|
10355
|
-
await storage.remove(STORAGE_KEYS_GLOBAL.TRACKED_ADDRESSES);
|
|
10356
|
-
await storage.remove(STORAGE_KEYS_GLOBAL.ADDRESS_NAMETAGS);
|
|
10357
|
-
await storage.remove(STORAGE_KEYS_ADDRESS.PENDING_TRANSFERS);
|
|
10358
|
-
await storage.remove(STORAGE_KEYS_ADDRESS.OUTBOX);
|
|
10359
|
-
console.log("[Sphere.clear] Storage keys removed");
|
|
12946
|
+
if (_Sphere.instance) {
|
|
12947
|
+
console.log("[Sphere.clear] Destroying Sphere instance...");
|
|
12948
|
+
await _Sphere.instance.destroy();
|
|
12949
|
+
console.log("[Sphere.clear] Sphere instance destroyed");
|
|
12950
|
+
}
|
|
12951
|
+
console.log("[Sphere.clear] Clearing L1 vesting cache...");
|
|
12952
|
+
await vestingClassifier.destroy();
|
|
12953
|
+
console.log("[Sphere.clear] Yielding 50ms for IDB transaction settlement...");
|
|
12954
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
10360
12955
|
if (tokenStorage?.clear) {
|
|
10361
12956
|
console.log("[Sphere.clear] Clearing token storage...");
|
|
10362
12957
|
try {
|
|
10363
|
-
await
|
|
10364
|
-
tokenStorage.clear(),
|
|
10365
|
-
new Promise(
|
|
10366
|
-
(_, reject) => setTimeout(() => reject(new Error("tokenStorage.clear() timed out after 2s")), 2e3)
|
|
10367
|
-
)
|
|
10368
|
-
]);
|
|
12958
|
+
await tokenStorage.clear();
|
|
10369
12959
|
console.log("[Sphere.clear] Token storage cleared");
|
|
10370
12960
|
} catch (err) {
|
|
10371
|
-
console.warn("[Sphere.clear] Token storage clear failed
|
|
12961
|
+
console.warn("[Sphere.clear] Token storage clear failed:", err);
|
|
10372
12962
|
}
|
|
12963
|
+
} else {
|
|
12964
|
+
console.log("[Sphere.clear] No token storage provider to clear");
|
|
10373
12965
|
}
|
|
10374
|
-
console.log("[Sphere.clear]
|
|
10375
|
-
|
|
10376
|
-
|
|
10377
|
-
|
|
10378
|
-
|
|
10379
|
-
|
|
10380
|
-
|
|
12966
|
+
console.log("[Sphere.clear] Clearing KV storage...");
|
|
12967
|
+
if (!storage.isConnected()) {
|
|
12968
|
+
try {
|
|
12969
|
+
await storage.connect();
|
|
12970
|
+
} catch {
|
|
12971
|
+
}
|
|
12972
|
+
}
|
|
12973
|
+
if (storage.isConnected()) {
|
|
12974
|
+
await storage.clear();
|
|
12975
|
+
console.log("[Sphere.clear] KV storage cleared");
|
|
10381
12976
|
} else {
|
|
10382
|
-
console.log("[Sphere.clear]
|
|
12977
|
+
console.log("[Sphere.clear] KV storage not connected, skipping");
|
|
10383
12978
|
}
|
|
12979
|
+
console.log("[Sphere.clear] Done");
|
|
10384
12980
|
}
|
|
10385
12981
|
/**
|
|
10386
12982
|
* Get current instance
|
|
@@ -10424,6 +13020,10 @@ var Sphere = class _Sphere {
|
|
|
10424
13020
|
get groupChat() {
|
|
10425
13021
|
return this._groupChat;
|
|
10426
13022
|
}
|
|
13023
|
+
/** Market module (intent bulletin board). Null if not configured. */
|
|
13024
|
+
get market() {
|
|
13025
|
+
return this._market;
|
|
13026
|
+
}
|
|
10427
13027
|
// ===========================================================================
|
|
10428
13028
|
// Public Properties - State
|
|
10429
13029
|
// ===========================================================================
|
|
@@ -11224,8 +13824,12 @@ var Sphere = class _Sphere {
|
|
|
11224
13824
|
await this._storage.set(STORAGE_KEYS_GLOBAL.CURRENT_ADDRESS_INDEX, index.toString());
|
|
11225
13825
|
this._storage.setIdentity(this._identity);
|
|
11226
13826
|
await this._transport.setIdentity(this._identity);
|
|
11227
|
-
|
|
13827
|
+
console.log(`[Sphere] switchToAddress(${index}): re-initializing ${this._tokenStorageProviders.size} token storage provider(s)`);
|
|
13828
|
+
for (const [providerId, provider] of this._tokenStorageProviders.entries()) {
|
|
13829
|
+
console.log(`[Sphere] switchToAddress(${index}): shutdown provider=${providerId}`);
|
|
13830
|
+
await provider.shutdown();
|
|
11228
13831
|
provider.setIdentity(this._identity);
|
|
13832
|
+
console.log(`[Sphere] switchToAddress(${index}): initialize provider=${providerId}`);
|
|
11229
13833
|
await provider.initialize();
|
|
11230
13834
|
}
|
|
11231
13835
|
await this.reinitializeModulesForNewAddress();
|
|
@@ -11299,9 +13903,17 @@ var Sphere = class _Sphere {
|
|
|
11299
13903
|
storage: this._storage,
|
|
11300
13904
|
emitEvent
|
|
11301
13905
|
});
|
|
13906
|
+
this._market?.initialize({
|
|
13907
|
+
identity: this._identity,
|
|
13908
|
+
emitEvent
|
|
13909
|
+
});
|
|
11302
13910
|
await this._payments.load();
|
|
11303
13911
|
await this._communications.load();
|
|
11304
13912
|
await this._groupChat?.load();
|
|
13913
|
+
await this._market?.load();
|
|
13914
|
+
this._payments.sync().catch((err) => {
|
|
13915
|
+
console.warn("[Sphere] Post-switch sync failed:", err);
|
|
13916
|
+
});
|
|
11305
13917
|
}
|
|
11306
13918
|
/**
|
|
11307
13919
|
* Derive address at a specific index
|
|
@@ -12126,6 +14738,7 @@ var Sphere = class _Sphere {
|
|
|
12126
14738
|
this._payments.destroy();
|
|
12127
14739
|
this._communications.destroy();
|
|
12128
14740
|
this._groupChat?.destroy();
|
|
14741
|
+
this._market?.destroy();
|
|
12129
14742
|
await this._transport.disconnect();
|
|
12130
14743
|
await this._storage.disconnect();
|
|
12131
14744
|
await this._oracle.disconnect();
|
|
@@ -12433,9 +15046,14 @@ var Sphere = class _Sphere {
|
|
|
12433
15046
|
storage: this._storage,
|
|
12434
15047
|
emitEvent
|
|
12435
15048
|
});
|
|
15049
|
+
this._market?.initialize({
|
|
15050
|
+
identity: this._identity,
|
|
15051
|
+
emitEvent
|
|
15052
|
+
});
|
|
12436
15053
|
await this._payments.load();
|
|
12437
15054
|
await this._communications.load();
|
|
12438
15055
|
await this._groupChat?.load();
|
|
15056
|
+
await this._market?.load();
|
|
12439
15057
|
}
|
|
12440
15058
|
// ===========================================================================
|
|
12441
15059
|
// Private: Helpers
|
|
@@ -12786,4 +15404,16 @@ async function runCustomCheck(name, checkFn, timeoutMs) {
|
|
|
12786
15404
|
toSmallestUnit,
|
|
12787
15405
|
validateMnemonic
|
|
12788
15406
|
});
|
|
15407
|
+
/*! Bundled license information:
|
|
15408
|
+
|
|
15409
|
+
@noble/hashes/utils.js:
|
|
15410
|
+
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
15411
|
+
|
|
15412
|
+
@noble/curves/utils.js:
|
|
15413
|
+
@noble/curves/abstract/modular.js:
|
|
15414
|
+
@noble/curves/abstract/curve.js:
|
|
15415
|
+
@noble/curves/abstract/weierstrass.js:
|
|
15416
|
+
@noble/curves/secp256k1.js:
|
|
15417
|
+
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
15418
|
+
*/
|
|
12789
15419
|
//# sourceMappingURL=index.cjs.map
|