OpenAsar/picheTohDekho2x.js

9928 lines
339 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

(()=>{
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb,mod3)=>function __require() {
return mod3 || (0,
cb[__getOwnPropNames(cb)[0]])((mod3 = {
exports: {}
}).exports, mod3),
mod3.exports;
}
;
var __export = (target,all)=>{
for (var name in all)
__defProp(target, name, {
get: all[name],
enumerable: true
});
}
;
var __copyProps = (to,from,except,desc)=>{
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, {
get: ()=>from[key],
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
}
;
var __toESM = (mod3,isNodeMode,target)=>(target = mod3 != null ? __create(__getProtoOf(mod3)) : {},
__copyProps(// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod3 || !mod3.__esModule ? __defProp(target, "default", {
value: mod3,
enumerable: true
}) : target, mod3));
// node_modules/.pnpm/webextension-polyfill@0.8.0/node_modules/webextension-polyfill/dist/browser-polyfill.js
var require_browser_polyfill = __commonJS({
"node_modules/.pnpm/webextension-polyfill@0.8.0/node_modules/webextension-polyfill/dist/browser-polyfill.js"(exports, module2) {
(function(global, factory) {
if (typeof define === "function" && define.amd) {
define("webextension-polyfill", ["module"], factory);
} else if (typeof exports !== "undefined") {
factory(module2);
} else {
var mod3 = {
exports: {}
};
factory(mod3);
global.browser = mod3.exports;
}
}
)(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : exports, function(module3) {
"use strict";
if (typeof browser === "undefined" || Object.getPrototypeOf(browser) !== Object.prototype) {
const CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE = "The message port closed before a response was received.";
const SEND_RESPONSE_DEPRECATION_WARNING = "Returning a Promise is the preferred way to send a reply from an onMessage/onMessageExternal listener, as the sendResponse will be removed from the specs (See https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage)";
const wrapAPIs = (extensionAPIs)=>{
const apiMetadata = {
"alarms": {
"clear": {
"minArgs": 0,
"maxArgs": 1
},
"clearAll": {
"minArgs": 0,
"maxArgs": 0
},
"get": {
"minArgs": 0,
"maxArgs": 1
},
"getAll": {
"minArgs": 0,
"maxArgs": 0
}
},
"bookmarks": {
"create": {
"minArgs": 1,
"maxArgs": 1
},
"get": {
"minArgs": 1,
"maxArgs": 1
},
"getChildren": {
"minArgs": 1,
"maxArgs": 1
},
"getRecent": {
"minArgs": 1,
"maxArgs": 1
},
"getSubTree": {
"minArgs": 1,
"maxArgs": 1
},
"getTree": {
"minArgs": 0,
"maxArgs": 0
},
"move": {
"minArgs": 2,
"maxArgs": 2
},
"remove": {
"minArgs": 1,
"maxArgs": 1
},
"removeTree": {
"minArgs": 1,
"maxArgs": 1
},
"search": {
"minArgs": 1,
"maxArgs": 1
},
"update": {
"minArgs": 2,
"maxArgs": 2
}
},
"browserAction": {
"disable": {
"minArgs": 0,
"maxArgs": 1,
"fallbackToNoCallback": true
},
"enable": {
"minArgs": 0,
"maxArgs": 1,
"fallbackToNoCallback": true
},
"getBadgeBackgroundColor": {
"minArgs": 1,
"maxArgs": 1
},
"getBadgeText": {
"minArgs": 1,
"maxArgs": 1
},
"getPopup": {
"minArgs": 1,
"maxArgs": 1
},
"getTitle": {
"minArgs": 1,
"maxArgs": 1
},
"openPopup": {
"minArgs": 0,
"maxArgs": 0
},
"setBadgeBackgroundColor": {
"minArgs": 1,
"maxArgs": 1,
"fallbackToNoCallback": true
},
"setBadgeText": {
"minArgs": 1,
"maxArgs": 1,
"fallbackToNoCallback": true
},
"setIcon": {
"minArgs": 1,
"maxArgs": 1
},
"setPopup": {
"minArgs": 1,
"maxArgs": 1,
"fallbackToNoCallback": true
},
"setTitle": {
"minArgs": 1,
"maxArgs": 1,
"fallbackToNoCallback": true
}
},
"browsingData": {
"remove": {
"minArgs": 2,
"maxArgs": 2
},
"removeCache": {
"minArgs": 1,
"maxArgs": 1
},
"removeCookies": {
"minArgs": 1,
"maxArgs": 1
},
"removeDownloads": {
"minArgs": 1,
"maxArgs": 1
},
"removeFormData": {
"minArgs": 1,
"maxArgs": 1
},
"removeHistory": {
"minArgs": 1,
"maxArgs": 1
},
"removeLocalStorage": {
"minArgs": 1,
"maxArgs": 1
},
"removePasswords": {
"minArgs": 1,
"maxArgs": 1
},
"removePluginData": {
"minArgs": 1,
"maxArgs": 1
},
"settings": {
"minArgs": 0,
"maxArgs": 0
}
},
"commands": {
"getAll": {
"minArgs": 0,
"maxArgs": 0
}
},
"contextMenus": {
"remove": {
"minArgs": 1,
"maxArgs": 1
},
"removeAll": {
"minArgs": 0,
"maxArgs": 0
},
"update": {
"minArgs": 2,
"maxArgs": 2
}
},
"cookies": {
"get": {
"minArgs": 1,
"maxArgs": 1
},
"getAll": {
"minArgs": 1,
"maxArgs": 1
},
"getAllCookieStores": {
"minArgs": 0,
"maxArgs": 0
},
"remove": {
"minArgs": 1,
"maxArgs": 1
},
"set": {
"minArgs": 1,
"maxArgs": 1
}
},
"devtools": {
"inspectedWindow": {
"eval": {
"minArgs": 1,
"maxArgs": 2,
"singleCallbackArg": false
}
},
"panels": {
"create": {
"minArgs": 3,
"maxArgs": 3,
"singleCallbackArg": true
},
"elements": {
"createSidebarPane": {
"minArgs": 1,
"maxArgs": 1
}
}
}
},
"downloads": {
"cancel": {
"minArgs": 1,
"maxArgs": 1
},
"download": {
"minArgs": 1,
"maxArgs": 1
},
"erase": {
"minArgs": 1,
"maxArgs": 1
},
"getFileIcon": {
"minArgs": 1,
"maxArgs": 2
},
"open": {
"minArgs": 1,
"maxArgs": 1,
"fallbackToNoCallback": true
},
"pause": {
"minArgs": 1,
"maxArgs": 1
},
"removeFile": {
"minArgs": 1,
"maxArgs": 1
},
"resume": {
"minArgs": 1,
"maxArgs": 1
},
"search": {
"minArgs": 1,
"maxArgs": 1
},
"show": {
"minArgs": 1,
"maxArgs": 1,
"fallbackToNoCallback": true
}
},
"extension": {
"isAllowedFileSchemeAccess": {
"minArgs": 0,
"maxArgs": 0
},
"isAllowedIncognitoAccess": {
"minArgs": 0,
"maxArgs": 0
}
},
"history": {
"addUrl": {
"minArgs": 1,
"maxArgs": 1
},
"deleteAll": {
"minArgs": 0,
"maxArgs": 0
},
"deleteRange": {
"minArgs": 1,
"maxArgs": 1
},
"deleteUrl": {
"minArgs": 1,
"maxArgs": 1
},
"getVisits": {
"minArgs": 1,
"maxArgs": 1
},
"search": {
"minArgs": 1,
"maxArgs": 1
}
},
"i18n": {
"detectLanguage": {
"minArgs": 1,
"maxArgs": 1
},
"getAcceptLanguages": {
"minArgs": 0,
"maxArgs": 0
}
},
"identity": {
"launchWebAuthFlow": {
"minArgs": 1,
"maxArgs": 1
}
},
"idle": {
"queryState": {
"minArgs": 1,
"maxArgs": 1
}
},
"management": {
"get": {
"minArgs": 1,
"maxArgs": 1
},
"getAll": {
"minArgs": 0,
"maxArgs": 0
},
"getSelf": {
"minArgs": 0,
"maxArgs": 0
},
"setEnabled": {
"minArgs": 2,
"maxArgs": 2
},
"uninstallSelf": {
"minArgs": 0,
"maxArgs": 1
}
},
"notifications": {
"clear": {
"minArgs": 1,
"maxArgs": 1
},
"create": {
"minArgs": 1,
"maxArgs": 2
},
"getAll": {
"minArgs": 0,
"maxArgs": 0
},
"getPermissionLevel": {
"minArgs": 0,
"maxArgs": 0
},
"update": {
"minArgs": 2,
"maxArgs": 2
}
},
"pageAction": {
"getPopup": {
"minArgs": 1,
"maxArgs": 1
},
"getTitle": {
"minArgs": 1,
"maxArgs": 1
},
"hide": {
"minArgs": 1,
"maxArgs": 1,
"fallbackToNoCallback": true
},
"setIcon": {
"minArgs": 1,
"maxArgs": 1
},
"setPopup": {
"minArgs": 1,
"maxArgs": 1,
"fallbackToNoCallback": true
},
"setTitle": {
"minArgs": 1,
"maxArgs": 1,
"fallbackToNoCallback": true
},
"show": {
"minArgs": 1,
"maxArgs": 1,
"fallbackToNoCallback": true
}
},
"permissions": {
"contains": {
"minArgs": 1,
"maxArgs": 1
},
"getAll": {
"minArgs": 0,
"maxArgs": 0
},
"remove": {
"minArgs": 1,
"maxArgs": 1
},
"request": {
"minArgs": 1,
"maxArgs": 1
}
},
"runtime": {
"getBackgroundPage": {
"minArgs": 0,
"maxArgs": 0
},
"getPlatformInfo": {
"minArgs": 0,
"maxArgs": 0
},
"openOptionsPage": {
"minArgs": 0,
"maxArgs": 0
},
"requestUpdateCheck": {
"minArgs": 0,
"maxArgs": 0
},
"sendMessage": {
"minArgs": 1,
"maxArgs": 3
},
"sendNativeMessage": {
"minArgs": 2,
"maxArgs": 2
},
"setUninstallURL": {
"minArgs": 1,
"maxArgs": 1
}
},
"sessions": {
"getDevices": {
"minArgs": 0,
"maxArgs": 1
},
"getRecentlyClosed": {
"minArgs": 0,
"maxArgs": 1
},
"restore": {
"minArgs": 0,
"maxArgs": 1
}
},
"storage": {
"local": {
"clear": {
"minArgs": 0,
"maxArgs": 0
},
"get": {
"minArgs": 0,
"maxArgs": 1
},
"getBytesInUse": {
"minArgs": 0,
"maxArgs": 1
},
"remove": {
"minArgs": 1,
"maxArgs": 1
},
"set": {
"minArgs": 1,
"maxArgs": 1
}
},
"managed": {
"get": {
"minArgs": 0,
"maxArgs": 1
},
"getBytesInUse": {
"minArgs": 0,
"maxArgs": 1
}
},
"sync": {
"clear": {
"minArgs": 0,
"maxArgs": 0
},
"get": {
"minArgs": 0,
"maxArgs": 1
},
"getBytesInUse": {
"minArgs": 0,
"maxArgs": 1
},
"remove": {
"minArgs": 1,
"maxArgs": 1
},
"set": {
"minArgs": 1,
"maxArgs": 1
}
}
},
"tabs": {
"captureVisibleTab": {
"minArgs": 0,
"maxArgs": 2
},
"create": {
"minArgs": 1,
"maxArgs": 1
},
"detectLanguage": {
"minArgs": 0,
"maxArgs": 1
},
"discard": {
"minArgs": 0,
"maxArgs": 1
},
"duplicate": {
"minArgs": 1,
"maxArgs": 1
},
"executeScript": {
"minArgs": 1,
"maxArgs": 2
},
"get": {
"minArgs": 1,
"maxArgs": 1
},
"getCurrent": {
"minArgs": 0,
"maxArgs": 0
},
"getZoom": {
"minArgs": 0,
"maxArgs": 1
},
"getZoomSettings": {
"minArgs": 0,
"maxArgs": 1
},
"goBack": {
"minArgs": 0,
"maxArgs": 1
},
"goForward": {
"minArgs": 0,
"maxArgs": 1
},
"highlight": {
"minArgs": 1,
"maxArgs": 1
},
"insertCSS": {
"minArgs": 1,
"maxArgs": 2
},
"move": {
"minArgs": 2,
"maxArgs": 2
},
"query": {
"minArgs": 1,
"maxArgs": 1
},
"reload": {
"minArgs": 0,
"maxArgs": 2
},
"remove": {
"minArgs": 1,
"maxArgs": 1
},
"removeCSS": {
"minArgs": 1,
"maxArgs": 2
},
"sendMessage": {
"minArgs": 2,
"maxArgs": 3
},
"setZoom": {
"minArgs": 1,
"maxArgs": 2
},
"setZoomSettings": {
"minArgs": 1,
"maxArgs": 2
},
"update": {
"minArgs": 1,
"maxArgs": 2
}
},
"topSites": {
"get": {
"minArgs": 0,
"maxArgs": 0
}
},
"webNavigation": {
"getAllFrames": {
"minArgs": 1,
"maxArgs": 1
},
"getFrame": {
"minArgs": 1,
"maxArgs": 1
}
},
"webRequest": {
"handlerBehaviorChanged": {
"minArgs": 0,
"maxArgs": 0
}
},
"windows": {
"create": {
"minArgs": 0,
"maxArgs": 1
},
"get": {
"minArgs": 1,
"maxArgs": 2
},
"getAll": {
"minArgs": 0,
"maxArgs": 1
},
"getCurrent": {
"minArgs": 0,
"maxArgs": 1
},
"getLastFocused": {
"minArgs": 0,
"maxArgs": 1
},
"remove": {
"minArgs": 1,
"maxArgs": 1
},
"update": {
"minArgs": 2,
"maxArgs": 2
}
}
};
if (Object.keys(apiMetadata).length === 0) {
throw new Error("api-metadata.json has not been included in browser-polyfill");
}
class DefaultWeakMap extends WeakMap {
constructor(createItem, items=void 0) {
super(items);
this.createItem = createItem;
}
get(key) {
if (!this.has(key)) {
this.set(key, this.createItem(key));
}
return super.get(key);
}
}
const isThenable = (value)=>{
return value && typeof value === "object" && typeof value.then === "function";
}
;
const makeCallback = (promise,metadata)=>{
return (...callbackArgs)=>{
if (extensionAPIs.runtime.lastError) {
promise.reject(new Error(extensionAPIs.runtime.lastError.message));
} else if (metadata.singleCallbackArg || callbackArgs.length <= 1 && metadata.singleCallbackArg !== false) {
promise.resolve(callbackArgs[0]);
} else {
promise.resolve(callbackArgs);
}
}
;
}
;
const pluralizeArguments = (numArgs)=>numArgs == 1 ? "argument" : "arguments";
const wrapAsyncFunction = (name,metadata)=>{
return function asyncFunctionWrapper(target, ...args) {
if (args.length < metadata.minArgs) {
throw new Error(`Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`);
}
if (args.length > metadata.maxArgs) {
throw new Error(`Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`);
}
return new Promise((resolve,reject)=>{
if (metadata.fallbackToNoCallback) {
try {
target[name](...args, makeCallback({
resolve,
reject
}, metadata));
} catch (cbError) {
console.warn(`${name} API method doesn't seem to support the callback parameter, falling back to call it without a callback: `, cbError);
target[name](...args);
metadata.fallbackToNoCallback = false;
metadata.noCallback = true;
resolve();
}
} else if (metadata.noCallback) {
target[name](...args);
resolve();
} else {
target[name](...args, makeCallback({
resolve,
reject
}, metadata));
}
}
);
}
;
}
;
const wrapMethod = (target,method,wrapper)=>{
return new Proxy(method,{
apply(targetMethod, thisObj, args) {
return wrapper.call(thisObj, target, ...args);
}
});
}
;
let hasOwnProperty = Function.call.bind(Object.prototype.hasOwnProperty);
const wrapObject = (target,wrappers={},metadata={})=>{
let cache = /* @__PURE__ */
Object.create(null);
let handlers = {
has(proxyTarget2, prop) {
return prop in target || prop in cache;
},
get(proxyTarget2, prop, receiver) {
if (prop in cache) {
return cache[prop];
}
if (!(prop in target)) {
return void 0;
}
let value = target[prop];
if (typeof value === "function") {
if (typeof wrappers[prop] === "function") {
value = wrapMethod(target, target[prop], wrappers[prop]);
} else if (hasOwnProperty(metadata, prop)) {
let wrapper = wrapAsyncFunction(prop, metadata[prop]);
value = wrapMethod(target, target[prop], wrapper);
} else {
value = value.bind(target);
}
} else if (typeof value === "object" && value !== null && (hasOwnProperty(wrappers, prop) || hasOwnProperty(metadata, prop))) {
value = wrapObject(value, wrappers[prop], metadata[prop]);
} else if (hasOwnProperty(metadata, "*")) {
value = wrapObject(value, wrappers[prop], metadata["*"]);
} else {
Object.defineProperty(cache, prop, {
configurable: true,
enumerable: true,
get() {
return target[prop];
},
set(value2) {
target[prop] = value2;
}
});
return value;
}
cache[prop] = value;
return value;
},
set(proxyTarget2, prop, value, receiver) {
if (prop in cache) {
cache[prop] = value;
} else {
target[prop] = value;
}
return true;
},
defineProperty(proxyTarget2, prop, desc) {
return Reflect.defineProperty(cache, prop, desc);
},
deleteProperty(proxyTarget2, prop) {
return Reflect.deleteProperty(cache, prop);
}
};
let proxyTarget = Object.create(target);
return new Proxy(proxyTarget,handlers);
}
;
const wrapEvent = (wrapperMap)=>({
addListener(target, listener, ...args) {
target.addListener(wrapperMap.get(listener), ...args);
},
hasListener(target, listener) {
return target.hasListener(wrapperMap.get(listener));
},
removeListener(target, listener) {
target.removeListener(wrapperMap.get(listener));
}
});
const onRequestFinishedWrappers = new DefaultWeakMap((listener)=>{
if (typeof listener !== "function") {
return listener;
}
return function onRequestFinished(req) {
const wrappedReq = wrapObject(req, {}, {
getContent: {
minArgs: 0,
maxArgs: 0
}
});
listener(wrappedReq);
}
;
}
);
let loggedSendResponseDeprecationWarning = false;
const onMessageWrappers = new DefaultWeakMap((listener)=>{
if (typeof listener !== "function") {
return listener;
}
return function onMessage(message, sender, sendResponse) {
let didCallSendResponse = false;
let wrappedSendResponse;
let sendResponsePromise = new Promise((resolve)=>{
wrappedSendResponse = function(response) {
if (!loggedSendResponseDeprecationWarning) {
console.warn(SEND_RESPONSE_DEPRECATION_WARNING, new Error().stack);
loggedSendResponseDeprecationWarning = true;
}
didCallSendResponse = true;
resolve(response);
}
;
}
);
let result;
try {
result = listener(message, sender, wrappedSendResponse);
} catch (err) {
result = Promise.reject(err);
}
const isResultThenable = result !== true && isThenable(result);
if (result !== true && !isResultThenable && !didCallSendResponse) {
return false;
}
const sendPromisedResult = (promise)=>{
promise.then((msg)=>{
sendResponse(msg);
}
, (error)=>{
let message2;
if (error && (error instanceof Error || typeof error.message === "string")) {
message2 = error.message;
} else {
message2 = "An unexpected error occurred";
}
sendResponse({
__mozWebExtensionPolyfillReject__: true,
message: message2
});
}
).catch((err)=>{
console.error("Failed to send onMessage rejected reply", err);
}
);
}
;
if (isResultThenable) {
sendPromisedResult(result);
} else {
sendPromisedResult(sendResponsePromise);
}
return true;
}
;
}
);
const wrappedSendMessageCallback = ({reject, resolve},reply)=>{
if (extensionAPIs.runtime.lastError) {
if (extensionAPIs.runtime.lastError.message === CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE) {
resolve();
} else {
reject(new Error(extensionAPIs.runtime.lastError.message));
}
} else if (reply && reply.__mozWebExtensionPolyfillReject__) {
reject(new Error(reply.message));
} else {
resolve(reply);
}
}
;
const wrappedSendMessage = (name,metadata,apiNamespaceObj,...args)=>{
if (args.length < metadata.minArgs) {
throw new Error(`Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`);
}
if (args.length > metadata.maxArgs) {
throw new Error(`Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`);
}
return new Promise((resolve,reject)=>{
const wrappedCb = wrappedSendMessageCallback.bind(null, {
resolve,
reject
});
args.push(wrappedCb);
apiNamespaceObj.sendMessage(...args);
}
);
}
;
const staticWrappers = {
devtools: {
network: {
onRequestFinished: wrapEvent(onRequestFinishedWrappers)
}
},
runtime: {
onMessage: wrapEvent(onMessageWrappers),
onMessageExternal: wrapEvent(onMessageWrappers),
sendMessage: wrappedSendMessage.bind(null, "sendMessage", {
minArgs: 1,
maxArgs: 3
})
},
tabs: {
sendMessage: wrappedSendMessage.bind(null, "sendMessage", {
minArgs: 2,
maxArgs: 3
})
}
};
const settingMetadata = {
clear: {
minArgs: 1,
maxArgs: 1
},
get: {
minArgs: 1,
maxArgs: 1
},
set: {
minArgs: 1,
maxArgs: 1
}
};
apiMetadata.privacy = {
network: {
"*": settingMetadata
},
services: {
"*": settingMetadata
},
websites: {
"*": settingMetadata
}
};
return wrapObject(extensionAPIs, staticWrappers, apiMetadata);
}
;
if (typeof chrome != "object" || !chrome || !chrome.runtime || !chrome.runtime.id) {
throw new Error("This script should only be loaded in a browser extension.");
}
module3.exports = wrapAPIs(chrome);
} else {
module3.exports = browser;
}
});
}
});
// (disabled):crypto
var require_crypto = __commonJS({
"(disabled):crypto"() {}
});
// node_modules/.pnpm/@scure+bip39@1.2.0/node_modules/@scure/bip39/wordlists/english.js
var require_english = __commonJS({
"node_modules/.pnpm/@scure+bip39@1.2.0/node_modules/@scure/bip39/wordlists/english.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.wordlist = void 0;
exports.wordlist = `abandon
ability
able
about
above
absent
absorb
abstract
absurd
abuse
access
accident
account
accuse
achieve
acid
acoustic
acquire
across
act
action
actor
actress
actual
adapt
add
addict
address
adjust
admit
adult
advance
advice
aerobic
affair
afford
afraid
again
age
agent
agree
ahead
aim
air
airport
aisle
alarm
album
alcohol
alert
alien
all
alley
allow
almost
alone
alpha
already
also
alter
always
amateur
amazing
among
amount
amused
analyst
anchor
ancient
anger
angle
angry
animal
ankle
announce
annual
another
answer
antenna
antique
anxiety
any
apart
apology
appear
apple
approve
april
arch
arctic
area
arena
argue
arm
armed
armor
army
around
arrange
arrest
arrive
arrow
art
artefact
artist
artwork
ask
aspect
assault
asset
assist
assume
asthma
athlete
atom
attack
attend
attitude
attract
auction
audit
august
aunt
author
auto
autumn
average
avocado
avoid
awake
aware
away
awesome
awful
awkward
axis
baby
bachelor
bacon
badge
bag
balance
balcony
ball
bamboo
banana
banner
bar
barely
bargain
barrel
base
basic
basket
battle
beach
bean
beauty
because
become
beef
before
begin
behave
behind
believe
below
belt
bench
benefit
best
betray
better
between
beyond
bicycle
bid
bike
bind
biology
bird
birth
bitter
black
blade
blame
blanket
blast
bleak
bless
blind
blood
blossom
blouse
blue
blur
blush
board
boat
body
boil
bomb
bone
bonus
book
boost
border
boring
borrow
boss
bottom
bounce
box
boy
bracket
brain
brand
brass
brave
bread
breeze
brick
bridge
brief
bright
bring
brisk
broccoli
broken
bronze
broom
brother
brown
brush
bubble
buddy
budget
buffalo
build
bulb
bulk
bullet
bundle
bunker
burden
burger
burst
bus
business
busy
butter
buyer
buzz
cabbage
cabin
cable
cactus
cage
cake
call
calm
camera
camp
can
canal
cancel
candy
cannon
canoe
canvas
canyon
capable
capital
captain
car
carbon
card
cargo
carpet
carry
cart
case
cash
casino
castle
casual
cat
catalog
catch
category
cattle
caught
cause
caution
cave
ceiling
celery
cement
census
century
cereal
certain
chair
chalk
champion
change
chaos
chapter
charge
chase
chat
cheap
check
cheese
chef
cherry
chest
chicken
chief
child
chimney
choice
choose
chronic
chuckle
chunk
churn
cigar
cinnamon
circle
citizen
city
civil
claim
clap
clarify
claw
clay
clean
clerk
clever
click
client
cliff
climb
clinic
clip
clock
clog
close
cloth
cloud
clown
club
clump
cluster
clutch
coach
coast
coconut
code
coffee
coil
coin
collect
color
column
combine
come
comfort
comic
common
company
concert
conduct
confirm
congress
connect
consider
control
convince
cook
cool
copper
copy
coral
core
corn
correct
cost
cotton
couch
country
couple
course
cousin
cover
coyote
crack
cradle
craft
cram
crane
crash
crater
crawl
crazy
cream
credit
creek
crew
cricket
crime
crisp
critic
crop
cross
crouch
crowd
crucial
cruel
cruise
crumble
crunch
crush
cry
crystal
cube
culture
cup
cupboard
curious
current
curtain
curve
cushion
custom
cute
cycle
dad
damage
damp
dance
danger
daring
dash
daughter
dawn
day
deal
debate
debris
decade
december
decide
decline
decorate
decrease
deer
defense
define
defy
degree
delay
deliver
demand
demise
denial
dentist
deny
depart
depend
deposit
depth
deputy
derive
describe
desert
design
desk
despair
destroy
detail
detect
develop
device
devote
diagram
dial
diamond
diary
dice
diesel
diet
differ
digital
dignity
dilemma
dinner
dinosaur
direct
dirt
disagree
discover
disease
dish
dismiss
disorder
display
distance
divert
divide
divorce
dizzy
doctor
document
dog
doll
dolphin
domain
donate
donkey
donor
door
dose
double
dove
draft
dragon
drama
drastic
draw
dream
dress
drift
drill
drink
drip
drive
drop
drum
dry
duck
dumb
dune
during
dust
dutch
duty
dwarf
dynamic
eager
eagle
early
earn
earth
easily
east
easy
echo
ecology
economy
edge
edit
educate
effort
egg
eight
either
elbow
elder
electric
elegant
element
elephant
elevator
elite
else
embark
embody
embrace
emerge
emotion
employ
empower
empty
enable
enact
end
endless
endorse
enemy
energy
enforce
engage
engine
enhance
enjoy
enlist
enough
enrich
enroll
ensure
enter
entire
entry
envelope
episode
equal
equip
era
erase
erode
erosion
error
erupt
escape
essay
essence
estate
eternal
ethics
evidence
evil
evoke
evolve
exact
example
excess
exchange
excite
exclude
excuse
execute
exercise
exhaust
exhibit
exile
exist
exit
exotic
expand
expect
expire
explain
expose
express
extend
extra
eye
eyebrow
fabric
face
faculty
fade
faint
faith
fall
false
fame
family
famous
fan
fancy
fantasy
farm
fashion
fat
fatal
father
fatigue
fault
favorite
feature
february
federal
fee
feed
feel
female
fence
festival
fetch
fever
few
fiber
fiction
field
figure
file
film
filter
final
find
fine
finger
finish
fire
firm
first
fiscal
fish
fit
fitness
fix
flag
flame
flash
flat
flavor
flee
flight
flip
float
flock
floor
flower
fluid
flush
fly
foam
focus
fog
foil
fold
follow
food
foot
force
forest
forget
fork
fortune
forum
forward
fossil
foster
found
fox
fragile
frame
frequent
fresh
friend
fringe
frog
front
frost
frown
frozen
fruit
fuel
fun
funny
furnace
fury
future
gadget
gain
galaxy
gallery
game
gap
garage
garbage
garden
garlic
garment
gas
gasp
gate
gather
gauge
gaze
general
genius
genre
gentle
genuine
gesture
ghost
giant
gift
giggle
ginger
giraffe
girl
give
glad
glance
glare
glass
glide
glimpse
globe
gloom
glory
glove
glow
glue
goat
goddess
gold
good
goose
gorilla
gospel
gossip
govern
gown
grab
grace
grain
grant
grape
grass
gravity
great
green
grid
grief
grit
grocery
group
grow
grunt
guard
guess
guide
guilt
guitar
gun
gym
habit
hair
half
hammer
hamster
hand
happy
harbor
hard
harsh
harvest
hat
have
hawk
hazard
head
health
heart
heavy
hedgehog
height
hello
helmet
help
hen
hero
hidden
high
hill
hint
hip
hire
history
hobby
hockey
hold
hole
holiday
hollow
home
honey
hood
hope
horn
horror
horse
hospital
host
hotel
hour
hover
hub
huge
human
humble
humor
hundred
hungry
hunt
hurdle
hurry
hurt
husband
hybrid
ice
icon
idea
identify
idle
ignore
ill
illegal
illness
image
imitate
immense
immune
impact
impose
improve
impulse
inch
include
income
increase
index
indicate
indoor
industry
infant
inflict
inform
inhale
inherit
initial
inject
injury
inmate
inner
innocent
input
inquiry
insane
insect
inside
inspire
install
intact
interest
into
invest
invite
involve
iron
island
isolate
issue
item
ivory
jacket
jaguar
jar
jazz
jealous
jeans
jelly
jewel
job
join
joke
journey
joy
judge
juice
jump
jungle
junior
junk
just
kangaroo
keen
keep
ketchup
key
kick
kid
kidney
kind
kingdom
kiss
kit
kitchen
kite
kitten
kiwi
knee
knife
knock
know
lab
label
labor
ladder
lady
lake
lamp
language
laptop
large
later
latin
laugh
laundry
lava
law
lawn
lawsuit
layer
lazy
leader
leaf
learn
leave
lecture
left
leg
legal
legend
leisure
lemon
lend
length
lens
leopard
lesson
letter
level
liar
liberty
library
license
life
lift
light
like
limb
limit
link
lion
liquid
list
little
live
lizard
load
loan
lobster
local
lock
logic
lonely
long
loop
lottery
loud
lounge
love
loyal
lucky
luggage
lumber
lunar
lunch
luxury
lyrics
machine
mad
magic
magnet
maid
mail
main
major
make
mammal
man
manage
mandate
mango
mansion
manual
maple
marble
march
margin
marine
market
marriage
mask
mass
master
match
material
math
matrix
matter
maximum
maze
meadow
mean
measure
meat
mechanic
medal
media
melody
melt
member
memory
mention
menu
mercy
merge
merit
merry
mesh
message
metal
method
middle
midnight
milk
million
mimic
mind
minimum
minor
minute
miracle
mirror
misery
miss
mistake
mix
mixed
mixture
mobile
model
modify
mom
moment
monitor
monkey
monster
month
moon
moral
more
morning
mosquito
mother
motion
motor
mountain
mouse
move
movie
much
muffin
mule
multiply
muscle
museum
mushroom
music
must
mutual
myself
mystery
myth
naive
name
napkin
narrow
nasty
nation
nature
near
neck
need
negative
neglect
neither
nephew
nerve
nest
net
network
neutral
never
news
next
nice
night
noble
noise
nominee
noodle
normal
north
nose
notable
note
nothing
notice
novel
now
nuclear
number
nurse
nut
oak
obey
object
oblige
obscure
observe
obtain
obvious
occur
ocean
october
odor
off
offer
office
often
oil
okay
old
olive
olympic
omit
once
one
onion
online
only
open
opera
opinion
oppose
option
orange
orbit
orchard
order
ordinary
organ
orient
original
orphan
ostrich
other
outdoor
outer
output
outside
oval
oven
over
own
owner
oxygen
oyster
ozone
pact
paddle
page
pair
palace
palm
panda
panel
panic
panther
paper
parade
parent
park
parrot
party
pass
patch
path
patient
patrol
pattern
pause
pave
payment
peace
peanut
pear
peasant
pelican
pen
penalty
pencil
people
pepper
perfect
permit
person
pet
phone
photo
phrase
physical
piano
picnic
picture
piece
pig
pigeon
pill
pilot
pink
pioneer
pipe
pistol
pitch
pizza
place
planet
plastic
plate
play
please
pledge
pluck
plug
plunge
poem
poet
point
polar
pole
police
pond
pony
pool
popular
portion
position
possible
post
potato
pottery
poverty
powder
power
practice
praise
predict
prefer
prepare
present
pretty
prevent
price
pride
primary
print
priority
prison
private
prize
problem
process
produce
profit
program
project
promote
proof
property
prosper
protect
proud
provide
public
pudding
pull
pulp
pulse
pumpkin
punch
pupil
puppy
purchase
purity
purpose
purse
push
put
puzzle
pyramid
quality
quantum
quarter
question
quick
quit
quiz
quote
rabbit
raccoon
race
rack
radar
radio
rail
rain
raise
rally
ramp
ranch
random
range
rapid
rare
rate
rather
raven
raw
razor
ready
real
reason
rebel
rebuild
recall
receive
recipe
record
recycle
reduce
reflect
reform
refuse
region
regret
regular
reject
relax
release
relief
rely
remain
remember
remind
remove
render
renew
rent
reopen
repair
repeat
replace
report
require
rescue
resemble
resist
resource
response
result
retire
retreat
return
reunion
reveal
review
reward
rhythm
rib
ribbon
rice
rich
ride
ridge
rifle
right
rigid
ring
riot
ripple
risk
ritual
rival
river
road
roast
robot
robust
rocket
romance
roof
rookie
room
rose
rotate
rough
round
route
royal
rubber
rude
rug
rule
run
runway
rural
sad
saddle
sadness
safe
sail
salad
salmon
salon
salt
salute
same
sample
sand
satisfy
satoshi
sauce
sausage
save
say
scale
scan
scare
scatter
scene
scheme
school
science
scissors
scorpion
scout
scrap
screen
script
scrub
sea
search
season
seat
second
secret
section
security
seed
seek
segment
select
sell
seminar
senior
sense
sentence
series
service
session
settle
setup
seven
shadow
shaft
shallow
share
shed
shell
sheriff
shield
shift
shine
ship
shiver
shock
shoe
shoot
shop
short
shoulder
shove
shrimp
shrug
shuffle
shy
sibling
sick
side
siege
sight
sign
silent
silk
silly
silver
similar
simple
since
sing
siren
sister
situate
six
size
skate
sketch
ski
skill
skin
skirt
skull
slab
slam
sleep
slender
slice
slide
slight
slim
slogan
slot
slow
slush
small
smart
smile
smoke
smooth
snack
snake
snap
sniff
snow
soap
soccer
social
sock
soda
soft
solar
soldier
solid
solution
solve
someone
song
soon
sorry
sort
soul
sound
soup
source
south
space
spare
spatial
spawn
speak
special
speed
spell
spend
sphere
spice
spider
spike
spin
spirit
split
spoil
sponsor
spoon
sport
spot
spray
spread
spring
spy
square
squeeze
squirrel
stable
stadium
staff
stage
stairs
stamp
stand
start
state
stay
steak
steel
stem
step
stereo
stick
still
sting
stock
stomach
stone
stool
story
stove
strategy
street
strike
strong
struggle
student
stuff
stumble
style
subject
submit
subway
success
such
sudden
suffer
sugar
suggest
suit
summer
sun
sunny
sunset
super
supply
supreme
sure
surface
surge
surprise
surround
survey
suspect
sustain
swallow
swamp
swap
swarm
swear
sweet
swift
swim
swing
switch
sword
symbol
symptom
syrup
system
table
tackle
tag
tail
talent
talk
tank
tape
target
task
taste
tattoo
taxi
teach
team
tell
ten
tenant
tennis
tent
term
test
text
thank
that
theme
then
theory
there
they
thing
this
thought
three
thrive
throw
thumb
thunder
ticket
tide
tiger
tilt
timber
time
tiny
tip
tired
tissue
title
toast
tobacco
today
toddler
toe
together
toilet
token
tomato
tomorrow
tone
tongue
tonight
tool
tooth
top
topic
topple
torch
tornado
tortoise
toss
total
tourist
toward
tower
town
toy
track
trade
traffic
tragic
train
transfer
trap
trash
travel
tray
treat
tree
trend
trial
tribe
trick
trigger
trim
trip
trophy
trouble
truck
true
truly
trumpet
trust
truth
try
tube
tuition
tumble
tuna
tunnel
turkey
turn
turtle
twelve
twenty
twice
twin
twist
two
type
typical
ugly
umbrella
unable
unaware
uncle
uncover
under
undo
unfair
unfold
unhappy
uniform
unique
unit
universe
unknown
unlock
until
unusual
unveil
update
upgrade
uphold
upon
upper
upset
urban
urge
usage
use
used
useful
useless
usual
utility
vacant
vacuum
vague
valid
valley
valve
van
vanish
vapor
various
vast
vault
vehicle
velvet
vendor
venture
venue
verb
verify
version
very
vessel
veteran
viable
vibrant
vicious
victory
video
view
village
vintage
violin
virtual
virus
visa
visit
visual
vital
vivid
vocal
voice
void
volcano
volume
vote
voyage
wage
wagon
wait
walk
wall
walnut
want
warfare
warm
warrior
wash
wasp
waste
water
wave
way
wealth
weapon
wear
weasel
weather
web
wedding
weekend
weird
welcome
west
wet
whale
what
wheat
wheel
when
where
whip
whisper
wide
width
wife
wild
will
win
window
wine
wing
wink
winner
winter
wire
wisdom
wise
wish
witness
wolf
woman
wonder
wood
wool
word
work
world
worry
worth
wrap
wreck
wrestle
wrist
write
wrong
yard
year
yellow
you
young
youth
zebra
zero
zone
zoo`.split("\n");
}
});
// node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/_assert.js
var require_assert = __commonJS({
"node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/_assert.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.output = exports.exists = exports.hash = exports.bytes = exports.bool = exports.number = void 0;
function number2(n) {
if (!Number.isSafeInteger(n) || n < 0)
throw new Error(`Wrong positive integer: ${n}`);
}
exports.number = number2;
function bool2(b) {
if (typeof b !== "boolean")
throw new Error(`Expected boolean, not ${b}`);
}
exports.bool = bool2;
function bytes2(b, ...lengths) {
if (!(b instanceof Uint8Array))
throw new TypeError("Expected Uint8Array");
if (lengths.length > 0 && !lengths.includes(b.length))
throw new TypeError(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
}
exports.bytes = bytes2;
function hash2(hash3) {
if (typeof hash3 !== "function" || typeof hash3.create !== "function")
throw new Error("Hash should be wrapped by utils.wrapConstructor");
number2(hash3.outputLen);
number2(hash3.blockLen);
}
exports.hash = hash2;
function exists2(instance, checkFinished=true) {
if (instance.destroyed)
throw new Error("Hash instance has been destroyed");
if (checkFinished && instance.finished)
throw new Error("Hash#digest() has already been called");
}
exports.exists = exists2;
function output2(out, instance) {
bytes2(out);
const min = instance.outputLen;
if (out.length < min) {
throw new Error(`digestInto() expects output buffer of length at least ${min}`);
}
}
exports.output = output2;
var assert2 = {
number: number2,
bool: bool2,
bytes: bytes2,
hash: hash2,
exists: exists2,
output: output2
};
exports.default = assert2;
}
});
// node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/crypto.js
var require_crypto2 = __commonJS({
"node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/crypto.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.crypto = void 0;
exports.crypto = typeof globalThis === "object" && "crypto"in globalThis ? globalThis.crypto : void 0;
}
});
// node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/utils.js
var require_utils = __commonJS({
"node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/utils.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.randomBytes = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.checkOpts = exports.Hash = exports.concatBytes = exports.toBytes = exports.utf8ToBytes = exports.asyncLoop = exports.nextTick = exports.hexToBytes = exports.bytesToHex = exports.isLE = exports.rotr = exports.createView = exports.u32 = exports.u8 = void 0;
var crypto_1 = require_crypto2();
var u8 = (arr)=>new Uint8Array(arr.buffer,arr.byteOffset,arr.byteLength);
exports.u8 = u8;
var u32 = (arr)=>new Uint32Array(arr.buffer,arr.byteOffset,Math.floor(arr.byteLength / 4));
exports.u32 = u32;
var createView3 = (arr)=>new DataView(arr.buffer,arr.byteOffset,arr.byteLength);
exports.createView = createView3;
var rotr3 = (word,shift)=>word << 32 - shift | word >>> shift;
exports.rotr = rotr3;
exports.isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
if (!exports.isLE)
throw new Error("Non little-endian hardware is not supported");
var hexes5 = Array.from({
length: 256
}, (v,i)=>i.toString(16).padStart(2, "0"));
function bytesToHex4(uint8a) {
if (!(uint8a instanceof Uint8Array))
throw new Error("Uint8Array expected");
let hex2 = "";
for (let i = 0; i < uint8a.length; i++) {
hex2 += hexes5[uint8a[i]];
}
return hex2;
}
exports.bytesToHex = bytesToHex4;
function hexToBytes4(hex2) {
if (typeof hex2 !== "string") {
throw new TypeError("hexToBytes: expected string, got " + typeof hex2);
}
if (hex2.length % 2)
throw new Error("hexToBytes: received invalid unpadded hex");
const array = new Uint8Array(hex2.length / 2);
for (let i = 0; i < array.length; i++) {
const j = i * 2;
const hexByte = hex2.slice(j, j + 2);
const byte = Number.parseInt(hexByte, 16);
if (Number.isNaN(byte) || byte < 0)
throw new Error("Invalid byte sequence");
array[i] = byte;
}
return array;
}
exports.hexToBytes = hexToBytes4;
var nextTick2 = async()=>{}
;
exports.nextTick = nextTick2;
async function asyncLoop(iters, tick, cb) {
let ts = Date.now();
for (let i = 0; i < iters; i++) {
cb(i);
const diff = Date.now() - ts;
if (diff >= 0 && diff < tick)
continue;
await (0,
exports.nextTick)();
ts += diff;
}
}
exports.asyncLoop = asyncLoop;
function utf8ToBytes4(str) {
if (typeof str !== "string") {
throw new TypeError(`utf8ToBytes expected string, got ${typeof str}`);
}
return new TextEncoder().encode(str);
}
exports.utf8ToBytes = utf8ToBytes4;
function toBytes3(data) {
if (typeof data === "string")
data = utf8ToBytes4(data);
if (!(data instanceof Uint8Array))
throw new TypeError(`Expected input type is Uint8Array (got ${typeof data})`);
return data;
}
exports.toBytes = toBytes3;
function concatBytes4(...arrays) {
if (!arrays.every((a)=>a instanceof Uint8Array))
throw new Error("Uint8Array list expected");
if (arrays.length === 1)
return arrays[0];
const length = arrays.reduce((a,arr)=>a + arr.length, 0);
const result = new Uint8Array(length);
for (let i = 0, pad = 0; i < arrays.length; i++) {
const arr = arrays[i];
result.set(arr, pad);
pad += arr.length;
}
return result;
}
exports.concatBytes = concatBytes4;
var Hash3 = class {
// Safe version that clones internal state
clone() {
return this._cloneInto();
}
}
;
exports.Hash = Hash3;
var isPlainObject = (obj)=>Object.prototype.toString.call(obj) === "[object Object]" && obj.constructor === Object;
function checkOpts(defaults, opts) {
if (opts !== void 0 && (typeof opts !== "object" || !isPlainObject(opts)))
throw new TypeError("Options should be object or undefined");
const merged = Object.assign(defaults, opts);
return merged;
}
exports.checkOpts = checkOpts;
function wrapConstructor3(hashConstructor) {
const hashC = (message)=>hashConstructor().update(toBytes3(message)).digest();
const tmp = hashConstructor();
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = ()=>hashConstructor();
return hashC;
}
exports.wrapConstructor = wrapConstructor3;
function wrapConstructorWithOpts(hashCons) {
const hashC = (msg,opts)=>hashCons(opts).update(toBytes3(msg)).digest();
const tmp = hashCons({});
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = (opts)=>hashCons(opts);
return hashC;
}
exports.wrapConstructorWithOpts = wrapConstructorWithOpts;
function randomBytes3(bytesLength=32) {
if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === "function") {
return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));
}
throw new Error("crypto.getRandomValues must be defined");
}
exports.randomBytes = randomBytes3;
}
});
// node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/hmac.js
var require_hmac = __commonJS({
"node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/hmac.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.hmac = void 0;
var _assert_js_1 = require_assert();
var utils_js_1 = require_utils();
var HMAC3 = class extends utils_js_1.Hash {
constructor(hash2, _key) {
super();
this.finished = false;
this.destroyed = false;
_assert_js_1.default.hash(hash2);
const key = (0,
utils_js_1.toBytes)(_key);
this.iHash = hash2.create();
if (typeof this.iHash.update !== "function")
throw new TypeError("Expected instance of class which extends utils.Hash");
this.blockLen = this.iHash.blockLen;
this.outputLen = this.iHash.outputLen;
const blockLen = this.blockLen;
const pad = new Uint8Array(blockLen);
pad.set(key.length > blockLen ? hash2.create().update(key).digest() : key);
for (let i = 0; i < pad.length; i++)
pad[i] ^= 54;
this.iHash.update(pad);
this.oHash = hash2.create();
for (let i = 0; i < pad.length; i++)
pad[i] ^= 54 ^ 92;
this.oHash.update(pad);
pad.fill(0);
}
update(buf) {
_assert_js_1.default.exists(this);
this.iHash.update(buf);
return this;
}
digestInto(out) {
_assert_js_1.default.exists(this);
_assert_js_1.default.bytes(out, this.outputLen);
this.finished = true;
this.iHash.digestInto(out);
this.oHash.update(out);
this.oHash.digestInto(out);
this.destroy();
}
digest() {
const out = new Uint8Array(this.oHash.outputLen);
this.digestInto(out);
return out;
}
_cloneInto(to) {
to || (to = Object.create(Object.getPrototypeOf(this), {}));
const {oHash, iHash, finished, destroyed, blockLen, outputLen} = this;
to = to;
to.finished = finished;
to.destroyed = destroyed;
to.blockLen = blockLen;
to.outputLen = outputLen;
to.oHash = oHash._cloneInto(to.oHash);
to.iHash = iHash._cloneInto(to.iHash);
return to;
}
destroy() {
this.destroyed = true;
this.oHash.destroy();
this.iHash.destroy();
}
}
;
var hmac3 = (hash2,key,message)=>new HMAC3(hash2,key).update(message).digest();
exports.hmac = hmac3;
exports.hmac.create = (hash2,key)=>new HMAC3(hash2,key);
}
});
// node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/pbkdf2.js
var require_pbkdf2 = __commonJS({
"node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/pbkdf2.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.pbkdf2Async = exports.pbkdf2 = void 0;
var _assert_js_1 = require_assert();
var hmac_js_1 = require_hmac();
var utils_js_1 = require_utils();
function pbkdf2Init(hash2, _password, _salt, _opts) {
_assert_js_1.default.hash(hash2);
const opts = (0,
utils_js_1.checkOpts)({
dkLen: 32,
asyncTick: 10
}, _opts);
const {c, dkLen, asyncTick} = opts;
_assert_js_1.default.number(c);
_assert_js_1.default.number(dkLen);
_assert_js_1.default.number(asyncTick);
if (c < 1)
throw new Error("PBKDF2: iterations (c) should be >= 1");
const password = (0,
utils_js_1.toBytes)(_password);
const salt = (0,
utils_js_1.toBytes)(_salt);
const DK = new Uint8Array(dkLen);
const PRF = hmac_js_1.hmac.create(hash2, password);
const PRFSalt = PRF._cloneInto().update(salt);
return {
c,
dkLen,
asyncTick,
DK,
PRF,
PRFSalt
};
}
function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
PRF.destroy();
PRFSalt.destroy();
if (prfW)
prfW.destroy();
u.fill(0);
return DK;
}
function pbkdf2(hash2, password, salt, opts) {
const {c, dkLen, DK, PRF, PRFSalt} = pbkdf2Init(hash2, password, salt, opts);
let prfW;
const arr = new Uint8Array(4);
const view = (0,
utils_js_1.createView)(arr);
const u = new Uint8Array(PRF.outputLen);
for (let ti = 1, pos = 0; pos < dkLen; ti++,
pos += PRF.outputLen) {
const Ti = DK.subarray(pos, pos + PRF.outputLen);
view.setInt32(0, ti, false);
(prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
Ti.set(u.subarray(0, Ti.length));
for (let ui = 1; ui < c; ui++) {
PRF._cloneInto(prfW).update(u).digestInto(u);
for (let i = 0; i < Ti.length; i++)
Ti[i] ^= u[i];
}
}
return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
}
exports.pbkdf2 = pbkdf2;
async function pbkdf2Async(hash2, password, salt, opts) {
const {c, dkLen, asyncTick, DK, PRF, PRFSalt} = pbkdf2Init(hash2, password, salt, opts);
let prfW;
const arr = new Uint8Array(4);
const view = (0,
utils_js_1.createView)(arr);
const u = new Uint8Array(PRF.outputLen);
for (let ti = 1, pos = 0; pos < dkLen; ti++,
pos += PRF.outputLen) {
const Ti = DK.subarray(pos, pos + PRF.outputLen);
view.setInt32(0, ti, false);
(prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
Ti.set(u.subarray(0, Ti.length));
await (0,
utils_js_1.asyncLoop)(c - 1, asyncTick, (i)=>{
PRF._cloneInto(prfW).update(u).digestInto(u);
for (let i2 = 0; i2 < Ti.length; i2++)
Ti[i2] ^= u[i2];
}
);
}
return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
}
exports.pbkdf2Async = pbkdf2Async;
}
});
// node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/_sha2.js
var require_sha2 = __commonJS({
"node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/_sha2.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.SHA2 = void 0;
var _assert_js_1 = require_assert();
var utils_js_1 = require_utils();
function setBigUint643(view, byteOffset, value, isLE3) {
if (typeof view.setBigUint64 === "function")
return view.setBigUint64(byteOffset, value, isLE3);
const _32n2 = BigInt(32);
const _u32_max = BigInt(4294967295);
const wh = Number(value >> _32n2 & _u32_max);
const wl = Number(value & _u32_max);
const h = isLE3 ? 4 : 0;
const l = isLE3 ? 0 : 4;
view.setUint32(byteOffset + h, wh, isLE3);
view.setUint32(byteOffset + l, wl, isLE3);
}
var SHA23 = class extends utils_js_1.Hash {
constructor(blockLen, outputLen, padOffset, isLE3) {
super();
this.blockLen = blockLen;
this.outputLen = outputLen;
this.padOffset = padOffset;
this.isLE = isLE3;
this.finished = false;
this.length = 0;
this.pos = 0;
this.destroyed = false;
this.buffer = new Uint8Array(blockLen);
this.view = (0,
utils_js_1.createView)(this.buffer);
}
update(data) {
_assert_js_1.default.exists(this);
const {view, buffer, blockLen} = this;
data = (0,
utils_js_1.toBytes)(data);
const len = data.length;
for (let pos = 0; pos < len; ) {
const take = Math.min(blockLen - this.pos, len - pos);
if (take === blockLen) {
const dataView = (0,
utils_js_1.createView)(data);
for (; blockLen <= len - pos; pos += blockLen)
this.process(dataView, pos);
continue;
}
buffer.set(data.subarray(pos, pos + take), this.pos);
this.pos += take;
pos += take;
if (this.pos === blockLen) {
this.process(view, 0);
this.pos = 0;
}
}
this.length += data.length;
this.roundClean();
return this;
}
digestInto(out) {
_assert_js_1.default.exists(this);
_assert_js_1.default.output(out, this);
this.finished = true;
const {buffer, view, blockLen, isLE: isLE3} = this;
let {pos} = this;
buffer[pos++] = 128;
this.buffer.subarray(pos).fill(0);
if (this.padOffset > blockLen - pos) {
this.process(view, 0);
pos = 0;
}
for (let i = pos; i < blockLen; i++)
buffer[i] = 0;
setBigUint643(view, blockLen - 8, BigInt(this.length * 8), isLE3);
this.process(view, 0);
const oview = (0,
utils_js_1.createView)(out);
const len = this.outputLen;
if (len % 4)
throw new Error("_sha2: outputLen should be aligned to 32bit");
const outLen = len / 4;
const state = this.get();
if (outLen > state.length)
throw new Error("_sha2: outputLen bigger than state");
for (let i = 0; i < outLen; i++)
oview.setUint32(4 * i, state[i], isLE3);
}
digest() {
const {buffer, outputLen} = this;
this.digestInto(buffer);
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
_cloneInto(to) {
to || (to = new this.constructor());
to.set(...this.get());
const {blockLen, buffer, length, finished, destroyed, pos} = this;
to.length = length;
to.pos = pos;
to.finished = finished;
to.destroyed = destroyed;
if (length % blockLen)
to.buffer.set(buffer);
return to;
}
}
;
exports.SHA2 = SHA23;
}
});
// node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/sha256.js
var require_sha256 = __commonJS({
"node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/sha256.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.sha224 = exports.sha256 = void 0;
var _sha2_js_1 = require_sha2();
var utils_js_1 = require_utils();
var Chi3 = (a,b,c)=>a & b ^ ~a & c;
var Maj3 = (a,b,c)=>a & b ^ a & c ^ b & c;
var SHA256_K3 = new Uint32Array([1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298]);
var IV3 = new Uint32Array([1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225]);
var SHA256_W3 = new Uint32Array(64);
var SHA2563 = class extends _sha2_js_1.SHA2 {
constructor() {
super(64, 32, 8, false);
this.A = IV3[0] | 0;
this.B = IV3[1] | 0;
this.C = IV3[2] | 0;
this.D = IV3[3] | 0;
this.E = IV3[4] | 0;
this.F = IV3[5] | 0;
this.G = IV3[6] | 0;
this.H = IV3[7] | 0;
}
get() {
const {A, B, C, D, E, F, G, H} = this;
return [A, B, C, D, E, F, G, H];
}
// prettier-ignore
set(A, B, C, D, E, F, G, H) {
this.A = A | 0;
this.B = B | 0;
this.C = C | 0;
this.D = D | 0;
this.E = E | 0;
this.F = F | 0;
this.G = G | 0;
this.H = H | 0;
}
process(view, offset) {
for (let i = 0; i < 16; i++,
offset += 4)
SHA256_W3[i] = view.getUint32(offset, false);
for (let i = 16; i < 64; i++) {
const W15 = SHA256_W3[i - 15];
const W2 = SHA256_W3[i - 2];
const s0 = (0,
utils_js_1.rotr)(W15, 7) ^ (0,
utils_js_1.rotr)(W15, 18) ^ W15 >>> 3;
const s1 = (0,
utils_js_1.rotr)(W2, 17) ^ (0,
utils_js_1.rotr)(W2, 19) ^ W2 >>> 10;
SHA256_W3[i] = s1 + SHA256_W3[i - 7] + s0 + SHA256_W3[i - 16] | 0;
}
let {A, B, C, D, E, F, G, H} = this;
for (let i = 0; i < 64; i++) {
const sigma1 = (0,
utils_js_1.rotr)(E, 6) ^ (0,
utils_js_1.rotr)(E, 11) ^ (0,
utils_js_1.rotr)(E, 25);
const T1 = H + sigma1 + Chi3(E, F, G) + SHA256_K3[i] + SHA256_W3[i] | 0;
const sigma0 = (0,
utils_js_1.rotr)(A, 2) ^ (0,
utils_js_1.rotr)(A, 13) ^ (0,
utils_js_1.rotr)(A, 22);
const T2 = sigma0 + Maj3(A, B, C) | 0;
H = G;
G = F;
F = E;
E = D + T1 | 0;
D = C;
C = B;
B = A;
A = T1 + T2 | 0;
}
A = A + this.A | 0;
B = B + this.B | 0;
C = C + this.C | 0;
D = D + this.D | 0;
E = E + this.E | 0;
F = F + this.F | 0;
G = G + this.G | 0;
H = H + this.H | 0;
this.set(A, B, C, D, E, F, G, H);
}
roundClean() {
SHA256_W3.fill(0);
}
destroy() {
this.set(0, 0, 0, 0, 0, 0, 0, 0);
this.buffer.fill(0);
}
}
;
var SHA2242 = class extends SHA2563 {
constructor() {
super();
this.A = 3238371032 | 0;
this.B = 914150663 | 0;
this.C = 812702999 | 0;
this.D = 4144912697 | 0;
this.E = 4290775857 | 0;
this.F = 1750603025 | 0;
this.G = 1694076839 | 0;
this.H = 3204075428 | 0;
this.outputLen = 28;
}
}
;
exports.sha256 = (0,
utils_js_1.wrapConstructor)(()=>new SHA2563());
exports.sha224 = (0,
utils_js_1.wrapConstructor)(()=>new SHA2242());
}
});
// node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/_u64.js
var require_u64 = __commonJS({
"node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/_u64.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.add = exports.toBig = exports.split = exports.fromBig = void 0;
var U32_MASK642 = BigInt(2 ** 32 - 1);
var _32n2 = BigInt(32);
function fromBig2(n, le=false) {
if (le)
return {
h: Number(n & U32_MASK642),
l: Number(n >> _32n2 & U32_MASK642)
};
return {
h: Number(n >> _32n2 & U32_MASK642) | 0,
l: Number(n & U32_MASK642) | 0
};
}
exports.fromBig = fromBig2;
function split2(lst, le=false) {
let Ah = new Uint32Array(lst.length);
let Al = new Uint32Array(lst.length);
for (let i = 0; i < lst.length; i++) {
const {h, l} = fromBig2(lst[i], le);
[Ah[i],Al[i]] = [h, l];
}
return [Ah, Al];
}
exports.split = split2;
var toBig2 = (h,l)=>BigInt(h >>> 0) << _32n2 | BigInt(l >>> 0);
exports.toBig = toBig2;
var shrSH2 = (h,l,s)=>h >>> s;
var shrSL2 = (h,l,s)=>h << 32 - s | l >>> s;
var rotrSH2 = (h,l,s)=>h >>> s | l << 32 - s;
var rotrSL2 = (h,l,s)=>h << 32 - s | l >>> s;
var rotrBH2 = (h,l,s)=>h << 64 - s | l >>> s - 32;
var rotrBL2 = (h,l,s)=>h >>> s - 32 | l << 64 - s;
var rotr32H2 = (h,l)=>l;
var rotr32L2 = (h,l)=>h;
var rotlSH2 = (h,l,s)=>h << s | l >>> 32 - s;
var rotlSL2 = (h,l,s)=>l << s | h >>> 32 - s;
var rotlBH2 = (h,l,s)=>l << s - 32 | h >>> 64 - s;
var rotlBL2 = (h,l,s)=>h << s - 32 | l >>> 64 - s;
function add2(Ah, Al, Bh, Bl) {
const l = (Al >>> 0) + (Bl >>> 0);
return {
h: Ah + Bh + (l / 2 ** 32 | 0) | 0,
l: l | 0
};
}
exports.add = add2;
var add3L2 = (Al,Bl,Cl)=>(Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
var add3H2 = (low,Ah,Bh,Ch)=>Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
var add4L2 = (Al,Bl,Cl,Dl)=>(Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
var add4H2 = (low,Ah,Bh,Ch,Dh)=>Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
var add5L2 = (Al,Bl,Cl,Dl,El)=>(Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
var add5H2 = (low,Ah,Bh,Ch,Dh,Eh)=>Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
var u642 = {
fromBig: fromBig2,
split: split2,
toBig: exports.toBig,
shrSH: shrSH2,
shrSL: shrSL2,
rotrSH: rotrSH2,
rotrSL: rotrSL2,
rotrBH: rotrBH2,
rotrBL: rotrBL2,
rotr32H: rotr32H2,
rotr32L: rotr32L2,
rotlSH: rotlSH2,
rotlSL: rotlSL2,
rotlBH: rotlBH2,
rotlBL: rotlBL2,
add: add2,
add3L: add3L2,
add3H: add3H2,
add4L: add4L2,
add4H: add4H2,
add5H: add5H2,
add5L: add5L2
};
exports.default = u642;
}
});
// node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/sha512.js
var require_sha512 = __commonJS({
"node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/sha512.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.sha384 = exports.sha512_256 = exports.sha512_224 = exports.sha512 = exports.SHA512 = void 0;
var _sha2_js_1 = require_sha2();
var _u64_js_1 = require_u64();
var utils_js_1 = require_utils();
var [SHA512_Kh2,SHA512_Kl2] = _u64_js_1.default.split(["0x428a2f98d728ae22", "0x7137449123ef65cd", "0xb5c0fbcfec4d3b2f", "0xe9b5dba58189dbbc", "0x3956c25bf348b538", "0x59f111f1b605d019", "0x923f82a4af194f9b", "0xab1c5ed5da6d8118", "0xd807aa98a3030242", "0x12835b0145706fbe", "0x243185be4ee4b28c", "0x550c7dc3d5ffb4e2", "0x72be5d74f27b896f", "0x80deb1fe3b1696b1", "0x9bdc06a725c71235", "0xc19bf174cf692694", "0xe49b69c19ef14ad2", "0xefbe4786384f25e3", "0x0fc19dc68b8cd5b5", "0x240ca1cc77ac9c65", "0x2de92c6f592b0275", "0x4a7484aa6ea6e483", "0x5cb0a9dcbd41fbd4", "0x76f988da831153b5", "0x983e5152ee66dfab", "0xa831c66d2db43210", "0xb00327c898fb213f", "0xbf597fc7beef0ee4", "0xc6e00bf33da88fc2", "0xd5a79147930aa725", "0x06ca6351e003826f", "0x142929670a0e6e70", "0x27b70a8546d22ffc", "0x2e1b21385c26c926", "0x4d2c6dfc5ac42aed", "0x53380d139d95b3df", "0x650a73548baf63de", "0x766a0abb3c77b2a8", "0x81c2c92e47edaee6", "0x92722c851482353b", "0xa2bfe8a14cf10364", "0xa81a664bbc423001", "0xc24b8b70d0f89791", "0xc76c51a30654be30", "0xd192e819d6ef5218", "0xd69906245565a910", "0xf40e35855771202a", "0x106aa07032bbd1b8", "0x19a4c116b8d2d0c8", "0x1e376c085141ab53", "0x2748774cdf8eeb99", "0x34b0bcb5e19b48a8", "0x391c0cb3c5c95a63", "0x4ed8aa4ae3418acb", "0x5b9cca4f7763e373", "0x682e6ff3d6b2b8a3", "0x748f82ee5defb2fc", "0x78a5636f43172f60", "0x84c87814a1f0ab72", "0x8cc702081a6439ec", "0x90befffa23631e28", "0xa4506cebde82bde9", "0xbef9a3f7b2c67915", "0xc67178f2e372532b", "0xca273eceea26619c", "0xd186b8c721c0c207", "0xeada7dd6cde0eb1e", "0xf57d4f7fee6ed178", "0x06f067aa72176fba", "0x0a637dc5a2c898a6", "0x113f9804bef90dae", "0x1b710b35131c471b", "0x28db77f523047d84", "0x32caab7b40c72493", "0x3c9ebe0a15c9bebc", "0x431d67c49c100d4c", "0x4cc5d4becb3e42b6", "0x597f299cfc657e2a", "0x5fcb6fab3ad6faec", "0x6c44198c4a475817"].map((n)=>BigInt(n)));
var SHA512_W_H2 = new Uint32Array(80);
var SHA512_W_L2 = new Uint32Array(80);
var SHA5122 = class extends _sha2_js_1.SHA2 {
constructor() {
super(128, 64, 16, false);
this.Ah = 1779033703 | 0;
this.Al = 4089235720 | 0;
this.Bh = 3144134277 | 0;
this.Bl = 2227873595 | 0;
this.Ch = 1013904242 | 0;
this.Cl = 4271175723 | 0;
this.Dh = 2773480762 | 0;
this.Dl = 1595750129 | 0;
this.Eh = 1359893119 | 0;
this.El = 2917565137 | 0;
this.Fh = 2600822924 | 0;
this.Fl = 725511199 | 0;
this.Gh = 528734635 | 0;
this.Gl = 4215389547 | 0;
this.Hh = 1541459225 | 0;
this.Hl = 327033209 | 0;
}
// prettier-ignore
get() {
const {Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl} = this;
return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
}
// prettier-ignore
set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
this.Ah = Ah | 0;
this.Al = Al | 0;
this.Bh = Bh | 0;
this.Bl = Bl | 0;
this.Ch = Ch | 0;
this.Cl = Cl | 0;
this.Dh = Dh | 0;
this.Dl = Dl | 0;
this.Eh = Eh | 0;
this.El = El | 0;
this.Fh = Fh | 0;
this.Fl = Fl | 0;
this.Gh = Gh | 0;
this.Gl = Gl | 0;
this.Hh = Hh | 0;
this.Hl = Hl | 0;
}
process(view, offset) {
for (let i = 0; i < 16; i++,
offset += 4) {
SHA512_W_H2[i] = view.getUint32(offset);
SHA512_W_L2[i] = view.getUint32(offset += 4);
}
for (let i = 16; i < 80; i++) {
const W15h = SHA512_W_H2[i - 15] | 0;
const W15l = SHA512_W_L2[i - 15] | 0;
const s0h = _u64_js_1.default.rotrSH(W15h, W15l, 1) ^ _u64_js_1.default.rotrSH(W15h, W15l, 8) ^ _u64_js_1.default.shrSH(W15h, W15l, 7);
const s0l = _u64_js_1.default.rotrSL(W15h, W15l, 1) ^ _u64_js_1.default.rotrSL(W15h, W15l, 8) ^ _u64_js_1.default.shrSL(W15h, W15l, 7);
const W2h = SHA512_W_H2[i - 2] | 0;
const W2l = SHA512_W_L2[i - 2] | 0;
const s1h = _u64_js_1.default.rotrSH(W2h, W2l, 19) ^ _u64_js_1.default.rotrBH(W2h, W2l, 61) ^ _u64_js_1.default.shrSH(W2h, W2l, 6);
const s1l = _u64_js_1.default.rotrSL(W2h, W2l, 19) ^ _u64_js_1.default.rotrBL(W2h, W2l, 61) ^ _u64_js_1.default.shrSL(W2h, W2l, 6);
const SUMl = _u64_js_1.default.add4L(s0l, s1l, SHA512_W_L2[i - 7], SHA512_W_L2[i - 16]);
const SUMh = _u64_js_1.default.add4H(SUMl, s0h, s1h, SHA512_W_H2[i - 7], SHA512_W_H2[i - 16]);
SHA512_W_H2[i] = SUMh | 0;
SHA512_W_L2[i] = SUMl | 0;
}
let {Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl} = this;
for (let i = 0; i < 80; i++) {
const sigma1h = _u64_js_1.default.rotrSH(Eh, El, 14) ^ _u64_js_1.default.rotrSH(Eh, El, 18) ^ _u64_js_1.default.rotrBH(Eh, El, 41);
const sigma1l = _u64_js_1.default.rotrSL(Eh, El, 14) ^ _u64_js_1.default.rotrSL(Eh, El, 18) ^ _u64_js_1.default.rotrBL(Eh, El, 41);
const CHIh = Eh & Fh ^ ~Eh & Gh;
const CHIl = El & Fl ^ ~El & Gl;
const T1ll = _u64_js_1.default.add5L(Hl, sigma1l, CHIl, SHA512_Kl2[i], SHA512_W_L2[i]);
const T1h = _u64_js_1.default.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh2[i], SHA512_W_H2[i]);
const T1l = T1ll | 0;
const sigma0h = _u64_js_1.default.rotrSH(Ah, Al, 28) ^ _u64_js_1.default.rotrBH(Ah, Al, 34) ^ _u64_js_1.default.rotrBH(Ah, Al, 39);
const sigma0l = _u64_js_1.default.rotrSL(Ah, Al, 28) ^ _u64_js_1.default.rotrBL(Ah, Al, 34) ^ _u64_js_1.default.rotrBL(Ah, Al, 39);
const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
Hh = Gh | 0;
Hl = Gl | 0;
Gh = Fh | 0;
Gl = Fl | 0;
Fh = Eh | 0;
Fl = El | 0;
({h: Eh, l: El} = _u64_js_1.default.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
Dh = Ch | 0;
Dl = Cl | 0;
Ch = Bh | 0;
Cl = Bl | 0;
Bh = Ah | 0;
Bl = Al | 0;
const All = _u64_js_1.default.add3L(T1l, sigma0l, MAJl);
Ah = _u64_js_1.default.add3H(All, T1h, sigma0h, MAJh);
Al = All | 0;
}
({h: Ah, l: Al} = _u64_js_1.default.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
({h: Bh, l: Bl} = _u64_js_1.default.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
({h: Ch, l: Cl} = _u64_js_1.default.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
({h: Dh, l: Dl} = _u64_js_1.default.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
({h: Eh, l: El} = _u64_js_1.default.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
({h: Fh, l: Fl} = _u64_js_1.default.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
({h: Gh, l: Gl} = _u64_js_1.default.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
({h: Hh, l: Hl} = _u64_js_1.default.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
}
roundClean() {
SHA512_W_H2.fill(0);
SHA512_W_L2.fill(0);
}
destroy() {
this.buffer.fill(0);
this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
}
;
exports.SHA512 = SHA5122;
var SHA512_2242 = class extends SHA5122 {
constructor() {
super();
this.Ah = 2352822216 | 0;
this.Al = 424955298 | 0;
this.Bh = 1944164710 | 0;
this.Bl = 2312950998 | 0;
this.Ch = 502970286 | 0;
this.Cl = 855612546 | 0;
this.Dh = 1738396948 | 0;
this.Dl = 1479516111 | 0;
this.Eh = 258812777 | 0;
this.El = 2077511080 | 0;
this.Fh = 2011393907 | 0;
this.Fl = 79989058 | 0;
this.Gh = 1067287976 | 0;
this.Gl = 1780299464 | 0;
this.Hh = 286451373 | 0;
this.Hl = 2446758561 | 0;
this.outputLen = 28;
}
}
;
var SHA512_2562 = class extends SHA5122 {
constructor() {
super();
this.Ah = 573645204 | 0;
this.Al = 4230739756 | 0;
this.Bh = 2673172387 | 0;
this.Bl = 3360449730 | 0;
this.Ch = 596883563 | 0;
this.Cl = 1867755857 | 0;
this.Dh = 2520282905 | 0;
this.Dl = 1497426621 | 0;
this.Eh = 2519219938 | 0;
this.El = 2827943907 | 0;
this.Fh = 3193839141 | 0;
this.Fl = 1401305490 | 0;
this.Gh = 721525244 | 0;
this.Gl = 746961066 | 0;
this.Hh = 246885852 | 0;
this.Hl = 2177182882 | 0;
this.outputLen = 32;
}
}
;
var SHA3842 = class extends SHA5122 {
constructor() {
super();
this.Ah = 3418070365 | 0;
this.Al = 3238371032 | 0;
this.Bh = 1654270250 | 0;
this.Bl = 914150663 | 0;
this.Ch = 2438529370 | 0;
this.Cl = 812702999 | 0;
this.Dh = 355462360 | 0;
this.Dl = 4144912697 | 0;
this.Eh = 1731405415 | 0;
this.El = 4290775857 | 0;
this.Fh = 2394180231 | 0;
this.Fl = 1750603025 | 0;
this.Gh = 3675008525 | 0;
this.Gl = 1694076839 | 0;
this.Hh = 1203062813 | 0;
this.Hl = 3204075428 | 0;
this.outputLen = 48;
}
}
;
exports.sha512 = (0,
utils_js_1.wrapConstructor)(()=>new SHA5122());
exports.sha512_224 = (0,
utils_js_1.wrapConstructor)(()=>new SHA512_2242());
exports.sha512_256 = (0,
utils_js_1.wrapConstructor)(()=>new SHA512_2562());
exports.sha384 = (0,
utils_js_1.wrapConstructor)(()=>new SHA3842());
}
});
// node_modules/.pnpm/@scure+base@1.1.1/node_modules/@scure/base/lib/index.js
var require_lib = __commonJS({
"node_modules/.pnpm/@scure+base@1.1.1/node_modules/@scure/base/lib/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.bytes = exports.stringToBytes = exports.str = exports.bytesToString = exports.hex = exports.utf8 = exports.bech32m = exports.bech32 = exports.base58check = exports.base58xmr = exports.base58xrp = exports.base58flickr = exports.base58 = exports.base64url = exports.base64 = exports.base32crockford = exports.base32hex = exports.base32 = exports.base16 = exports.utils = exports.assertNumber = void 0;
function assertNumber3(n) {
if (!Number.isSafeInteger(n))
throw new Error(`Wrong integer: ${n}`);
}
exports.assertNumber = assertNumber3;
function chain2(...args) {
const wrap = (a,b)=>(c)=>a(b(c));
const encode = Array.from(args).reverse().reduce((acc,i)=>acc ? wrap(acc, i.encode) : i.encode, void 0);
const decode2 = args.reduce((acc,i)=>acc ? wrap(acc, i.decode) : i.decode, void 0);
return {
encode,
decode: decode2
};
}
function alphabet2(alphabet3) {
return {
encode: (digits)=>{
if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number")
throw new Error("alphabet.encode input should be an array of numbers");
return digits.map((i)=>{
assertNumber3(i);
if (i < 0 || i >= alphabet3.length)
throw new Error(`Digit index outside alphabet: ${i} (alphabet: ${alphabet3.length})`);
return alphabet3[i];
}
);
}
,
decode: (input)=>{
if (!Array.isArray(input) || input.length && typeof input[0] !== "string")
throw new Error("alphabet.decode input should be array of strings");
return input.map((letter)=>{
if (typeof letter !== "string")
throw new Error(`alphabet.decode: not string element=${letter}`);
const index = alphabet3.indexOf(letter);
if (index === -1)
throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet3}`);
return index;
}
);
}
};
}
function join2(separator="") {
if (typeof separator !== "string")
throw new Error("join separator should be string");
return {
encode: (from)=>{
if (!Array.isArray(from) || from.length && typeof from[0] !== "string")
throw new Error("join.encode input should be array of strings");
for (let i of from)
if (typeof i !== "string")
throw new Error(`join.encode: non-string input=${i}`);
return from.join(separator);
}
,
decode: (to)=>{
if (typeof to !== "string")
throw new Error("join.decode input should be string");
return to.split(separator);
}
};
}
function padding2(bits, chr="=") {
assertNumber3(bits);
if (typeof chr !== "string")
throw new Error("padding chr should be string");
return {
encode(data) {
if (!Array.isArray(data) || data.length && typeof data[0] !== "string")
throw new Error("padding.encode input should be array of strings");
for (let i of data)
if (typeof i !== "string")
throw new Error(`padding.encode: non-string input=${i}`);
while (data.length * bits % 8)
data.push(chr);
return data;
},
decode(input) {
if (!Array.isArray(input) || input.length && typeof input[0] !== "string")
throw new Error("padding.encode input should be array of strings");
for (let i of input)
if (typeof i !== "string")
throw new Error(`padding.decode: non-string input=${i}`);
let end = input.length;
if (end * bits % 8)
throw new Error("Invalid padding: string should have whole number of bytes");
for (; end > 0 && input[end - 1] === chr; end--) {
if (!((end - 1) * bits % 8))
throw new Error("Invalid padding: string has too much padding");
}
return input.slice(0, end);
}
};
}
function normalize2(fn) {
if (typeof fn !== "function")
throw new Error("normalize fn should be function");
return {
encode: (from)=>from,
decode: (to)=>fn(to)
};
}
function convertRadix3(data, from, to) {
if (from < 2)
throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`);
if (to < 2)
throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`);
if (!Array.isArray(data))
throw new Error("convertRadix: data should be array");
if (!data.length)
return [];
let pos = 0;
const res = [];
const digits = Array.from(data);
digits.forEach((d)=>{
assertNumber3(d);
if (d < 0 || d >= from)
throw new Error(`Wrong integer: ${d}`);
}
);
while (true) {
let carry = 0;
let done = true;
for (let i = pos; i < digits.length; i++) {
const digit = digits[i];
const digitBase = from * carry + digit;
if (!Number.isSafeInteger(digitBase) || from * carry / from !== carry || digitBase - digit !== from * carry) {
throw new Error("convertRadix: carry overflow");
}
carry = digitBase % to;
digits[i] = Math.floor(digitBase / to);
if (!Number.isSafeInteger(digits[i]) || digits[i] * to + carry !== digitBase)
throw new Error("convertRadix: carry overflow");
if (!done)
continue;
else if (!digits[i])
pos = i;
else
done = false;
}
res.push(carry);
if (done)
break;
}
for (let i = 0; i < data.length - 1 && data[i] === 0; i++)
res.push(0);
return res.reverse();
}
var gcd2 = (a,b)=>!b ? a : gcd2(b, a % b);
var radix2carry2 = (from,to)=>from + (to - gcd2(from, to));
function convertRadix22(data, from, to, padding3) {
if (!Array.isArray(data))
throw new Error("convertRadix2: data should be array");
if (from <= 0 || from > 32)
throw new Error(`convertRadix2: wrong from=${from}`);
if (to <= 0 || to > 32)
throw new Error(`convertRadix2: wrong to=${to}`);
if (radix2carry2(from, to) > 32) {
throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry2(from, to)}`);
}
let carry = 0;
let pos = 0;
const mask = 2 ** to - 1;
const res = [];
for (const n of data) {
assertNumber3(n);
if (n >= 2 ** from)
throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);
carry = carry << from | n;
if (pos + from > 32)
throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);
pos += from;
for (; pos >= to; pos -= to)
res.push((carry >> pos - to & mask) >>> 0);
carry &= 2 ** pos - 1;
}
carry = carry << to - pos & mask;
if (!padding3 && pos >= from)
throw new Error("Excess padding");
if (!padding3 && carry)
throw new Error(`Non-zero padding: ${carry}`);
if (padding3 && pos > 0)
res.push(carry >>> 0);
return res;
}
function radix3(num) {
assertNumber3(num);
return {
encode: (bytes2)=>{
if (!(bytes2 instanceof Uint8Array))
throw new Error("radix.encode input should be Uint8Array");
return convertRadix3(Array.from(bytes2), 2 ** 8, num);
}
,
decode: (digits)=>{
if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number")
throw new Error("radix.decode input should be array of strings");
return Uint8Array.from(convertRadix3(digits, num, 2 ** 8));
}
};
}
function radix22(bits, revPadding=false) {
assertNumber3(bits);
if (bits <= 0 || bits > 32)
throw new Error("radix2: bits should be in (0..32]");
if (radix2carry2(8, bits) > 32 || radix2carry2(bits, 8) > 32)
throw new Error("radix2: carry overflow");
return {
encode: (bytes2)=>{
if (!(bytes2 instanceof Uint8Array))
throw new Error("radix2.encode input should be Uint8Array");
return convertRadix22(Array.from(bytes2), 8, bits, !revPadding);
}
,
decode: (digits)=>{
if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number")
throw new Error("radix2.decode input should be array of strings");
return Uint8Array.from(convertRadix22(digits, bits, 8, revPadding));
}
};
}
function unsafeWrapper2(fn) {
if (typeof fn !== "function")
throw new Error("unsafeWrapper fn should be function");
return function(...args) {
try {
return fn.apply(null, args);
} catch (e) {}
}
;
}
function checksum2(len, fn) {
assertNumber3(len);
if (typeof fn !== "function")
throw new Error("checksum fn should be function");
return {
encode(data) {
if (!(data instanceof Uint8Array))
throw new Error("checksum.encode: input should be Uint8Array");
const checksum3 = fn(data).slice(0, len);
const res = new Uint8Array(data.length + len);
res.set(data);
res.set(checksum3, data.length);
return res;
},
decode(data) {
if (!(data instanceof Uint8Array))
throw new Error("checksum.decode: input should be Uint8Array");
const payload = data.slice(0, -len);
const newChecksum = fn(payload).slice(0, len);
const oldChecksum = data.slice(-len);
for (let i = 0; i < len; i++)
if (newChecksum[i] !== oldChecksum[i])
throw new Error("Invalid checksum");
return payload;
}
};
}
exports.utils = {
alphabet: alphabet2,
chain: chain2,
checksum: checksum2,
radix: radix3,
radix2: radix22,
join: join2,
padding: padding2
};
exports.base16 = chain2(radix22(4), alphabet2("0123456789ABCDEF"), join2(""));
exports.base32 = chain2(radix22(5), alphabet2("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), padding2(5), join2(""));
exports.base32hex = chain2(radix22(5), alphabet2("0123456789ABCDEFGHIJKLMNOPQRSTUV"), padding2(5), join2(""));
exports.base32crockford = chain2(radix22(5), alphabet2("0123456789ABCDEFGHJKMNPQRSTVWXYZ"), join2(""), normalize2((s)=>s.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1")));
exports.base64 = chain2(radix22(6), alphabet2("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), padding2(6), join2(""));
exports.base64url = chain2(radix22(6), alphabet2("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), padding2(6), join2(""));
var genBase582 = (abc)=>chain2(radix3(58), alphabet2(abc), join2(""));
exports.base58 = genBase582("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
exports.base58flickr = genBase582("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ");
exports.base58xrp = genBase582("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");
var XMR_BLOCK_LEN2 = [0, 2, 3, 5, 6, 7, 9, 10, 11];
exports.base58xmr = {
encode(data) {
let res = "";
for (let i = 0; i < data.length; i += 8) {
const block = data.subarray(i, i + 8);
res += exports.base58.encode(block).padStart(XMR_BLOCK_LEN2[block.length], "1");
}
return res;
},
decode(str) {
let res = [];
for (let i = 0; i < str.length; i += 11) {
const slice = str.slice(i, i + 11);
const blockLen = XMR_BLOCK_LEN2.indexOf(slice.length);
const block = exports.base58.decode(slice);
for (let j = 0; j < block.length - blockLen; j++) {
if (block[j] !== 0)
throw new Error("base58xmr: wrong padding");
}
res = res.concat(Array.from(block.slice(block.length - blockLen)));
}
return Uint8Array.from(res);
}
};
var base58check3 = (sha2563)=>chain2(checksum2(4, (data)=>sha2563(sha2563(data))), exports.base58);
exports.base58check = base58check3;
var BECH_ALPHABET2 = chain2(alphabet2("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), join2(""));
var POLYMOD_GENERATORS2 = [996825010, 642813549, 513874426, 1027748829, 705979059];
function bech32Polymod2(pre) {
const b = pre >> 25;
let chk = (pre & 33554431) << 5;
for (let i = 0; i < POLYMOD_GENERATORS2.length; i++) {
if ((b >> i & 1) === 1)
chk ^= POLYMOD_GENERATORS2[i];
}
return chk;
}
function bechChecksum2(prefix, words, encodingConst=1) {
const len = prefix.length;
let chk = 1;
for (let i = 0; i < len; i++) {
const c = prefix.charCodeAt(i);
if (c < 33 || c > 126)
throw new Error(`Invalid prefix (${prefix})`);
chk = bech32Polymod2(chk) ^ c >> 5;
}
chk = bech32Polymod2(chk);
for (let i = 0; i < len; i++)
chk = bech32Polymod2(chk) ^ prefix.charCodeAt(i) & 31;
for (let v of words)
chk = bech32Polymod2(chk) ^ v;
for (let i = 0; i < 6; i++)
chk = bech32Polymod2(chk);
chk ^= encodingConst;
return BECH_ALPHABET2.encode(convertRadix22([chk % 2 ** 30], 30, 5, false));
}
function genBech322(encoding) {
const ENCODING_CONST = encoding === "bech32" ? 1 : 734539939;
const _words = radix22(5);
const fromWords = _words.decode;
const toWords = _words.encode;
const fromWordsUnsafe = unsafeWrapper2(fromWords);
function encode(prefix, words, limit=90) {
if (typeof prefix !== "string")
throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`);
if (!Array.isArray(words) || words.length && typeof words[0] !== "number")
throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`);
const actualLength = prefix.length + 7 + words.length;
if (limit !== false && actualLength > limit)
throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);
prefix = prefix.toLowerCase();
return `${prefix}1 ${BECH_ALPHABET2.encode(words)}${bechChecksum2(prefix, words, ENCODING_CONST)}`;
}
function decode2(str, limit=90) {
if (typeof str !== "string")
throw new Error(`bech32.decode input should be string, not ${typeof str}`);
if (str.length < 8 || limit !== false && str.length > limit)
throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`);
const lowered = str.toLowerCase();
if (str !== lowered && str !== str.toUpperCase())
throw new Error(`String must be lowercase or uppercase`);
str = lowered;
const sepIndex = str.lastIndexOf("1");
if (sepIndex === 0 || sepIndex === -1)
throw new Error(`Letter "1" must be present between prefix and data only`);
const prefix = str.slice(0, sepIndex);
const _words2 = str.slice(sepIndex + 1);
if (_words2.length < 6)
throw new Error("Data must be at least 6 characters long");
const words = BECH_ALPHABET2.decode(_words2).slice(0, -6);
const sum = bechChecksum2(prefix, words, ENCODING_CONST);
if (!_words2.endsWith(sum))
throw new Error(`Invalid checksum in ${str}: expected "${sum}"`);
return {
prefix,
words
};
}
const decodeUnsafe = unsafeWrapper2(decode2);
function decodeToBytes(str) {
const {prefix, words} = decode2(str, false);
return {
prefix,
words,
bytes: fromWords(words)
};
}
return {
encode,
decode: decode2,
decodeToBytes,
decodeUnsafe,
fromWords,
fromWordsUnsafe,
toWords
};
}
exports.bech32 = genBech322("bech32");
exports.bech32m = genBech322("bech32m");
exports.utf8 = {
encode: (data)=>new TextDecoder().decode(data),
decode: (str)=>new TextEncoder().encode(str)
};
exports.hex = chain2(radix22(4), alphabet2("0123456789abcdef"), join2(""), normalize2((s)=>{
if (typeof s !== "string" || s.length % 2)
throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);
return s.toLowerCase();
}
));
var CODERS2 = {
utf8: exports.utf8,
hex: exports.hex,
base16: exports.base16,
base32: exports.base32,
base64: exports.base64,
base64url: exports.base64url,
base58: exports.base58,
base58xmr: exports.base58xmr
};
var coderTypeError2 = `Invalid encoding type. Available types: ${Object.keys(CODERS2).join(", ")}`;
var bytesToString = (type,bytes2)=>{
if (typeof type !== "string" || !CODERS2.hasOwnProperty(type))
throw new TypeError(coderTypeError2);
if (!(bytes2 instanceof Uint8Array))
throw new TypeError("bytesToString() expects Uint8Array");
return CODERS2[type].encode(bytes2);
}
;
exports.bytesToString = bytesToString;
exports.str = exports.bytesToString;
var stringToBytes = (type,str)=>{
if (!CODERS2.hasOwnProperty(type))
throw new TypeError(coderTypeError2);
if (typeof str !== "string")
throw new TypeError("stringToBytes() expects string");
return CODERS2[type].decode(str);
}
;
exports.stringToBytes = stringToBytes;
exports.bytes = exports.stringToBytes;
}
});
// node_modules/.pnpm/@scure+bip39@1.2.0/node_modules/@scure/bip39/index.js
var require_bip39 = __commonJS({
"node_modules/.pnpm/@scure+bip39@1.2.0/node_modules/@scure/bip39/index.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.mnemonicToSeedSync = exports.mnemonicToSeed = exports.validateMnemonic = exports.entropyToMnemonic = exports.mnemonicToEntropy = exports.generateMnemonic = void 0;
var _assert_1 = require_assert();
var pbkdf2_1 = require_pbkdf2();
var sha256_1 = require_sha256();
var sha512_1 = require_sha512();
var utils_1 = require_utils();
var base_1 = require_lib();
var isJapanese = (wordlist2)=>wordlist2[0] === "\u3042\u3044\u3053\u304F\u3057\u3093";
function nfkd(str) {
if (typeof str !== "string")
throw new TypeError(`Invalid mnemonic type: ${typeof str}`);
return str.normalize("NFKD");
}
function normalize2(str) {
const norm = nfkd(str);
const words = norm.split(" ");
if (![12, 15, 18, 21, 24].includes(words.length))
throw new Error("Invalid mnemonic");
return {
nfkd: norm,
words
};
}
function assertEntropy(entropy) {
_assert_1.default.bytes(entropy, 16, 20, 24, 28, 32);
}
function generateMnemonic2(wordlist2, strength=128) {
_assert_1.default.number(strength);
if (strength % 32 !== 0 || strength > 256)
throw new TypeError("Invalid entropy");
return entropyToMnemonic((0,
utils_1.randomBytes)(strength / 8), wordlist2);
}
exports.generateMnemonic = generateMnemonic2;
var calcChecksum = (entropy)=>{
const bitsLeft = 8 - entropy.length / 4;
return new Uint8Array([(0,
sha256_1.sha256)(entropy)[0] >> bitsLeft << bitsLeft]);
}
;
function getCoder(wordlist2) {
if (!Array.isArray(wordlist2) || wordlist2.length !== 2048 || typeof wordlist2[0] !== "string")
throw new Error("Worlist: expected array of 2048 strings");
wordlist2.forEach((i)=>{
if (typeof i !== "string")
throw new Error(`Wordlist: non-string element: ${i}`);
}
);
return base_1.utils.chain(base_1.utils.checksum(1, calcChecksum), base_1.utils.radix2(11, true), base_1.utils.alphabet(wordlist2));
}
function mnemonicToEntropy(mnemonic, wordlist2) {
const {words} = normalize2(mnemonic);
const entropy = getCoder(wordlist2).decode(words);
assertEntropy(entropy);
return entropy;
}
exports.mnemonicToEntropy = mnemonicToEntropy;
function entropyToMnemonic(entropy, wordlist2) {
assertEntropy(entropy);
const words = getCoder(wordlist2).encode(entropy);
return words.join(isJapanese(wordlist2) ? "\u3000" : " ");
}
exports.entropyToMnemonic = entropyToMnemonic;
function validateMnemonic2(mnemonic, wordlist2) {
try {
mnemonicToEntropy(mnemonic, wordlist2);
} catch (e) {
return false;
}
return true;
}
exports.validateMnemonic = validateMnemonic2;
var salt = (passphrase)=>nfkd(`mnemonic ${passphrase}`);
function mnemonicToSeed(mnemonic, passphrase="") {
return (0,
pbkdf2_1.pbkdf2Async)(sha512_1.sha512, normalize2(mnemonic).nfkd, salt(passphrase), {
c: 2048,
dkLen: 64
});
}
exports.mnemonicToSeed = mnemonicToSeed;
function mnemonicToSeedSync2(mnemonic, passphrase="") {
return (0,
pbkdf2_1.pbkdf2)(sha512_1.sha512, normalize2(mnemonic).nfkd, salt(passphrase), {
c: 2048,
dkLen: 64
});
}
exports.mnemonicToSeedSync = mnemonicToSeedSync2;
}
});
// src/background.js
var import_webextension_polyfill2 = __toESM(require_browser_polyfill());
// node_modules/.pnpm/@noble+secp256k1@1.7.1/node_modules/@noble/secp256k1/lib/esm/index.js
var nodeCrypto = __toESM(require_crypto(), 1);
var _0n = BigInt(0);
var _1n = BigInt(1);
var _2n = BigInt(2);
var _3n = BigInt(3);
var _8n = BigInt(8);
var CURVE = Object.freeze({
a: _0n,
b: BigInt(7),
P: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
h: _1n,
Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),
Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),
beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")
});
var divNearest = (a,b)=>(a + b / _2n) / b;
var endo = {
beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
splitScalar(k) {
const {n} = CURVE;
const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15");
const b1 = -_1n * BigInt("0xe4437ed6010e88286f547fa90abfe4c3");
const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8");
const b2 = a1;
const POW_2_128 = BigInt("0x100000000000000000000000000000000");
const c1 = divNearest(b2 * k, n);
const c2 = divNearest(-b1 * k, n);
let k1 = mod(k - c1 * a1 - c2 * a2, n);
let k2 = mod(-c1 * b1 - c2 * b2, n);
const k1neg = k1 > POW_2_128;
const k2neg = k2 > POW_2_128;
if (k1neg)
k1 = n - k1;
if (k2neg)
k2 = n - k2;
if (k1 > POW_2_128 || k2 > POW_2_128) {
throw new Error("splitScalarEndo: Endomorphism failed, k=" + k);
}
return {
k1neg,
k1,
k2neg,
k2
};
}
};
var fieldLen = 32;
var groupLen = 32;
var compressedLen = fieldLen + 1;
var uncompressedLen = 2 * fieldLen + 1;
function weierstrass(x) {
const {a, b} = CURVE;
const x2 = mod(x * x);
const x3 = mod(x2 * x);
return mod(x3 + a * x + b);
}
var USE_ENDOMORPHISM = CURVE.a === _0n;
var ShaError = class extends Error {
constructor(message) {
super(message);
}
}
;
function assertJacPoint(other) {
if (!(other instanceof JacobianPoint))
throw new TypeError("JacobianPoint expected");
}
var JacobianPoint = class {
constructor(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
}
static fromAffine(p) {
if (!(p instanceof Point)) {
throw new TypeError("JacobianPoint#fromAffine: expected Point");
}
if (p.equals(Point.ZERO))
return JacobianPoint.ZERO;
return new JacobianPoint(p.x,p.y,_1n);
}
static toAffineBatch(points) {
const toInv = invertBatch(points.map((p)=>p.z));
return points.map((p,i)=>p.toAffine(toInv[i]));
}
static normalizeZ(points) {
return JacobianPoint.toAffineBatch(points).map(JacobianPoint.fromAffine);
}
equals(other) {
assertJacPoint(other);
const {x: X1, y: Y1, z: Z1} = this;
const {x: X2, y: Y2, z: Z2} = other;
const Z1Z1 = mod(Z1 * Z1);
const Z2Z2 = mod(Z2 * Z2);
const U1 = mod(X1 * Z2Z2);
const U2 = mod(X2 * Z1Z1);
const S1 = mod(mod(Y1 * Z2) * Z2Z2);
const S2 = mod(mod(Y2 * Z1) * Z1Z1);
return U1 === U2 && S1 === S2;
}
negate() {
return new JacobianPoint(this.x,mod(-this.y),this.z);
}
double() {
const {x: X1, y: Y1, z: Z1} = this;
const A = mod(X1 * X1);
const B = mod(Y1 * Y1);
const C = mod(B * B);
const x1b = X1 + B;
const D = mod(_2n * (mod(x1b * x1b) - A - C));
const E = mod(_3n * A);
const F = mod(E * E);
const X3 = mod(F - _2n * D);
const Y3 = mod(E * (D - X3) - _8n * C);
const Z3 = mod(_2n * Y1 * Z1);
return new JacobianPoint(X3,Y3,Z3);
}
add(other) {
assertJacPoint(other);
const {x: X1, y: Y1, z: Z1} = this;
const {x: X2, y: Y2, z: Z2} = other;
if (X2 === _0n || Y2 === _0n)
return this;
if (X1 === _0n || Y1 === _0n)
return other;
const Z1Z1 = mod(Z1 * Z1);
const Z2Z2 = mod(Z2 * Z2);
const U1 = mod(X1 * Z2Z2);
const U2 = mod(X2 * Z1Z1);
const S1 = mod(mod(Y1 * Z2) * Z2Z2);
const S2 = mod(mod(Y2 * Z1) * Z1Z1);
const H = mod(U2 - U1);
const r = mod(S2 - S1);
if (H === _0n) {
if (r === _0n) {
return this.double();
} else {
return JacobianPoint.ZERO;
}
}
const HH = mod(H * H);
const HHH = mod(H * HH);
const V = mod(U1 * HH);
const X3 = mod(r * r - HHH - _2n * V);
const Y3 = mod(r * (V - X3) - S1 * HHH);
const Z3 = mod(Z1 * Z2 * H);
return new JacobianPoint(X3,Y3,Z3);
}
subtract(other) {
return this.add(other.negate());
}
multiplyUnsafe(scalar) {
const P0 = JacobianPoint.ZERO;
if (typeof scalar === "bigint" && scalar === _0n)
return P0;
let n = normalizeScalar(scalar);
if (n === _1n)
return this;
if (!USE_ENDOMORPHISM) {
let p = P0;
let d2 = this;
while (n > _0n) {
if (n & _1n)
p = p.add(d2);
d2 = d2.double();
n >>= _1n;
}
return p;
}
let {k1neg, k1, k2neg, k2} = endo.splitScalar(n);
let k1p = P0;
let k2p = P0;
let d = this;
while (k1 > _0n || k2 > _0n) {
if (k1 & _1n)
k1p = k1p.add(d);
if (k2 & _1n)
k2p = k2p.add(d);
d = d.double();
k1 >>= _1n;
k2 >>= _1n;
}
if (k1neg)
k1p = k1p.negate();
if (k2neg)
k2p = k2p.negate();
k2p = new JacobianPoint(mod(k2p.x * endo.beta),k2p.y,k2p.z);
return k1p.add(k2p);
}
precomputeWindow(W) {
const windows = USE_ENDOMORPHISM ? 128 / W + 1 : 256 / W + 1;
const points = [];
let p = this;
let base = p;
for (let window = 0; window < windows; window++) {
base = p;
points.push(base);
for (let i = 1; i < 2 ** (W - 1); i++) {
base = base.add(p);
points.push(base);
}
p = base.double();
}
return points;
}
wNAF(n, affinePoint) {
if (!affinePoint && this.equals(JacobianPoint.BASE))
affinePoint = Point.BASE;
const W = affinePoint && affinePoint._WINDOW_SIZE || 1;
if (256 % W) {
throw new Error("Point#wNAF: Invalid precomputation window, must be power of 2");
}
let precomputes = affinePoint && pointPrecomputes.get(affinePoint);
if (!precomputes) {
precomputes = this.precomputeWindow(W);
if (affinePoint && W !== 1) {
precomputes = JacobianPoint.normalizeZ(precomputes);
pointPrecomputes.set(affinePoint, precomputes);
}
}
let p = JacobianPoint.ZERO;
let f2 = JacobianPoint.BASE;
const windows = 1 + (USE_ENDOMORPHISM ? 128 / W : 256 / W);
const windowSize = 2 ** (W - 1);
const mask = BigInt(2 ** W - 1);
const maxNumber = 2 ** W;
const shiftBy = BigInt(W);
for (let window = 0; window < windows; window++) {
const offset = window * windowSize;
let wbits = Number(n & mask);
n >>= shiftBy;
if (wbits > windowSize) {
wbits -= maxNumber;
n += _1n;
}
const offset1 = offset;
const offset2 = offset + Math.abs(wbits) - 1;
const cond1 = window % 2 !== 0;
const cond2 = wbits < 0;
if (wbits === 0) {
f2 = f2.add(constTimeNegate(cond1, precomputes[offset1]));
} else {
p = p.add(constTimeNegate(cond2, precomputes[offset2]));
}
}
return {
p,
f: f2
};
}
multiply(scalar, affinePoint) {
let n = normalizeScalar(scalar);
let point;
let fake;
if (USE_ENDOMORPHISM) {
const {k1neg, k1, k2neg, k2} = endo.splitScalar(n);
let {p: k1p, f: f1p} = this.wNAF(k1, affinePoint);
let {p: k2p, f: f2p} = this.wNAF(k2, affinePoint);
k1p = constTimeNegate(k1neg, k1p);
k2p = constTimeNegate(k2neg, k2p);
k2p = new JacobianPoint(mod(k2p.x * endo.beta),k2p.y,k2p.z);
point = k1p.add(k2p);
fake = f1p.add(f2p);
} else {
const {p, f: f2} = this.wNAF(n, affinePoint);
point = p;
fake = f2;
}
return JacobianPoint.normalizeZ([point, fake])[0];
}
toAffine(invZ) {
const {x, y, z} = this;
const is0 = this.equals(JacobianPoint.ZERO);
if (invZ == null)
invZ = is0 ? _8n : invert(z);
const iz1 = invZ;
const iz2 = mod(iz1 * iz1);
const iz3 = mod(iz2 * iz1);
const ax = mod(x * iz2);
const ay = mod(y * iz3);
const zz = mod(z * iz1);
if (is0)
return Point.ZERO;
if (zz !== _1n)
throw new Error("invZ was invalid");
return new Point(ax,ay);
}
}
;
JacobianPoint.BASE = new JacobianPoint(CURVE.Gx,CURVE.Gy,_1n);
JacobianPoint.ZERO = new JacobianPoint(_0n,_1n,_0n);
function constTimeNegate(condition, item) {
const neg = item.negate();
return condition ? neg : item;
}
var pointPrecomputes = /* @__PURE__ */
new WeakMap();
var Point = class {
constructor(x, y) {
this.x = x;
this.y = y;
}
_setWindowSize(windowSize) {
this._WINDOW_SIZE = windowSize;
pointPrecomputes.delete(this);
}
hasEvenY() {
return this.y % _2n === _0n;
}
static fromCompressedHex(bytes2) {
const isShort = bytes2.length === 32;
const x = bytesToNumber(isShort ? bytes2 : bytes2.subarray(1));
if (!isValidFieldElement(x))
throw new Error("Point is not on curve");
const y2 = weierstrass(x);
let y = sqrtMod(y2);
const isYOdd = (y & _1n) === _1n;
if (isShort) {
if (isYOdd)
y = mod(-y);
} else {
const isFirstByteOdd = (bytes2[0] & 1) === 1;
if (isFirstByteOdd !== isYOdd)
y = mod(-y);
}
const point = new Point(x,y);
point.assertValidity();
return point;
}
static fromUncompressedHex(bytes2) {
const x = bytesToNumber(bytes2.subarray(1, fieldLen + 1));
const y = bytesToNumber(bytes2.subarray(fieldLen + 1, fieldLen * 2 + 1));
const point = new Point(x,y);
point.assertValidity();
return point;
}
static fromHex(hex2) {
const bytes2 = ensureBytes(hex2);
const len = bytes2.length;
const header = bytes2[0];
if (len === fieldLen)
return this.fromCompressedHex(bytes2);
if (len === compressedLen && (header === 2 || header === 3)) {
return this.fromCompressedHex(bytes2);
}
if (len === uncompressedLen && header === 4)
return this.fromUncompressedHex(bytes2);
throw new Error(`Point.fromHex: received invalid point. Expected 32-${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes, not ${len}`);
}
static fromPrivateKey(privateKey) {
return Point.BASE.multiply(normalizePrivateKey(privateKey));
}
static fromSignature(msgHash, signature, recovery) {
const {r, s} = normalizeSignature(signature);
if (![0, 1, 2, 3].includes(recovery))
throw new Error("Cannot recover: invalid recovery bit");
const h = truncateHash(ensureBytes(msgHash));
const {n} = CURVE;
const radj = recovery === 2 || recovery === 3 ? r + n : r;
const rinv = invert(radj, n);
const u1 = mod(-h * rinv, n);
const u2 = mod(s * rinv, n);
const prefix = recovery & 1 ? "03" : "02";
const R = Point.fromHex(prefix + numTo32bStr(radj));
const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2);
if (!Q)
throw new Error("Cannot recover signature: point at infinify");
Q.assertValidity();
return Q;
}
toRawBytes(isCompressed=false) {
return hexToBytes(this.toHex(isCompressed));
}
toHex(isCompressed=false) {
const x = numTo32bStr(this.x);
if (isCompressed) {
const prefix = this.hasEvenY() ? "02" : "03";
return `${prefix}${x}`;
} else {
return `04 ${x}${numTo32bStr(this.y)}`;
}
}
toHexX() {
return this.toHex(true).slice(2);
}
toRawX() {
return this.toRawBytes(true).slice(1);
}
assertValidity() {
const msg = "Point is not on elliptic curve";
const {x, y} = this;
if (!isValidFieldElement(x) || !isValidFieldElement(y))
throw new Error(msg);
const left = mod(y * y);
const right = weierstrass(x);
if (mod(left - right) !== _0n)
throw new Error(msg);
}
equals(other) {
return this.x === other.x && this.y === other.y;
}
negate() {
return new Point(this.x,mod(-this.y));
}
double() {
return JacobianPoint.fromAffine(this).double().toAffine();
}
add(other) {
return JacobianPoint.fromAffine(this).add(JacobianPoint.fromAffine(other)).toAffine();
}
subtract(other) {
return this.add(other.negate());
}
multiply(scalar) {
return JacobianPoint.fromAffine(this).multiply(scalar, this).toAffine();
}
multiplyAndAddUnsafe(Q, a, b) {
const P = JacobianPoint.fromAffine(this);
const aP = a === _0n || a === _1n || this !== Point.BASE ? P.multiplyUnsafe(a) : P.multiply(a);
const bQ = JacobianPoint.fromAffine(Q).multiplyUnsafe(b);
const sum = aP.add(bQ);
return sum.equals(JacobianPoint.ZERO) ? void 0 : sum.toAffine();
}
}
;
Point.BASE = new Point(CURVE.Gx,CURVE.Gy);
Point.ZERO = new Point(_0n,_0n);
function sliceDER(s) {
return Number.parseInt(s[0], 16) >= 8 ? "00" + s : s;
}
function parseDERInt(data) {
if (data.length < 2 || data[0] !== 2) {
throw new Error(`Invalid signature integer tag: ${bytesToHex(data)}`);
}
const len = data[1];
const res = data.subarray(2, len + 2);
if (!len || res.length !== len) {
throw new Error(`Invalid signature integer: wrong length`);
}
if (res[0] === 0 && res[1] <= 127) {
throw new Error("Invalid signature integer: trailing length");
}
return {
data: bytesToNumber(res),
left: data.subarray(len + 2)
};
}
function parseDERSignature(data) {
if (data.length < 2 || data[0] != 48) {
throw new Error(`Invalid signature tag: ${bytesToHex(data)}`);
}
if (data[1] !== data.length - 2) {
throw new Error("Invalid signature: incorrect length");
}
const {data: r, left: sBytes} = parseDERInt(data.subarray(2));
const {data: s, left: rBytesLeft} = parseDERInt(sBytes);
if (rBytesLeft.length) {
throw new Error(`Invalid signature: left bytes after parsing: ${bytesToHex(rBytesLeft)}`);
}
return {
r,
s
};
}
var Signature = class {
constructor(r, s) {
this.r = r;
this.s = s;
this.assertValidity();
}
static fromCompact(hex2) {
const arr = hex2 instanceof Uint8Array;
const name = "Signature.fromCompact";
if (typeof hex2 !== "string" && !arr)
throw new TypeError(`${name}: Expected string or Uint8Array`);
const str = arr ? bytesToHex(hex2) : hex2;
if (str.length !== 128)
throw new Error(`${name}: Expected 64-byte hex`);
return new Signature(hexToNumber(str.slice(0, 64)),hexToNumber(str.slice(64, 128)));
}
static fromDER(hex2) {
const arr = hex2 instanceof Uint8Array;
if (typeof hex2 !== "string" && !arr)
throw new TypeError(`Signature.fromDER: Expected string or Uint8Array`);
const {r, s} = parseDERSignature(arr ? hex2 : hexToBytes(hex2));
return new Signature(r,s);
}
static fromHex(hex2) {
return this.fromDER(hex2);
}
assertValidity() {
const {r, s} = this;
if (!isWithinCurveOrder(r))
throw new Error("Invalid Signature: r must be 0 < r < n");
if (!isWithinCurveOrder(s))
throw new Error("Invalid Signature: s must be 0 < s < n");
}
hasHighS() {
const HALF = CURVE.n >> _1n;
return this.s > HALF;
}
normalizeS() {
return this.hasHighS() ? new Signature(this.r,mod(-this.s, CURVE.n)) : this;
}
toDERRawBytes() {
return hexToBytes(this.toDERHex());
}
toDERHex() {
const sHex = sliceDER(numberToHexUnpadded(this.s));
const rHex = sliceDER(numberToHexUnpadded(this.r));
const sHexL = sHex.length / 2;
const rHexL = rHex.length / 2;
const sLen = numberToHexUnpadded(sHexL);
const rLen = numberToHexUnpadded(rHexL);
const length = numberToHexUnpadded(rHexL + sHexL + 4);
return `30 ${length}02 ${rLen}${rHex}02 ${sLen}${sHex}`;
}
toRawBytes() {
return this.toDERRawBytes();
}
toHex() {
return this.toDERHex();
}
toCompactRawBytes() {
return hexToBytes(this.toCompactHex());
}
toCompactHex() {
return numTo32bStr(this.r) + numTo32bStr(this.s);
}
}
;
function concatBytes(...arrays) {
if (!arrays.every((b)=>b instanceof Uint8Array))
throw new Error("Uint8Array list expected");
if (arrays.length === 1)
return arrays[0];
const length = arrays.reduce((a,arr)=>a + arr.length, 0);
const result = new Uint8Array(length);
for (let i = 0, pad = 0; i < arrays.length; i++) {
const arr = arrays[i];
result.set(arr, pad);
pad += arr.length;
}
return result;
}
var hexes = Array.from({
length: 256
}, (v,i)=>i.toString(16).padStart(2, "0"));
function bytesToHex(uint8a) {
if (!(uint8a instanceof Uint8Array))
throw new Error("Expected Uint8Array");
let hex2 = "";
for (let i = 0; i < uint8a.length; i++) {
hex2 += hexes[uint8a[i]];
}
return hex2;
}
var POW_2_256 = BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");
function numTo32bStr(num) {
if (typeof num !== "bigint")
throw new Error("Expected bigint");
if (!(_0n <= num && num < POW_2_256))
throw new Error("Expected number 0 <= n < 2^256");
return num.toString(16).padStart(64, "0");
}
function numTo32b(num) {
const b = hexToBytes(numTo32bStr(num));
if (b.length !== 32)
throw new Error("Error: expected 32 bytes");
return b;
}
function numberToHexUnpadded(num) {
const hex2 = num.toString(16);
return hex2.length & 1 ? `0 ${hex2}` : hex2;
}
function hexToNumber(hex2) {
if (typeof hex2 !== "string") {
throw new TypeError("hexToNumber: expected string, got " + typeof hex2);
}
return BigInt(`0x ${hex2}`);
}
function hexToBytes(hex2) {
if (typeof hex2 !== "string") {
throw new TypeError("hexToBytes: expected string, got " + typeof hex2);
}
if (hex2.length % 2)
throw new Error("hexToBytes: received invalid unpadded hex" + hex2.length);
const array = new Uint8Array(hex2.length / 2);
for (let i = 0; i < array.length; i++) {
const j = i * 2;
const hexByte = hex2.slice(j, j + 2);
const byte = Number.parseInt(hexByte, 16);
if (Number.isNaN(byte) || byte < 0)
throw new Error("Invalid byte sequence");
array[i] = byte;
}
return array;
}
function bytesToNumber(bytes2) {
return hexToNumber(bytesToHex(bytes2));
}
function ensureBytes(hex2) {
return hex2 instanceof Uint8Array ? Uint8Array.from(hex2) : hexToBytes(hex2);
}
function normalizeScalar(num) {
if (typeof num === "number" && Number.isSafeInteger(num) && num > 0)
return BigInt(num);
if (typeof num === "bigint" && isWithinCurveOrder(num))
return num;
throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n");
}
function mod(a, b=CURVE.P) {
const result = a % b;
return result >= _0n ? result : b + result;
}
function pow2(x, power) {
const {P} = CURVE;
let res = x;
while (power-- > _0n) {
res *= res;
res %= P;
}
return res;
}
function sqrtMod(x) {
const {P} = CURVE;
const _6n = BigInt(6);
const _11n = BigInt(11);
const _22n = BigInt(22);
const _23n = BigInt(23);
const _44n = BigInt(44);
const _88n = BigInt(88);
const b2 = x * x * x % P;
const b3 = b2 * b2 * x % P;
const b6 = pow2(b3, _3n) * b3 % P;
const b9 = pow2(b6, _3n) * b3 % P;
const b11 = pow2(b9, _2n) * b2 % P;
const b22 = pow2(b11, _11n) * b11 % P;
const b44 = pow2(b22, _22n) * b22 % P;
const b88 = pow2(b44, _44n) * b44 % P;
const b176 = pow2(b88, _88n) * b88 % P;
const b220 = pow2(b176, _44n) * b44 % P;
const b223 = pow2(b220, _3n) * b3 % P;
const t1 = pow2(b223, _23n) * b22 % P;
const t2 = pow2(t1, _6n) * b2 % P;
const rt = pow2(t2, _2n);
const xc = rt * rt % P;
if (xc !== x)
throw new Error("Cannot find square root");
return rt;
}
function invert(number2, modulo=CURVE.P) {
if (number2 === _0n || modulo <= _0n) {
throw new Error(`invert: expected positive integers, got n=${number2} mod=${modulo}`);
}
let a = mod(number2, modulo);
let b = modulo;
let x = _0n
, y = _1n
, u = _1n
, v = _0n;
while (a !== _0n) {
const q = b / a;
const r = b % a;
const m = x - u * q;
const n = y - v * q;
b = a,
a = r,
x = u,
y = v,
u = m,
v = n;
}
const gcd2 = b;
if (gcd2 !== _1n)
throw new Error("invert: does not exist");
return mod(x, modulo);
}
function invertBatch(nums, p=CURVE.P) {
const scratch = new Array(nums.length);
const lastMultiplied = nums.reduce((acc,num,i)=>{
if (num === _0n)
return acc;
scratch[i] = acc;
return mod(acc * num, p);
}
, _1n);
const inverted = invert(lastMultiplied, p);
nums.reduceRight((acc,num,i)=>{
if (num === _0n)
return acc;
scratch[i] = mod(acc * scratch[i], p);
return mod(acc * num, p);
}
, inverted);
return scratch;
}
function bits2int_2(bytes2) {
const delta = bytes2.length * 8 - groupLen * 8;
const num = bytesToNumber(bytes2);
return delta > 0 ? num >> BigInt(delta) : num;
}
function truncateHash(hash2, truncateOnly=false) {
const h = bits2int_2(hash2);
if (truncateOnly)
return h;
const {n} = CURVE;
return h >= n ? h - n : h;
}
var _sha256Sync;
var _hmacSha256Sync;
function isWithinCurveOrder(num) {
return _0n < num && num < CURVE.n;
}
function isValidFieldElement(num) {
return _0n < num && num < CURVE.P;
}
function normalizePrivateKey(key) {
let num;
if (typeof key === "bigint") {
num = key;
} else if (typeof key === "number" && Number.isSafeInteger(key) && key > 0) {
num = BigInt(key);
} else if (typeof key === "string") {
if (key.length !== 2 * groupLen)
throw new Error("Expected 32 bytes of private key");
num = hexToNumber(key);
} else if (key instanceof Uint8Array) {
if (key.length !== groupLen)
throw new Error("Expected 32 bytes of private key");
num = bytesToNumber(key);
} else {
throw new TypeError("Expected valid private key");
}
if (!isWithinCurveOrder(num))
throw new Error("Expected private key: 0 < key < n");
return num;
}
function normalizePublicKey(publicKey) {
if (publicKey instanceof Point) {
publicKey.assertValidity();
return publicKey;
} else {
return Point.fromHex(publicKey);
}
}
function normalizeSignature(signature) {
if (signature instanceof Signature) {
signature.assertValidity();
return signature;
}
try {
return Signature.fromDER(signature);
} catch (error) {
return Signature.fromCompact(signature);
}
}
function isProbPub(item) {
const arr = item instanceof Uint8Array;
const str = typeof item === "string";
const len = (arr || str) && item.length;
if (arr)
return len === compressedLen || len === uncompressedLen;
if (str)
return len === compressedLen * 2 || len === uncompressedLen * 2;
if (item instanceof Point)
return true;
return false;
}
function getSharedSecret(privateA, publicB, isCompressed=false) {
if (isProbPub(privateA))
throw new TypeError("getSharedSecret: first arg must be private key");
if (!isProbPub(publicB))
throw new TypeError("getSharedSecret: second arg must be public key");
const b = normalizePublicKey(publicB);
b.assertValidity();
return b.multiply(normalizePrivateKey(privateA)).toRawBytes(isCompressed);
}
function schnorrChallengeFinalize(ch) {
return mod(bytesToNumber(ch), CURVE.n);
}
var SchnorrSignature = class {
constructor(r, s) {
this.r = r;
this.s = s;
this.assertValidity();
}
static fromHex(hex2) {
const bytes2 = ensureBytes(hex2);
if (bytes2.length !== 64)
throw new TypeError(`SchnorrSignature.fromHex: expected 64 bytes, not ${bytes2.length}`);
const r = bytesToNumber(bytes2.subarray(0, 32));
const s = bytesToNumber(bytes2.subarray(32, 64));
return new SchnorrSignature(r,s);
}
assertValidity() {
const {r, s} = this;
if (!isValidFieldElement(r) || !isWithinCurveOrder(s))
throw new Error("Invalid signature");
}
toHex() {
return numTo32bStr(this.r) + numTo32bStr(this.s);
}
toRawBytes() {
return hexToBytes(this.toHex());
}
}
;
function schnorrGetPublicKey(privateKey) {
return Point.fromPrivateKey(privateKey).toRawX();
}
var InternalSchnorrSignature = class {
constructor(message, privateKey, auxRand=utils.randomBytes()) {
if (message == null)
throw new TypeError(`sign: Expected valid message, not "${message}"`);
this.m = ensureBytes(message);
const {x, scalar} = this.getScalar(normalizePrivateKey(privateKey));
this.px = x;
this.d = scalar;
this.rand = ensureBytes(auxRand);
if (this.rand.length !== 32)
throw new TypeError("sign: Expected 32 bytes of aux randomness");
}
getScalar(priv) {
const point = Point.fromPrivateKey(priv);
const scalar = point.hasEvenY() ? priv : CURVE.n - priv;
return {
point,
scalar,
x: point.toRawX()
};
}
initNonce(d, t0h) {
return numTo32b(d ^ bytesToNumber(t0h));
}
finalizeNonce(k0h) {
const k0 = mod(bytesToNumber(k0h), CURVE.n);
if (k0 === _0n)
throw new Error("sign: Creation of signature failed. k is zero");
const {point: R, x: rx, scalar: k} = this.getScalar(k0);
return {
R,
rx,
k
};
}
finalizeSig(R, k, e, d) {
return new SchnorrSignature(R.x,mod(k + e * d, CURVE.n)).toRawBytes();
}
error() {
throw new Error("sign: Invalid signature produced");
}
async calc() {
const {m, d, px, rand} = this;
const tag = utils.taggedHash;
const t = this.initNonce(d, await tag(TAGS.aux, rand));
const {R, rx, k} = this.finalizeNonce(await tag(TAGS.nonce, t, px, m));
const e = schnorrChallengeFinalize(await tag(TAGS.challenge, rx, px, m));
const sig = this.finalizeSig(R, k, e, d);
if (!await schnorrVerify(sig, m, px))
this.error();
return sig;
}
calcSync() {
const {m, d, px, rand} = this;
const tag = utils.taggedHashSync;
const t = this.initNonce(d, tag(TAGS.aux, rand));
const {R, rx, k} = this.finalizeNonce(tag(TAGS.nonce, t, px, m));
const e = schnorrChallengeFinalize(tag(TAGS.challenge, rx, px, m));
const sig = this.finalizeSig(R, k, e, d);
if (!schnorrVerifySync(sig, m, px))
this.error();
return sig;
}
}
;
async function schnorrSign(msg, privKey, auxRand) {
return new InternalSchnorrSignature(msg,privKey,auxRand).calc();
}
function schnorrSignSync(msg, privKey, auxRand) {
return new InternalSchnorrSignature(msg,privKey,auxRand).calcSync();
}
function initSchnorrVerify(signature, message, publicKey) {
const raw = signature instanceof SchnorrSignature;
const sig = raw ? signature : SchnorrSignature.fromHex(signature);
if (raw)
sig.assertValidity();
return {
...sig,
m: ensureBytes(message),
P: normalizePublicKey(publicKey)
};
}
function finalizeSchnorrVerify(r, P, s, e) {
const R = Point.BASE.multiplyAndAddUnsafe(P, normalizePrivateKey(s), mod(-e, CURVE.n));
if (!R || !R.hasEvenY() || R.x !== r)
return false;
return true;
}
async function schnorrVerify(signature, message, publicKey) {
try {
const {r, s, m, P} = initSchnorrVerify(signature, message, publicKey);
const e = schnorrChallengeFinalize(await utils.taggedHash(TAGS.challenge, numTo32b(r), P.toRawX(), m));
return finalizeSchnorrVerify(r, P, s, e);
} catch (error) {
return false;
}
}
function schnorrVerifySync(signature, message, publicKey) {
try {
const {r, s, m, P} = initSchnorrVerify(signature, message, publicKey);
const e = schnorrChallengeFinalize(utils.taggedHashSync(TAGS.challenge, numTo32b(r), P.toRawX(), m));
return finalizeSchnorrVerify(r, P, s, e);
} catch (error) {
if (error instanceof ShaError)
throw error;
return false;
}
}
var schnorr = {
Signature: SchnorrSignature,
getPublicKey: schnorrGetPublicKey,
sign: schnorrSign,
verify: schnorrVerify,
signSync: schnorrSignSync,
verifySync: schnorrVerifySync
};
Point.BASE._setWindowSize(8);
var crypto2 = {
node: nodeCrypto,
web: typeof self === "object" && "crypto"in self ? self.crypto : void 0
};
var TAGS = {
challenge: "BIP0340/challenge",
aux: "BIP0340/aux",
nonce: "BIP0340/nonce"
};
var TAGGED_HASH_PREFIXES = {};
var utils = {
bytesToHex,
hexToBytes,
concatBytes,
mod,
invert,
isValidPrivateKey(privateKey) {
try {
normalizePrivateKey(privateKey);
return true;
} catch (error) {
return false;
}
},
_bigintTo32Bytes: numTo32b,
_normalizePrivateKey: normalizePrivateKey,
hashToPrivateKey: (hash2)=>{
hash2 = ensureBytes(hash2);
const minLen = groupLen + 8;
if (hash2.length < minLen || hash2.length > 1024) {
throw new Error(`Expected valid bytes of private key as per FIPS 186`);
}
const num = mod(bytesToNumber(hash2), CURVE.n - _1n) + _1n;
return numTo32b(num);
}
,
randomBytes: (bytesLength=32)=>{
if (crypto2.web) {
return crypto2.web.getRandomValues(new Uint8Array(bytesLength));
} else if (crypto2.node) {
const {randomBytes: randomBytes3} = crypto2.node;
return Uint8Array.from(randomBytes3(bytesLength));
} else {
throw new Error("The environment doesn't have randomBytes function");
}
}
,
randomPrivateKey: ()=>utils.hashToPrivateKey(utils.randomBytes(groupLen + 8)),
precompute(windowSize=8, point=Point.BASE) {
const cached = point === Point.BASE ? point : new Point(point.x,point.y);
cached._setWindowSize(windowSize);
cached.multiply(_3n);
return cached;
},
sha256: async(...messages)=>{
if (crypto2.web) {
const buffer = await crypto2.web.subtle.digest("SHA-256", concatBytes(...messages));
return new Uint8Array(buffer);
} else if (crypto2.node) {
const {createHash} = crypto2.node;
const hash2 = createHash("sha256");
messages.forEach((m)=>hash2.update(m));
return Uint8Array.from(hash2.digest());
} else {
throw new Error("The environment doesn't have sha256 function");
}
}
,
hmacSha256: async(key,...messages)=>{
if (crypto2.web) {
const ckey = await crypto2.web.subtle.importKey("raw", key, {
name: "HMAC",
hash: {
name: "SHA-256"
}
}, false, ["sign"]);
const message = concatBytes(...messages);
const buffer = await crypto2.web.subtle.sign("HMAC", ckey, message);
return new Uint8Array(buffer);
} else if (crypto2.node) {
const {createHmac} = crypto2.node;
const hash2 = createHmac("sha256", key);
messages.forEach((m)=>hash2.update(m));
return Uint8Array.from(hash2.digest());
} else {
throw new Error("The environment doesn't have hmac-sha256 function");
}
}
,
sha256Sync: void 0,
hmacSha256Sync: void 0,
taggedHash: async(tag,...messages)=>{
let tagP = TAGGED_HASH_PREFIXES[tag];
if (tagP === void 0) {
const tagH = await utils.sha256(Uint8Array.from(tag, (c)=>c.charCodeAt(0)));
tagP = concatBytes(tagH, tagH);
TAGGED_HASH_PREFIXES[tag] = tagP;
}
return utils.sha256(tagP, ...messages);
}
,
taggedHashSync: (tag,...messages)=>{
if (typeof _sha256Sync !== "function")
throw new ShaError("sha256Sync is undefined, you need to set it");
let tagP = TAGGED_HASH_PREFIXES[tag];
if (tagP === void 0) {
const tagH = _sha256Sync(Uint8Array.from(tag, (c)=>c.charCodeAt(0)));
tagP = concatBytes(tagH, tagH);
TAGGED_HASH_PREFIXES[tag] = tagP;
}
return _sha256Sync(tagP, ...messages);
}
,
_JacobianPoint: JacobianPoint
};
Object.defineProperties(utils, {
sha256Sync: {
configurable: false,
get() {
return _sha256Sync;
},
set(val) {
if (!_sha256Sync)
_sha256Sync = val;
}
},
hmacSha256Sync: {
configurable: false,
get() {
return _hmacSha256Sync;
},
set(val) {
if (!_hmacSha256Sync)
_hmacSha256Sync = val;
}
}
});
// node_modules/.pnpm/@noble+hashes@0.5.9/node_modules/@noble/hashes/esm/cryptoBrowser.js
var crypto3 = {
node: void 0,
web: typeof self === "object" && "crypto"in self ? self.crypto : void 0
};
// node_modules/.pnpm/@noble+hashes@0.5.9/node_modules/@noble/hashes/esm/utils.js
var createView = (arr)=>new DataView(arr.buffer,arr.byteOffset,arr.byteLength);
var rotr = (word,shift)=>word << 32 - shift | word >>> shift;
var isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
if (!isLE)
throw new Error("Non little-endian hardware is not supported");
var hexes2 = Array.from({
length: 256
}, (v,i)=>i.toString(16).padStart(2, "0"));
var nextTick = (()=>{
const nodeRequire = typeof module !== "undefined" && typeof module.require === "function" && module.require.bind(module);
try {
if (nodeRequire) {
const {setImmediate} = nodeRequire("timers");
return ()=>new Promise((resolve)=>setImmediate(resolve));
}
} catch (e) {}
return ()=>new Promise((resolve)=>setTimeout(resolve, 0));
}
)();
function utf8ToBytes(str) {
if (typeof str !== "string") {
throw new TypeError(`utf8ToBytes expected string, got ${typeof str}`);
}
return new TextEncoder().encode(str);
}
function toBytes(data) {
if (typeof data === "string")
data = utf8ToBytes(data);
if (!(data instanceof Uint8Array))
throw new TypeError(`Expected input type is Uint8Array (got ${typeof data})`);
return data;
}
function assertNumber(n) {
if (!Number.isSafeInteger(n) || n < 0)
throw new Error(`Wrong positive integer: ${n}`);
}
function assertHash(hash2) {
if (typeof hash2 !== "function" || typeof hash2.init !== "function")
throw new Error("Hash should be wrapped by utils.wrapConstructor");
assertNumber(hash2.outputLen);
assertNumber(hash2.blockLen);
}
var Hash = class {
// Safe version that clones internal state
clone() {
return this._cloneInto();
}
}
;
function wrapConstructor(hashConstructor) {
const hashC = (message)=>hashConstructor().update(toBytes(message)).digest();
const tmp = hashConstructor();
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = ()=>hashConstructor();
hashC.init = hashC.create;
return hashC;
}
function randomBytes(bytesLength=32) {
if (crypto3.web) {
return crypto3.web.getRandomValues(new Uint8Array(bytesLength));
} else if (crypto3.node) {
return new Uint8Array(crypto3.node.randomBytes(bytesLength).buffer);
} else {
throw new Error("The environment doesn't have randomBytes function");
}
}
// node_modules/.pnpm/@noble+hashes@0.5.9/node_modules/@noble/hashes/esm/_sha2.js
function setBigUint64(view, byteOffset, value, isLE3) {
if (typeof view.setBigUint64 === "function")
return view.setBigUint64(byteOffset, value, isLE3);
const _32n2 = BigInt(32);
const _u32_max = BigInt(4294967295);
const wh = Number(value >> _32n2 & _u32_max);
const wl = Number(value & _u32_max);
const h = isLE3 ? 4 : 0;
const l = isLE3 ? 0 : 4;
view.setUint32(byteOffset + h, wh, isLE3);
view.setUint32(byteOffset + l, wl, isLE3);
}
var SHA2 = class extends Hash {
constructor(blockLen, outputLen, padOffset, isLE3) {
super();
this.blockLen = blockLen;
this.outputLen = outputLen;
this.padOffset = padOffset;
this.isLE = isLE3;
this.finished = false;
this.length = 0;
this.pos = 0;
this.destroyed = false;
this.buffer = new Uint8Array(blockLen);
this.view = createView(this.buffer);
}
update(data) {
if (this.destroyed)
throw new Error("instance is destroyed");
const {view, buffer, blockLen, finished} = this;
if (finished)
throw new Error("digest() was already called");
data = toBytes(data);
const len = data.length;
for (let pos = 0; pos < len; ) {
const take = Math.min(blockLen - this.pos, len - pos);
if (take === blockLen) {
const dataView = createView(data);
for (; blockLen <= len - pos; pos += blockLen)
this.process(dataView, pos);
continue;
}
buffer.set(data.subarray(pos, pos + take), this.pos);
this.pos += take;
pos += take;
if (this.pos === blockLen) {
this.process(view, 0);
this.pos = 0;
}
}
this.length += data.length;
this.roundClean();
return this;
}
digestInto(out) {
if (this.destroyed)
throw new Error("instance is destroyed");
if (!(out instanceof Uint8Array) || out.length < this.outputLen)
throw new Error("_Sha2: Invalid output buffer");
if (this.finished)
throw new Error("digest() was already called");
this.finished = true;
const {buffer, view, blockLen, isLE: isLE3} = this;
let {pos} = this;
buffer[pos++] = 128;
this.buffer.subarray(pos).fill(0);
if (this.padOffset > blockLen - pos) {
this.process(view, 0);
pos = 0;
}
for (let i = pos; i < blockLen; i++)
buffer[i] = 0;
setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE3);
this.process(view, 0);
const oview = createView(out);
this.get().forEach((v,i)=>oview.setUint32(4 * i, v, isLE3));
}
digest() {
const {buffer, outputLen} = this;
this.digestInto(buffer);
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
_cloneInto(to) {
to || (to = new this.constructor());
to.set(...this.get());
const {blockLen, buffer, length, finished, destroyed, pos} = this;
to.length = length;
to.pos = pos;
to.finished = finished;
to.destroyed = destroyed;
if (length % blockLen)
to.buffer.set(buffer);
return to;
}
}
;
// node_modules/.pnpm/@noble+hashes@0.5.9/node_modules/@noble/hashes/esm/sha256.js
var Chi = (a,b,c)=>a & b ^ ~a & c;
var Maj = (a,b,c)=>a & b ^ a & c ^ b & c;
var SHA256_K = new Uint32Array([1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298]);
var IV = new Uint32Array([1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225]);
var SHA256_W = new Uint32Array(64);
var SHA256 = class extends SHA2 {
constructor() {
super(64, 32, 8, false);
this.A = IV[0] | 0;
this.B = IV[1] | 0;
this.C = IV[2] | 0;
this.D = IV[3] | 0;
this.E = IV[4] | 0;
this.F = IV[5] | 0;
this.G = IV[6] | 0;
this.H = IV[7] | 0;
}
get() {
const {A, B, C, D, E, F, G, H} = this;
return [A, B, C, D, E, F, G, H];
}
// prettier-ignore
set(A, B, C, D, E, F, G, H) {
this.A = A | 0;
this.B = B | 0;
this.C = C | 0;
this.D = D | 0;
this.E = E | 0;
this.F = F | 0;
this.G = G | 0;
this.H = H | 0;
}
process(view, offset) {
for (let i = 0; i < 16; i++,
offset += 4)
SHA256_W[i] = view.getUint32(offset, false);
for (let i = 16; i < 64; i++) {
const W15 = SHA256_W[i - 15];
const W2 = SHA256_W[i - 2];
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
}
let {A, B, C, D, E, F, G, H} = this;
for (let i = 0; i < 64; i++) {
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
const T2 = sigma0 + Maj(A, B, C) | 0;
H = G;
G = F;
F = E;
E = D + T1 | 0;
D = C;
C = B;
B = A;
A = T1 + T2 | 0;
}
A = A + this.A | 0;
B = B + this.B | 0;
C = C + this.C | 0;
D = D + this.D | 0;
E = E + this.E | 0;
F = F + this.F | 0;
G = G + this.G | 0;
H = H + this.H | 0;
this.set(A, B, C, D, E, F, G, H);
}
roundClean() {
SHA256_W.fill(0);
}
destroy() {
this.set(0, 0, 0, 0, 0, 0, 0, 0);
this.buffer.fill(0);
}
}
;
var sha256 = wrapConstructor(()=>new SHA256());
// node_modules/.pnpm/@scure+base@1.1.1/node_modules/@scure/base/lib/esm/index.js
function assertNumber2(n) {
if (!Number.isSafeInteger(n))
throw new Error(`Wrong integer: ${n}`);
}
function chain(...args) {
const wrap = (a,b)=>(c)=>a(b(c));
const encode = Array.from(args).reverse().reduce((acc,i)=>acc ? wrap(acc, i.encode) : i.encode, void 0);
const decode2 = args.reduce((acc,i)=>acc ? wrap(acc, i.decode) : i.decode, void 0);
return {
encode,
decode: decode2
};
}
function alphabet(alphabet2) {
return {
encode: (digits)=>{
if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number")
throw new Error("alphabet.encode input should be an array of numbers");
return digits.map((i)=>{
assertNumber2(i);
if (i < 0 || i >= alphabet2.length)
throw new Error(`Digit index outside alphabet: ${i} (alphabet: ${alphabet2.length})`);
return alphabet2[i];
}
);
}
,
decode: (input)=>{
if (!Array.isArray(input) || input.length && typeof input[0] !== "string")
throw new Error("alphabet.decode input should be array of strings");
return input.map((letter)=>{
if (typeof letter !== "string")
throw new Error(`alphabet.decode: not string element=${letter}`);
const index = alphabet2.indexOf(letter);
if (index === -1)
throw new Error(`Unknown letter: "${letter}". Allowed: ${alphabet2}`);
return index;
}
);
}
};
}
function join(separator="") {
if (typeof separator !== "string")
throw new Error("join separator should be string");
return {
encode: (from)=>{
if (!Array.isArray(from) || from.length && typeof from[0] !== "string")
throw new Error("join.encode input should be array of strings");
for (let i of from)
if (typeof i !== "string")
throw new Error(`join.encode: non-string input=${i}`);
return from.join(separator);
}
,
decode: (to)=>{
if (typeof to !== "string")
throw new Error("join.decode input should be string");
return to.split(separator);
}
};
}
function padding(bits, chr="=") {
assertNumber2(bits);
if (typeof chr !== "string")
throw new Error("padding chr should be string");
return {
encode(data) {
if (!Array.isArray(data) || data.length && typeof data[0] !== "string")
throw new Error("padding.encode input should be array of strings");
for (let i of data)
if (typeof i !== "string")
throw new Error(`padding.encode: non-string input=${i}`);
while (data.length * bits % 8)
data.push(chr);
return data;
},
decode(input) {
if (!Array.isArray(input) || input.length && typeof input[0] !== "string")
throw new Error("padding.encode input should be array of strings");
for (let i of input)
if (typeof i !== "string")
throw new Error(`padding.decode: non-string input=${i}`);
let end = input.length;
if (end * bits % 8)
throw new Error("Invalid padding: string should have whole number of bytes");
for (; end > 0 && input[end - 1] === chr; end--) {
if (!((end - 1) * bits % 8))
throw new Error("Invalid padding: string has too much padding");
}
return input.slice(0, end);
}
};
}
function normalize(fn) {
if (typeof fn !== "function")
throw new Error("normalize fn should be function");
return {
encode: (from)=>from,
decode: (to)=>fn(to)
};
}
function convertRadix(data, from, to) {
if (from < 2)
throw new Error(`convertRadix: wrong from=${from}, base cannot be less than 2`);
if (to < 2)
throw new Error(`convertRadix: wrong to=${to}, base cannot be less than 2`);
if (!Array.isArray(data))
throw new Error("convertRadix: data should be array");
if (!data.length)
return [];
let pos = 0;
const res = [];
const digits = Array.from(data);
digits.forEach((d)=>{
assertNumber2(d);
if (d < 0 || d >= from)
throw new Error(`Wrong integer: ${d}`);
}
);
while (true) {
let carry = 0;
let done = true;
for (let i = pos; i < digits.length; i++) {
const digit = digits[i];
const digitBase = from * carry + digit;
if (!Number.isSafeInteger(digitBase) || from * carry / from !== carry || digitBase - digit !== from * carry) {
throw new Error("convertRadix: carry overflow");
}
carry = digitBase % to;
digits[i] = Math.floor(digitBase / to);
if (!Number.isSafeInteger(digits[i]) || digits[i] * to + carry !== digitBase)
throw new Error("convertRadix: carry overflow");
if (!done)
continue;
else if (!digits[i])
pos = i;
else
done = false;
}
res.push(carry);
if (done)
break;
}
for (let i = 0; i < data.length - 1 && data[i] === 0; i++)
res.push(0);
return res.reverse();
}
var gcd = (a,b)=>!b ? a : gcd(b, a % b);
var radix2carry = (from,to)=>from + (to - gcd(from, to));
function convertRadix2(data, from, to, padding2) {
if (!Array.isArray(data))
throw new Error("convertRadix2: data should be array");
if (from <= 0 || from > 32)
throw new Error(`convertRadix2: wrong from=${from}`);
if (to <= 0 || to > 32)
throw new Error(`convertRadix2: wrong to=${to}`);
if (radix2carry(from, to) > 32) {
throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`);
}
let carry = 0;
let pos = 0;
const mask = 2 ** to - 1;
const res = [];
for (const n of data) {
assertNumber2(n);
if (n >= 2 ** from)
throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);
carry = carry << from | n;
if (pos + from > 32)
throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);
pos += from;
for (; pos >= to; pos -= to)
res.push((carry >> pos - to & mask) >>> 0);
carry &= 2 ** pos - 1;
}
carry = carry << to - pos & mask;
if (!padding2 && pos >= from)
throw new Error("Excess padding");
if (!padding2 && carry)
throw new Error(`Non-zero padding: ${carry}`);
if (padding2 && pos > 0)
res.push(carry >>> 0);
return res;
}
function radix(num) {
assertNumber2(num);
return {
encode: (bytes2)=>{
if (!(bytes2 instanceof Uint8Array))
throw new Error("radix.encode input should be Uint8Array");
return convertRadix(Array.from(bytes2), 2 ** 8, num);
}
,
decode: (digits)=>{
if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number")
throw new Error("radix.decode input should be array of strings");
return Uint8Array.from(convertRadix(digits, num, 2 ** 8));
}
};
}
function radix2(bits, revPadding=false) {
assertNumber2(bits);
if (bits <= 0 || bits > 32)
throw new Error("radix2: bits should be in (0..32]");
if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)
throw new Error("radix2: carry overflow");
return {
encode: (bytes2)=>{
if (!(bytes2 instanceof Uint8Array))
throw new Error("radix2.encode input should be Uint8Array");
return convertRadix2(Array.from(bytes2), 8, bits, !revPadding);
}
,
decode: (digits)=>{
if (!Array.isArray(digits) || digits.length && typeof digits[0] !== "number")
throw new Error("radix2.decode input should be array of strings");
return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));
}
};
}
function unsafeWrapper(fn) {
if (typeof fn !== "function")
throw new Error("unsafeWrapper fn should be function");
return function(...args) {
try {
return fn.apply(null, args);
} catch (e) {}
}
;
}
function checksum(len, fn) {
assertNumber2(len);
if (typeof fn !== "function")
throw new Error("checksum fn should be function");
return {
encode(data) {
if (!(data instanceof Uint8Array))
throw new Error("checksum.encode: input should be Uint8Array");
const checksum2 = fn(data).slice(0, len);
const res = new Uint8Array(data.length + len);
res.set(data);
res.set(checksum2, data.length);
return res;
},
decode(data) {
if (!(data instanceof Uint8Array))
throw new Error("checksum.decode: input should be Uint8Array");
const payload = data.slice(0, -len);
const newChecksum = fn(payload).slice(0, len);
const oldChecksum = data.slice(-len);
for (let i = 0; i < len; i++)
if (newChecksum[i] !== oldChecksum[i])
throw new Error("Invalid checksum");
return payload;
}
};
}
var base16 = chain(radix2(4), alphabet("0123456789ABCDEF"), join(""));
var base32 = chain(radix2(5), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), padding(5), join(""));
var base32hex = chain(radix2(5), alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), padding(5), join(""));
var base32crockford = chain(radix2(5), alphabet("0123456789ABCDEFGHJKMNPQRSTVWXYZ"), join(""), normalize((s)=>s.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1")));
var base64 = chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), padding(6), join(""));
var base64url = chain(radix2(6), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), padding(6), join(""));
var genBase58 = (abc)=>chain(radix(58), alphabet(abc), join(""));
var base58 = genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
var base58flickr = genBase58("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ");
var base58xrp = genBase58("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");
var XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];
var base58xmr = {
encode(data) {
let res = "";
for (let i = 0; i < data.length; i += 8) {
const block = data.subarray(i, i + 8);
res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], "1");
}
return res;
},
decode(str) {
let res = [];
for (let i = 0; i < str.length; i += 11) {
const slice = str.slice(i, i + 11);
const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);
const block = base58.decode(slice);
for (let j = 0; j < block.length - blockLen; j++) {
if (block[j] !== 0)
throw new Error("base58xmr: wrong padding");
}
res = res.concat(Array.from(block.slice(block.length - blockLen)));
}
return Uint8Array.from(res);
}
};
var base58check = (sha2563)=>chain(checksum(4, (data)=>sha2563(sha2563(data))), base58);
var BECH_ALPHABET = chain(alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"), join(""));
var POLYMOD_GENERATORS = [996825010, 642813549, 513874426, 1027748829, 705979059];
function bech32Polymod(pre) {
const b = pre >> 25;
let chk = (pre & 33554431) << 5;
for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {
if ((b >> i & 1) === 1)
chk ^= POLYMOD_GENERATORS[i];
}
return chk;
}
function bechChecksum(prefix, words, encodingConst=1) {
const len = prefix.length;
let chk = 1;
for (let i = 0; i < len; i++) {
const c = prefix.charCodeAt(i);
if (c < 33 || c > 126)
throw new Error(`Invalid prefix (${prefix})`);
chk = bech32Polymod(chk) ^ c >> 5;
}
chk = bech32Polymod(chk);
for (let i = 0; i < len; i++)
chk = bech32Polymod(chk) ^ prefix.charCodeAt(i) & 31;
for (let v of words)
chk = bech32Polymod(chk) ^ v;
for (let i = 0; i < 6; i++)
chk = bech32Polymod(chk);
chk ^= encodingConst;
return BECH_ALPHABET.encode(convertRadix2([chk % 2 ** 30], 30, 5, false));
}
function genBech32(encoding) {
const ENCODING_CONST = encoding === "bech32" ? 1 : 734539939;
const _words = radix2(5);
const fromWords = _words.decode;
const toWords = _words.encode;
const fromWordsUnsafe = unsafeWrapper(fromWords);
function encode(prefix, words, limit=90) {
if (typeof prefix !== "string")
throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`);
if (!Array.isArray(words) || words.length && typeof words[0] !== "number")
throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`);
const actualLength = prefix.length + 7 + words.length;
if (limit !== false && actualLength > limit)
throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);
prefix = prefix.toLowerCase();
return `${prefix}1 ${BECH_ALPHABET.encode(words)}${bechChecksum(prefix, words, ENCODING_CONST)}`;
}
function decode2(str, limit=90) {
if (typeof str !== "string")
throw new Error(`bech32.decode input should be string, not ${typeof str}`);
if (str.length < 8 || limit !== false && str.length > limit)
throw new TypeError(`Wrong string length: ${str.length} (${str}). Expected (8..${limit})`);
const lowered = str.toLowerCase();
if (str !== lowered && str !== str.toUpperCase())
throw new Error(`String must be lowercase or uppercase`);
str = lowered;
const sepIndex = str.lastIndexOf("1");
if (sepIndex === 0 || sepIndex === -1)
throw new Error(`Letter "1" must be present between prefix and data only`);
const prefix = str.slice(0, sepIndex);
const _words2 = str.slice(sepIndex + 1);
if (_words2.length < 6)
throw new Error("Data must be at least 6 characters long");
const words = BECH_ALPHABET.decode(_words2).slice(0, -6);
const sum = bechChecksum(prefix, words, ENCODING_CONST);
if (!_words2.endsWith(sum))
throw new Error(`Invalid checksum in ${str}: expected "${sum}"`);
return {
prefix,
words
};
}
const decodeUnsafe = unsafeWrapper(decode2);
function decodeToBytes(str) {
const {prefix, words} = decode2(str, false);
return {
prefix,
words,
bytes: fromWords(words)
};
}
return {
encode,
decode: decode2,
decodeToBytes,
decodeUnsafe,
fromWords,
fromWordsUnsafe,
toWords
};
}
var bech32 = genBech32("bech32");
var bech32m = genBech32("bech32m");
var utf8 = {
encode: (data)=>new TextDecoder().decode(data),
decode: (str)=>new TextEncoder().encode(str)
};
var hex = chain(radix2(4), alphabet("0123456789abcdef"), join(""), normalize((s)=>{
if (typeof s !== "string" || s.length % 2)
throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);
return s.toLowerCase();
}
));
var CODERS = {
utf8,
hex,
base16,
base32,
base64,
base64url,
base58,
base58xmr
};
var coderTypeError = `Invalid encoding type. Available types: ${Object.keys(CODERS).join(", ")}`;
// node_modules/.pnpm/nostr-tools@1.1.0/node_modules/nostr-tools/lib/nostr.esm.js
var import_english = __toESM(require_english());
var import_bip39 = __toESM(require_bip39());
// node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/esm/_assert.js
function number(n) {
if (!Number.isSafeInteger(n) || n < 0)
throw new Error(`Wrong positive integer: ${n}`);
}
function bool(b) {
if (typeof b !== "boolean")
throw new Error(`Expected boolean, not ${b}`);
}
function bytes(b, ...lengths) {
if (!(b instanceof Uint8Array))
throw new TypeError("Expected Uint8Array");
if (lengths.length > 0 && !lengths.includes(b.length))
throw new TypeError(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
}
function hash(hash2) {
if (typeof hash2 !== "function" || typeof hash2.create !== "function")
throw new Error("Hash should be wrapped by utils.wrapConstructor");
number(hash2.outputLen);
number(hash2.blockLen);
}
function exists(instance, checkFinished=true) {
if (instance.destroyed)
throw new Error("Hash instance has been destroyed");
if (checkFinished && instance.finished)
throw new Error("Hash#digest() has already been called");
}
function output(out, instance) {
bytes(out);
const min = instance.outputLen;
if (out.length < min) {
throw new Error(`digestInto() expects output buffer of length at least ${min}`);
}
}
var assert = {
number,
bool,
bytes,
hash,
exists,
output
};
var assert_default = assert;
// node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/esm/crypto.js
var crypto4 = typeof globalThis === "object" && "crypto"in globalThis ? globalThis.crypto : void 0;
// node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/esm/utils.js
var createView2 = (arr)=>new DataView(arr.buffer,arr.byteOffset,arr.byteLength);
var rotr2 = (word,shift)=>word << 32 - shift | word >>> shift;
var isLE2 = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
if (!isLE2)
throw new Error("Non little-endian hardware is not supported");
var hexes3 = Array.from({
length: 256
}, (v,i)=>i.toString(16).padStart(2, "0"));
function bytesToHex2(uint8a) {
if (!(uint8a instanceof Uint8Array))
throw new Error("Uint8Array expected");
let hex2 = "";
for (let i = 0; i < uint8a.length; i++) {
hex2 += hexes3[uint8a[i]];
}
return hex2;
}
function hexToBytes2(hex2) {
if (typeof hex2 !== "string") {
throw new TypeError("hexToBytes: expected string, got " + typeof hex2);
}
if (hex2.length % 2)
throw new Error("hexToBytes: received invalid unpadded hex");
const array = new Uint8Array(hex2.length / 2);
for (let i = 0; i < array.length; i++) {
const j = i * 2;
const hexByte = hex2.slice(j, j + 2);
const byte = Number.parseInt(hexByte, 16);
if (Number.isNaN(byte) || byte < 0)
throw new Error("Invalid byte sequence");
array[i] = byte;
}
return array;
}
function utf8ToBytes2(str) {
if (typeof str !== "string") {
throw new TypeError(`utf8ToBytes expected string, got ${typeof str}`);
}
return new TextEncoder().encode(str);
}
function toBytes2(data) {
if (typeof data === "string")
data = utf8ToBytes2(data);
if (!(data instanceof Uint8Array))
throw new TypeError(`Expected input type is Uint8Array (got ${typeof data})`);
return data;
}
function concatBytes2(...arrays) {
if (!arrays.every((a)=>a instanceof Uint8Array))
throw new Error("Uint8Array list expected");
if (arrays.length === 1)
return arrays[0];
const length = arrays.reduce((a,arr)=>a + arr.length, 0);
const result = new Uint8Array(length);
for (let i = 0, pad = 0; i < arrays.length; i++) {
const arr = arrays[i];
result.set(arr, pad);
pad += arr.length;
}
return result;
}
var Hash2 = class {
// Safe version that clones internal state
clone() {
return this._cloneInto();
}
}
;
function wrapConstructor2(hashConstructor) {
const hashC = (message)=>hashConstructor().update(toBytes2(message)).digest();
const tmp = hashConstructor();
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = ()=>hashConstructor();
return hashC;
}
function randomBytes2(bytesLength=32) {
if (crypto4 && typeof crypto4.getRandomValues === "function") {
return crypto4.getRandomValues(new Uint8Array(bytesLength));
}
throw new Error("crypto.getRandomValues must be defined");
}
// node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/esm/hmac.js
var HMAC = class extends Hash2 {
constructor(hash2, _key) {
super();
this.finished = false;
this.destroyed = false;
assert_default.hash(hash2);
const key = toBytes2(_key);
this.iHash = hash2.create();
if (typeof this.iHash.update !== "function")
throw new TypeError("Expected instance of class which extends utils.Hash");
this.blockLen = this.iHash.blockLen;
this.outputLen = this.iHash.outputLen;
const blockLen = this.blockLen;
const pad = new Uint8Array(blockLen);
pad.set(key.length > blockLen ? hash2.create().update(key).digest() : key);
for (let i = 0; i < pad.length; i++)
pad[i] ^= 54;
this.iHash.update(pad);
this.oHash = hash2.create();
for (let i = 0; i < pad.length; i++)
pad[i] ^= 54 ^ 92;
this.oHash.update(pad);
pad.fill(0);
}
update(buf) {
assert_default.exists(this);
this.iHash.update(buf);
return this;
}
digestInto(out) {
assert_default.exists(this);
assert_default.bytes(out, this.outputLen);
this.finished = true;
this.iHash.digestInto(out);
this.oHash.update(out);
this.oHash.digestInto(out);
this.destroy();
}
digest() {
const out = new Uint8Array(this.oHash.outputLen);
this.digestInto(out);
return out;
}
_cloneInto(to) {
to || (to = Object.create(Object.getPrototypeOf(this), {}));
const {oHash, iHash, finished, destroyed, blockLen, outputLen} = this;
to = to;
to.finished = finished;
to.destroyed = destroyed;
to.blockLen = blockLen;
to.outputLen = outputLen;
to.oHash = oHash._cloneInto(to.oHash);
to.iHash = iHash._cloneInto(to.iHash);
return to;
}
destroy() {
this.destroyed = true;
this.oHash.destroy();
this.iHash.destroy();
}
}
;
var hmac = (hash2,key,message)=>new HMAC(hash2,key).update(message).digest();
hmac.create = (hash2,key)=>new HMAC(hash2,key);
// node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/esm/_sha2.js
function setBigUint642(view, byteOffset, value, isLE3) {
if (typeof view.setBigUint64 === "function")
return view.setBigUint64(byteOffset, value, isLE3);
const _32n2 = BigInt(32);
const _u32_max = BigInt(4294967295);
const wh = Number(value >> _32n2 & _u32_max);
const wl = Number(value & _u32_max);
const h = isLE3 ? 4 : 0;
const l = isLE3 ? 0 : 4;
view.setUint32(byteOffset + h, wh, isLE3);
view.setUint32(byteOffset + l, wl, isLE3);
}
var SHA22 = class extends Hash2 {
constructor(blockLen, outputLen, padOffset, isLE3) {
super();
this.blockLen = blockLen;
this.outputLen = outputLen;
this.padOffset = padOffset;
this.isLE = isLE3;
this.finished = false;
this.length = 0;
this.pos = 0;
this.destroyed = false;
this.buffer = new Uint8Array(blockLen);
this.view = createView2(this.buffer);
}
update(data) {
assert_default.exists(this);
const {view, buffer, blockLen} = this;
data = toBytes2(data);
const len = data.length;
for (let pos = 0; pos < len; ) {
const take = Math.min(blockLen - this.pos, len - pos);
if (take === blockLen) {
const dataView = createView2(data);
for (; blockLen <= len - pos; pos += blockLen)
this.process(dataView, pos);
continue;
}
buffer.set(data.subarray(pos, pos + take), this.pos);
this.pos += take;
pos += take;
if (this.pos === blockLen) {
this.process(view, 0);
this.pos = 0;
}
}
this.length += data.length;
this.roundClean();
return this;
}
digestInto(out) {
assert_default.exists(this);
assert_default.output(out, this);
this.finished = true;
const {buffer, view, blockLen, isLE: isLE3} = this;
let {pos} = this;
buffer[pos++] = 128;
this.buffer.subarray(pos).fill(0);
if (this.padOffset > blockLen - pos) {
this.process(view, 0);
pos = 0;
}
for (let i = pos; i < blockLen; i++)
buffer[i] = 0;
setBigUint642(view, blockLen - 8, BigInt(this.length * 8), isLE3);
this.process(view, 0);
const oview = createView2(out);
const len = this.outputLen;
if (len % 4)
throw new Error("_sha2: outputLen should be aligned to 32bit");
const outLen = len / 4;
const state = this.get();
if (outLen > state.length)
throw new Error("_sha2: outputLen bigger than state");
for (let i = 0; i < outLen; i++)
oview.setUint32(4 * i, state[i], isLE3);
}
digest() {
const {buffer, outputLen} = this;
this.digestInto(buffer);
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
_cloneInto(to) {
to || (to = new this.constructor());
to.set(...this.get());
const {blockLen, buffer, length, finished, destroyed, pos} = this;
to.length = length;
to.pos = pos;
to.finished = finished;
to.destroyed = destroyed;
if (length % blockLen)
to.buffer.set(buffer);
return to;
}
}
;
// node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/esm/ripemd160.js
var Rho = new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]);
var Id = Uint8Array.from({
length: 16
}, (_,i)=>i);
var Pi = Id.map((i)=>(9 * i + 5) % 16);
var idxL = [Id];
var idxR = [Pi];
for (let i = 0; i < 4; i++)
for (let j of [idxL, idxR])
j.push(j[i].map((k)=>Rho[k]));
var shifts = [[11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5]].map((i)=>new Uint8Array(i));
var shiftsL = idxL.map((idx,i)=>idx.map((j)=>shifts[i][j]));
var shiftsR = idxR.map((idx,i)=>idx.map((j)=>shifts[i][j]));
var Kl = new Uint32Array([0, 1518500249, 1859775393, 2400959708, 2840853838]);
var Kr = new Uint32Array([1352829926, 1548603684, 1836072691, 2053994217, 0]);
var rotl = (word,shift)=>word << shift | word >>> 32 - shift;
function f(group, x, y, z) {
if (group === 0)
return x ^ y ^ z;
else if (group === 1)
return x & y | ~x & z;
else if (group === 2)
return (x | ~y) ^ z;
else if (group === 3)
return x & z | y & ~z;
else
return x ^ (y | ~z);
}
var BUF = new Uint32Array(16);
var RIPEMD160 = class extends SHA22 {
constructor() {
super(64, 20, 8, true);
this.h0 = 1732584193 | 0;
this.h1 = 4023233417 | 0;
this.h2 = 2562383102 | 0;
this.h3 = 271733878 | 0;
this.h4 = 3285377520 | 0;
}
get() {
const {h0, h1, h2, h3, h4} = this;
return [h0, h1, h2, h3, h4];
}
set(h0, h1, h2, h3, h4) {
this.h0 = h0 | 0;
this.h1 = h1 | 0;
this.h2 = h2 | 0;
this.h3 = h3 | 0;
this.h4 = h4 | 0;
}
process(view, offset) {
for (let i = 0; i < 16; i++,
offset += 4)
BUF[i] = view.getUint32(offset, true);
let al = this.h0 | 0
, ar = al
, bl = this.h1 | 0
, br = bl
, cl = this.h2 | 0
, cr = cl
, dl = this.h3 | 0
, dr = dl
, el = this.h4 | 0
, er = el;
for (let group = 0; group < 5; group++) {
const rGroup = 4 - group;
const hbl = Kl[group]
, hbr = Kr[group];
const rl = idxL[group]
, rr = idxR[group];
const sl = shiftsL[group]
, sr = shiftsR[group];
for (let i = 0; i < 16; i++) {
const tl = rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el | 0;
al = el,
el = dl,
dl = rotl(cl, 10) | 0,
cl = bl,
bl = tl;
}
for (let i = 0; i < 16; i++) {
const tr = rotl(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er | 0;
ar = er,
er = dr,
dr = rotl(cr, 10) | 0,
cr = br,
br = tr;
}
}
this.set(this.h1 + cl + dr | 0, this.h2 + dl + er | 0, this.h3 + el + ar | 0, this.h4 + al + br | 0, this.h0 + bl + cr | 0);
}
roundClean() {
BUF.fill(0);
}
destroy() {
this.destroyed = true;
this.buffer.fill(0);
this.set(0, 0, 0, 0, 0);
}
}
;
var ripemd160 = wrapConstructor2(()=>new RIPEMD160());
// node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/esm/sha256.js
var Chi2 = (a,b,c)=>a & b ^ ~a & c;
var Maj2 = (a,b,c)=>a & b ^ a & c ^ b & c;
var SHA256_K2 = new Uint32Array([1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298]);
var IV2 = new Uint32Array([1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225]);
var SHA256_W2 = new Uint32Array(64);
var SHA2562 = class extends SHA22 {
constructor() {
super(64, 32, 8, false);
this.A = IV2[0] | 0;
this.B = IV2[1] | 0;
this.C = IV2[2] | 0;
this.D = IV2[3] | 0;
this.E = IV2[4] | 0;
this.F = IV2[5] | 0;
this.G = IV2[6] | 0;
this.H = IV2[7] | 0;
}
get() {
const {A, B, C, D, E, F, G, H} = this;
return [A, B, C, D, E, F, G, H];
}
// prettier-ignore
set(A, B, C, D, E, F, G, H) {
this.A = A | 0;
this.B = B | 0;
this.C = C | 0;
this.D = D | 0;
this.E = E | 0;
this.F = F | 0;
this.G = G | 0;
this.H = H | 0;
}
process(view, offset) {
for (let i = 0; i < 16; i++,
offset += 4)
SHA256_W2[i] = view.getUint32(offset, false);
for (let i = 16; i < 64; i++) {
const W15 = SHA256_W2[i - 15];
const W2 = SHA256_W2[i - 2];
const s0 = rotr2(W15, 7) ^ rotr2(W15, 18) ^ W15 >>> 3;
const s1 = rotr2(W2, 17) ^ rotr2(W2, 19) ^ W2 >>> 10;
SHA256_W2[i] = s1 + SHA256_W2[i - 7] + s0 + SHA256_W2[i - 16] | 0;
}
let {A, B, C, D, E, F, G, H} = this;
for (let i = 0; i < 64; i++) {
const sigma1 = rotr2(E, 6) ^ rotr2(E, 11) ^ rotr2(E, 25);
const T1 = H + sigma1 + Chi2(E, F, G) + SHA256_K2[i] + SHA256_W2[i] | 0;
const sigma0 = rotr2(A, 2) ^ rotr2(A, 13) ^ rotr2(A, 22);
const T2 = sigma0 + Maj2(A, B, C) | 0;
H = G;
G = F;
F = E;
E = D + T1 | 0;
D = C;
C = B;
B = A;
A = T1 + T2 | 0;
}
A = A + this.A | 0;
B = B + this.B | 0;
C = C + this.C | 0;
D = D + this.D | 0;
E = E + this.E | 0;
F = F + this.F | 0;
G = G + this.G | 0;
H = H + this.H | 0;
this.set(A, B, C, D, E, F, G, H);
}
roundClean() {
SHA256_W2.fill(0);
}
destroy() {
this.set(0, 0, 0, 0, 0, 0, 0, 0);
this.buffer.fill(0);
}
}
;
var SHA224 = class extends SHA2562 {
constructor() {
super();
this.A = 3238371032 | 0;
this.B = 914150663 | 0;
this.C = 812702999 | 0;
this.D = 4144912697 | 0;
this.E = 4290775857 | 0;
this.F = 1750603025 | 0;
this.G = 1694076839 | 0;
this.H = 3204075428 | 0;
this.outputLen = 28;
}
}
;
var sha2562 = wrapConstructor2(()=>new SHA2562());
var sha224 = wrapConstructor2(()=>new SHA224());
// node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/esm/_u64.js
var U32_MASK64 = BigInt(2 ** 32 - 1);
var _32n = BigInt(32);
function fromBig(n, le=false) {
if (le)
return {
h: Number(n & U32_MASK64),
l: Number(n >> _32n & U32_MASK64)
};
return {
h: Number(n >> _32n & U32_MASK64) | 0,
l: Number(n & U32_MASK64) | 0
};
}
function split(lst, le=false) {
let Ah = new Uint32Array(lst.length);
let Al = new Uint32Array(lst.length);
for (let i = 0; i < lst.length; i++) {
const {h, l} = fromBig(lst[i], le);
[Ah[i],Al[i]] = [h, l];
}
return [Ah, Al];
}
var toBig = (h,l)=>BigInt(h >>> 0) << _32n | BigInt(l >>> 0);
var shrSH = (h,l,s)=>h >>> s;
var shrSL = (h,l,s)=>h << 32 - s | l >>> s;
var rotrSH = (h,l,s)=>h >>> s | l << 32 - s;
var rotrSL = (h,l,s)=>h << 32 - s | l >>> s;
var rotrBH = (h,l,s)=>h << 64 - s | l >>> s - 32;
var rotrBL = (h,l,s)=>h >>> s - 32 | l << 64 - s;
var rotr32H = (h,l)=>l;
var rotr32L = (h,l)=>h;
var rotlSH = (h,l,s)=>h << s | l >>> 32 - s;
var rotlSL = (h,l,s)=>l << s | h >>> 32 - s;
var rotlBH = (h,l,s)=>l << s - 32 | h >>> 64 - s;
var rotlBL = (h,l,s)=>h << s - 32 | l >>> 64 - s;
function add(Ah, Al, Bh, Bl) {
const l = (Al >>> 0) + (Bl >>> 0);
return {
h: Ah + Bh + (l / 2 ** 32 | 0) | 0,
l: l | 0
};
}
var add3L = (Al,Bl,Cl)=>(Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
var add3H = (low,Ah,Bh,Ch)=>Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
var add4L = (Al,Bl,Cl,Dl)=>(Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
var add4H = (low,Ah,Bh,Ch,Dh)=>Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
var add5L = (Al,Bl,Cl,Dl,El)=>(Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
var add5H = (low,Ah,Bh,Ch,Dh,Eh)=>Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
var u64 = {
fromBig,
split,
toBig,
shrSH,
shrSL,
rotrSH,
rotrSL,
rotrBH,
rotrBL,
rotr32H,
rotr32L,
rotlSH,
rotlSL,
rotlBH,
rotlBL,
add,
add3L,
add3H,
add4L,
add4H,
add5H,
add5L
};
var u64_default = u64;
// node_modules/.pnpm/@noble+hashes@1.3.0/node_modules/@noble/hashes/esm/sha512.js
var [SHA512_Kh,SHA512_Kl] = u64_default.split(["0x428a2f98d728ae22", "0x7137449123ef65cd", "0xb5c0fbcfec4d3b2f", "0xe9b5dba58189dbbc", "0x3956c25bf348b538", "0x59f111f1b605d019", "0x923f82a4af194f9b", "0xab1c5ed5da6d8118", "0xd807aa98a3030242", "0x12835b0145706fbe", "0x243185be4ee4b28c", "0x550c7dc3d5ffb4e2", "0x72be5d74f27b896f", "0x80deb1fe3b1696b1", "0x9bdc06a725c71235", "0xc19bf174cf692694", "0xe49b69c19ef14ad2", "0xefbe4786384f25e3", "0x0fc19dc68b8cd5b5", "0x240ca1cc77ac9c65", "0x2de92c6f592b0275", "0x4a7484aa6ea6e483", "0x5cb0a9dcbd41fbd4", "0x76f988da831153b5", "0x983e5152ee66dfab", "0xa831c66d2db43210", "0xb00327c898fb213f", "0xbf597fc7beef0ee4", "0xc6e00bf33da88fc2", "0xd5a79147930aa725", "0x06ca6351e003826f", "0x142929670a0e6e70", "0x27b70a8546d22ffc", "0x2e1b21385c26c926", "0x4d2c6dfc5ac42aed", "0x53380d139d95b3df", "0x650a73548baf63de", "0x766a0abb3c77b2a8", "0x81c2c92e47edaee6", "0x92722c851482353b", "0xa2bfe8a14cf10364", "0xa81a664bbc423001", "0xc24b8b70d0f89791", "0xc76c51a30654be30", "0xd192e819d6ef5218", "0xd69906245565a910", "0xf40e35855771202a", "0x106aa07032bbd1b8", "0x19a4c116b8d2d0c8", "0x1e376c085141ab53", "0x2748774cdf8eeb99", "0x34b0bcb5e19b48a8", "0x391c0cb3c5c95a63", "0x4ed8aa4ae3418acb", "0x5b9cca4f7763e373", "0x682e6ff3d6b2b8a3", "0x748f82ee5defb2fc", "0x78a5636f43172f60", "0x84c87814a1f0ab72", "0x8cc702081a6439ec", "0x90befffa23631e28", "0xa4506cebde82bde9", "0xbef9a3f7b2c67915", "0xc67178f2e372532b", "0xca273eceea26619c", "0xd186b8c721c0c207", "0xeada7dd6cde0eb1e", "0xf57d4f7fee6ed178", "0x06f067aa72176fba", "0x0a637dc5a2c898a6", "0x113f9804bef90dae", "0x1b710b35131c471b", "0x28db77f523047d84", "0x32caab7b40c72493", "0x3c9ebe0a15c9bebc", "0x431d67c49c100d4c", "0x4cc5d4becb3e42b6", "0x597f299cfc657e2a", "0x5fcb6fab3ad6faec", "0x6c44198c4a475817"].map((n)=>BigInt(n)));
var SHA512_W_H = new Uint32Array(80);
var SHA512_W_L = new Uint32Array(80);
var SHA512 = class extends SHA22 {
constructor() {
super(128, 64, 16, false);
this.Ah = 1779033703 | 0;
this.Al = 4089235720 | 0;
this.Bh = 3144134277 | 0;
this.Bl = 2227873595 | 0;
this.Ch = 1013904242 | 0;
this.Cl = 4271175723 | 0;
this.Dh = 2773480762 | 0;
this.Dl = 1595750129 | 0;
this.Eh = 1359893119 | 0;
this.El = 2917565137 | 0;
this.Fh = 2600822924 | 0;
this.Fl = 725511199 | 0;
this.Gh = 528734635 | 0;
this.Gl = 4215389547 | 0;
this.Hh = 1541459225 | 0;
this.Hl = 327033209 | 0;
}
// prettier-ignore
get() {
const {Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl} = this;
return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
}
// prettier-ignore
set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
this.Ah = Ah | 0;
this.Al = Al | 0;
this.Bh = Bh | 0;
this.Bl = Bl | 0;
this.Ch = Ch | 0;
this.Cl = Cl | 0;
this.Dh = Dh | 0;
this.Dl = Dl | 0;
this.Eh = Eh | 0;
this.El = El | 0;
this.Fh = Fh | 0;
this.Fl = Fl | 0;
this.Gh = Gh | 0;
this.Gl = Gl | 0;
this.Hh = Hh | 0;
this.Hl = Hl | 0;
}
process(view, offset) {
for (let i = 0; i < 16; i++,
offset += 4) {
SHA512_W_H[i] = view.getUint32(offset);
SHA512_W_L[i] = view.getUint32(offset += 4);
}
for (let i = 16; i < 80; i++) {
const W15h = SHA512_W_H[i - 15] | 0;
const W15l = SHA512_W_L[i - 15] | 0;
const s0h = u64_default.rotrSH(W15h, W15l, 1) ^ u64_default.rotrSH(W15h, W15l, 8) ^ u64_default.shrSH(W15h, W15l, 7);
const s0l = u64_default.rotrSL(W15h, W15l, 1) ^ u64_default.rotrSL(W15h, W15l, 8) ^ u64_default.shrSL(W15h, W15l, 7);
const W2h = SHA512_W_H[i - 2] | 0;
const W2l = SHA512_W_L[i - 2] | 0;
const s1h = u64_default.rotrSH(W2h, W2l, 19) ^ u64_default.rotrBH(W2h, W2l, 61) ^ u64_default.shrSH(W2h, W2l, 6);
const s1l = u64_default.rotrSL(W2h, W2l, 19) ^ u64_default.rotrBL(W2h, W2l, 61) ^ u64_default.shrSL(W2h, W2l, 6);
const SUMl = u64_default.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
const SUMh = u64_default.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
SHA512_W_H[i] = SUMh | 0;
SHA512_W_L[i] = SUMl | 0;
}
let {Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl} = this;
for (let i = 0; i < 80; i++) {
const sigma1h = u64_default.rotrSH(Eh, El, 14) ^ u64_default.rotrSH(Eh, El, 18) ^ u64_default.rotrBH(Eh, El, 41);
const sigma1l = u64_default.rotrSL(Eh, El, 14) ^ u64_default.rotrSL(Eh, El, 18) ^ u64_default.rotrBL(Eh, El, 41);
const CHIh = Eh & Fh ^ ~Eh & Gh;
const CHIl = El & Fl ^ ~El & Gl;
const T1ll = u64_default.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
const T1h = u64_default.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
const T1l = T1ll | 0;
const sigma0h = u64_default.rotrSH(Ah, Al, 28) ^ u64_default.rotrBH(Ah, Al, 34) ^ u64_default.rotrBH(Ah, Al, 39);
const sigma0l = u64_default.rotrSL(Ah, Al, 28) ^ u64_default.rotrBL(Ah, Al, 34) ^ u64_default.rotrBL(Ah, Al, 39);
const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
Hh = Gh | 0;
Hl = Gl | 0;
Gh = Fh | 0;
Gl = Fl | 0;
Fh = Eh | 0;
Fl = El | 0;
({h: Eh, l: El} = u64_default.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
Dh = Ch | 0;
Dl = Cl | 0;
Ch = Bh | 0;
Cl = Bl | 0;
Bh = Ah | 0;
Bl = Al | 0;
const All = u64_default.add3L(T1l, sigma0l, MAJl);
Ah = u64_default.add3H(All, T1h, sigma0h, MAJh);
Al = All | 0;
}
({h: Ah, l: Al} = u64_default.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
({h: Bh, l: Bl} = u64_default.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
({h: Ch, l: Cl} = u64_default.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
({h: Dh, l: Dl} = u64_default.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
({h: Eh, l: El} = u64_default.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
({h: Fh, l: Fl} = u64_default.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
({h: Gh, l: Gl} = u64_default.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
({h: Hh, l: Hl} = u64_default.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
}
roundClean() {
SHA512_W_H.fill(0);
SHA512_W_L.fill(0);
}
destroy() {
this.buffer.fill(0);
this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
}
;
var SHA512_224 = class extends SHA512 {
constructor() {
super();
this.Ah = 2352822216 | 0;
this.Al = 424955298 | 0;
this.Bh = 1944164710 | 0;
this.Bl = 2312950998 | 0;
this.Ch = 502970286 | 0;
this.Cl = 855612546 | 0;
this.Dh = 1738396948 | 0;
this.Dl = 1479516111 | 0;
this.Eh = 258812777 | 0;
this.El = 2077511080 | 0;
this.Fh = 2011393907 | 0;
this.Fl = 79989058 | 0;
this.Gh = 1067287976 | 0;
this.Gl = 1780299464 | 0;
this.Hh = 286451373 | 0;
this.Hl = 2446758561 | 0;
this.outputLen = 28;
}
}
;
var SHA512_256 = class extends SHA512 {
constructor() {
super();
this.Ah = 573645204 | 0;
this.Al = 4230739756 | 0;
this.Bh = 2673172387 | 0;
this.Bl = 3360449730 | 0;
this.Ch = 596883563 | 0;
this.Cl = 1867755857 | 0;
this.Dh = 2520282905 | 0;
this.Dl = 1497426621 | 0;
this.Eh = 2519219938 | 0;
this.El = 2827943907 | 0;
this.Fh = 3193839141 | 0;
this.Fl = 1401305490 | 0;
this.Gh = 721525244 | 0;
this.Gl = 746961066 | 0;
this.Hh = 246885852 | 0;
this.Hl = 2177182882 | 0;
this.outputLen = 32;
}
}
;
var SHA384 = class extends SHA512 {
constructor() {
super();
this.Ah = 3418070365 | 0;
this.Al = 3238371032 | 0;
this.Bh = 1654270250 | 0;
this.Bl = 914150663 | 0;
this.Ch = 2438529370 | 0;
this.Cl = 812702999 | 0;
this.Dh = 355462360 | 0;
this.Dl = 4144912697 | 0;
this.Eh = 1731405415 | 0;
this.El = 4290775857 | 0;
this.Fh = 2394180231 | 0;
this.Fl = 1750603025 | 0;
this.Gh = 3675008525 | 0;
this.Gl = 1694076839 | 0;
this.Hh = 1203062813 | 0;
this.Hl = 3204075428 | 0;
this.outputLen = 48;
}
}
;
var sha512 = wrapConstructor2(()=>new SHA512());
var sha512_224 = wrapConstructor2(()=>new SHA512_224());
var sha512_256 = wrapConstructor2(()=>new SHA512_256());
var sha384 = wrapConstructor2(()=>new SHA384());
// node_modules/.pnpm/@noble+curves@1.0.0/node_modules/@noble/curves/esm/abstract/utils.js
var utils_exports = {};
__export(utils_exports, {
bitGet: ()=>bitGet,
bitLen: ()=>bitLen,
bitMask: ()=>bitMask,
bitSet: ()=>bitSet,
bytesToHex: ()=>bytesToHex3,
bytesToNumberBE: ()=>bytesToNumberBE,
bytesToNumberLE: ()=>bytesToNumberLE,
concatBytes: ()=>concatBytes3,
createHmacDrbg: ()=>createHmacDrbg,
ensureBytes: ()=>ensureBytes2,
equalBytes: ()=>equalBytes,
hexToBytes: ()=>hexToBytes3,
hexToNumber: ()=>hexToNumber2,
numberToBytesBE: ()=>numberToBytesBE,
numberToBytesLE: ()=>numberToBytesLE,
numberToHexUnpadded: ()=>numberToHexUnpadded2,
numberToVarBytesBE: ()=>numberToVarBytesBE,
utf8ToBytes: ()=>utf8ToBytes3,
validateObject: ()=>validateObject
});
var _0n2 = BigInt(0);
var _1n2 = BigInt(1);
var _2n2 = BigInt(2);
var u8a = (a)=>a instanceof Uint8Array;
var hexes4 = Array.from({
length: 256
}, (v,i)=>i.toString(16).padStart(2, "0"));
function bytesToHex3(bytes2) {
if (!u8a(bytes2))
throw new Error("Uint8Array expected");
let hex2 = "";
for (let i = 0; i < bytes2.length; i++) {
hex2 += hexes4[bytes2[i]];
}
return hex2;
}
function numberToHexUnpadded2(num) {
const hex2 = num.toString(16);
return hex2.length & 1 ? `0 ${hex2}` : hex2;
}
function hexToNumber2(hex2) {
if (typeof hex2 !== "string")
throw new Error("hex string expected, got " + typeof hex2);
return BigInt(hex2 === "" ? "0" : `0x ${hex2}`);
}
function hexToBytes3(hex2) {
if (typeof hex2 !== "string")
throw new Error("hex string expected, got " + typeof hex2);
if (hex2.length % 2)
throw new Error("hex string is invalid: unpadded " + hex2.length);
const array = new Uint8Array(hex2.length / 2);
for (let i = 0; i < array.length; i++) {
const j = i * 2;
const hexByte = hex2.slice(j, j + 2);
const byte = Number.parseInt(hexByte, 16);
if (Number.isNaN(byte) || byte < 0)
throw new Error("invalid byte sequence");
array[i] = byte;
}
return array;
}
function bytesToNumberBE(bytes2) {
return hexToNumber2(bytesToHex3(bytes2));
}
function bytesToNumberLE(bytes2) {
if (!u8a(bytes2))
throw new Error("Uint8Array expected");
return hexToNumber2(bytesToHex3(Uint8Array.from(bytes2).reverse()));
}
var numberToBytesBE = (n,len)=>hexToBytes3(n.toString(16).padStart(len * 2, "0"));
var numberToBytesLE = (n,len)=>numberToBytesBE(n, len).reverse();
var numberToVarBytesBE = (n)=>hexToBytes3(numberToHexUnpadded2(n));
function ensureBytes2(title, hex2, expectedLength) {
let res;
if (typeof hex2 === "string") {
try {
res = hexToBytes3(hex2);
} catch (e) {
throw new Error(`${title} must be valid hex string, got "${hex2}". Cause: ${e}`);
}
} else if (u8a(hex2)) {
res = Uint8Array.from(hex2);
} else {
throw new Error(`${title} must be hex string or Uint8Array`);
}
const len = res.length;
if (typeof expectedLength === "number" && len !== expectedLength)
throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
return res;
}
function concatBytes3(...arrs) {
const r = new Uint8Array(arrs.reduce((sum,a)=>sum + a.length, 0));
let pad = 0;
arrs.forEach((a)=>{
if (!u8a(a))
throw new Error("Uint8Array expected");
r.set(a, pad);
pad += a.length;
}
);
return r;
}
function equalBytes(b1, b2) {
if (b1.length !== b2.length)
return false;
for (let i = 0; i < b1.length; i++)
if (b1[i] !== b2[i])
return false;
return true;
}
function utf8ToBytes3(str) {
if (typeof str !== "string") {
throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
}
return new TextEncoder().encode(str);
}
function bitLen(n) {
let len;
for (len = 0; n > _0n2; n >>= _1n2,
len += 1)
;
return len;
}
var bitGet = (n,pos)=>n >> BigInt(pos) & _1n2;
var bitSet = (n,pos,value)=>n | (value ? _1n2 : _0n2) << BigInt(pos);
var bitMask = (n)=>(_2n2 << BigInt(n - 1)) - _1n2;
var u8n = (data)=>new Uint8Array(data);
var u8fr = (arr)=>Uint8Array.from(arr);
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
if (typeof hashLen !== "number" || hashLen < 2)
throw new Error("hashLen must be a number");
if (typeof qByteLen !== "number" || qByteLen < 2)
throw new Error("qByteLen must be a number");
if (typeof hmacFn !== "function")
throw new Error("hmacFn must be a function");
let v = u8n(hashLen);
let k = u8n(hashLen);
let i = 0;
const reset = ()=>{
v.fill(1);
k.fill(0);
i = 0;
}
;
const h = (...b)=>hmacFn(k, v, ...b);
const reseed = (seed=u8n())=>{
k = h(u8fr([0]), seed);
v = h();
if (seed.length === 0)
return;
k = h(u8fr([1]), seed);
v = h();
}
;
const gen = ()=>{
if (i++ >= 1e3)
throw new Error("drbg: tried 1000 values");
let len = 0;
const out = [];
while (len < qByteLen) {
v = h();
const sl = v.slice();
out.push(sl);
len += v.length;
}
return concatBytes3(...out);
}
;
const genUntil = (seed,pred)=>{
reset();
reseed(seed);
let res = void 0;
while (!(res = pred(gen())))
reseed();
reset();
return res;
}
;
return genUntil;
}
var validatorFns = {
bigint: (val)=>typeof val === "bigint",
function: (val)=>typeof val === "function",
boolean: (val)=>typeof val === "boolean",
string: (val)=>typeof val === "string",
isSafeInteger: (val)=>Number.isSafeInteger(val),
array: (val)=>Array.isArray(val),
field: (val,object)=>object.Fp.isValid(val),
hash: (val)=>typeof val === "function" && Number.isSafeInteger(val.outputLen)
};
function validateObject(object, validators, optValidators={}) {
const checkField = (fieldName,type,isOptional)=>{
const checkVal = validatorFns[type];
if (typeof checkVal !== "function")
throw new Error(`Invalid validator "${type}", expected function`);
const val = object[fieldName];
if (isOptional && val === void 0)
return;
if (!checkVal(val, object)) {
throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);
}
}
;
for (const [fieldName,type] of Object.entries(validators))
checkField(fieldName, type, false);
for (const [fieldName,type] of Object.entries(optValidators))
checkField(fieldName, type, true);
return object;
}
// node_modules/.pnpm/@noble+curves@1.0.0/node_modules/@noble/curves/esm/abstract/modular.js
var _0n3 = BigInt(0);
var _1n3 = BigInt(1);
var _2n3 = BigInt(2);
var _3n2 = BigInt(3);
var _4n = BigInt(4);
var _5n = BigInt(5);
var _8n2 = BigInt(8);
var _9n = BigInt(9);
var _16n = BigInt(16);
function mod2(a, b) {
const result = a % b;
return result >= _0n3 ? result : b + result;
}
function pow(num, power, modulo) {
if (modulo <= _0n3 || power < _0n3)
throw new Error("Expected power/modulo > 0");
if (modulo === _1n3)
return _0n3;
let res = _1n3;
while (power > _0n3) {
if (power & _1n3)
res = res * num % modulo;
num = num * num % modulo;
power >>= _1n3;
}
return res;
}
function pow22(x, power, modulo) {
let res = x;
while (power-- > _0n3) {
res *= res;
res %= modulo;
}
return res;
}
function invert2(number2, modulo) {
if (number2 === _0n3 || modulo <= _0n3) {
throw new Error(`invert: expected positive integers, got n=${number2} mod=${modulo}`);
}
let a = mod2(number2, modulo);
let b = modulo;
let x = _0n3
, y = _1n3
, u = _1n3
, v = _0n3;
while (a !== _0n3) {
const q = b / a;
const r = b % a;
const m = x - u * q;
const n = y - v * q;
b = a,
a = r,
x = u,
y = v,
u = m,
v = n;
}
const gcd2 = b;
if (gcd2 !== _1n3)
throw new Error("invert: does not exist");
return mod2(x, modulo);
}
function tonelliShanks(P) {
const legendreC = (P - _1n3) / _2n3;
let Q, S, Z;
for (Q = P - _1n3,
S = 0; Q % _2n3 === _0n3; Q /= _2n3,
S++)
;
for (Z = _2n3; Z < P && pow(Z, legendreC, P) !== P - _1n3; Z++)
;
if (S === 1) {
const p1div4 = (P + _1n3) / _4n;
return function tonelliFast(Fp2, n) {
const root = Fp2.pow(n, p1div4);
if (!Fp2.eql(Fp2.sqr(root), n))
throw new Error("Cannot find square root");
return root;
}
;
}
const Q1div2 = (Q + _1n3) / _2n3;
return function tonelliSlow(Fp2, n) {
if (Fp2.pow(n, legendreC) === Fp2.neg(Fp2.ONE))
throw new Error("Cannot find square root");
let r = S;
let g = Fp2.pow(Fp2.mul(Fp2.ONE, Z), Q);
let x = Fp2.pow(n, Q1div2);
let b = Fp2.pow(n, Q);
while (!Fp2.eql(b, Fp2.ONE)) {
if (Fp2.eql(b, Fp2.ZERO))
return Fp2.ZERO;
let m = 1;
for (let t2 = Fp2.sqr(b); m < r; m++) {
if (Fp2.eql(t2, Fp2.ONE))
break;
t2 = Fp2.sqr(t2);
}
const ge2 = Fp2.pow(g, _1n3 << BigInt(r - m - 1));
g = Fp2.sqr(ge2);
x = Fp2.mul(x, ge2);
b = Fp2.mul(b, g);
r = m;
}
return x;
}
;
}
function FpSqrt(P) {
if (P % _4n === _3n2) {
const p1div4 = (P + _1n3) / _4n;
return function sqrt3mod4(Fp2, n) {
const root = Fp2.pow(n, p1div4);
if (!Fp2.eql(Fp2.sqr(root), n))
throw new Error("Cannot find square root");
return root;
}
;
}
if (P % _8n2 === _5n) {
const c1 = (P - _5n) / _8n2;
return function sqrt5mod8(Fp2, n) {
const n2 = Fp2.mul(n, _2n3);
const v = Fp2.pow(n2, c1);
const nv = Fp2.mul(n, v);
const i = Fp2.mul(Fp2.mul(nv, _2n3), v);
const root = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE));
if (!Fp2.eql(Fp2.sqr(root), n))
throw new Error("Cannot find square root");
return root;
}
;
}
if (P % _16n === _9n) {}
return tonelliShanks(P);
}
var FIELD_FIELDS = ["create", "isValid", "is0", "neg", "inv", "sqrt", "sqr", "eql", "add", "sub", "mul", "pow", "div", "addN", "subN", "mulN", "sqrN"];
function validateField(field) {
const initial = {
ORDER: "bigint",
MASK: "bigint",
BYTES: "isSafeInteger",
BITS: "isSafeInteger"
};
const opts = FIELD_FIELDS.reduce((map,val)=>{
map[val] = "function";
return map;
}
, initial);
return validateObject(field, opts);
}
function FpPow(f2, num, power) {
if (power < _0n3)
throw new Error("Expected power > 0");
if (power === _0n3)
return f2.ONE;
if (power === _1n3)
return num;
let p = f2.ONE;
let d = num;
while (power > _0n3) {
if (power & _1n3)
p = f2.mul(p, d);
d = f2.sqr(d);
power >>= _1n3;
}
return p;
}
function FpInvertBatch(f2, nums) {
const tmp = new Array(nums.length);
const lastMultiplied = nums.reduce((acc,num,i)=>{
if (f2.is0(num))
return acc;
tmp[i] = acc;
return f2.mul(acc, num);
}
, f2.ONE);
const inverted = f2.inv(lastMultiplied);
nums.reduceRight((acc,num,i)=>{
if (f2.is0(num))
return acc;
tmp[i] = f2.mul(acc, tmp[i]);
return f2.mul(acc, num);
}
, inverted);
return tmp;
}
function nLength(n, nBitLength) {
const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
const nByteLength = Math.ceil(_nBitLength / 8);
return {
nBitLength: _nBitLength,
nByteLength
};
}
function Field(ORDER, bitLen2, isLE3=false, redef={}) {
if (ORDER <= _0n3)
throw new Error(`Expected Fp ORDER > 0, got ${ORDER}`);
const {nBitLength: BITS, nByteLength: BYTES} = nLength(ORDER, bitLen2);
if (BYTES > 2048)
throw new Error("Field lengths over 2048 bytes are not supported");
const sqrtP = FpSqrt(ORDER);
const f2 = Object.freeze({
ORDER,
BITS,
BYTES,
MASK: bitMask(BITS),
ZERO: _0n3,
ONE: _1n3,
create: (num)=>mod2(num, ORDER),
isValid: (num)=>{
if (typeof num !== "bigint")
throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);
return _0n3 <= num && num < ORDER;
}
,
is0: (num)=>num === _0n3,
isOdd: (num)=>(num & _1n3) === _1n3,
neg: (num)=>mod2(-num, ORDER),
eql: (lhs,rhs)=>lhs === rhs,
sqr: (num)=>mod2(num * num, ORDER),
add: (lhs,rhs)=>mod2(lhs + rhs, ORDER),
sub: (lhs,rhs)=>mod2(lhs - rhs, ORDER),
mul: (lhs,rhs)=>mod2(lhs * rhs, ORDER),
pow: (num,power)=>FpPow(f2, num, power),
div: (lhs,rhs)=>mod2(lhs * invert2(rhs, ORDER), ORDER),
// Same as above, but doesn't normalize
sqrN: (num)=>num * num,
addN: (lhs,rhs)=>lhs + rhs,
subN: (lhs,rhs)=>lhs - rhs,
mulN: (lhs,rhs)=>lhs * rhs,
inv: (num)=>invert2(num, ORDER),
sqrt: redef.sqrt || ((n)=>sqrtP(f2, n)),
invertBatch: (lst)=>FpInvertBatch(f2, lst),
// TODO: do we really need constant cmov?
// We don't have const-time bigints anyway, so probably will be not very useful
cmov: (a,b,c)=>c ? b : a,
toBytes: (num)=>isLE3 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
fromBytes: (bytes2)=>{
if (bytes2.length !== BYTES)
throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes2.length}`);
return isLE3 ? bytesToNumberLE(bytes2) : bytesToNumberBE(bytes2);
}
});
return Object.freeze(f2);
}
function hashToPrivateScalar(hash2, groupOrder, isLE3=false) {
hash2 = ensureBytes2("privateHash", hash2);
const hashLen = hash2.length;
const minLen = nLength(groupOrder).nByteLength + 8;
if (minLen < 24 || hashLen < minLen || hashLen > 1024)
throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);
const num = isLE3 ? bytesToNumberLE(hash2) : bytesToNumberBE(hash2);
return mod2(num, groupOrder - _1n3) + _1n3;
}
// node_modules/.pnpm/@noble+curves@1.0.0/node_modules/@noble/curves/esm/abstract/curve.js
var _0n4 = BigInt(0);
var _1n4 = BigInt(1);
function wNAF(c, bits) {
const constTimeNegate2 = (condition,item)=>{
const neg = item.negate();
return condition ? neg : item;
}
;
const opts = (W)=>{
const windows = Math.ceil(bits / W) + 1;
const windowSize = 2 ** (W - 1);
return {
windows,
windowSize
};
}
;
return {
constTimeNegate: constTimeNegate2,
// non-const time multiplication ladder
unsafeLadder(elm, n) {
let p = c.ZERO;
let d = elm;
while (n > _0n4) {
if (n & _1n4)
p = p.add(d);
d = d.double();
n >>= _1n4;
}
return p;
},
/**
* Creates a wNAF precomputation window. Used for caching.
* Default window size is set by `utils.precompute()` and is equal to 8.
* Number of precomputed points depends on the curve size:
* 2^(𝑊1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
* - 𝑊 is the window size
* - 𝑛 is the bitlength of the curve order.
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
* @returns precomputed point tables flattened to a single array
*/
precomputeWindow(elm, W) {
const {windows, windowSize} = opts(W);
const points = [];
let p = elm;
let base = p;
for (let window = 0; window < windows; window++) {
base = p;
points.push(base);
for (let i = 1; i < windowSize; i++) {
base = base.add(p);
points.push(base);
}
p = base.double();
}
return points;
},
/**
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
* @param W window size
* @param precomputes precomputed tables
* @param n scalar (we don't check here, but should be less than curve order)
* @returns real and fake (for const-time) points
*/
wNAF(W, precomputes, n) {
const {windows, windowSize} = opts(W);
let p = c.ZERO;
let f2 = c.BASE;
const mask = BigInt(2 ** W - 1);
const maxNumber = 2 ** W;
const shiftBy = BigInt(W);
for (let window = 0; window < windows; window++) {
const offset = window * windowSize;
let wbits = Number(n & mask);
n >>= shiftBy;
if (wbits > windowSize) {
wbits -= maxNumber;
n += _1n4;
}
const offset1 = offset;
const offset2 = offset + Math.abs(wbits) - 1;
const cond1 = window % 2 !== 0;
const cond2 = wbits < 0;
if (wbits === 0) {
f2 = f2.add(constTimeNegate2(cond1, precomputes[offset1]));
} else {
p = p.add(constTimeNegate2(cond2, precomputes[offset2]));
}
}
return {
p,
f: f2
};
},
wNAFCached(P, precomputesMap, n, transform) {
const W = P._WINDOW_SIZE || 1;
let comp = precomputesMap.get(P);
if (!comp) {
comp = this.precomputeWindow(P, W);
if (W !== 1) {
precomputesMap.set(P, transform(comp));
}
}
return this.wNAF(W, comp, n);
}
};
}
function validateBasic(curve) {
validateField(curve.Fp);
validateObject(curve, {
n: "bigint",
h: "bigint",
Gx: "field",
Gy: "field"
}, {
nBitLength: "isSafeInteger",
nByteLength: "isSafeInteger"
});
return Object.freeze({
...nLength(curve.n, curve.nBitLength),
...curve,
...{
p: curve.Fp.ORDER
}
});
}
// node_modules/.pnpm/@noble+curves@1.0.0/node_modules/@noble/curves/esm/abstract/weierstrass.js
function validatePointOpts(curve) {
const opts = validateBasic(curve);
validateObject(opts, {
a: "field",
b: "field"
}, {
allowedPrivateKeyLengths: "array",
wrapPrivateKey: "boolean",
isTorsionFree: "function",
clearCofactor: "function",
allowInfinityPoint: "boolean",
fromBytes: "function",
toBytes: "function"
});
const {endo: endo2, Fp: Fp2, a} = opts;
if (endo2) {
if (!Fp2.eql(a, Fp2.ZERO)) {
throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");
}
if (typeof endo2 !== "object" || typeof endo2.beta !== "bigint" || typeof endo2.splitScalar !== "function") {
throw new Error("Expected endomorphism with beta: bigint and splitScalar: function");
}
}
return Object.freeze({
...opts
});
}
var {bytesToNumberBE: b2n, hexToBytes: h2b} = utils_exports;
var DER = {
// asn.1 DER encoding utils
Err: class DERErr extends Error {
constructor(m="") {
super(m);
}
}
,
_parseInt(data) {
const {Err: E} = DER;
if (data.length < 2 || data[0] !== 2)
throw new E("Invalid signature integer tag");
const len = data[1];
const res = data.subarray(2, len + 2);
if (!len || res.length !== len)
throw new E("Invalid signature integer: wrong length");
if (res[0] & 128)
throw new E("Invalid signature integer: negative");
if (res[0] === 0 && !(res[1] & 128))
throw new E("Invalid signature integer: unnecessary leading zero");
return {
d: b2n(res),
l: data.subarray(len + 2)
};
},
toSig(hex2) {
const {Err: E} = DER;
const data = typeof hex2 === "string" ? h2b(hex2) : hex2;
if (!(data instanceof Uint8Array))
throw new Error("ui8a expected");
let l = data.length;
if (l < 2 || data[0] != 48)
throw new E("Invalid signature tag");
if (data[1] !== l - 2)
throw new E("Invalid signature: incorrect length");
const {d: r, l: sBytes} = DER._parseInt(data.subarray(2));
const {d: s, l: rBytesLeft} = DER._parseInt(sBytes);
if (rBytesLeft.length)
throw new E("Invalid signature: left bytes after parsing");
return {
r,
s
};
},
hexFromSig(sig) {
const slice = (s2)=>Number.parseInt(s2[0], 16) & 8 ? "00" + s2 : s2;
const h = (num)=>{
const hex2 = num.toString(16);
return hex2.length & 1 ? `0 ${hex2}` : hex2;
}
;
const s = slice(h(sig.s));
const r = slice(h(sig.r));
const shl = s.length / 2;
const rhl = r.length / 2;
const sl = h(shl);
const rl = h(rhl);
return `30 ${h(rhl + shl + 4)}02 ${rl}${r}02 ${sl}${s}`;
}
};
var _0n5 = BigInt(0);
var _1n5 = BigInt(1);
var _2n4 = BigInt(2);
var _3n3 = BigInt(3);
var _4n2 = BigInt(4);
function weierstrassPoints(opts) {
const CURVE2 = validatePointOpts(opts);
const {Fp: Fp2} = CURVE2;
const toBytes3 = CURVE2.toBytes || ((c,point,isCompressed)=>{
const a = point.toAffine();
return concatBytes3(Uint8Array.from([4]), Fp2.toBytes(a.x), Fp2.toBytes(a.y));
}
);
const fromBytes = CURVE2.fromBytes || ((bytes2)=>{
const tail = bytes2.subarray(1);
const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES));
const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES));
return {
x,
y
};
}
);
function weierstrassEquation(x) {
const {a, b} = CURVE2;
const x2 = Fp2.sqr(x);
const x3 = Fp2.mul(x2, x);
return Fp2.add(Fp2.add(x3, Fp2.mul(x, a)), b);
}
if (!Fp2.eql(Fp2.sqr(CURVE2.Gy), weierstrassEquation(CURVE2.Gx)))
throw new Error("bad generator point: equation left != right");
function isWithinCurveOrder2(num) {
return typeof num === "bigint" && _0n5 < num && num < CURVE2.n;
}
function assertGE(num) {
if (!isWithinCurveOrder2(num))
throw new Error("Expected valid bigint: 0 < bigint < curve.n");
}
function normPrivateKeyToScalar(key) {
const {allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n} = CURVE2;
if (lengths && typeof key !== "bigint") {
if (key instanceof Uint8Array)
key = bytesToHex3(key);
if (typeof key !== "string" || !lengths.includes(key.length))
throw new Error("Invalid key");
key = key.padStart(nByteLength * 2, "0");
}
let num;
try {
num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes2("private key", key, nByteLength));
} catch (error) {
throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);
}
if (wrapPrivateKey)
num = mod2(num, n);
assertGE(num);
return num;
}
const pointPrecomputes2 = /* @__PURE__ */
new Map();
function assertPrjPoint(other) {
if (!(other instanceof Point4))
throw new Error("ProjectivePoint expected");
}
class Point4 {
constructor(px, py, pz) {
this.px = px;
this.py = py;
this.pz = pz;
if (px == null || !Fp2.isValid(px))
throw new Error("x required");
if (py == null || !Fp2.isValid(py))
throw new Error("y required");
if (pz == null || !Fp2.isValid(pz))
throw new Error("z required");
}
// Does not validate if the point is on-curve.
// Use fromHex instead, or call assertValidity() later.
static fromAffine(p) {
const {x, y} = p || {};
if (!p || !Fp2.isValid(x) || !Fp2.isValid(y))
throw new Error("invalid affine point");
if (p instanceof Point4)
throw new Error("projective point not allowed");
const is0 = (i)=>Fp2.eql(i, Fp2.ZERO);
if (is0(x) && is0(y))
return Point4.ZERO;
return new Point4(x,y,Fp2.ONE);
}
get x() {
return this.toAffine().x;
}
get y() {
return this.toAffine().y;
}
/**
* Takes a bunch of Projective Points but executes only one
* inversion on all of them. Inversion is very slow operation,
* so this improves performance massively.
* Optimization: converts a list of projective points to a list of identical points with Z=1.
*/
static normalizeZ(points) {
const toInv = Fp2.invertBatch(points.map((p)=>p.pz));
return points.map((p,i)=>p.toAffine(toInv[i])).map(Point4.fromAffine);
}
/**
* Converts hash string or Uint8Array to Point.
* @param hex short/long ECDSA hex
*/
static fromHex(hex2) {
const P = Point4.fromAffine(fromBytes(ensureBytes2("pointHex", hex2)));
P.assertValidity();
return P;
}
// Multiplies generator point by privateKey.
static fromPrivateKey(privateKey) {
return Point4.BASE.multiply(normPrivateKeyToScalar(privateKey));
}
// "Private method", don't use it directly
_setWindowSize(windowSize) {
this._WINDOW_SIZE = windowSize;
pointPrecomputes2.delete(this);
}
// A point on curve is valid if it conforms to equation.
assertValidity() {
if (this.is0()) {
if (CURVE2.allowInfinityPoint)
return;
throw new Error("bad point: ZERO");
}
const {x, y} = this.toAffine();
if (!Fp2.isValid(x) || !Fp2.isValid(y))
throw new Error("bad point: x or y not FE");
const left = Fp2.sqr(y);
const right = weierstrassEquation(x);
if (!Fp2.eql(left, right))
throw new Error("bad point: equation left != right");
if (!this.isTorsionFree())
throw new Error("bad point: not in prime-order subgroup");
}
hasEvenY() {
const {y} = this.toAffine();
if (Fp2.isOdd)
return !Fp2.isOdd(y);
throw new Error("Field doesn't support isOdd");
}
/**
* Compare one point to another.
*/
equals(other) {
assertPrjPoint(other);
const {px: X1, py: Y1, pz: Z1} = this;
const {px: X2, py: Y2, pz: Z2} = other;
const U1 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1));
const U2 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1));
return U1 && U2;
}
/**
* Flips point to one corresponding to (x, -y) in Affine coordinates.
*/
negate() {
return new Point4(this.px,Fp2.neg(this.py),this.pz);
}
// Renes-Costello-Batina exception-free doubling formula.
// There is 30% faster Jacobian formula, but it is not complete.
// https://eprint.iacr.org/2015/1060, algorithm 3
// Cost: 8M + 3S + 3*a + 2*b3 + 15add.
double() {
const {a, b} = CURVE2;
const b3 = Fp2.mul(b, _3n3);
const {px: X1, py: Y1, pz: Z1} = this;
let X3 = Fp2.ZERO
, Y3 = Fp2.ZERO
, Z3 = Fp2.ZERO;
let t0 = Fp2.mul(X1, X1);
let t1 = Fp2.mul(Y1, Y1);
let t2 = Fp2.mul(Z1, Z1);
let t3 = Fp2.mul(X1, Y1);
t3 = Fp2.add(t3, t3);
Z3 = Fp2.mul(X1, Z1);
Z3 = Fp2.add(Z3, Z3);
X3 = Fp2.mul(a, Z3);
Y3 = Fp2.mul(b3, t2);
Y3 = Fp2.add(X3, Y3);
X3 = Fp2.sub(t1, Y3);
Y3 = Fp2.add(t1, Y3);
Y3 = Fp2.mul(X3, Y3);
X3 = Fp2.mul(t3, X3);
Z3 = Fp2.mul(b3, Z3);
t2 = Fp2.mul(a, t2);
t3 = Fp2.sub(t0, t2);
t3 = Fp2.mul(a, t3);
t3 = Fp2.add(t3, Z3);
Z3 = Fp2.add(t0, t0);
t0 = Fp2.add(Z3, t0);
t0 = Fp2.add(t0, t2);
t0 = Fp2.mul(t0, t3);
Y3 = Fp2.add(Y3, t0);
t2 = Fp2.mul(Y1, Z1);
t2 = Fp2.add(t2, t2);
t0 = Fp2.mul(t2, t3);
X3 = Fp2.sub(X3, t0);
Z3 = Fp2.mul(t2, t1);
Z3 = Fp2.add(Z3, Z3);
Z3 = Fp2.add(Z3, Z3);
return new Point4(X3,Y3,Z3);
}
// Renes-Costello-Batina exception-free addition formula.
// There is 30% faster Jacobian formula, but it is not complete.
// https://eprint.iacr.org/2015/1060, algorithm 1
// Cost: 12M + 0S + 3*a + 3*b3 + 23add.
add(other) {
assertPrjPoint(other);
const {px: X1, py: Y1, pz: Z1} = this;
const {px: X2, py: Y2, pz: Z2} = other;
let X3 = Fp2.ZERO
, Y3 = Fp2.ZERO
, Z3 = Fp2.ZERO;
const a = CURVE2.a;
const b3 = Fp2.mul(CURVE2.b, _3n3);
let t0 = Fp2.mul(X1, X2);
let t1 = Fp2.mul(Y1, Y2);
let t2 = Fp2.mul(Z1, Z2);
let t3 = Fp2.add(X1, Y1);
let t4 = Fp2.add(X2, Y2);
t3 = Fp2.mul(t3, t4);
t4 = Fp2.add(t0, t1);
t3 = Fp2.sub(t3, t4);
t4 = Fp2.add(X1, Z1);
let t5 = Fp2.add(X2, Z2);
t4 = Fp2.mul(t4, t5);
t5 = Fp2.add(t0, t2);
t4 = Fp2.sub(t4, t5);
t5 = Fp2.add(Y1, Z1);
X3 = Fp2.add(Y2, Z2);
t5 = Fp2.mul(t5, X3);
X3 = Fp2.add(t1, t2);
t5 = Fp2.sub(t5, X3);
Z3 = Fp2.mul(a, t4);
X3 = Fp2.mul(b3, t2);
Z3 = Fp2.add(X3, Z3);
X3 = Fp2.sub(t1, Z3);
Z3 = Fp2.add(t1, Z3);
Y3 = Fp2.mul(X3, Z3);
t1 = Fp2.add(t0, t0);
t1 = Fp2.add(t1, t0);
t2 = Fp2.mul(a, t2);
t4 = Fp2.mul(b3, t4);
t1 = Fp2.add(t1, t2);
t2 = Fp2.sub(t0, t2);
t2 = Fp2.mul(a, t2);
t4 = Fp2.add(t4, t2);
t0 = Fp2.mul(t1, t4);
Y3 = Fp2.add(Y3, t0);
t0 = Fp2.mul(t5, t4);
X3 = Fp2.mul(t3, X3);
X3 = Fp2.sub(X3, t0);
t0 = Fp2.mul(t3, t1);
Z3 = Fp2.mul(t5, Z3);
Z3 = Fp2.add(Z3, t0);
return new Point4(X3,Y3,Z3);
}
subtract(other) {
return this.add(other.negate());
}
is0() {
return this.equals(Point4.ZERO);
}
wNAF(n) {
return wnaf.wNAFCached(this, pointPrecomputes2, n, (comp)=>{
const toInv = Fp2.invertBatch(comp.map((p)=>p.pz));
return comp.map((p,i)=>p.toAffine(toInv[i])).map(Point4.fromAffine);
}
);
}
/**
* Non-constant-time multiplication. Uses double-and-add algorithm.
* It's faster, but should only be used when you don't care about
* an exposed private key e.g. sig verification, which works over *public* keys.
*/
multiplyUnsafe(n) {
const I = Point4.ZERO;
if (n === _0n5)
return I;
assertGE(n);
if (n === _1n5)
return this;
const {endo: endo2} = CURVE2;
if (!endo2)
return wnaf.unsafeLadder(this, n);
let {k1neg, k1, k2neg, k2} = endo2.splitScalar(n);
let k1p = I;
let k2p = I;
let d = this;
while (k1 > _0n5 || k2 > _0n5) {
if (k1 & _1n5)
k1p = k1p.add(d);
if (k2 & _1n5)
k2p = k2p.add(d);
d = d.double();
k1 >>= _1n5;
k2 >>= _1n5;
}
if (k1neg)
k1p = k1p.negate();
if (k2neg)
k2p = k2p.negate();
k2p = new Point4(Fp2.mul(k2p.px, endo2.beta),k2p.py,k2p.pz);
return k1p.add(k2p);
}
/**
* Constant time multiplication.
* Uses wNAF method. Windowed method may be 10% faster,
* but takes 2x longer to generate and consumes 2x memory.
* Uses precomputes when available.
* Uses endomorphism for Koblitz curves.
* @param scalar by which the point would be multiplied
* @returns New point
*/
multiply(scalar) {
assertGE(scalar);
let n = scalar;
let point, fake;
const {endo: endo2} = CURVE2;
if (endo2) {
const {k1neg, k1, k2neg, k2} = endo2.splitScalar(n);
let {p: k1p, f: f1p} = this.wNAF(k1);
let {p: k2p, f: f2p} = this.wNAF(k2);
k1p = wnaf.constTimeNegate(k1neg, k1p);
k2p = wnaf.constTimeNegate(k2neg, k2p);
k2p = new Point4(Fp2.mul(k2p.px, endo2.beta),k2p.py,k2p.pz);
point = k1p.add(k2p);
fake = f1p.add(f2p);
} else {
const {p, f: f2} = this.wNAF(n);
point = p;
fake = f2;
}
return Point4.normalizeZ([point, fake])[0];
}
/**
* Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
* Not using Strauss-Shamir trick: precomputation tables are faster.
* The trick could be useful if both P and Q are not G (not in our case).
* @returns non-zero affine point
*/
multiplyAndAddUnsafe(Q, a, b) {
const G = Point4.BASE;
const mul = (P,a2)=>a2 === _0n5 || a2 === _1n5 || !P.equals(G) ? P.multiplyUnsafe(a2) : P.multiply(a2);
const sum = mul(this, a).add(mul(Q, b));
return sum.is0() ? void 0 : sum;
}
// Converts Projective point to affine (x, y) coordinates.
// Can accept precomputed Z^-1 - for example, from invertBatch.
// (x, y, z) ∋ (x=x/z, y=y/z)
toAffine(iz) {
const {px: x, py: y, pz: z} = this;
const is0 = this.is0();
if (iz == null)
iz = is0 ? Fp2.ONE : Fp2.inv(z);
const ax = Fp2.mul(x, iz);
const ay = Fp2.mul(y, iz);
const zz = Fp2.mul(z, iz);
if (is0)
return {
x: Fp2.ZERO,
y: Fp2.ZERO
};
if (!Fp2.eql(zz, Fp2.ONE))
throw new Error("invZ was invalid");
return {
x: ax,
y: ay
};
}
isTorsionFree() {
const {h: cofactor, isTorsionFree} = CURVE2;
if (cofactor === _1n5)
return true;
if (isTorsionFree)
return isTorsionFree(Point4, this);
throw new Error("isTorsionFree() has not been declared for the elliptic curve");
}
clearCofactor() {
const {h: cofactor, clearCofactor} = CURVE2;
if (cofactor === _1n5)
return this;
if (clearCofactor)
return clearCofactor(Point4, this);
return this.multiplyUnsafe(CURVE2.h);
}
toRawBytes(isCompressed=true) {
this.assertValidity();
return toBytes3(Point4, this, isCompressed);
}
toHex(isCompressed=true) {
return bytesToHex3(this.toRawBytes(isCompressed));
}
}
Point4.BASE = new Point4(CURVE2.Gx,CURVE2.Gy,Fp2.ONE);
Point4.ZERO = new Point4(Fp2.ZERO,Fp2.ONE,Fp2.ZERO);
const _bits = CURVE2.nBitLength;
const wnaf = wNAF(Point4, CURVE2.endo ? Math.ceil(_bits / 2) : _bits);
return {
CURVE: CURVE2,
ProjectivePoint: Point4,
normPrivateKeyToScalar,
weierstrassEquation,
isWithinCurveOrder: isWithinCurveOrder2
};
}
function validateOpts(curve) {
const opts = validateBasic(curve);
validateObject(opts, {
hash: "hash",
hmac: "function",
randomBytes: "function"
}, {
bits2int: "function",
bits2int_modN: "function",
lowS: "boolean"
});
return Object.freeze({
lowS: true,
...opts
});
}
function weierstrass2(curveDef) {
const CURVE2 = validateOpts(curveDef);
const {Fp: Fp2, n: CURVE_ORDER} = CURVE2;
const compressedLen2 = Fp2.BYTES + 1;
const uncompressedLen2 = 2 * Fp2.BYTES + 1;
function isValidFieldElement2(num) {
return _0n5 < num && num < Fp2.ORDER;
}
function modN2(a) {
return mod2(a, CURVE_ORDER);
}
function invN(a) {
return invert2(a, CURVE_ORDER);
}
const {ProjectivePoint: Point4, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder: isWithinCurveOrder2} = weierstrassPoints({
...CURVE2,
toBytes(c, point, isCompressed) {
const a = point.toAffine();
const x = Fp2.toBytes(a.x);
const cat = concatBytes3;
if (isCompressed) {
return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x);
} else {
return cat(Uint8Array.from([4]), x, Fp2.toBytes(a.y));
}
},
fromBytes(bytes2) {
const len = bytes2.length;
const head = bytes2[0];
const tail = bytes2.subarray(1);
if (len === compressedLen2 && (head === 2 || head === 3)) {
const x = bytesToNumberBE(tail);
if (!isValidFieldElement2(x))
throw new Error("Point is not on curve");
const y2 = weierstrassEquation(x);
let y = Fp2.sqrt(y2);
const isYOdd = (y & _1n5) === _1n5;
const isHeadOdd = (head & 1) === 1;
if (isHeadOdd !== isYOdd)
y = Fp2.neg(y);
return {
x,
y
};
} else if (len === uncompressedLen2 && head === 4) {
const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES));
const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES));
return {
x,
y
};
} else {
throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen2} compressed bytes or ${uncompressedLen2} uncompressed bytes`);
}
}
});
const numToNByteStr = (num)=>bytesToHex3(numberToBytesBE(num, CURVE2.nByteLength));
function isBiggerThanHalfOrder(number2) {
const HALF = CURVE_ORDER >> _1n5;
return number2 > HALF;
}
function normalizeS(s) {
return isBiggerThanHalfOrder(s) ? modN2(-s) : s;
}
const slcNum = (b,from,to)=>bytesToNumberBE(b.slice(from, to));
class Signature2 {
constructor(r, s, recovery) {
this.r = r;
this.s = s;
this.recovery = recovery;
this.assertValidity();
}
// pair (bytes of r, bytes of s)
static fromCompact(hex2) {
const l = CURVE2.nByteLength;
hex2 = ensureBytes2("compactSignature", hex2, l * 2);
return new Signature2(slcNum(hex2, 0, l),slcNum(hex2, l, 2 * l));
}
// DER encoded ECDSA signature
// https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
static fromDER(hex2) {
const {r, s} = DER.toSig(ensureBytes2("DER", hex2));
return new Signature2(r,s);
}
assertValidity() {
if (!isWithinCurveOrder2(this.r))
throw new Error("r must be 0 < r < CURVE.n");
if (!isWithinCurveOrder2(this.s))
throw new Error("s must be 0 < s < CURVE.n");
}
addRecoveryBit(recovery) {
return new Signature2(this.r,this.s,recovery);
}
recoverPublicKey(msgHash) {
const {r, s, recovery: rec} = this;
const h = bits2int_modN(ensureBytes2("msgHash", msgHash));
if (rec == null || ![0, 1, 2, 3].includes(rec))
throw new Error("recovery id invalid");
const radj = rec === 2 || rec === 3 ? r + CURVE2.n : r;
if (radj >= Fp2.ORDER)
throw new Error("recovery id 2 or 3 invalid");
const prefix = (rec & 1) === 0 ? "02" : "03";
const R = Point4.fromHex(prefix + numToNByteStr(radj));
const ir = invN(radj);
const u1 = modN2(-h * ir);
const u2 = modN2(s * ir);
const Q = Point4.BASE.multiplyAndAddUnsafe(R, u1, u2);
if (!Q)
throw new Error("point at infinify");
Q.assertValidity();
return Q;
}
// Signatures should be low-s, to prevent malleability.
hasHighS() {
return isBiggerThanHalfOrder(this.s);
}
normalizeS() {
return this.hasHighS() ? new Signature2(this.r,modN2(-this.s),this.recovery) : this;
}
// DER-encoded
toDERRawBytes() {
return hexToBytes3(this.toDERHex());
}
toDERHex() {
return DER.hexFromSig({
r: this.r,
s: this.s
});
}
// padded bytes of r, then padded bytes of s
toCompactRawBytes() {
return hexToBytes3(this.toCompactHex());
}
toCompactHex() {
return numToNByteStr(this.r) + numToNByteStr(this.s);
}
}
const utils2 = {
isValidPrivateKey(privateKey) {
try {
normPrivateKeyToScalar(privateKey);
return true;
} catch (error) {
return false;
}
},
normPrivateKeyToScalar,
/**
* Produces cryptographically secure private key from random of size (nBitLength+64)
* as per FIPS 186 B.4.1 with modulo bias being neglible.
*/
randomPrivateKey: ()=>{
const rand = CURVE2.randomBytes(Fp2.BYTES + 8);
const num = hashToPrivateScalar(rand, CURVE_ORDER);
return numberToBytesBE(num, CURVE2.nByteLength);
}
,
/**
* Creates precompute table for an arbitrary EC point. Makes point "cached".
* Allows to massively speed-up `point.multiply(scalar)`.
* @returns cached point
* @example
* const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
* fast.multiply(privKey); // much faster ECDH now
*/
precompute(windowSize=8, point=Point4.BASE) {
point._setWindowSize(windowSize);
point.multiply(BigInt(3));
return point;
}
};
function getPublicKey2(privateKey, isCompressed=true) {
return Point4.fromPrivateKey(privateKey).toRawBytes(isCompressed);
}
function isProbPub2(item) {
const arr = item instanceof Uint8Array;
const str = typeof item === "string";
const len = (arr || str) && item.length;
if (arr)
return len === compressedLen2 || len === uncompressedLen2;
if (str)
return len === 2 * compressedLen2 || len === 2 * uncompressedLen2;
if (item instanceof Point4)
return true;
return false;
}
function getSharedSecret2(privateA, publicB, isCompressed=true) {
if (isProbPub2(privateA))
throw new Error("first arg must be private key");
if (!isProbPub2(publicB))
throw new Error("second arg must be public key");
const b = Point4.fromHex(publicB);
return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
}
const bits2int = CURVE2.bits2int || function(bytes2) {
const num = bytesToNumberBE(bytes2);
const delta = bytes2.length * 8 - CURVE2.nBitLength;
return delta > 0 ? num >> BigInt(delta) : num;
}
;
const bits2int_modN = CURVE2.bits2int_modN || function(bytes2) {
return modN2(bits2int(bytes2));
}
;
const ORDER_MASK = bitMask(CURVE2.nBitLength);
function int2octets(num) {
if (typeof num !== "bigint")
throw new Error("bigint expected");
if (!(_0n5 <= num && num < ORDER_MASK))
throw new Error(`bigint expected < 2^${CURVE2.nBitLength}`);
return numberToBytesBE(num, CURVE2.nByteLength);
}
function prepSig(msgHash, privateKey, opts=defaultSigOpts) {
if (["recovered", "canonical"].some((k)=>k in opts))
throw new Error("sign() legacy options not supported");
const {hash: hash2, randomBytes: randomBytes3} = CURVE2;
let {lowS, prehash, extraEntropy: ent} = opts;
if (lowS == null)
lowS = true;
msgHash = ensureBytes2("msgHash", msgHash);
if (prehash)
msgHash = ensureBytes2("prehashed msgHash", hash2(msgHash));
const h1int = bits2int_modN(msgHash);
const d = normPrivateKeyToScalar(privateKey);
const seedArgs = [int2octets(d), int2octets(h1int)];
if (ent != null) {
const e = ent === true ? randomBytes3(Fp2.BYTES) : ent;
seedArgs.push(ensureBytes2("extraEntropy", e, Fp2.BYTES));
}
const seed = concatBytes3(...seedArgs);
const m = h1int;
function k2sig(kBytes) {
const k = bits2int(kBytes);
if (!isWithinCurveOrder2(k))
return;
const ik = invN(k);
const q = Point4.BASE.multiply(k).toAffine();
const r = modN2(q.x);
if (r === _0n5)
return;
const s = modN2(ik * modN2(m + r * d));
if (s === _0n5)
return;
let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n5);
let normS = s;
if (lowS && isBiggerThanHalfOrder(s)) {
normS = normalizeS(s);
recovery ^= 1;
}
return new Signature2(r,normS,recovery);
}
return {
seed,
k2sig
};
}
const defaultSigOpts = {
lowS: CURVE2.lowS,
prehash: false
};
const defaultVerOpts = {
lowS: CURVE2.lowS,
prehash: false
};
function sign(msgHash, privKey, opts=defaultSigOpts) {
const {seed, k2sig} = prepSig(msgHash, privKey, opts);
const drbg = createHmacDrbg(CURVE2.hash.outputLen, CURVE2.nByteLength, CURVE2.hmac);
return drbg(seed, k2sig);
}
Point4.BASE._setWindowSize(8);
function verify(signature, msgHash, publicKey, opts=defaultVerOpts) {
const sg = signature;
msgHash = ensureBytes2("msgHash", msgHash);
publicKey = ensureBytes2("publicKey", publicKey);
if ("strict"in opts)
throw new Error("options.strict was renamed to lowS");
const {lowS, prehash} = opts;
let _sig = void 0;
let P;
try {
if (typeof sg === "string" || sg instanceof Uint8Array) {
try {
_sig = Signature2.fromDER(sg);
} catch (derError) {
if (!(derError instanceof DER.Err))
throw derError;
_sig = Signature2.fromCompact(sg);
}
} else if (typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint") {
const {r: r2, s: s2} = sg;
_sig = new Signature2(r2,s2);
} else {
throw new Error("PARSE");
}
P = Point4.fromHex(publicKey);
} catch (error) {
if (error.message === "PARSE")
throw new Error(`signature must be Signature instance, Uint8Array or hex string`);
return false;
}
if (lowS && _sig.hasHighS())
return false;
if (prehash)
msgHash = CURVE2.hash(msgHash);
const {r, s} = _sig;
const h = bits2int_modN(msgHash);
const is = invN(s);
const u1 = modN2(h * is);
const u2 = modN2(r * is);
const R = Point4.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine();
if (!R)
return false;
const v = modN2(R.x);
return v === r;
}
return {
CURVE: CURVE2,
getPublicKey: getPublicKey2,
getSharedSecret: getSharedSecret2,
sign,
verify,
ProjectivePoint: Point4,
Signature: Signature2,
utils: utils2
};
}
function SWUFpSqrtRatio(Fp2, Z) {
const q = Fp2.ORDER;
let l = _0n5;
for (let o = q - _1n5; o % _2n4 === _0n5; o /= _2n4)
l += _1n5;
const c1 = l;
const c2 = (q - _1n5) / _2n4 ** c1;
const c3 = (c2 - _1n5) / _2n4;
const c4 = _2n4 ** c1 - _1n5;
const c5 = _2n4 ** (c1 - _1n5);
const c6 = Fp2.pow(Z, c2);
const c7 = Fp2.pow(Z, (c2 + _1n5) / _2n4);
let sqrtRatio = (u,v)=>{
let tv1 = c6;
let tv2 = Fp2.pow(v, c4);
let tv3 = Fp2.sqr(tv2);
tv3 = Fp2.mul(tv3, v);
let tv5 = Fp2.mul(u, tv3);
tv5 = Fp2.pow(tv5, c3);
tv5 = Fp2.mul(tv5, tv2);
tv2 = Fp2.mul(tv5, v);
tv3 = Fp2.mul(tv5, u);
let tv4 = Fp2.mul(tv3, tv2);
tv5 = Fp2.pow(tv4, c5);
let isQR = Fp2.eql(tv5, Fp2.ONE);
tv2 = Fp2.mul(tv3, c7);
tv5 = Fp2.mul(tv4, tv1);
tv3 = Fp2.cmov(tv2, tv3, isQR);
tv4 = Fp2.cmov(tv5, tv4, isQR);
for (let i = c1; i > _1n5; i--) {
let tv52 = _2n4 ** (i - _2n4);
let tvv5 = Fp2.pow(tv4, tv52);
const e1 = Fp2.eql(tvv5, Fp2.ONE);
tv2 = Fp2.mul(tv3, tv1);
tv1 = Fp2.mul(tv1, tv1);
tvv5 = Fp2.mul(tv4, tv1);
tv3 = Fp2.cmov(tv2, tv3, e1);
tv4 = Fp2.cmov(tvv5, tv4, e1);
}
return {
isValid: isQR,
value: tv3
};
}
;
if (Fp2.ORDER % _4n2 === _3n3) {
const c12 = (Fp2.ORDER - _3n3) / _4n2;
const c22 = Fp2.sqrt(Fp2.neg(Z));
sqrtRatio = (u,v)=>{
let tv1 = Fp2.sqr(v);
const tv2 = Fp2.mul(u, v);
tv1 = Fp2.mul(tv1, tv2);
let y1 = Fp2.pow(tv1, c12);
y1 = Fp2.mul(y1, tv2);
const y2 = Fp2.mul(y1, c22);
const tv3 = Fp2.mul(Fp2.sqr(y1), v);
const isQR = Fp2.eql(tv3, u);
let y = Fp2.cmov(y2, y1, isQR);
return {
isValid: isQR,
value: y
};
}
;
}
return sqrtRatio;
}
function mapToCurveSimpleSWU(Fp2, opts) {
validateField(Fp2);
if (!Fp2.isValid(opts.A) || !Fp2.isValid(opts.B) || !Fp2.isValid(opts.Z))
throw new Error("mapToCurveSimpleSWU: invalid opts");
const sqrtRatio = SWUFpSqrtRatio(Fp2, opts.Z);
if (!Fp2.isOdd)
throw new Error("Fp.isOdd is not implemented!");
return (u)=>{
let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
tv1 = Fp2.sqr(u);
tv1 = Fp2.mul(tv1, opts.Z);
tv2 = Fp2.sqr(tv1);
tv2 = Fp2.add(tv2, tv1);
tv3 = Fp2.add(tv2, Fp2.ONE);
tv3 = Fp2.mul(tv3, opts.B);
tv4 = Fp2.cmov(opts.Z, Fp2.neg(tv2), !Fp2.eql(tv2, Fp2.ZERO));
tv4 = Fp2.mul(tv4, opts.A);
tv2 = Fp2.sqr(tv3);
tv6 = Fp2.sqr(tv4);
tv5 = Fp2.mul(tv6, opts.A);
tv2 = Fp2.add(tv2, tv5);
tv2 = Fp2.mul(tv2, tv3);
tv6 = Fp2.mul(tv6, tv4);
tv5 = Fp2.mul(tv6, opts.B);
tv2 = Fp2.add(tv2, tv5);
x = Fp2.mul(tv1, tv3);
const {isValid, value} = sqrtRatio(tv2, tv6);
y = Fp2.mul(tv1, u);
y = Fp2.mul(y, value);
x = Fp2.cmov(x, tv3, isValid);
y = Fp2.cmov(y, value, isValid);
const e1 = Fp2.isOdd(u) === Fp2.isOdd(y);
y = Fp2.cmov(Fp2.neg(y), y, e1);
x = Fp2.div(x, tv4);
return {
x,
y
};
}
;
}
// node_modules/.pnpm/@noble+curves@1.0.0/node_modules/@noble/curves/esm/abstract/hash-to-curve.js
function validateDST(dst) {
if (dst instanceof Uint8Array)
return dst;
if (typeof dst === "string")
return utf8ToBytes3(dst);
throw new Error("DST must be Uint8Array or string");
}
var os2ip = bytesToNumberBE;
function i2osp(value, length) {
if (value < 0 || value >= 1 << 8 * length) {
throw new Error(`bad I2OSP call: value=${value} length=${length}`);
}
const res = Array.from({
length
}).fill(0);
for (let i = length - 1; i >= 0; i--) {
res[i] = value & 255;
value >>>= 8;
}
return new Uint8Array(res);
}
function strxor(a, b) {
const arr = new Uint8Array(a.length);
for (let i = 0; i < a.length; i++) {
arr[i] = a[i] ^ b[i];
}
return arr;
}
function isBytes(item) {
if (!(item instanceof Uint8Array))
throw new Error("Uint8Array expected");
}
function isNum(item) {
if (!Number.isSafeInteger(item))
throw new Error("number expected");
}
function expand_message_xmd(msg, DST, lenInBytes, H) {
isBytes(msg);
isBytes(DST);
isNum(lenInBytes);
if (DST.length > 255)
DST = H(concatBytes3(utf8ToBytes3("H2C-OVERSIZE-DST-"), DST));
const {outputLen: b_in_bytes, blockLen: r_in_bytes} = H;
const ell = Math.ceil(lenInBytes / b_in_bytes);
if (ell > 255)
throw new Error("Invalid xmd length");
const DST_prime = concatBytes3(DST, i2osp(DST.length, 1));
const Z_pad = i2osp(0, r_in_bytes);
const l_i_b_str = i2osp(lenInBytes, 2);
const b = new Array(ell);
const b_0 = H(concatBytes3(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
b[0] = H(concatBytes3(b_0, i2osp(1, 1), DST_prime));
for (let i = 1; i <= ell; i++) {
const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
b[i] = H(concatBytes3(...args));
}
const pseudo_random_bytes = concatBytes3(...b);
return pseudo_random_bytes.slice(0, lenInBytes);
}
function expand_message_xof(msg, DST, lenInBytes, k, H) {
isBytes(msg);
isBytes(DST);
isNum(lenInBytes);
if (DST.length > 255) {
const dkLen = Math.ceil(2 * k / 8);
DST = H.create({
dkLen
}).update(utf8ToBytes3("H2C-OVERSIZE-DST-")).update(DST).digest();
}
if (lenInBytes > 65535 || DST.length > 255)
throw new Error("expand_message_xof: invalid lenInBytes");
return H.create({
dkLen: lenInBytes
}).update(msg).update(i2osp(lenInBytes, 2)).update(DST).update(i2osp(DST.length, 1)).digest();
}
function hash_to_field(msg, count, options) {
validateObject(options, {
DST: "string",
p: "bigint",
m: "isSafeInteger",
k: "isSafeInteger",
hash: "hash"
});
const {p, k, m, hash: hash2, expand, DST: _DST} = options;
isBytes(msg);
isNum(count);
const DST = validateDST(_DST);
const log2p = p.toString(2).length;
const L = Math.ceil((log2p + k) / 8);
const len_in_bytes = count * m * L;
let prb;
if (expand === "xmd") {
prb = expand_message_xmd(msg, DST, len_in_bytes, hash2);
} else if (expand === "xof") {
prb = expand_message_xof(msg, DST, len_in_bytes, k, hash2);
} else if (expand === "_internal_pass") {
prb = msg;
} else {
throw new Error('expand must be "xmd" or "xof"');
}
const u = new Array(count);
for (let i = 0; i < count; i++) {
const e = new Array(m);
for (let j = 0; j < m; j++) {
const elm_offset = L * (j + i * m);
const tv = prb.subarray(elm_offset, elm_offset + L);
e[j] = mod2(os2ip(tv), p);
}
u[i] = e;
}
return u;
}
function isogenyMap(field, map) {
const COEFF = map.map((i)=>Array.from(i).reverse());
return (x,y)=>{
const [xNum,xDen,yNum,yDen] = COEFF.map((val)=>val.reduce((acc,i)=>field.add(field.mul(acc, x), i)));
x = field.div(xNum, xDen);
y = field.mul(y, field.div(yNum, yDen));
return {
x,
y
};
}
;
}
function createHasher(Point4, mapToCurve, def) {
if (typeof mapToCurve !== "function")
throw new Error("mapToCurve() must be defined");
return {
// Encodes byte string to elliptic curve
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-3
hashToCurve(msg, options) {
const u = hash_to_field(msg, 2, {
...def,
DST: def.DST,
...options
});
const u0 = Point4.fromAffine(mapToCurve(u[0]));
const u1 = Point4.fromAffine(mapToCurve(u[1]));
const P = u0.add(u1).clearCofactor();
P.assertValidity();
return P;
},
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#section-3
encodeToCurve(msg, options) {
const u = hash_to_field(msg, 1, {
...def,
DST: def.encodeDST,
...options
});
const P = Point4.fromAffine(mapToCurve(u[0])).clearCofactor();
P.assertValidity();
return P;
}
};
}
// node_modules/.pnpm/@noble+curves@1.0.0/node_modules/@noble/curves/esm/_shortw_utils.js
function getHash(hash2) {
return {
hash: hash2,
hmac: (key,...msgs)=>hmac(hash2, key, concatBytes2(...msgs)),
randomBytes: randomBytes2
};
}
function createCurve(curveDef, defHash) {
const create = (hash2)=>weierstrass2({
...curveDef,
...getHash(hash2)
});
return Object.freeze({
...create(defHash),
create
});
}
// node_modules/.pnpm/@noble+curves@1.0.0/node_modules/@noble/curves/esm/secp256k1.js
var secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f");
var secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");
var _1n6 = BigInt(1);
var _2n5 = BigInt(2);
var divNearest2 = (a,b)=>(a + b / _2n5) / b;
function sqrtMod2(y) {
const P = secp256k1P;
const _3n4 = BigInt(3)
, _6n = BigInt(6)
, _11n = BigInt(11)
, _22n = BigInt(22);
const _23n = BigInt(23)
, _44n = BigInt(44)
, _88n = BigInt(88);
const b2 = y * y * y % P;
const b3 = b2 * b2 * y % P;
const b6 = pow22(b3, _3n4, P) * b3 % P;
const b9 = pow22(b6, _3n4, P) * b3 % P;
const b11 = pow22(b9, _2n5, P) * b2 % P;
const b22 = pow22(b11, _11n, P) * b11 % P;
const b44 = pow22(b22, _22n, P) * b22 % P;
const b88 = pow22(b44, _44n, P) * b44 % P;
const b176 = pow22(b88, _88n, P) * b88 % P;
const b220 = pow22(b176, _44n, P) * b44 % P;
const b223 = pow22(b220, _3n4, P) * b3 % P;
const t1 = pow22(b223, _23n, P) * b22 % P;
const t2 = pow22(t1, _6n, P) * b2 % P;
const root = pow22(t2, _2n5, P);
if (!Fp.eql(Fp.sqr(root), y))
throw new Error("Cannot find square root");
return root;
}
var Fp = Field(secp256k1P, void 0, void 0, {
sqrt: sqrtMod2
});
var secp256k1 = createCurve({
a: BigInt(0),
b: BigInt(7),
Fp,
n: secp256k1N,
// Base point (x, y) aka generator point
Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),
Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),
h: BigInt(1),
lowS: true,
/**
* secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.
* Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.
* For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.
* Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066
*/
endo: {
beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
splitScalar: (k)=>{
const n = secp256k1N;
const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15");
const b1 = -_1n6 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3");
const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8");
const b2 = a1;
const POW_2_128 = BigInt("0x100000000000000000000000000000000");
const c1 = divNearest2(b2 * k, n);
const c2 = divNearest2(-b1 * k, n);
let k1 = mod2(k - c1 * a1 - c2 * a2, n);
let k2 = mod2(-c1 * b1 - c2 * b2, n);
const k1neg = k1 > POW_2_128;
const k2neg = k2 > POW_2_128;
if (k1neg)
k1 = n - k1;
if (k2neg)
k2 = n - k2;
if (k1 > POW_2_128 || k2 > POW_2_128) {
throw new Error("splitScalar: Endomorphism failed, k=" + k);
}
return {
k1neg,
k1,
k2neg,
k2
};
}
}
}, sha2562);
var _0n6 = BigInt(0);
var fe = (x)=>typeof x === "bigint" && _0n6 < x && x < secp256k1P;
var ge = (x)=>typeof x === "bigint" && _0n6 < x && x < secp256k1N;
var TAGGED_HASH_PREFIXES2 = {};
function taggedHash(tag, ...messages) {
let tagP = TAGGED_HASH_PREFIXES2[tag];
if (tagP === void 0) {
const tagH = sha2562(Uint8Array.from(tag, (c)=>c.charCodeAt(0)));
tagP = concatBytes3(tagH, tagH);
TAGGED_HASH_PREFIXES2[tag] = tagP;
}
return sha2562(concatBytes3(tagP, ...messages));
}
var pointToBytes = (point)=>point.toRawBytes(true).slice(1);
var numTo32b2 = (n)=>numberToBytesBE(n, 32);
var modP = (x)=>mod2(x, secp256k1P);
var modN = (x)=>mod2(x, secp256k1N);
var Point2 = secp256k1.ProjectivePoint;
var GmulAdd = (Q,a,b)=>Point2.BASE.multiplyAndAddUnsafe(Q, a, b);
function schnorrGetExtPubKey(priv) {
let d_ = secp256k1.utils.normPrivateKeyToScalar(priv);
let p = Point2.fromPrivateKey(d_);
const scalar = p.hasEvenY() ? d_ : modN(-d_);
return {
scalar,
bytes: pointToBytes(p)
};
}
function lift_x(x) {
if (!fe(x))
throw new Error("bad x: need 0 < x < p");
const xx = modP(x * x);
const c = modP(xx * x + BigInt(7));
let y = sqrtMod2(c);
if (y % _2n5 !== _0n6)
y = modP(-y);
const p = new Point2(x,y,_1n6);
p.assertValidity();
return p;
}
function challenge(...args) {
return modN(bytesToNumberBE(taggedHash("BIP0340/challenge", ...args)));
}
function schnorrGetPublicKey2(privateKey) {
return schnorrGetExtPubKey(privateKey).bytes;
}
function schnorrSign2(message, privateKey, auxRand=randomBytes2(32)) {
const m = ensureBytes2("message", message);
const {bytes: px, scalar: d} = schnorrGetExtPubKey(privateKey);
const a = ensureBytes2("auxRand", auxRand, 32);
const t = numTo32b2(d ^ bytesToNumberBE(taggedHash("BIP0340/aux", a)));
const rand = taggedHash("BIP0340/nonce", t, px, m);
const k_ = modN(bytesToNumberBE(rand));
if (k_ === _0n6)
throw new Error("sign failed: k is zero");
const {bytes: rx, scalar: k} = schnorrGetExtPubKey(k_);
const e = challenge(rx, px, m);
const sig = new Uint8Array(64);
sig.set(rx, 0);
sig.set(numTo32b2(modN(k + e * d)), 32);
if (!schnorrVerify2(sig, m, px))
throw new Error("sign: Invalid signature produced");
return sig;
}
function schnorrVerify2(signature, message, publicKey) {
const sig = ensureBytes2("signature", signature, 64);
const m = ensureBytes2("message", message);
const pub = ensureBytes2("publicKey", publicKey, 32);
try {
const P = lift_x(bytesToNumberBE(pub));
const r = bytesToNumberBE(sig.subarray(0, 32));
if (!fe(r))
return false;
const s = bytesToNumberBE(sig.subarray(32, 64));
if (!ge(s))
return false;
const e = challenge(numTo32b2(r), pointToBytes(P), m);
const R = GmulAdd(P, s, modN(-e));
if (!R || !R.hasEvenY() || R.toAffine().x !== r)
return false;
return true;
} catch (error) {
return false;
}
}
var schnorr2 = {
getPublicKey: schnorrGetPublicKey2,
sign: schnorrSign2,
verify: schnorrVerify2,
utils: {
randomPrivateKey: secp256k1.utils.randomPrivateKey,
lift_x,
pointToBytes,
numberToBytesBE,
bytesToNumberBE,
taggedHash,
mod: mod2
}
};
var isoMap = isogenyMap(Fp, [// xNum
["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7", "0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581", "0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262", "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"], // xDen
["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b", "0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14", "0x0000000000000000000000000000000000000000000000000000000000000001"// LAST 1
], // yNum
["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c", "0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3", "0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931", "0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"], // yDen
["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b", "0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573", "0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f", "0x0000000000000000000000000000000000000000000000000000000000000001"// LAST 1
]].map((i)=>i.map((j)=>BigInt(j))));
var mapSWU = mapToCurveSimpleSWU(Fp, {
A: BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),
B: BigInt("1771"),
Z: Fp.create(BigInt("-11"))
});
var {hashToCurve, encodeToCurve} = createHasher(secp256k1.ProjectivePoint, (scalars)=>{
const {x, y} = mapSWU(Fp.create(scalars[0]));
return isoMap(x, y);
}
, {
DST: "secp256k1_XMD:SHA-256_SSWU_RO_",
encodeDST: "secp256k1_XMD:SHA-256_SSWU_NU_",
p: Fp.ORDER,
m: 1,
k: 128,
expand: "xmd",
hash: sha2562
});
// node_modules/.pnpm/@scure+bip32@1.3.0/node_modules/@scure/bip32/lib/esm/index.js
var Point3 = secp256k1.ProjectivePoint;
var base58check2 = base58check(sha2562);
function bytesToNumber2(bytes2) {
return BigInt(`0x ${bytesToHex2(bytes2)}`);
}
function numberToBytes(num) {
return hexToBytes2(num.toString(16).padStart(64, "0"));
}
var MASTER_SECRET = utf8ToBytes2("Bitcoin seed");
var BITCOIN_VERSIONS = {
private: 76066276,
public: 76067358
};
var HARDENED_OFFSET = 2147483648;
var hash160 = (data)=>ripemd160(sha2562(data));
var fromU32 = (data)=>createView2(data).getUint32(0, false);
var toU32 = (n)=>{
if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) {
throw new Error(`Invalid number=${n}. Should be from 0 to 2 ** 32 - 1`);
}
const buf = new Uint8Array(4);
createView2(buf).setUint32(0, n, false);
return buf;
}
;
var HDKey = class {
get fingerprint() {
if (!this.pubHash) {
throw new Error("No publicKey set!");
}
return fromU32(this.pubHash);
}
get identifier() {
return this.pubHash;
}
get pubKeyHash() {
return this.pubHash;
}
get privateKey() {
return this.privKeyBytes || null;
}
get publicKey() {
return this.pubKey || null;
}
get privateExtendedKey() {
const priv = this.privateKey;
if (!priv) {
throw new Error("No private key");
}
return base58check2.encode(this.serialize(this.versions.private, concatBytes2(new Uint8Array([0]), priv)));
}
get publicExtendedKey() {
if (!this.pubKey) {
throw new Error("No public key");
}
return base58check2.encode(this.serialize(this.versions.public, this.pubKey));
}
static fromMasterSeed(seed, versions=BITCOIN_VERSIONS) {
bytes(seed);
if (8 * seed.length < 128 || 8 * seed.length > 512) {
throw new Error(`HDKey: wrong seed length=${seed.length}. Should be between 128 and 512 bits; 256 bits is advised)`);
}
const I = hmac(sha512, MASTER_SECRET, seed);
return new HDKey({
versions,
chainCode: I.slice(32),
privateKey: I.slice(0, 32)
});
}
static fromExtendedKey(base58key, versions=BITCOIN_VERSIONS) {
const keyBuffer = base58check2.decode(base58key);
const keyView = createView2(keyBuffer);
const version = keyView.getUint32(0, false);
const opt = {
versions,
depth: keyBuffer[4],
parentFingerprint: keyView.getUint32(5, false),
index: keyView.getUint32(9, false),
chainCode: keyBuffer.slice(13, 45)
};
const key = keyBuffer.slice(45);
const isPriv = key[0] === 0;
if (version !== versions[isPriv ? "private" : "public"]) {
throw new Error("Version mismatch");
}
if (isPriv) {
return new HDKey({
...opt,
privateKey: key.slice(1)
});
} else {
return new HDKey({
...opt,
publicKey: key
});
}
}
static fromJSON(json) {
return HDKey.fromExtendedKey(json.xpriv);
}
constructor(opt) {
this.depth = 0;
this.index = 0;
this.chainCode = null;
this.parentFingerprint = 0;
if (!opt || typeof opt !== "object") {
throw new Error("HDKey.constructor must not be called directly");
}
this.versions = opt.versions || BITCOIN_VERSIONS;
this.depth = opt.depth || 0;
this.chainCode = opt.chainCode;
this.index = opt.index || 0;
this.parentFingerprint = opt.parentFingerprint || 0;
if (!this.depth) {
if (this.parentFingerprint || this.index) {
throw new Error("HDKey: zero depth with non-zero index/parent fingerprint");
}
}
if (opt.publicKey && opt.privateKey) {
throw new Error("HDKey: publicKey and privateKey at same time.");
}
if (opt.privateKey) {
if (!secp256k1.utils.isValidPrivateKey(opt.privateKey)) {
throw new Error("Invalid private key");
}
this.privKey = typeof opt.privateKey === "bigint" ? opt.privateKey : bytesToNumber2(opt.privateKey);
this.privKeyBytes = numberToBytes(this.privKey);
this.pubKey = secp256k1.getPublicKey(opt.privateKey, true);
} else if (opt.publicKey) {
this.pubKey = Point3.fromHex(opt.publicKey).toRawBytes(true);
} else {
throw new Error("HDKey: no public or private key provided");
}
this.pubHash = hash160(this.pubKey);
}
derive(path) {
if (!/^[mM]'?/.test(path)) {
throw new Error('Path must start with "m" or "M"');
}
if (/^[mM]'?$/.test(path)) {
return this;
}
const parts = path.replace(/^[mM]'?\//, "").split("/");
let child = this;
for (const c of parts) {
const m = /^(\d+)('?)$/.exec(c);
if (!m || m.length !== 3) {
throw new Error(`Invalid child index: ${c}`);
}
let idx = +m[1];
if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) {
throw new Error("Invalid index");
}
if (m[2] === "'") {
idx += HARDENED_OFFSET;
}
child = child.deriveChild(idx);
}
return child;
}
deriveChild(index) {
if (!this.pubKey || !this.chainCode) {
throw new Error("No publicKey or chainCode set");
}
let data = toU32(index);
if (index >= HARDENED_OFFSET) {
const priv = this.privateKey;
if (!priv) {
throw new Error("Could not derive hardened child key");
}
data = concatBytes2(new Uint8Array([0]), priv, data);
} else {
data = concatBytes2(this.pubKey, data);
}
const I = hmac(sha512, this.chainCode, data);
const childTweak = bytesToNumber2(I.slice(0, 32));
const chainCode = I.slice(32);
if (!secp256k1.utils.isValidPrivateKey(childTweak)) {
throw new Error("Tweak bigger than curve order");
}
const opt = {
versions: this.versions,
chainCode,
depth: this.depth + 1,
parentFingerprint: this.fingerprint,
index
};
try {
if (this.privateKey) {
const added = mod2(this.privKey + childTweak, secp256k1.CURVE.n);
if (!secp256k1.utils.isValidPrivateKey(added)) {
throw new Error("The tweak was out of range or the resulted private key is invalid");
}
opt.privateKey = added;
} else {
const added = Point3.fromHex(this.pubKey).add(Point3.fromPrivateKey(childTweak));
if (added.equals(Point3.ZERO)) {
throw new Error("The tweak was equal to negative P, which made the result key invalid");
}
opt.publicKey = added.toRawBytes(true);
}
return new HDKey(opt);
} catch (err) {
return this.deriveChild(index + 1);
}
}
sign(hash2) {
if (!this.privateKey) {
throw new Error("No privateKey set!");
}
bytes(hash2, 32);
return secp256k1.sign(hash2, this.privKey).toCompactRawBytes();
}
verify(hash2, signature) {
bytes(hash2, 32);
bytes(signature, 64);
if (!this.publicKey) {
throw new Error("No publicKey set!");
}
let sig;
try {
sig = secp256k1.Signature.fromCompact(signature);
} catch (error) {
return false;
}
return secp256k1.verify(sig, hash2, this.publicKey);
}
wipePrivateData() {
this.privKey = void 0;
if (this.privKeyBytes) {
this.privKeyBytes.fill(0);
this.privKeyBytes = void 0;
}
return this;
}
toJSON() {
return {
xpriv: this.privateExtendedKey,
xpub: this.publicExtendedKey
};
}
serialize(version, key) {
if (!this.chainCode) {
throw new Error("No chainCode set");
}
bytes(key, 33);
return concatBytes2(toU32(version), new Uint8Array([this.depth]), toU32(this.parentFingerprint), toU32(this.index), this.chainCode, key);
}
}
;
// node_modules/.pnpm/@noble+hashes@0.5.9/node_modules/@noble/hashes/esm/hmac.js
var HMAC2 = class extends Hash {
constructor(hash2, _key) {
super();
this.finished = false;
this.destroyed = false;
assertHash(hash2);
const key = toBytes(_key);
this.iHash = hash2.create();
if (!(this.iHash instanceof Hash))
throw new TypeError("Expected instance of class which extends utils.Hash");
const blockLen = this.blockLen = this.iHash.blockLen;
this.outputLen = this.iHash.outputLen;
const pad = new Uint8Array(blockLen);
pad.set(key.length > this.iHash.blockLen ? hash2.create().update(key).digest() : key);
for (let i = 0; i < pad.length; i++)
pad[i] ^= 54;
this.iHash.update(pad);
this.oHash = hash2.create();
for (let i = 0; i < pad.length; i++)
pad[i] ^= 54 ^ 92;
this.oHash.update(pad);
pad.fill(0);
}
update(buf) {
if (this.destroyed)
throw new Error("instance is destroyed");
this.iHash.update(buf);
return this;
}
digestInto(out) {
if (this.destroyed)
throw new Error("instance is destroyed");
if (!(out instanceof Uint8Array) || out.length !== this.outputLen)
throw new Error("HMAC: Invalid output buffer");
if (this.finished)
throw new Error("digest() was already called");
this.finished = true;
this.iHash.digestInto(out);
this.oHash.update(out);
this.oHash.digestInto(out);
this.destroy();
}
digest() {
const out = new Uint8Array(this.oHash.outputLen);
this.digestInto(out);
return out;
}
_cloneInto(to) {
to || (to = Object.create(Object.getPrototypeOf(this), {}));
const {oHash, iHash, finished, destroyed, blockLen, outputLen} = this;
to = to;
to.finished = finished;
to.destroyed = destroyed;
to.blockLen = blockLen;
to.outputLen = outputLen;
to.oHash = oHash._cloneInto(to.oHash);
to.iHash = iHash._cloneInto(to.iHash);
return to;
}
destroy() {
this.destroyed = true;
this.oHash.destroy();
this.iHash.destroy();
}
}
;
var hmac2 = (hash2,key,message)=>new HMAC2(hash2,key).update(message).digest();
hmac2.create = (hash2,key)=>new HMAC2(hash2,key);
hmac2.init = hmac2.create;
// node_modules/.pnpm/nostr-tools@1.1.0/node_modules/nostr-tools/lib/nostr.esm.js
var __defProp2 = Object.defineProperty;
var __export2 = (target,all)=>{
for (var name in all)
__defProp2(target, name, {
get: all[name],
enumerable: true
});
}
;
function getPublicKey(privateKey) {
return utils.bytesToHex(schnorr.getPublicKey(privateKey));
}
var utf8Decoder = new TextDecoder("utf-8");
var utf8Encoder = new TextEncoder();
function serializeEvent(evt) {
return JSON.stringify([0, evt.pubkey, evt.created_at, evt.kind, evt.tags, evt.content]);
}
function getEventHash(event) {
let eventHash = sha256(utf8Encoder.encode(serializeEvent(event)));
return utils.bytesToHex(eventHash);
}
function validateEvent(event) {
if (event.id !== getEventHash(event))
return false;
if (typeof event.content !== "string")
return false;
if (typeof event.created_at !== "number")
return false;
if (!Array.isArray(event.tags))
return false;
for (let i = 0; i < event.tags.length; i++) {
let tag = event.tags[i];
if (!Array.isArray(tag))
return false;
for (let j = 0; j < tag.length; j++) {
if (typeof tag[j] === "object")
return false;
}
}
return true;
}
function signEvent(event, key) {
return utils.bytesToHex(schnorr.signSync(getEventHash(event), key));
}
var nip04_exports = {};
__export2(nip04_exports, {
decrypt: ()=>decrypt,
encrypt: ()=>encrypt
});
async function encrypt(privkey, pubkey, text) {
const key = getSharedSecret(privkey, "02" + pubkey);
const normalizedKey = getNormalizedX(key);
let iv = Uint8Array.from(randomBytes(16));
let plaintext = utf8Encoder.encode(text);
let cryptoKey = await crypto.subtle.importKey("raw", normalizedKey, {
name: "AES-CBC"
}, false, ["encrypt"]);
let ciphertext = await crypto.subtle.encrypt({
name: "AES-CBC",
iv
}, cryptoKey, plaintext);
let ctb64 = base64.encode(new Uint8Array(ciphertext));
let ivb64 = base64.encode(new Uint8Array(iv.buffer));
return `${ctb64}?iv=${ivb64}`;
}
async function decrypt(privkey, pubkey, data) {
let[ctb64,ivb64] = data.split("?iv=");
let key = getSharedSecret(privkey, "02" + pubkey);
let normalizedKey = getNormalizedX(key);
let cryptoKey = await crypto.subtle.importKey("raw", normalizedKey, {
name: "AES-CBC"
}, false, ["decrypt"]);
let ciphertext = base64.decode(ctb64);
let iv = base64.decode(ivb64);
let plaintext = await crypto.subtle.decrypt({
name: "AES-CBC",
iv
}, cryptoKey, ciphertext);
let text = utf8Decoder.decode(plaintext);
return text;
}
function getNormalizedX(key) {
return key.slice(1, 33);
}
var nip05_exports = {};
__export2(nip05_exports, {
queryProfile: ()=>queryProfile,
searchDomain: ()=>searchDomain,
useFetchImplementation: ()=>useFetchImplementation
});
var _fetch;
try {
_fetch = fetch;
} catch {}
function useFetchImplementation(fetchImplementation) {
_fetch = fetchImplementation;
}
async function searchDomain(domain, query="") {
try {
let res = await (await _fetch(`https://${domain}/.well-known/nostr.json?name=${query}`)).json();
return res.names;
} catch (_) {
return {};
}
}
async function queryProfile(fullname) {
let[name,domain] = fullname.split("@");
if (!domain) {
domain = name;
name = "_";
}
if (!name.match(/^[a-z0-9-_]+$/))
return null;
let res = await (await _fetch(`https://${domain}/.well-known/nostr.json?name=${name}`)).json();
if (!res?.names?.[name])
return null;
let pubkey = res.names[name];
let relays = res.relays?.[pubkey] || [];
return {
pubkey,
relays
};
}
var nip06_exports = {};
__export2(nip06_exports, {
generateSeedWords: ()=>generateSeedWords,
privateKeyFromSeedWords: ()=>privateKeyFromSeedWords,
validateWords: ()=>validateWords
});
function privateKeyFromSeedWords(mnemonic) {
let root = HDKey.fromMasterSeed((0,
import_bip39.mnemonicToSeedSync)(mnemonic));
let privateKey = root.derive(`m/44'/1237'/0'/0/0`).privateKey;
if (!privateKey)
throw new Error("could not derive private key");
return utils.bytesToHex(privateKey);
}
function generateSeedWords() {
return (0,
import_bip39.generateMnemonic)(import_english.wordlist);
}
function validateWords(words) {
return (0,
import_bip39.validateMnemonic)(words, import_english.wordlist);
}
var nip19_exports = {};
__export2(nip19_exports, {
decode: ()=>decode,
neventEncode: ()=>neventEncode,
noteEncode: ()=>noteEncode,
nprofileEncode: ()=>nprofileEncode,
npubEncode: ()=>npubEncode,
nsecEncode: ()=>nsecEncode
});
function decode(nip19) {
let {prefix, words} = bech32.decode(nip19, 1e3);
let data = new Uint8Array(bech32.fromWords(words));
if (prefix === "nprofile") {
let tlv = parseTLV(data);
if (!tlv[0]?.[0])
throw new Error("missing TLV 0 for nprofile");
if (tlv[0][0].length !== 32)
throw new Error("TLV 0 should be 32 bytes");
return {
type: "nprofile",
data: {
pubkey: utils.bytesToHex(tlv[0][0]),
relays: tlv[1].map((d)=>utf8Decoder.decode(d))
}
};
}
if (prefix === "nevent") {
let tlv = parseTLV(data);
if (!tlv[0]?.[0])
throw new Error("missing TLV 0 for nevent");
if (tlv[0][0].length !== 32)
throw new Error("TLV 0 should be 32 bytes");
return {
type: "nevent",
data: {
id: utils.bytesToHex(tlv[0][0]),
relays: tlv[1].map((d)=>utf8Decoder.decode(d))
}
};
}
if (prefix === "nsec" || prefix === "npub" || prefix === "note") {
return {
type: prefix,
data: utils.bytesToHex(data)
};
}
throw new Error(`unknown prefix ${prefix}`);
}
function parseTLV(data) {
let result = {};
let rest = data;
while (rest.length > 0) {
let t = rest[0];
let l = rest[1];
let v = rest.slice(2, 2 + l);
rest = rest.slice(2 + l);
if (v.length < l)
continue;
result[t] = result[t] || [];
result[t].push(v);
}
return result;
}
function nsecEncode(hex2) {
return encodeBytes("nsec", hex2);
}
function npubEncode(hex2) {
return encodeBytes("npub", hex2);
}
function noteEncode(hex2) {
return encodeBytes("note", hex2);
}
function encodeBytes(prefix, hex2) {
let data = utils.hexToBytes(hex2);
let words = bech32.toWords(data);
return bech32.encode(prefix, words, 1e3);
}
function nprofileEncode(profile) {
let data = encodeTLV({
0: [utils.hexToBytes(profile.pubkey)],
1: (profile.relays || []).map((url)=>utf8Encoder.encode(url))
});
let words = bech32.toWords(data);
return bech32.encode("nprofile", words, 1e3);
}
function neventEncode(event) {
let data = encodeTLV({
0: [utils.hexToBytes(event.id)],
1: (event.relays || []).map((url)=>utf8Encoder.encode(url))
});
let words = bech32.toWords(data);
return bech32.encode("nevent", words, 1e3);
}
function encodeTLV(tlv) {
let entries = [];
Object.entries(tlv).forEach(([t,vs])=>{
vs.forEach((v)=>{
let entry = new Uint8Array(v.length + 2);
entry.set([parseInt(t)], 0);
entry.set([v.length], 1);
entry.set(v, 2);
entries.push(entry);
}
);
}
);
return utils.concatBytes(...entries);
}
var nip26_exports = {};
__export2(nip26_exports, {
createDelegation: ()=>createDelegation,
getDelegator: ()=>getDelegator
});
function createDelegation(privateKey, parameters) {
let conditions = [];
if ((parameters.kind || -1) >= 0)
conditions.push(`kind=${parameters.kind}`);
if (parameters.until)
conditions.push(`created_at<${parameters.until}`);
if (parameters.since)
conditions.push(`created_at>${parameters.since}`);
let cond = conditions.join("&");
if (cond === "")
throw new Error("refusing to create a delegation without any conditions");
let sighash = sha256(utf8Encoder.encode(`nostr:delegation:${parameters.pubkey}:${cond}`));
let sig = utils.bytesToHex(schnorr.signSync(sighash, privateKey));
return {
from: getPublicKey(privateKey),
to: parameters.pubkey,
cond,
sig
};
}
function getDelegator(event) {
let tag = event.tags.find((tag2)=>tag2[0] === "delegation" && tag2.length >= 4);
if (!tag)
return null;
let pubkey = tag[1];
let cond = tag[2];
let sig = tag[3];
let conditions = cond.split("&");
for (let i = 0; i < conditions.length; i++) {
let[key,operator,value] = conditions[i].split(/\b/);
if (key === "kind" && operator === "=" && event.kind === parseInt(value))
continue;
else if (key === "created_at" && operator === "<" && event.created_at < parseInt(value))
continue;
else if (key === "created_at" && operator === ">" && event.created_at > parseInt(value))
continue;
else
return null;
}
let sighash = sha256(utf8Encoder.encode(`nostr:delegation:${event.pubkey}:${cond}`));
if (!schnorr.verifySync(sig, sighash, pubkey))
return null;
return pubkey;
}
utils.hmacSha256Sync = (key,...msgs)=>hmac2(sha256, key, utils.concatBytes(...msgs));
utils.sha256Sync = (...msgs)=>sha256(utils.concatBytes(...msgs));
// node_modules/.pnpm/nostr-tools@1.1.0/node_modules/nostr-tools/utils.ts
var utf8Decoder2 = new TextDecoder("utf-8");
var utf8Encoder2 = new TextEncoder();
// node_modules/.pnpm/nostr-tools@1.1.0/node_modules/nostr-tools/nip04.ts
async function encrypt2(privkey, pubkey, text) {
const key = getSharedSecret(privkey, "02" + pubkey);
const normalizedKey = getNormalizedX2(key);
let iv = Uint8Array.from(randomBytes(16));
let plaintext = utf8Encoder2.encode(text);
let cryptoKey = await crypto.subtle.importKey("raw", normalizedKey, {
name: "AES-CBC"
}, false, ["encrypt"]);
let ciphertext = await crypto.subtle.encrypt({
name: "AES-CBC",
iv
}, cryptoKey, plaintext);
let ctb64 = base64.encode(new Uint8Array(ciphertext));
let ivb64 = base64.encode(new Uint8Array(iv.buffer));
return `${ctb64}?iv=${ivb64}`;
}
async function decrypt2(privkey, pubkey, data) {
let[ctb64,ivb64] = data.split("?iv=");
let key = getSharedSecret(privkey, "02" + pubkey);
let normalizedKey = getNormalizedX2(key);
let cryptoKey = await crypto.subtle.importKey("raw", normalizedKey, {
name: "AES-CBC"
}, false, ["decrypt"]);
let ciphertext = base64.decode(ctb64);
let iv = base64.decode(ivb64);
let plaintext = await crypto.subtle.decrypt({
name: "AES-CBC",
iv
}, cryptoKey, ciphertext);
let text = utf8Decoder2.decode(plaintext);
return text;
}
function getNormalizedX2(key) {
return key.slice(1, 33);
}
// src/storage.ts
var import_webextension_polyfill = __toESM(require_browser_polyfill());
async function readPrivateKey() {
const data = await import_webextension_polyfill.default.storage.local.get("private_key"/* PRIVATE_KEY */
);
return data["private_key"/* PRIVATE_KEY */
];
}
async function readRelays() {
const data = await import_webextension_polyfill.default.storage.local.get("relays"/* RELAYS */
);
return data["relays"/* RELAYS */
];
}
async function readPermissions() {
let {permissions={}} = await import_webextension_polyfill.default.storage.local.get("permissions"/* PERMISSIONS */
);
var needsUpdate = false;
for (let host in permissions) {
if (permissions[host].condition === "expirable" && permissions[host].created_at < Date.now() / 1e3 - 5 * 60) {
delete permissions[host];
needsUpdate = true;
}
}
if (needsUpdate)
import_webextension_polyfill.default.storage.local.set({
permissions
});
return permissions;
}
async function updatePermission(host, permission) {
import_webextension_polyfill.default.storage.local.set({
permissions: {
...await import_webextension_polyfill.default.storage.local.get("permissions"/* PERMISSIONS */
).permissions || {},
[host]: {
...permission,
created_at: Math.round(Date.now() / 1e3)
}
}
});
}
// src/common.ts
var PERMISSIONS_REQUIRED = {
getPublicKey: 1,
getRelays: 5,
signEvent: 10,
"nip04.encrypt": 20,
"nip04.decrypt": 20
};
async function readPermissionLevel(host) {
return (await readPermissions())[host]?.level || 0;
}
// src/background.js
var prompts = {};
import_webextension_polyfill2.default.runtime.onMessage.addListener(async(req,sender)=>{
let {prompt} = req;
if (prompt) {
return handlePromptMessage(req, sender);
} else {
return handleContentScriptMessage(req);
}
}
);
import_webextension_polyfill2.default.runtime.onMessageExternal.addListener(async({type, params},sender)=>{
let extensionId = new URL(sender.url).host;
handleContentScriptMessage({
type,
params,
host: extensionId
});
}
);
async function handleContentScriptMessage({type, params, host}) {
let level = await readPermissionLevel(host);
if (level >= PERMISSIONS_REQUIRED[type]) {} else {
try {
await promptPermission(host, PERMISSIONS_REQUIRED[type], params);
} catch (_) {
return {
error: `insufficient permissions, required ${PERMISSIONS_REQUIRED[type]}`
};
}
}
let privateKey = await readPrivateKey();
if (!privateKey) {
return {
error: "no private key found"
};
}
let sk = privateKey;
try {
switch (type) {
case "getPublicKey":
{
return getPublicKey(sk);
}
case "getRelays":
{
let relays = await readRelays();
return relays || {};
}
case "signEvent":
{
let {event} = params;
if (!event.pubkey)
event.pubkey = getPublicKey(sk);
if (!event.id)
event.id = getEventHash(event);
if (!validateEvent(event))
return {
error: "invalid event"
};
event.sig = await signEvent(event, sk);
return event;
}
case "nip04.encrypt":
{
let {peer, plaintext} = params;
return encrypt2(sk, peer, plaintext);
}
case "nip04.decrypt":
{
let {peer, ciphertext} = params;
return decrypt2(sk, peer, ciphertext);
}
}
} catch (error) {
return {
error: {
message: error.message,
stack: error.stack
}
};
}
}
function handlePromptMessage({id, condition, host, level}, sender) {
switch (condition) {
case "forever":
case "expirable":
prompts[id]?.resolve?.();
updatePermission(host, {
level,
condition
});
break;
case "single":
prompts[id]?.resolve?.();
break;
case "no":
prompts[id]?.reject?.();
break;
}
delete prompts[id];
import_webextension_polyfill2.default.windows.remove(sender.tab.windowId);
}
function promptPermission(host, level, params) {
let id = Math.random().toString().slice(4);
let qs = new URLSearchParams({
host,
level,
id,
params: JSON.stringify(params)
});
return new Promise((resolve,reject)=>{
import_webextension_polyfill2.default.windows.create({
url: `${import_webextension_polyfill2.default.runtime.getURL("prompt.html")}?${qs.toString()}`,
type: "popup",
width: 600,
height: 400
});
prompts[id] = {
resolve,
reject
};
}
);
}
}
)();
/*! Bundled license information:
@noble/hashes/utils.js:
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@scure/base/lib/index.js:
(*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@scure/bip39/index.js:
(*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) *)
@noble/secp256k1/lib/esm/index.js:
(*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
@noble/hashes/esm/utils.js:
(*! noble-hashes - MIT License (c) 2021 Paul Miller (paulmillr.com) *)
@scure/base/lib/esm/index.js:
(*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@noble/hashes/esm/utils.js:
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@noble/curves/esm/abstract/utils.js:
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@noble/curves/esm/abstract/modular.js:
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@noble/curves/esm/abstract/curve.js:
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@noble/curves/esm/abstract/weierstrass.js:
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@noble/curves/esm/_shortw_utils.js:
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
@noble/curves/esm/secp256k1.js:
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
*/