signet-login 0.9.8 → 0.9.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/modal.js +39 -27
- package/dist/signet-login.iife.js +9 -9
- package/package.json +1 -1
package/dist/modal.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* top-layer placement, theme-aware colours, no third-party UI deps.
|
|
6
6
|
*/
|
|
7
7
|
import { DEFAULTS } from './types.js';
|
|
8
|
-
import { hasNip07, createNip07Signer, createBunkerSigner, createBunkerSignerFromNostrConnect, buildNostrConnectUri, EphemeralSigner,
|
|
8
|
+
import { hasNip07, createNip07Signer, createBunkerSigner, createBunkerSignerFromNostrConnect, buildNostrConnectUri, EphemeralSigner, createLocalSignerFromNsec } from './signers.js';
|
|
9
9
|
import { isAndroid, startAmberSignIn } from './amber.js';
|
|
10
10
|
import { loadOrCreatePersistentClientSk } from './storage.js';
|
|
11
11
|
import { waitForAuthResponse } from 'signet-verify';
|
|
@@ -657,36 +657,48 @@ export async function showLoginModal(opts) {
|
|
|
657
657
|
let method = 'redirect';
|
|
658
658
|
// Cross-device bunker passthrough: when the signer device hands back a
|
|
659
659
|
// `bunker://` URI (its own NIP-46 server, or an upstream hardware
|
|
660
|
-
// bunker),
|
|
661
|
-
// and
|
|
662
|
-
//
|
|
663
|
-
//
|
|
660
|
+
// bunker), connect before resolving the QR flow. QR is already an
|
|
661
|
+
// in-place modal, and consumers such as Pallasite reject auth-only at
|
|
662
|
+
// their auth boundary; returning a cold DeferredBunkerSigner makes them
|
|
663
|
+
// classify the session as non-signing before the relay handshake can
|
|
664
|
+
// finish.
|
|
664
665
|
if (result.bunkerUri) {
|
|
665
666
|
const clientSecretKey = loadOrCreatePersistentClientSk();
|
|
666
667
|
const expected = result.pubkey;
|
|
667
|
-
const
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
668
|
+
const status = refs.dialog.querySelector('#signet-login-status');
|
|
669
|
+
if (status)
|
|
670
|
+
status.textContent = 'Connecting signer...';
|
|
671
|
+
try {
|
|
672
|
+
const bunkerSigner = await createBunkerSigner({
|
|
673
|
+
uri: result.bunkerUri,
|
|
674
|
+
clientSecretKey,
|
|
675
|
+
timeoutMs: QR_BUNKER_CONNECT_TIMEOUT_MS,
|
|
676
|
+
});
|
|
677
|
+
if (bunkerSigner.pubkey.toLowerCase() !== expected.toLowerCase()) {
|
|
678
|
+
console.warn('[signet-login] QR upgrade: bunker pubkey mismatch — cannot sign', { connected: bunkerSigner.pubkey, expected });
|
|
679
|
+
void bunkerSigner.close().catch(() => { });
|
|
680
|
+
if (status) {
|
|
681
|
+
status.textContent = 'Signer connected with the wrong public key.';
|
|
682
|
+
status.style.color = '#d04848';
|
|
683
|
+
}
|
|
684
|
+
await Promise.race([new Promise(resolve => setTimeout(resolve, 2500)), aborted]);
|
|
685
|
+
if (userAborted || resolved.preferredMethod)
|
|
686
|
+
return null;
|
|
687
|
+
continue;
|
|
676
688
|
}
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
689
|
+
signer = bunkerSigner;
|
|
690
|
+
}
|
|
691
|
+
catch (err) {
|
|
692
|
+
console.warn('[signet-login] QR upgrade: createBunkerSigner failed — signer did not become live.', err);
|
|
693
|
+
if (status) {
|
|
694
|
+
status.textContent = `Signer connection failed: ${err instanceof Error ? err.message : String(err)}`;
|
|
695
|
+
status.style.color = '#d04848';
|
|
696
|
+
}
|
|
697
|
+
await Promise.race([new Promise(resolve => setTimeout(resolve, 2500)), aborted]);
|
|
698
|
+
if (userAborted || resolved.preferredMethod)
|
|
699
|
+
return null;
|
|
700
|
+
continue;
|
|
701
|
+
}
|
|
690
702
|
method = 'bunker';
|
|
691
703
|
}
|
|
692
704
|
else {
|
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
"use strict";var __SignetLoginIIFE=(()=>{var ol=Object.create;var
|
|
2
|
-
]))+`;ze.KANJI=new RegExp(
|
|
3
|
-
Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),t.put(n,13)}};Ic.exports=
|
|
4
|
-
Suggested mode is: `+J.toString(r));switch(n===J.KANJI&&!Ir.isKanjiModeEnabled()&&(n=J.BYTE),n){case J.NUMERIC:return new Pc(t);case J.ALPHANUMERIC:return new Hc(t);case J.KANJI:return new qc(t);case J.BYTE:return new Mc(t)}}
|
|
1
|
+
"use strict";var __SignetLoginIIFE=(()=>{var ol=Object.create;var Ft=Object.defineProperty;var il=Object.getOwnPropertyDescriptor;var sl=Object.getOwnPropertyNames;var al=Object.getPrototypeOf,cl=Object.prototype.hasOwnProperty;var ll=(t,e,n)=>e in t?Ft(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var X=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ul=(t,e)=>{for(var n in e)Ft(t,n,{get:e[n],enumerable:!0})},Ci=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of sl(e))!cl.call(t,o)&&o!==n&&Ft(t,o,{get:()=>e[o],enumerable:!(r=il(e,o))||r.enumerable});return t};var fl=(t,e,n)=>(n=t!=null?ol(al(t)):{},Ci(e||!t||!t.__esModule?Ft(n,"default",{value:t,enumerable:!0}):n,t)),dl=t=>Ci(Ft({},"__esModule",{value:!0}),t);var S=(t,e,n)=>ll(t,typeof e!="symbol"?e+"":e,n);var Fa=X((qg,Xa)=>{Xa.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var nt=X(Et=>{var ri,Bf=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];Et.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17};Et.getSymbolTotalCodewords=function(e){return Bf[e]};Et.getBCHDigit=function(t){let e=0;for(;t!==0;)e++,t>>>=1;return e};Et.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');ri=e};Et.isKanjiModeEnabled=function(){return typeof ri<"u"};Et.toSJIS=function(e){return ri(e)}});var kr=X(ve=>{ve.L={bit:1};ve.M={bit:0};ve.Q={bit:3};ve.H={bit:2};function Af(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return ve.L;case"m":case"medium":return ve.M;case"q":case"quartile":return ve.Q;case"h":case"high":return ve.H;default:throw new Error("Unknown EC Level: "+t)}}ve.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};ve.from=function(e,n){if(ve.isValid(e))return e;try{return Af(e)}catch{return n}}});var tc=X((Vg,ec)=>{function Qa(){this.buffer=[],this.length=0}Qa.prototype={get:function(t){let e=Math.floor(t/8);return(this.buffer[e]>>>7-t%8&1)===1},put:function(t,e){for(let n=0;n<e;n++)this.putBit((t>>>e-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(t){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}};ec.exports=Qa});var rc=X((Kg,nc)=>{function xn(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=new Uint8Array(t*t),this.reservedBit=new Uint8Array(t*t)}xn.prototype.set=function(t,e,n,r){let o=t*this.size+e;this.data[o]=n,r&&(this.reservedBit[o]=!0)};xn.prototype.get=function(t,e){return this.data[t*this.size+e]};xn.prototype.xor=function(t,e,n){this.data[t*this.size+e]^=n};xn.prototype.isReserved=function(t,e){return this.reservedBit[t*this.size+e]};nc.exports=xn});var oc=X(Br=>{var Rf=nt().getSymbolSize;Br.getRowColCoords=function(e){if(e===1)return[];let n=Math.floor(e/7)+2,r=Rf(e),o=r===145?26:Math.ceil((r-13)/(2*n-2))*2,i=[r-7];for(let s=1;s<n-1;s++)i[s]=i[s-1]-o;return i.push(6),i.reverse()};Br.getPositions=function(e){let n=[],r=Br.getRowColCoords(e),o=r.length;for(let i=0;i<o;i++)for(let s=0;s<o;s++)i===0&&s===0||i===0&&s===o-1||i===o-1&&s===0||n.push([r[i],r[s]]);return n}});var ac=X(sc=>{var Cf=nt().getSymbolSize,ic=7;sc.getPositions=function(e){let n=Cf(e);return[[0,0],[n-ic,0],[0,n-ic]]}});var cc=X(Q=>{Q.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var vt={N1:3,N2:3,N3:40,N4:10};Q.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};Q.from=function(e){return Q.isValid(e)?parseInt(e,10):void 0};Q.getPenaltyN1=function(e){let n=e.size,r=0,o=0,i=0,s=null,a=null;for(let c=0;c<n;c++){o=i=0,s=a=null;for(let l=0;l<n;l++){let d=e.get(c,l);d===s?o++:(o>=5&&(r+=vt.N1+(o-5)),s=d,o=1),d=e.get(l,c),d===a?i++:(i>=5&&(r+=vt.N1+(i-5)),a=d,i=1)}o>=5&&(r+=vt.N1+(o-5)),i>=5&&(r+=vt.N1+(i-5))}return r};Q.getPenaltyN2=function(e){let n=e.size,r=0;for(let o=0;o<n-1;o++)for(let i=0;i<n-1;i++){let s=e.get(o,i)+e.get(o,i+1)+e.get(o+1,i)+e.get(o+1,i+1);(s===4||s===0)&&r++}return r*vt.N2};Q.getPenaltyN3=function(e){let n=e.size,r=0,o=0,i=0;for(let s=0;s<n;s++){o=i=0;for(let a=0;a<n;a++)o=o<<1&2047|e.get(s,a),a>=10&&(o===1488||o===93)&&r++,i=i<<1&2047|e.get(a,s),a>=10&&(i===1488||i===93)&&r++}return r*vt.N3};Q.getPenaltyN4=function(e){let n=0,r=e.data.length;for(let i=0;i<r;i++)n+=e.data[i];return Math.abs(Math.ceil(n*100/r/5)-10)*vt.N4};function Tf(t,e,n){switch(t){case Q.Patterns.PATTERN000:return(e+n)%2===0;case Q.Patterns.PATTERN001:return e%2===0;case Q.Patterns.PATTERN010:return n%3===0;case Q.Patterns.PATTERN011:return(e+n)%3===0;case Q.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(n/3))%2===0;case Q.Patterns.PATTERN101:return e*n%2+e*n%3===0;case Q.Patterns.PATTERN110:return(e*n%2+e*n%3)%2===0;case Q.Patterns.PATTERN111:return(e*n%3+(e+n)%2)%2===0;default:throw new Error("bad maskPattern:"+t)}}Q.applyMask=function(e,n){let r=n.size;for(let o=0;o<r;o++)for(let i=0;i<r;i++)n.isReserved(i,o)||n.xor(i,o,Tf(e,i,o))};Q.getBestMask=function(e,n){let r=Object.keys(Q.Patterns).length,o=0,i=1/0;for(let s=0;s<r;s++){n(s),Q.applyMask(s,e);let a=Q.getPenaltyN1(e)+Q.getPenaltyN2(e)+Q.getPenaltyN3(e)+Q.getPenaltyN4(e);Q.applyMask(s,e),a<i&&(i=a,o=s)}return o}});var ii=X(oi=>{var rt=kr(),Ar=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],Rr=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];oi.getBlocksCount=function(e,n){switch(n){case rt.L:return Ar[(e-1)*4+0];case rt.M:return Ar[(e-1)*4+1];case rt.Q:return Ar[(e-1)*4+2];case rt.H:return Ar[(e-1)*4+3];default:return}};oi.getTotalCodewordsCount=function(e,n){switch(n){case rt.L:return Rr[(e-1)*4+0];case rt.M:return Rr[(e-1)*4+1];case rt.Q:return Rr[(e-1)*4+2];case rt.H:return Rr[(e-1)*4+3];default:return}}});var lc=X(Tr=>{var En=new Uint8Array(512),Cr=new Uint8Array(256);(function(){let e=1;for(let n=0;n<255;n++)En[n]=e,Cr[e]=n,e<<=1,e&256&&(e^=285);for(let n=255;n<512;n++)En[n]=En[n-255]})();Tr.log=function(e){if(e<1)throw new Error("log("+e+")");return Cr[e]};Tr.exp=function(e){return En[e]};Tr.mul=function(e,n){return e===0||n===0?0:En[Cr[e]+Cr[n]]}});var uc=X(vn=>{var si=lc();vn.mul=function(e,n){let r=new Uint8Array(e.length+n.length-1);for(let o=0;o<e.length;o++)for(let i=0;i<n.length;i++)r[o+i]^=si.mul(e[o],n[i]);return r};vn.mod=function(e,n){let r=new Uint8Array(e);for(;r.length-n.length>=0;){let o=r[0];for(let s=0;s<n.length;s++)r[s]^=si.mul(n[s],o);let i=0;for(;i<r.length&&r[i]===0;)i++;r=r.slice(i)}return r};vn.generateECPolynomial=function(e){let n=new Uint8Array([1]);for(let r=0;r<e;r++)n=vn.mul(n,new Uint8Array([1,si.exp(r)]));return n}});var hc=X((Jg,dc)=>{var fc=uc();function ai(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}ai.prototype.initialize=function(e){this.degree=e,this.genPoly=fc.generateECPolynomial(this.degree)};ai.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let n=new Uint8Array(e.length+this.degree);n.set(e);let r=fc.mod(n,this.genPoly),o=this.degree-r.length;if(o>0){let i=new Uint8Array(this.degree);return i.set(r,o),i}return r};dc.exports=ai});var ci=X(gc=>{gc.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var li=X(ze=>{var pc="[0-9]+",Lf="[A-Z $%*+\\-./:]+",Sn="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Sn=Sn.replace(/u/g,"\\u");var If="(?:(?![A-Z0-9 $%*+\\-./:]|"+Sn+`)(?:.|[\r
|
|
2
|
+
]))+`;ze.KANJI=new RegExp(Sn,"g");ze.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");ze.BYTE=new RegExp(If,"g");ze.NUMERIC=new RegExp(pc,"g");ze.ALPHANUMERIC=new RegExp(Lf,"g");var Nf=new RegExp("^"+Sn+"$"),_f=new RegExp("^"+pc+"$"),Uf=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");ze.testKanji=function(e){return Nf.test(e)};ze.testNumeric=function(e){return _f.test(e)};ze.testAlphanumeric=function(e){return Uf.test(e)}});var ot=X(ie=>{var Of=ci(),ui=li();ie.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};ie.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};ie.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};ie.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};ie.MIXED={bit:-1};ie.getCharCountIndicator=function(e,n){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Of.isValid(n))throw new Error("Invalid version: "+n);return n>=1&&n<10?e.ccBits[0]:n<27?e.ccBits[1]:e.ccBits[2]};ie.getBestModeForData=function(e){return ui.testNumeric(e)?ie.NUMERIC:ui.testAlphanumeric(e)?ie.ALPHANUMERIC:ui.testKanji(e)?ie.KANJI:ie.BYTE};ie.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};ie.isValid=function(e){return e&&e.bit&&e.ccBits};function Pf(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return ie.NUMERIC;case"alphanumeric":return ie.ALPHANUMERIC;case"kanji":return ie.KANJI;case"byte":return ie.BYTE;default:throw new Error("Unknown mode: "+t)}}ie.from=function(e,n){if(ie.isValid(e))return e;try{return Pf(e)}catch{return n}}});var xc=X(St=>{var Lr=nt(),Hf=ii(),yc=kr(),it=ot(),fi=ci(),mc=7973,bc=Lr.getBCHDigit(mc);function Mf(t,e,n){for(let r=1;r<=40;r++)if(e<=St.getCapacity(r,n,t))return r}function wc(t,e){return it.getCharCountIndicator(t,e)+4}function qf(t,e){let n=0;return t.forEach(function(r){let o=wc(r.mode,e);n+=o+r.getBitsLength()}),n}function Df(t,e){for(let n=1;n<=40;n++)if(qf(t,n)<=St.getCapacity(n,e,it.MIXED))return n}St.from=function(e,n){return fi.isValid(e)?parseInt(e,10):n};St.getCapacity=function(e,n,r){if(!fi.isValid(e))throw new Error("Invalid QR Code version");typeof r>"u"&&(r=it.BYTE);let o=Lr.getSymbolTotalCodewords(e),i=Hf.getTotalCodewordsCount(e,n),s=(o-i)*8;if(r===it.MIXED)return s;let a=s-wc(r,e);switch(r){case it.NUMERIC:return Math.floor(a/10*3);case it.ALPHANUMERIC:return Math.floor(a/11*2);case it.KANJI:return Math.floor(a/13);case it.BYTE:default:return Math.floor(a/8)}};St.getBestVersionForData=function(e,n){let r,o=yc.from(n,yc.M);if(Array.isArray(e)){if(e.length>1)return Df(e,o);if(e.length===0)return 1;r=e[0]}else r=e;return Mf(r.mode,r.getLength(),o)};St.getEncodedBits=function(e){if(!fi.isValid(e)||e<7)throw new Error("Invalid QR Code version");let n=e<<12;for(;Lr.getBCHDigit(n)-bc>=0;)n^=mc<<Lr.getBCHDigit(n)-bc;return e<<12|n}});var kc=X(Sc=>{var di=nt(),vc=1335,$f=21522,Ec=di.getBCHDigit(vc);Sc.getEncodedBits=function(e,n){let r=e.bit<<3|n,o=r<<10;for(;di.getBCHDigit(o)-Ec>=0;)o^=vc<<di.getBCHDigit(o)-Ec;return(r<<10|o)^$f}});var Ac=X((np,Bc)=>{var Vf=ot();function jt(t){this.mode=Vf.NUMERIC,this.data=t.toString()}jt.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};jt.prototype.getLength=function(){return this.data.length};jt.prototype.getBitsLength=function(){return jt.getBitsLength(this.data.length)};jt.prototype.write=function(e){let n,r,o;for(n=0;n+3<=this.data.length;n+=3)r=this.data.substr(n,3),o=parseInt(r,10),e.put(o,10);let i=this.data.length-n;i>0&&(r=this.data.substr(n),o=parseInt(r,10),e.put(o,i*3+1))};Bc.exports=jt});var Cc=X((rp,Rc)=>{var Kf=ot(),hi=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function Zt(t){this.mode=Kf.ALPHANUMERIC,this.data=t}Zt.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};Zt.prototype.getLength=function(){return this.data.length};Zt.prototype.getBitsLength=function(){return Zt.getBitsLength(this.data.length)};Zt.prototype.write=function(e){let n;for(n=0;n+2<=this.data.length;n+=2){let r=hi.indexOf(this.data[n])*45;r+=hi.indexOf(this.data[n+1]),e.put(r,11)}this.data.length%2&&e.put(hi.indexOf(this.data[n]),6)};Rc.exports=Zt});var Lc=X((op,Tc)=>{var zf=ot();function Gt(t){this.mode=zf.BYTE,typeof t=="string"?this.data=new TextEncoder().encode(t):this.data=new Uint8Array(t)}Gt.getBitsLength=function(e){return e*8};Gt.prototype.getLength=function(){return this.data.length};Gt.prototype.getBitsLength=function(){return Gt.getBitsLength(this.data.length)};Gt.prototype.write=function(t){for(let e=0,n=this.data.length;e<n;e++)t.put(this.data[e],8)};Tc.exports=Gt});var Nc=X((ip,Ic)=>{var jf=ot(),Zf=nt();function Wt(t){this.mode=jf.KANJI,this.data=t}Wt.getBitsLength=function(e){return e*13};Wt.prototype.getLength=function(){return this.data.length};Wt.prototype.getBitsLength=function(){return Wt.getBitsLength(this.data.length)};Wt.prototype.write=function(t){let e;for(e=0;e<this.data.length;e++){let n=Zf.toSJIS(this.data[e]);if(n>=33088&&n<=40956)n-=33088;else if(n>=57408&&n<=60351)n-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
|
|
3
|
+
Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),t.put(n,13)}};Ic.exports=Wt});var _c=X((sp,gi)=>{"use strict";var kn={single_source_shortest_paths:function(t,e,n){var r={},o={};o[e]=0;var i=kn.PriorityQueue.make();i.push(e,0);for(var s,a,c,l,d,g,u,f,y;!i.empty();){s=i.pop(),a=s.value,l=s.cost,d=t[a]||{};for(c in d)d.hasOwnProperty(c)&&(g=d[c],u=l+g,f=o[c],y=typeof o[c]>"u",(y||f>u)&&(o[c]=u,i.push(c,u),r[c]=a))}if(typeof n<"u"&&typeof o[n]>"u"){var m=["Could not find a path from ",e," to ",n,"."].join("");throw new Error(m)}return r},extract_shortest_path_from_predecessor_list:function(t,e){for(var n=[],r=e,o;r;)n.push(r),o=t[r],r=t[r];return n.reverse(),n},find_path:function(t,e,n){var r=kn.single_source_shortest_paths(t,e,n);return kn.extract_shortest_path_from_predecessor_list(r,n)},PriorityQueue:{make:function(t){var e=kn.PriorityQueue,n={},r;t=t||{};for(r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);return n.queue=[],n.sorter=t.sorter||e.default_sorter,n},default_sorter:function(t,e){return t.cost-e.cost},push:function(t,e){var n={value:t,cost:e};this.queue.push(n),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof gi<"u"&&(gi.exports=kn)});var $c=X(Yt=>{var J=ot(),Pc=Ac(),Hc=Cc(),Mc=Lc(),qc=Nc(),Bn=li(),Ir=nt(),Gf=_c();function Uc(t){return unescape(encodeURIComponent(t)).length}function An(t,e,n){let r=[],o;for(;(o=t.exec(n))!==null;)r.push({data:o[0],index:o.index,mode:e,length:o[0].length});return r}function Dc(t){let e=An(Bn.NUMERIC,J.NUMERIC,t),n=An(Bn.ALPHANUMERIC,J.ALPHANUMERIC,t),r,o;return Ir.isKanjiModeEnabled()?(r=An(Bn.BYTE,J.BYTE,t),o=An(Bn.KANJI,J.KANJI,t)):(r=An(Bn.BYTE_KANJI,J.BYTE,t),o=[]),e.concat(n,r,o).sort(function(s,a){return s.index-a.index}).map(function(s){return{data:s.data,mode:s.mode,length:s.length}})}function pi(t,e){switch(e){case J.NUMERIC:return Pc.getBitsLength(t);case J.ALPHANUMERIC:return Hc.getBitsLength(t);case J.KANJI:return qc.getBitsLength(t);case J.BYTE:return Mc.getBitsLength(t)}}function Wf(t){return t.reduce(function(e,n){let r=e.length-1>=0?e[e.length-1]:null;return r&&r.mode===n.mode?(e[e.length-1].data+=n.data,e):(e.push(n),e)},[])}function Yf(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n];switch(r.mode){case J.NUMERIC:e.push([r,{data:r.data,mode:J.ALPHANUMERIC,length:r.length},{data:r.data,mode:J.BYTE,length:r.length}]);break;case J.ALPHANUMERIC:e.push([r,{data:r.data,mode:J.BYTE,length:r.length}]);break;case J.KANJI:e.push([r,{data:r.data,mode:J.BYTE,length:Uc(r.data)}]);break;case J.BYTE:e.push([{data:r.data,mode:J.BYTE,length:Uc(r.data)}])}}return e}function Jf(t,e){let n={},r={start:{}},o=["start"];for(let i=0;i<t.length;i++){let s=t[i],a=[];for(let c=0;c<s.length;c++){let l=s[c],d=""+i+c;a.push(d),n[d]={node:l,lastCount:0},r[d]={};for(let g=0;g<o.length;g++){let u=o[g];n[u]&&n[u].node.mode===l.mode?(r[u][d]=pi(n[u].lastCount+l.length,l.mode)-pi(n[u].lastCount,l.mode),n[u].lastCount+=l.length):(n[u]&&(n[u].lastCount=l.length),r[u][d]=pi(l.length,l.mode)+4+J.getCharCountIndicator(l.mode,e))}}o=a}for(let i=0;i<o.length;i++)r[o[i]].end=0;return{map:r,table:n}}function Oc(t,e){let n,r=J.getBestModeForData(t);if(n=J.from(e,r),n!==J.BYTE&&n.bit<r.bit)throw new Error('"'+t+'" cannot be encoded with mode '+J.toString(n)+`.
|
|
4
|
+
Suggested mode is: `+J.toString(r));switch(n===J.KANJI&&!Ir.isKanjiModeEnabled()&&(n=J.BYTE),n){case J.NUMERIC:return new Pc(t);case J.ALPHANUMERIC:return new Hc(t);case J.KANJI:return new qc(t);case J.BYTE:return new Mc(t)}}Yt.fromArray=function(e){return e.reduce(function(n,r){return typeof r=="string"?n.push(Oc(r,null)):r.data&&n.push(Oc(r.data,r.mode)),n},[])};Yt.fromString=function(e,n){let r=Dc(e,Ir.isKanjiModeEnabled()),o=Yf(r),i=Jf(o,n),s=Gf.find_path(i.map,"start","end"),a=[];for(let c=1;c<s.length-1;c++)a.push(i.table[s[c]].node);return Yt.fromArray(Wf(a))};Yt.rawSplit=function(e){return Yt.fromArray(Dc(e,Ir.isKanjiModeEnabled()))}});var Kc=X(Vc=>{var _r=nt(),yi=kr(),Xf=tc(),Ff=rc(),Qf=oc(),ed=ac(),wi=cc(),xi=ii(),td=hc(),Nr=xc(),nd=kc(),rd=ot(),bi=$c();function od(t,e){let n=t.size,r=ed.getPositions(e);for(let o=0;o<r.length;o++){let i=r[o][0],s=r[o][1];for(let a=-1;a<=7;a++)if(!(i+a<=-1||n<=i+a))for(let c=-1;c<=7;c++)s+c<=-1||n<=s+c||(a>=0&&a<=6&&(c===0||c===6)||c>=0&&c<=6&&(a===0||a===6)||a>=2&&a<=4&&c>=2&&c<=4?t.set(i+a,s+c,!0,!0):t.set(i+a,s+c,!1,!0))}}function id(t){let e=t.size;for(let n=8;n<e-8;n++){let r=n%2===0;t.set(n,6,r,!0),t.set(6,n,r,!0)}}function sd(t,e){let n=Qf.getPositions(e);for(let r=0;r<n.length;r++){let o=n[r][0],i=n[r][1];for(let s=-2;s<=2;s++)for(let a=-2;a<=2;a++)s===-2||s===2||a===-2||a===2||s===0&&a===0?t.set(o+s,i+a,!0,!0):t.set(o+s,i+a,!1,!0)}}function ad(t,e){let n=t.size,r=Nr.getEncodedBits(e),o,i,s;for(let a=0;a<18;a++)o=Math.floor(a/3),i=a%3+n-8-3,s=(r>>a&1)===1,t.set(o,i,s,!0),t.set(i,o,s,!0)}function mi(t,e,n){let r=t.size,o=nd.getEncodedBits(e,n),i,s;for(i=0;i<15;i++)s=(o>>i&1)===1,i<6?t.set(i,8,s,!0):i<8?t.set(i+1,8,s,!0):t.set(r-15+i,8,s,!0),i<8?t.set(8,r-i-1,s,!0):i<9?t.set(8,15-i-1+1,s,!0):t.set(8,15-i-1,s,!0);t.set(r-8,8,1,!0)}function cd(t,e){let n=t.size,r=-1,o=n-1,i=7,s=0;for(let a=n-1;a>0;a-=2)for(a===6&&a--;;){for(let c=0;c<2;c++)if(!t.isReserved(o,a-c)){let l=!1;s<e.length&&(l=(e[s]>>>i&1)===1),t.set(o,a-c,l),i--,i===-1&&(s++,i=7)}if(o+=r,o<0||n<=o){o-=r,r=-r;break}}}function ld(t,e,n){let r=new Xf;n.forEach(function(c){r.put(c.mode.bit,4),r.put(c.getLength(),rd.getCharCountIndicator(c.mode,t)),c.write(r)});let o=_r.getSymbolTotalCodewords(t),i=xi.getTotalCodewordsCount(t,e),s=(o-i)*8;for(r.getLengthInBits()+4<=s&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);let a=(s-r.getLengthInBits())/8;for(let c=0;c<a;c++)r.put(c%2?17:236,8);return ud(r,t,e)}function ud(t,e,n){let r=_r.getSymbolTotalCodewords(e),o=xi.getTotalCodewordsCount(e,n),i=r-o,s=xi.getBlocksCount(e,n),a=r%s,c=s-a,l=Math.floor(r/s),d=Math.floor(i/s),g=d+1,u=l-d,f=new td(u),y=0,m=new Array(s),v=new Array(s),R=0,O=new Uint8Array(t.buffer);for(let j=0;j<s;j++){let Z=j<c?d:g;m[j]=O.slice(y,y+Z),v[j]=f.encode(m[j]),y+=Z,R=Math.max(R,Z)}let I=new Uint8Array(r),N=0,_,q;for(_=0;_<R;_++)for(q=0;q<s;q++)_<m[q].length&&(I[N++]=m[q][_]);for(_=0;_<u;_++)for(q=0;q<s;q++)I[N++]=v[q][_];return I}function fd(t,e,n,r){let o;if(Array.isArray(t))o=bi.fromArray(t);else if(typeof t=="string"){let l=e;if(!l){let d=bi.rawSplit(t);l=Nr.getBestVersionForData(d,n)}o=bi.fromString(t,l||40)}else throw new Error("Invalid data");let i=Nr.getBestVersionForData(o,n);if(!i)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=i;else if(e<i)throw new Error(`
|
|
5
5
|
The chosen QR Code version cannot contain this amount of data.
|
|
6
6
|
Minimum version required to store current data is: `+i+`.
|
|
7
7
|
`);let s=ld(e,n,o),a=_r.getSymbolSize(e),c=new Ff(a);return od(c,e),id(c),sd(c,e),mi(c,n,0),e>=7&&ad(c,e),cd(c,s),isNaN(r)&&(r=wi.getBestMask(c,mi.bind(null,c,n))),wi.applyMask(r,c),mi(c,n,r),{modules:c,version:e,errorCorrectionLevel:n,maskPattern:r,segments:o}}Vc.create=function(e,n){if(typeof e>"u"||e==="")throw new Error("No input text");let r=yi.M,o,i;return typeof n<"u"&&(r=yi.from(n.errorCorrectionLevel,yi.M),o=Nr.from(n.version),i=wi.from(n.maskPattern),n.toSJISFunc&&_r.setToSJISFunction(n.toSJISFunc)),fd(e,o,r,i)}});var Ei=X(kt=>{function zc(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let e=t.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+t);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(r){return[r,r]}))),e.length===6&&e.push("F","F");let n=parseInt(e.join(""),16);return{r:n>>24&255,g:n>>16&255,b:n>>8&255,a:n&255,hex:"#"+e.slice(0,6).join("")}}kt.getOptions=function(e){e||(e={}),e.color||(e.color={});let n=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,r=e.width&&e.width>=21?e.width:void 0,o=e.scale||4;return{width:r,scale:r?4:o,margin:n,color:{dark:zc(e.color.dark||"#000000ff"),light:zc(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};kt.getScale=function(e,n){return n.width&&n.width>=e+n.margin*2?n.width/(e+n.margin*2):n.scale};kt.getImageWidth=function(e,n){let r=kt.getScale(e,n);return Math.floor((e+n.margin*2)*r)};kt.qrToImageData=function(e,n,r){let o=n.modules.size,i=n.modules.data,s=kt.getScale(o,r),a=Math.floor((o+r.margin*2)*s),c=r.margin*s,l=[r.color.light,r.color.dark];for(let d=0;d<a;d++)for(let g=0;g<a;g++){let u=(d*a+g)*4,f=r.color.light;if(d>=c&&g>=c&&d<a-c&&g<a-c){let y=Math.floor((d-c)/s),m=Math.floor((g-c)/s);f=l[i[y*o+m]?1:0]}e[u++]=f.r,e[u++]=f.g,e[u++]=f.b,e[u]=f.a}}});var jc=X(Ur=>{var vi=Ei();function dd(t,e,n){t.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=n,e.width=n,e.style.height=n+"px",e.style.width=n+"px"}function hd(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Ur.render=function(e,n,r){let o=r,i=n;typeof o>"u"&&(!n||!n.getContext)&&(o=n,n=void 0),n||(i=hd()),o=vi.getOptions(o);let s=vi.getImageWidth(e.modules.size,o),a=i.getContext("2d"),c=a.createImageData(s,s);return vi.qrToImageData(c.data,e,o),dd(a,i,s),a.putImageData(c,0,0),i};Ur.renderToDataURL=function(e,n,r){let o=r;typeof o>"u"&&(!n||!n.getContext)&&(o=n,n=void 0),o||(o={});let i=Ur.render(e,n,o),s=o.type||"image/png",a=o.rendererOpts||{};return i.toDataURL(s,a.quality)}});var Wc=X(Gc=>{var gd=Ei();function Zc(t,e){let n=t.a/255,r=e+'="'+t.hex+'"';return n<1?r+" "+e+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function Si(t,e,n){let r=t+e;return typeof n<"u"&&(r+=" "+n),r}function pd(t,e,n){let r="",o=0,i=!1,s=0;for(let a=0;a<t.length;a++){let c=Math.floor(a%e),l=Math.floor(a/e);!c&&!i&&(i=!0),t[a]?(s++,a>0&&c>0&&t[a-1]||(r+=i?Si("M",c+n,.5+l+n):Si("m",o,0),o=0,i=!1),c+1<e&&t[a+1]||(r+=Si("h",s),s=0)):o++}return r}Gc.render=function(e,n,r){let o=gd.getOptions(n),i=e.modules.size,s=e.modules.data,a=i+o.margin*2,c=o.color.light.a?"<path "+Zc(o.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",l="<path "+Zc(o.color.dark,"stroke")+' d="'+pd(s,i,o.margin)+'"/>',d='viewBox="0 0 '+a+" "+a+'"',u='<svg xmlns="http://www.w3.org/2000/svg" '+(o.width?'width="'+o.width+'" height="'+o.width+'" ':"")+d+' shape-rendering="crispEdges">'+c+l+`</svg>
|
|
8
|
-
`;return typeof r=="function"&&r(null,u),u}});var Jc=X(Cn=>{var yd=Fa(),ki=Kc(),Yc=jc(),bd=Wc();function Bi(t,e,n,r,o){let i=[].slice.call(arguments,1),s=i.length,a=typeof i[s-1]=="function";if(!a&&!yd())throw new Error("Callback required as last argument");if(a){if(s<2)throw new Error("Too few arguments provided");s===2?(o=n,n=e,e=r=void 0):s===3&&(e.getContext&&typeof o>"u"?(o=r,r=void 0):(o=r,r=n,n=e,e=void 0))}else{if(s<1)throw new Error("Too few arguments provided");return s===1?(n=e,e=r=void 0):s===2&&!e.getContext&&(r=n,n=e,e=void 0),new Promise(function(c,l){try{let d=ki.create(n,r);c(t(d,e,r))}catch(d){l(d)}})}try{let c=ki.create(n,r);o(null,t(c,e,r))}catch(c){o(c)}}Cn.create=ki.create;Cn.toCanvas=Bi.bind(null,Yc.render);Cn.toDataURL=Bi.bind(null,Yc.renderToDataURL);Cn.toString=Bi.bind(null,function(t,e,n){return bd.render(t,n)})});var Id={};ul(Id,{handleCallback:()=>tl,handleRedirectCallback:()=>nl,isAndroid:()=>sr,login:()=>Qc,logout:()=>rl,restoreSession:()=>el});var je={relayUrl:"wss://relay.damus.io",signetAppOrigin:"https://mysignet.app",timeout:12e4,theme:"auto",persist:!0,mode:"relay"},Ln=300*1e3,F={pubkey:"signet:login.pubkey",method:"signet:login.method",authEvent:"signet:login.authEvent",bunkerUri:"signet:login.bunkerUri",bunkerClientSk:"signet:login.bunkerClientSk",clientSk:"signet:login.clientSk",expiresAt:"signet:login.expiresAt",displayName:"signet:login.displayName",pendingRedirect:"signet:login.pendingRedirect"};function en(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function we(t,e=""){if(!Number.isSafeInteger(t)||t<0){let n=e&&`"${e}" `;throw new Error(`${n}expected integer >= 0, got ${t}`)}}function Y(t,e,n=""){let r=en(t),o=t?.length,i=e!==void 0;if(!r||i&&o!==e){let s=n&&`"${n}" `,a=i?` of length ${e}`:"",c=r?`length=${o}`:`type=${typeof t}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return t}function st(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash must wrapped by utils.createHasher");we(t.outputLen),we(t.blockLen)}function At(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Li(t,e){Y(t,void 0,"digestInto() output");let n=e.outputLen;if(t.length<n)throw new Error('"digestInto() output" expected to be of length >='+n)}function Ie(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function In(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Se(t,e){return t<<32-e|t>>>e}var Ii=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",hl=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ee(t){if(Y(t),Ii)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=hl[t[n]];return e}var Le={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ti(t){if(t>=Le._0&&t<=Le._9)return t-Le._0;if(t>=Le.A&&t<=Le.F)return t-(Le.A-10);if(t>=Le.a&&t<=Le.f)return t-(Le.a-10)}function ne(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Ii)return Uint8Array.fromHex(t);let e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let o=0,i=0;o<n;o++,i+=2){let s=Ti(t.charCodeAt(i)),a=Ti(t.charCodeAt(i+1));if(s===void 0||a===void 0){let c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}r[o]=s*16+a}return r}function te(...t){let e=0;for(let r=0;r<t.length;r++){let o=t[r];Y(o),e+=o.length}let n=new Uint8Array(e);for(let r=0,o=0;r<t.length;r++){let i=t[r];n.set(i,o),o+=i.length}return n}function Ni(t,e={}){let n=(o,i)=>t(i).update(o).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.create=o=>t(o),Object.assign(n,e),Object.freeze(n)}function ke(t=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(t))}var _i=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function Ui(t,e,n){return t&e^~t&n}function Oi(t,e,n){return t&e^t&n^e&n}var Nn=class{constructor(e,n,r,o){S(this,"blockLen");S(this,"outputLen");S(this,"padOffset");S(this,"isLE");S(this,"buffer");S(this,"view");S(this,"finished",!1);S(this,"length",0);S(this,"pos",0);S(this,"destroyed",!1);this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=In(this.buffer)}update(e){At(this),Y(e);let{view:n,buffer:r,blockLen:o}=this,i=e.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=In(e);for(;o<=i-s;s+=o)this.process(c,s);continue}r.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){At(this),Li(e,this),this.finished=!0;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,Ie(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(r,0),s=0);for(let g=s;g<o;g++)n[g]=0;r.setBigUint64(o-8,BigInt(this.length*8),i),this.process(r,0);let a=In(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let g=0;g<l;g++)a.setUint32(4*g,d[g],i)}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:i,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=i,e.length=o,e.pos=a,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}},Ne=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var gl=Uint32Array.from([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]),Ze=new Uint32Array(64),Or=class extends Nn{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:n,C:r,D:o,E:i,F:s,G:a,H:c}=this;return[e,n,r,o,i,s,a,c]}set(e,n,r,o,i,s,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,n){for(let g=0;g<16;g++,n+=4)Ze[g]=e.getUint32(n,!1);for(let g=16;g<64;g++){let u=Ze[g-15],f=Ze[g-2],y=Se(u,7)^Se(u,18)^u>>>3,m=Se(f,17)^Se(f,19)^f>>>10;Ze[g]=m+Ze[g-7]+y+Ze[g-16]|0}let{A:r,B:o,C:i,D:s,E:a,F:c,G:l,H:d}=this;for(let g=0;g<64;g++){let u=Se(a,6)^Se(a,11)^Se(a,25),f=d+u+Ui(a,c,l)+gl[g]+Ze[g]|0,m=(Se(r,2)^Se(r,13)^Se(r,22))+Oi(r,o,i)|0;d=l,l=c,c=a,a=s+f|0,s=i,i=o,o=r,r=f+m|0}r=r+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(r,o,i,s,a,c,l,d)}roundClean(){Ie(Ze)}destroy(){this.set(0,0,0,0,0,0,0,0),Ie(this.buffer)}},Pr=class extends Or{constructor(){super(32);S(this,"A",Ne[0]|0);S(this,"B",Ne[1]|0);S(this,"C",Ne[2]|0);S(this,"D",Ne[3]|0);S(this,"E",Ne[4]|0);S(this,"F",Ne[5]|0);S(this,"G",Ne[6]|0);S(this,"H",Ne[7]|0)}};var ue=Ni(()=>new Pr,_i(1));var Mr=BigInt(0),Hr=BigInt(1);function tn(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}" `;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function Pi(t){if(typeof t=="bigint"){if(!_n(t))throw new Error("positive bigint expected, got "+t)}else we(t);return t}function nn(t){let e=Pi(t).toString(16);return e.length&1?"0"+e:e}function Hi(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Mr:BigInt("0x"+t)}function Ge(t){return Hi(ee(t))}function qr(t){return Hi(ee(pl(Y(t)).reverse()))}function Un(t,e){we(e),t=Pi(t);let n=ne(t.toString(16).padStart(e*2,"0"));if(n.length!==e)throw new Error("number too large");return n}function Dr(t,e){return Un(t,e).reverse()}function pl(t){return Uint8Array.from(t)}function Mi(t){return Uint8Array.from(t,(e,n)=>{let r=e.charCodeAt(0);if(e.length!==1||r>127)throw new Error(`string contains non-ASCII character "${t[n]}" with code ${r} at position ${n}`);return r})}var _n=t=>typeof t=="bigint"&&Mr<=t;function yl(t,e,n){return _n(t)&&_n(e)&&_n(n)&&e<=t&&t<n}function qi(t,e,n,r){if(!yl(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function $r(t){let e;for(e=0;t>Mr;t>>=Hr,e+=1);return e}var rn=t=>(Hr<<BigInt(t))-Hr;function Di(t,e,n){if(we(t,"hashLen"),we(e,"qByteLen"),typeof n!="function")throw new Error("hmacFn must be a function");let r=v=>new Uint8Array(v),o=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1e3,c=r(t),l=r(t),d=0,g=()=>{c.fill(1),l.fill(0),d=0},u=(...v)=>n(l,te(c,...v)),f=(v=o)=>{l=u(i,v),c=u(),v.length!==0&&(l=u(s,v),c=u())},y=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let v=0,R=[];for(;v<e;){c=u();let O=c.slice();R.push(O),v+=c.length}return te(...R)};return(v,R)=>{g(),f(v);let O;for(;!(O=R(y()));)f();return g(),O}}function on(t,e={},n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(i,s,a){let c=t[i];if(a&&c===void 0)return;let l=typeof c;if(l!==s||c===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${l}`)}let o=(i,s)=>Object.entries(i).forEach(([a,c])=>r(a,c,s));o(e,!1),o(n,!0)}function Vr(t){let e=new WeakMap;return(n,...r)=>{let o=e.get(n);if(o!==void 0)return o;let i=t(n,...r);return e.set(n,i),i}}var he=BigInt(0),fe=BigInt(1),at=BigInt(2),Ki=BigInt(3),zi=BigInt(4),ji=BigInt(5),bl=BigInt(7),Zi=BigInt(8),ml=BigInt(9),Gi=BigInt(16);function Be(t,e){let n=t%e;return n>=he?n:e+n}function ye(t,e,n){let r=t;for(;e-- >he;)r*=r,r%=n;return r}function $i(t,e){if(t===he)throw new Error("invert: expected non-zero number");if(e<=he)throw new Error("invert: expected positive modulus, got "+e);let n=Be(t,e),r=e,o=he,i=fe,s=fe,a=he;for(;n!==he;){let l=r/n,d=r%n,g=o-s*l,u=i-a*l;r=n,n=d,o=s,i=a,s=g,a=u}if(r!==fe)throw new Error("invert: does not exist");return Be(o,e)}function zr(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function Wi(t,e){let n=(t.ORDER+fe)/zi,r=t.pow(e,n);return zr(t,r,e),r}function wl(t,e){let n=(t.ORDER-ji)/Zi,r=t.mul(e,at),o=t.pow(r,n),i=t.mul(e,o),s=t.mul(t.mul(i,at),o),a=t.mul(i,t.sub(s,t.ONE));return zr(t,a,e),a}function xl(t){let e=Rt(t),n=Yi(t),r=n(e,e.neg(e.ONE)),o=n(e,r),i=n(e,e.neg(r)),s=(t+bl)/Gi;return(a,c)=>{let l=a.pow(c,s),d=a.mul(l,r),g=a.mul(l,o),u=a.mul(l,i),f=a.eql(a.sqr(d),c),y=a.eql(a.sqr(g),c);l=a.cmov(l,d,f),d=a.cmov(u,g,y);let m=a.eql(a.sqr(d),c),v=a.cmov(l,d,m);return zr(a,v,c),v}}function Yi(t){if(t<Ki)throw new Error("sqrt is not defined for small field");let e=t-fe,n=0;for(;e%at===he;)e/=at,n++;let r=at,o=Rt(t);for(;Vi(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Wi;let i=o.pow(r,e),s=(e+fe)/at;return function(c,l){if(c.is0(l))return l;if(Vi(c,l)!==1)throw new Error("Cannot find square root");let d=n,g=c.mul(c.ONE,i),u=c.pow(l,e),f=c.pow(l,s);for(;!c.eql(u,c.ONE);){if(c.is0(u))return c.ZERO;let y=1,m=c.sqr(u);for(;!c.eql(m,c.ONE);)if(y++,m=c.sqr(m),y===d)throw new Error("Cannot find square root");let v=fe<<BigInt(d-y-1),R=c.pow(g,v);d=y,g=c.sqr(R),u=c.mul(u,g),f=c.mul(f,R)}return f}}function El(t){return t%zi===Ki?Wi:t%Zi===ji?wl:t%Gi===ml?xl(t):Yi(t)}var vl=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function jr(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},n=vl.reduce((r,o)=>(r[o]="function",r),e);return on(t,n),t}function Sl(t,e,n){if(n<he)throw new Error("invalid exponent, negatives unsupported");if(n===he)return t.ONE;if(n===fe)return e;let r=t.ONE,o=e;for(;n>he;)n&fe&&(r=t.mul(r,o)),o=t.sqr(o),n>>=fe;return r}function On(t,e,n=!1){let r=new Array(e.length).fill(n?t.ZERO:void 0),o=e.reduce((s,a,c)=>t.is0(a)?s:(r[c]=s,t.mul(s,a)),t.ONE),i=t.inv(o);return e.reduceRight((s,a,c)=>t.is0(a)?s:(r[c]=t.mul(s,r[c]),t.mul(s,a)),i),r}function Vi(t,e){let n=(t.ORDER-fe)/at,r=t.pow(e,n),o=t.eql(r,t.ONE),i=t.eql(r,t.ZERO),s=t.eql(r,t.neg(t.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function kl(t,e){e!==void 0&&we(e);let n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}var Kr=class{constructor(e,n={}){S(this,"ORDER");S(this,"BITS");S(this,"BYTES");S(this,"isLE");S(this,"ZERO",he);S(this,"ONE",fe);S(this,"_lengths");S(this,"_sqrt");S(this,"_mod");if(e<=he)throw new Error("invalid field: expected ORDER > 0, got "+e);let r;this.isLE=!1,n!=null&&typeof n=="object"&&(typeof n.BITS=="number"&&(r=n.BITS),typeof n.sqrt=="function"&&(this.sqrt=n.sqrt),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=n.allowedLengths?.slice()),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=kl(e,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return Be(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return he<=e&&e<this.ORDER}is0(e){return e===he}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&fe)===fe}neg(e){return Be(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return Be(e*e,this.ORDER)}add(e,n){return Be(e+n,this.ORDER)}sub(e,n){return Be(e-n,this.ORDER)}mul(e,n){return Be(e*n,this.ORDER)}pow(e,n){return Sl(this,e,n)}div(e,n){return Be(e*$i(n,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return $i(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=El(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Dr(e,this.BYTES):Un(e,this.BYTES)}fromBytes(e,n=!1){Y(e);let{_lengths:r,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(r){if(!r.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,i?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=i?qr(e):Ge(e);if(a&&(c=Be(c,s)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return On(this,e)}cmov(e,n,r){return r?n:e}};function Rt(t,e={}){return new Kr(t,e)}function Ji(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function Zr(t){let e=Ji(t);return e+Math.ceil(e/2)}function Pn(t,e,n=!1){Y(t);let r=t.length,o=Ji(e),i=Zr(e);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let s=n?qr(t):Ge(t),a=Be(s,e-fe)+fe;return n?Dr(a,o):Un(a,o)}var Ct=BigInt(0),ct=BigInt(1);function sn(t,e){let n=e.negate();return t?n:e}function Jr(t,e){let n=On(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function es(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Gr(t,e){es(t,e);let n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,i=rn(t),s=BigInt(t);return{windows:n,windowSize:r,mask:i,maxNumber:o,shiftBy:s}}function Xi(t,e,n){let{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n,a=Number(t&o),c=t>>s;a>r&&(a-=i,c+=ct);let l=e*r,d=l+Math.abs(a)-1,g=a===0,u=a<0,f=e%2!==0;return{nextN:c,offset:d,isZero:g,isNeg:u,isNegF:f,offsetF:l}}var Wr=new WeakMap,ts=new WeakMap;function Yr(t){return ts.get(t)||1}function Fi(t){if(t!==Ct)throw new Error("invalid wNAF")}var Hn=class{constructor(e,n){S(this,"BASE");S(this,"ZERO");S(this,"Fn");S(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>Ct;)n&ct&&(r=r.add(o)),o=o.double(),n>>=ct;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=Gr(n,this.bits),i=[],s=e,a=s;for(let c=0;c<r;c++){a=s,i.push(a);for(let l=1;l<o;l++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,s=Gr(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:d,isNeg:g,isNegF:u,offsetF:f}=Xi(r,a,s);r=c,d?i=i.add(sn(u,n[f])):o=o.add(sn(g,n[l]))}return Fi(r),{p:o,f:i}}wNAFUnsafe(e,n,r,o=this.ZERO){let i=Gr(e,this.bits);for(let s=0;s<i.windows&&r!==Ct;s++){let{nextN:a,offset:c,isZero:l,isNeg:d}=Xi(r,s,i);if(r=a,!l){let g=n[c];o=o.add(d?g.negate():g)}}return Fi(r),o}getPrecomputes(e,n,r){let o=Wr.get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),Wr.set(n,o))),o}cached(e,n,r){let o=Yr(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){let i=Yr(e);return i===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),n,o)}createCache(e,n){es(n,this.bits),ts.set(e,n),Wr.delete(e)}hasCache(e){return Yr(e)!==1}};function ns(t,e,n,r){let o=e,i=t.ZERO,s=t.ZERO;for(;n>Ct||r>Ct;)n&ct&&(i=i.add(o)),r&ct&&(s=s.add(o)),o=o.double(),n>>=ct,r>>=ct;return{p1:i,p2:s}}function Qi(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return jr(e),e}else return Rt(t,{isLE:n})}function rs(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>Ct))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Qi(e.p,n.Fp,r),i=Qi(e.n,n.Fn,r),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:i}}function Mn(t,e){return function(r){let o=t(r);return{secretKey:o,publicKey:e(o)}}}var qn=class{constructor(e,n){S(this,"oHash");S(this,"iHash");S(this,"blockLen");S(this,"outputLen");S(this,"finished",!1);S(this,"destroyed",!1);if(st(e),Y(n,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,o=new Uint8Array(r);o.set(n.length>r?e.create().update(n).digest():n);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),Ie(o)}update(e){return At(this),this.iHash.update(e),this}digestInto(e){At(this),Y(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:n,iHash:r,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ce=(t,e,n)=>new qn(t,e).update(n).digest();Ce.create=(t,e)=>new qn(t,e);var os=(t,e)=>(t+(t>=0?e:-e)/is)/e;function Bl(t,e,n){let[[r,o],[i,s]]=e,a=os(s*t,n),c=os(-o*t,n),l=t-a*r-c*i,d=-a*o-c*s,g=l<_e,u=d<_e;g&&(l=-l),u&&(d=-d);let f=rn(Math.ceil($r(n)/2))+Tt;if(l<_e||l>=f||d<_e||d>=f)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:g,k1:l,k2neg:u,k2:d}}function Fr(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Xr(t,e){let n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return tn(n.lowS,"lowS"),tn(n.prehash,"prehash"),n.format!==void 0&&Fr(n.format),n}var Qr=class extends Error{constructor(e=""){super(e)}},We={Err:Qr,_tlv:{encode:(t,e)=>{let{Err:n}=We;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");let r=e.length/2,o=nn(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");let i=r>127?nn(o.length/2|128):"";return nn(t)+i+o+e},decode(t,e){let{Err:n}=We,r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");let o=e[r++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");let l=e.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(let d of l)s=s<<8|d;if(r+=c,s<128)throw new n("tlv.decode(long): not minimal encoding")}let a=e.subarray(r,r+s);if(a.length!==s)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+s)}}},_int:{encode(t){let{Err:e}=We;if(t<_e)throw new e("integer: negative integers are not allowed");let n=nn(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){let{Err:e}=We;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Ge(t)}},toSig(t){let{Err:e,_int:n,_tlv:r}=We,o=Y(t,void 0,"signature"),{v:i,l:s}=r.decode(48,o);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=r.decode(2,i),{v:l,l:d}=r.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(t){let{_tlv:e,_int:n}=We,r=e.encode(2,n.encode(t.r)),o=e.encode(2,n.encode(t.s)),i=r+o;return e.encode(48,i)}},_e=BigInt(0),Tt=BigInt(1),is=BigInt(2),Dn=BigInt(3),Al=BigInt(4);function ss(t,e={}){let n=rs("weierstrass",t,e),{Fp:r,Fn:o}=n,i=n.CURVE,{h:s,n:a}=i;on(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!r.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=cs(r,o);function d(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function g(x,p,h){let{x:b,y:E}=p.toAffine(),B=r.toBytes(b);if(tn(h,"isCompressed"),h){d();let w=!r.isOdd(E);return te(as(w),B)}else return te(Uint8Array.of(4),B,r.toBytes(E))}function u(x){Y(x,void 0,"Point");let{publicKey:p,publicKeyUncompressed:h}=l,b=x.length,E=x[0],B=x.subarray(1);if(b===p&&(E===2||E===3)){let w=r.fromBytes(B);if(!r.isValid(w))throw new Error("bad point: is not on curve, wrong x");let A=m(w),k;try{k=r.sqrt(A)}catch(D){let M=D instanceof Error?": "+D.message:"";throw new Error("bad point: is not on curve, sqrt error"+M)}d();let C=r.isOdd(k);return(E&1)===1!==C&&(k=r.neg(k)),{x:w,y:k}}else if(b===h&&E===4){let w=r.BYTES,A=r.fromBytes(B.subarray(0,w)),k=r.fromBytes(B.subarray(w,w*2));if(!v(A,k))throw new Error("bad point: is not on curve");return{x:A,y:k}}else throw new Error(`bad point: got length ${b}, expected compressed=${p} or uncompressed=${h}`)}let f=e.toBytes||g,y=e.fromBytes||u;function m(x){let p=r.sqr(x),h=r.mul(p,x);return r.add(r.add(h,r.mul(x,i.a)),i.b)}function v(x,p){let h=r.sqr(p),b=m(x);return r.eql(h,b)}if(!v(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let R=r.mul(r.pow(i.a,Dn),Al),O=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(R,O)))throw new Error("bad curve params: a or b");function I(x,p,h=!1){if(!r.isValid(p)||h&&r.is0(p))throw new Error(`bad point coordinate ${x}`);return p}function N(x){if(!(x instanceof L))throw new Error("Weierstrass Point expected")}function _(x){if(!c||!c.basises)throw new Error("no endo");return Bl(x,c.basises,o.ORDER)}let q=Vr((x,p)=>{let{X:h,Y:b,Z:E}=x;if(r.eql(E,r.ONE))return{x:h,y:b};let B=x.is0();p==null&&(p=B?r.ONE:r.inv(E));let w=r.mul(h,p),A=r.mul(b,p),k=r.mul(E,p);if(B)return{x:r.ZERO,y:r.ZERO};if(!r.eql(k,r.ONE))throw new Error("invZ was invalid");return{x:w,y:A}}),j=Vr(x=>{if(x.is0()){if(e.allowInfinityPoint&&!r.is0(x.Y))return;throw new Error("bad point: ZERO")}let{x:p,y:h}=x.toAffine();if(!r.isValid(p)||!r.isValid(h))throw new Error("bad point: x or y not field elements");if(!v(p,h))throw new Error("bad point: equation left != right");if(!x.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Z(x,p,h,b,E){return h=new L(r.mul(h.X,x),h.Y,h.Z),p=sn(b,p),h=sn(E,h),p.add(h)}let T=class T{constructor(p,h,b){S(this,"X");S(this,"Y");S(this,"Z");this.X=I("x",p),this.Y=I("y",h,!0),this.Z=I("z",b),Object.freeze(this)}static CURVE(){return i}static fromAffine(p){let{x:h,y:b}=p||{};if(!p||!r.isValid(h)||!r.isValid(b))throw new Error("invalid affine point");if(p instanceof T)throw new Error("projective point not allowed");return r.is0(h)&&r.is0(b)?T.ZERO:new T(h,b,r.ONE)}static fromBytes(p){let h=T.fromAffine(y(Y(p,void 0,"point")));return h.assertValidity(),h}static fromHex(p){return T.fromBytes(ne(p))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,h=!0){return $.createCache(this,p),h||this.multiply(Dn),this}assertValidity(){j(this)}hasEvenY(){let{y:p}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(p)}equals(p){N(p);let{X:h,Y:b,Z:E}=this,{X:B,Y:w,Z:A}=p,k=r.eql(r.mul(h,A),r.mul(B,E)),C=r.eql(r.mul(b,A),r.mul(w,E));return k&&C}negate(){return new T(this.X,r.neg(this.Y),this.Z)}double(){let{a:p,b:h}=i,b=r.mul(h,Dn),{X:E,Y:B,Z:w}=this,A=r.ZERO,k=r.ZERO,C=r.ZERO,P=r.mul(E,E),D=r.mul(B,B),M=r.mul(w,w),U=r.mul(E,B);return U=r.add(U,U),C=r.mul(E,w),C=r.add(C,C),A=r.mul(p,C),k=r.mul(b,M),k=r.add(A,k),A=r.sub(D,k),k=r.add(D,k),k=r.mul(A,k),A=r.mul(U,A),C=r.mul(b,C),M=r.mul(p,M),U=r.sub(P,M),U=r.mul(p,U),U=r.add(U,C),C=r.add(P,P),P=r.add(C,P),P=r.add(P,M),P=r.mul(P,U),k=r.add(k,P),M=r.mul(B,w),M=r.add(M,M),P=r.mul(M,U),A=r.sub(A,P),C=r.mul(M,D),C=r.add(C,C),C=r.add(C,C),new T(A,k,C)}add(p){N(p);let{X:h,Y:b,Z:E}=this,{X:B,Y:w,Z:A}=p,k=r.ZERO,C=r.ZERO,P=r.ZERO,D=i.a,M=r.mul(i.b,Dn),U=r.mul(h,B),V=r.mul(b,w),W=r.mul(E,A),K=r.add(h,b),G=r.add(B,w);K=r.mul(K,G),G=r.add(U,V),K=r.sub(K,G),G=r.add(h,E);let oe=r.add(B,A);return G=r.mul(G,oe),oe=r.add(U,W),G=r.sub(G,oe),oe=r.add(b,E),k=r.add(w,A),oe=r.mul(oe,k),k=r.add(V,W),oe=r.sub(oe,k),P=r.mul(D,G),k=r.mul(M,W),P=r.add(k,P),k=r.sub(V,P),P=r.add(V,P),C=r.mul(k,P),V=r.add(U,U),V=r.add(V,U),W=r.mul(D,W),G=r.mul(M,G),V=r.add(V,W),W=r.sub(U,W),W=r.mul(D,W),G=r.add(G,W),U=r.mul(V,G),C=r.add(C,U),U=r.mul(oe,G),k=r.mul(K,k),k=r.sub(k,U),U=r.mul(K,V),P=r.mul(oe,P),P=r.add(P,U),new T(k,C,P)}subtract(p){return this.add(p.negate())}is0(){return this.equals(T.ZERO)}multiply(p){let{endo:h}=e;if(!o.isValidNot0(p))throw new Error("invalid scalar: out of range");let b,E,B=w=>$.cached(this,w,A=>Jr(T,A));if(h){let{k1neg:w,k1:A,k2neg:k,k2:C}=_(p),{p:P,f:D}=B(A),{p:M,f:U}=B(C);E=D.add(U),b=Z(h.beta,P,M,w,k)}else{let{p:w,f:A}=B(p);b=w,E=A}return Jr(T,[b,E])[0]}multiplyUnsafe(p){let{endo:h}=e,b=this;if(!o.isValid(p))throw new Error("invalid scalar: out of range");if(p===_e||b.is0())return T.ZERO;if(p===Tt)return b;if($.hasCache(this))return this.multiply(p);if(h){let{k1neg:E,k1:B,k2neg:w,k2:A}=_(p),{p1:k,p2:C}=ns(T,b,B,A);return Z(h.beta,k,C,E,w)}else return $.unsafe(b,p)}toAffine(p){return q(this,p)}isTorsionFree(){let{isTorsionFree:p}=e;return s===Tt?!0:p?p(T,this):$.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:p}=e;return s===Tt?this:p?p(T,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(p=!0){return tn(p,"isCompressed"),this.assertValidity(),f(T,this,p)}toHex(p=!0){return ee(this.toBytes(p))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};S(T,"BASE",new T(i.Gx,i.Gy,r.ONE)),S(T,"ZERO",new T(r.ZERO,r.ONE,r.ZERO)),S(T,"Fp",r),S(T,"Fn",o);let L=T,z=o.BITS,$=new Hn(L,e.endo?Math.ceil(z/2):z);return L.BASE.precompute(8),L}function as(t){return Uint8Array.of(t?2:3)}function cs(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Rl(t,e={}){let{Fn:n}=t,r=e.randomBytes||ke,o=Object.assign(cs(t.Fp,n),{seed:Zr(n.ORDER)});function i(f){try{let y=n.fromBytes(f);return n.isValidNot0(y)}catch{return!1}}function s(f,y){let{publicKey:m,publicKeyUncompressed:v}=o;try{let R=f.length;return y===!0&&R!==m||y===!1&&R!==v?!1:!!t.fromBytes(f)}catch{return!1}}function a(f=r(o.seed)){return Pn(Y(f,o.seed,"seed"),n.ORDER)}function c(f,y=!0){return t.BASE.multiply(n.fromBytes(f)).toBytes(y)}function l(f){let{secretKey:y,publicKey:m,publicKeyUncompressed:v}=o;if(!en(f)||"_lengths"in n&&n._lengths||y===m)return;let R=Y(f,void 0,"key").length;return R===m||R===v}function d(f,y,m=!0){if(l(f)===!0)throw new Error("first arg must be private key");if(l(y)===!1)throw new Error("second arg must be public key");let v=n.fromBytes(f);return t.fromBytes(y).multiply(v).toBytes(m)}let g={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},u=Mn(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:u,Point:t,utils:g,lengths:o})}function ls(t,e,n={}){st(e),on(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),n=Object.assign({},n);let r=n.randomBytes||ke,o=n.hmac||((p,h)=>Ce(e,p,h)),{Fp:i,Fn:s}=t,{ORDER:a,BITS:c}=s,{keygen:l,getPublicKey:d,getSharedSecret:g,utils:u,lengths:f}=Rl(t,n),y={prehash:!0,lowS:typeof n.lowS=="boolean"?n.lowS:!0,format:"compact",extraEntropy:!1},m=a*is<i.ORDER;function v(p){let h=a>>Tt;return p>h}function R(p,h){if(!s.isValidNot0(h))throw new Error(`invalid signature ${p}: out of range 1..Point.Fn.ORDER`);return h}function O(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function I(p,h){Fr(h);let b=f.signature,E=h==="compact"?b:h==="recovered"?b+1:void 0;return Y(p,E)}class N{constructor(h,b,E){S(this,"r");S(this,"s");S(this,"recovery");if(this.r=R("r",h),this.s=R("s",b),E!=null){if(O(),![0,1,2,3].includes(E))throw new Error("invalid recovery id");this.recovery=E}Object.freeze(this)}static fromBytes(h,b=y.format){I(h,b);let E;if(b==="der"){let{r:k,s:C}=We.toSig(Y(h));return new N(k,C)}b==="recovered"&&(E=h[0],b="compact",h=h.subarray(1));let B=f.signature/2,w=h.subarray(0,B),A=h.subarray(B,B*2);return new N(s.fromBytes(w),s.fromBytes(A),E)}static fromHex(h,b){return this.fromBytes(ne(h),b)}assertRecovery(){let{recovery:h}=this;if(h==null)throw new Error("invalid recovery id: must be present");return h}addRecoveryBit(h){return new N(this.r,this.s,h)}recoverPublicKey(h){let{r:b,s:E}=this,B=this.assertRecovery(),w=B===2||B===3?b+a:b;if(!i.isValid(w))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let A=i.toBytes(w),k=t.fromBytes(te(as((B&1)===0),A)),C=s.inv(w),P=q(Y(h,void 0,"msgHash")),D=s.create(-P*C),M=s.create(E*C),U=t.BASE.multiplyUnsafe(D).add(k.multiplyUnsafe(M));if(U.is0())throw new Error("invalid recovery: point at infinify");return U.assertValidity(),U}hasHighS(){return v(this.s)}toBytes(h=y.format){if(Fr(h),h==="der")return ne(We.hexFromSig(this));let{r:b,s:E}=this,B=s.toBytes(b),w=s.toBytes(E);return h==="recovered"?(O(),te(Uint8Array.of(this.assertRecovery()),B,w)):te(B,w)}toHex(h){return ee(this.toBytes(h))}}let _=n.bits2int||function(h){if(h.length>8192)throw new Error("input is too large");let b=Ge(h),E=h.length*8-c;return E>0?b>>BigInt(E):b},q=n.bits2int_modN||function(h){return s.create(_(h))},j=rn(c);function Z(p){return qi("num < 2^"+c,p,_e,j),s.toBytes(p)}function L(p,h){return Y(p,void 0,"message"),h?Y(e(p),void 0,"prehashed message"):p}function z(p,h,b){let{lowS:E,prehash:B,extraEntropy:w}=Xr(b,y);p=L(p,B);let A=q(p),k=s.fromBytes(h);if(!s.isValidNot0(k))throw new Error("invalid private key");let C=[Z(k),Z(A)];if(w!=null&&w!==!1){let U=w===!0?r(f.secretKey):w;C.push(Y(U,void 0,"extraEntropy"))}let P=te(...C),D=A;function M(U){let V=_(U);if(!s.isValidNot0(V))return;let W=s.inv(V),K=t.BASE.multiply(V).toAffine(),G=s.create(K.x);if(G===_e)return;let oe=s.create(W*s.create(D+G*k));if(oe===_e)return;let Xt=(K.x===G?0:2)|Number(K.y&Tt),Ft=oe;return E&&v(oe)&&(Ft=s.neg(oe),Xt^=1),new N(G,Ft,m?void 0:Xt)}return{seed:P,k2sig:M}}function $(p,h,b={}){let{seed:E,k2sig:B}=z(p,h,b);return Di(e.outputLen,s.BYTES,o)(E,B).toBytes(b.format)}function T(p,h,b,E={}){let{lowS:B,prehash:w,format:A}=Xr(E,y);if(b=Y(b,void 0,"publicKey"),h=L(h,w),!en(p)){let k=p instanceof N?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+k)}I(p,A);try{let k=N.fromBytes(p,A),C=t.fromBytes(b);if(B&&k.hasHighS())return!1;let{r:P,s:D}=k,M=q(h),U=s.inv(D),V=s.create(M*U),W=s.create(P*U),K=t.BASE.multiplyUnsafe(V).add(C.multiplyUnsafe(W));return K.is0()?!1:s.create(K.x)===P}catch{return!1}}function x(p,h,b={}){let{prehash:E}=Xr(b,y);return h=L(h,E),N.fromBytes(p,"recovered").recoverPublicKey(h).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:g,utils:u,lengths:f,Point:t,sign:$,verify:T,recoverPublicKey:x,Signature:N,hash:e})}var Kn={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Cl={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Tl=BigInt(0),eo=BigInt(2);function Ll(t){let e=Kn.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,d=l*l*t%e,g=ye(d,n,e)*d%e,u=ye(g,n,e)*d%e,f=ye(u,eo,e)*l%e,y=ye(f,o,e)*f%e,m=ye(y,i,e)*y%e,v=ye(m,a,e)*m%e,R=ye(v,c,e)*v%e,O=ye(R,a,e)*m%e,I=ye(O,n,e)*d%e,N=ye(I,s,e)*y%e,_=ye(N,r,e)*l%e,q=ye(_,eo,e);if(!$n.eql($n.sqr(q),t))throw new Error("Cannot find square root");return q}var $n=Rt(Kn.p,{sqrt:Ll}),lt=ss(Kn,{Fp:$n,endo:Cl}),zn=ls(lt,ue),us={};function Vn(t,...e){let n=us[t];if(n===void 0){let r=ue(Mi(t));n=te(r,r),us[t]=n}return ue(te(n,...e))}var no=t=>t.toBytes(!0).slice(1),ro=t=>t%eo===Tl;function to(t){let{Fn:e,BASE:n}=lt,r=e.fromBytes(t),o=n.multiply(r);return{scalar:ro(o.y)?r:e.neg(r),bytes:no(o)}}function ds(t){let e=$n;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x \u2265 p");let n=e.create(t*t),r=e.create(n*t+BigInt(7)),o=e.sqrt(r);ro(o)||(o=e.neg(o));let i=lt.fromAffine({x:t,y:o});return i.assertValidity(),i}var an=Ge;function hs(...t){return lt.Fn.create(an(Vn("BIP0340/challenge",...t)))}function fs(t){return to(t).bytes}function Il(t,e,n=ke(32)){let{Fn:r}=lt,o=Y(t,void 0,"message"),{bytes:i,scalar:s}=to(e),a=Y(n,32,"auxRand"),c=r.toBytes(s^an(Vn("BIP0340/aux",a))),l=Vn("BIP0340/nonce",c,i,o),{bytes:d,scalar:g}=to(l),u=hs(d,i,o),f=new Uint8Array(64);if(f.set(d,0),f.set(r.toBytes(r.create(g+u*s)),32),!gs(f,o,i))throw new Error("sign: Invalid signature produced");return f}function gs(t,e,n){let{Fp:r,Fn:o,BASE:i}=lt,s=Y(t,64,"signature"),a=Y(e,void 0,"message"),c=Y(n,32,"publicKey");try{let l=ds(an(c)),d=an(s.subarray(0,32));if(!r.isValidNot0(d))return!1;let g=an(s.subarray(32,64));if(!o.isValidNot0(g))return!1;let u=hs(o.toBytes(d),no(l),a),f=i.multiplyUnsafe(g).add(l.multiplyUnsafe(o.neg(u))),{x:y,y:m}=f.toAffine();return!(f.is0()||!ro(m)||y!==d)}catch{return!1}}var xe=(()=>{let n=(r=ke(48))=>Pn(r,Kn.n);return{keygen:Mn(n,fs),getPublicKey:fs,sign:Il,verify:gs,Point:lt,utils:{randomSecretKey:n,taggedHash:Vn,lift_x:ds,pointToBytes:no},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();function Nl(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function jn(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function Zn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function se(t,e,n=""){let r=Nl(t),o=t?.length,i=e!==void 0;if(!r||i&&o!==e){let s=n&&`"${n}" `,a=i?` of length ${e}`:"",c=r?`length=${o}`:`type=${typeof t}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return t}function oo(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function ps(t,e){se(t,void 0,"output");let n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function Ue(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Oe(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function _l(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var Ul=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ys(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function Lt(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}var io=(t,e)=>{function n(r,...o){if(se(r,void 0,"key"),!Ul)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){let d=o[0];se(d,t.varSizeNonce?void 0:t.nonceLength,"nonce")}let i=t.tagLength;i&&o[1]!==void 0&&se(o[1],void 0,"AAD");let s=e(r,...o),a=(d,g)=>{if(g!==void 0){if(d!==2)throw new Error("cipher output not supported");se(g,void 0,"output")}},c=!1;return{encrypt(d,g){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,se(d),a(s.encrypt.length,g),s.encrypt(d,g)},decrypt(d,g){if(se(d),i&&d.length<i)throw new Error('"ciphertext" expected length bigger than tagLength='+i);return a(s.decrypt.length,g),s.decrypt(d,g)}}}return Object.assign(n,t),n};function so(t,e,n=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error('"output" expected Uint8Array of length '+t+", got: "+e.length);if(n&&!Ol(e))throw new Error("invalid output, must be aligned");return e}function bs(t,e,n){jn(n);let r=new Uint8Array(16),o=_l(r);return o.setBigUint64(0,BigInt(e),n),o.setBigUint64(8,BigInt(t),n),r}function Ol(t){return t.byteOffset%4===0}function It(t){return Uint8Array.from(t)}var ws=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),Pl=ws("expand 16-byte k"),Hl=ws("expand 32-byte k"),Ml=Ue(Pl),ql=Ue(Hl);function H(t,e){return t<<e|t>>>32-e}function ao(t){return t.byteOffset%4===0}var Gn=64,Dl=16,xs=2**32-1,ms=Uint32Array.of();function $l(t,e,n,r,o,i,s,a){let c=o.length,l=new Uint8Array(Gn),d=Ue(l),g=ao(o)&&ao(i),u=g?Ue(o):ms,f=g?Ue(i):ms;for(let y=0;y<c;s++){if(t(e,n,r,d,s,a),s>=xs)throw new Error("arx: counter overflow");let m=Math.min(Gn,c-y);if(g&&m===Gn){let v=y/4;if(y%4!==0)throw new Error("arx: invalid block position");for(let R=0,O;R<Dl;R++)O=v+R,f[O]=u[O]^d[R];y+=Gn;continue}for(let v=0,R;v<m;v++)R=y+v,i[R]=o[R]^l[v];y+=m}}function co(t,e){let{allowShortKeys:n,extendNonceFn:r,counterLength:o,counterRight:i,rounds:s}=ys({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Zn(o),Zn(s),jn(i),jn(n),(a,c,l,d,g=0)=>{se(a,void 0,"key"),se(c,void 0,"nonce"),se(l,void 0,"data");let u=l.length;if(d===void 0&&(d=new Uint8Array(u)),se(d,void 0,"output"),Zn(g),g<0||g>=xs)throw new Error("arx: counter overflow");if(d.length<u)throw new Error(`arx: output (${d.length}) is shorter than data (${u})`);let f=[],y=a.length,m,v;if(y===32)f.push(m=It(a)),v=ql;else if(y===16&&n)m=new Uint8Array(32),m.set(a),m.set(a,16),v=Ml,f.push(m);else throw se(a,32,"arx key"),new Error("invalid key size");ao(c)||f.push(c=It(c));let R=Ue(m);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(v,R,Ue(c.subarray(0,16)),R),c=c.subarray(16)}let O=16-o;if(O!==c.length)throw new Error(`arx: nonce must be ${O} or 16 bytes`);if(O!==12){let N=new Uint8Array(12);N.set(c,i?0:12-c.length),c=N,f.push(c)}let I=Ue(c);return $l(t,v,R,I,l,d,g,s),Oe(...f),d}}function ce(t,e){return t[e++]&255|(t[e++]&255)<<8}var lo=class{constructor(e){S(this,"blockLen",16);S(this,"outputLen",16);S(this,"buffer",new Uint8Array(16));S(this,"r",new Uint16Array(10));S(this,"h",new Uint16Array(10));S(this,"pad",new Uint16Array(8));S(this,"pos",0);S(this,"finished",!1);e=It(se(e,32,"key"));let n=ce(e,0),r=ce(e,2),o=ce(e,4),i=ce(e,6),s=ce(e,8),a=ce(e,10),c=ce(e,12),l=ce(e,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|o<<6)&7939,this.r[3]=(o>>>7|i<<9)&8191,this.r[4]=(i>>>4|s<<12)&255,this.r[5]=s>>>1&8190,this.r[6]=(s>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let d=0;d<8;d++)this.pad[d]=ce(e,16+2*d)}process(e,n,r=!1){let o=r?0:2048,{h:i,r:s}=this,a=s[0],c=s[1],l=s[2],d=s[3],g=s[4],u=s[5],f=s[6],y=s[7],m=s[8],v=s[9],R=ce(e,n+0),O=ce(e,n+2),I=ce(e,n+4),N=ce(e,n+6),_=ce(e,n+8),q=ce(e,n+10),j=ce(e,n+12),Z=ce(e,n+14),L=i[0]+(R&8191),z=i[1]+((R>>>13|O<<3)&8191),$=i[2]+((O>>>10|I<<6)&8191),T=i[3]+((I>>>7|N<<9)&8191),x=i[4]+((N>>>4|_<<12)&8191),p=i[5]+(_>>>1&8191),h=i[6]+((_>>>14|q<<2)&8191),b=i[7]+((q>>>11|j<<5)&8191),E=i[8]+((j>>>8|Z<<8)&8191),B=i[9]+(Z>>>5|o),w=0,A=w+L*a+z*(5*v)+$*(5*m)+T*(5*y)+x*(5*f);w=A>>>13,A&=8191,A+=p*(5*u)+h*(5*g)+b*(5*d)+E*(5*l)+B*(5*c),w+=A>>>13,A&=8191;let k=w+L*c+z*a+$*(5*v)+T*(5*m)+x*(5*y);w=k>>>13,k&=8191,k+=p*(5*f)+h*(5*u)+b*(5*g)+E*(5*d)+B*(5*l),w+=k>>>13,k&=8191;let C=w+L*l+z*c+$*a+T*(5*v)+x*(5*m);w=C>>>13,C&=8191,C+=p*(5*y)+h*(5*f)+b*(5*u)+E*(5*g)+B*(5*d),w+=C>>>13,C&=8191;let P=w+L*d+z*l+$*c+T*a+x*(5*v);w=P>>>13,P&=8191,P+=p*(5*m)+h*(5*y)+b*(5*f)+E*(5*u)+B*(5*g),w+=P>>>13,P&=8191;let D=w+L*g+z*d+$*l+T*c+x*a;w=D>>>13,D&=8191,D+=p*(5*v)+h*(5*m)+b*(5*y)+E*(5*f)+B*(5*u),w+=D>>>13,D&=8191;let M=w+L*u+z*g+$*d+T*l+x*c;w=M>>>13,M&=8191,M+=p*a+h*(5*v)+b*(5*m)+E*(5*y)+B*(5*f),w+=M>>>13,M&=8191;let U=w+L*f+z*u+$*g+T*d+x*l;w=U>>>13,U&=8191,U+=p*c+h*a+b*(5*v)+E*(5*m)+B*(5*y),w+=U>>>13,U&=8191;let V=w+L*y+z*f+$*u+T*g+x*d;w=V>>>13,V&=8191,V+=p*l+h*c+b*a+E*(5*v)+B*(5*m),w+=V>>>13,V&=8191;let W=w+L*m+z*y+$*f+T*u+x*g;w=W>>>13,W&=8191,W+=p*d+h*l+b*c+E*a+B*(5*v),w+=W>>>13,W&=8191;let K=w+L*v+z*m+$*y+T*f+x*u;w=K>>>13,K&=8191,K+=p*g+h*d+b*l+E*c+B*a,w+=K>>>13,K&=8191,w=(w<<2)+w|0,w=w+A|0,A=w&8191,w=w>>>13,k+=w,i[0]=A,i[1]=k,i[2]=C,i[3]=P,i[4]=D,i[5]=M,i[6]=U,i[7]=V,i[8]=W,i[9]=K}finalize(){let{h:e,pad:n}=this,r=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,r[0]=e[0]+5,o=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+o,o=r[a]>>>13,r[a]&=8191;r[9]-=8192;let i=(o^1)-1;for(let a=0;a<10;a++)r[a]&=i;i=~i;for(let a=0;a<10;a++)e[a]=e[a]&i|r[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let s=e[0]+n[0];e[0]=s&65535;for(let a=1;a<8;a++)s=(e[a]+n[a]|0)+(s>>>16)|0,e[a]=s&65535;Oe(r)}update(e){oo(this),se(e),e=It(e);let{buffer:n,blockLen:r}=this,o=e.length;for(let i=0;i<o;){let s=Math.min(r-this.pos,o-i);if(s===r){for(;r<=o-i;i+=r)this.process(e,i);continue}n.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){Oe(this.h,this.r,this.buffer,this.pad)}digestInto(e){oo(this),ps(e,this),this.finished=!0;let{buffer:n,h:r}=this,{pos:o}=this;if(o){for(n[o++]=1;o<16;o++)n[o]=0;this.process(n,0,!0)}this.finalize();let i=0;for(let s=0;s<8;s++)e[i++]=r[s]>>>0,e[i++]=r[s]>>>8;return e}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let r=e.slice(0,n);return this.destroy(),r}};function Vl(t){let e=(r,o)=>t(o).update(r).digest(),n=t(new Uint8Array(32));return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}var Es=Vl(t=>new lo(t));function ks(t,e,n,r,o,i=20){let s=t[0],a=t[1],c=t[2],l=t[3],d=e[0],g=e[1],u=e[2],f=e[3],y=e[4],m=e[5],v=e[6],R=e[7],O=o,I=n[0],N=n[1],_=n[2],q=s,j=a,Z=c,L=l,z=d,$=g,T=u,x=f,p=y,h=m,b=v,E=R,B=O,w=I,A=N,k=_;for(let P=0;P<i;P+=2)q=q+z|0,B=H(B^q,16),p=p+B|0,z=H(z^p,12),q=q+z|0,B=H(B^q,8),p=p+B|0,z=H(z^p,7),j=j+$|0,w=H(w^j,16),h=h+w|0,$=H($^h,12),j=j+$|0,w=H(w^j,8),h=h+w|0,$=H($^h,7),Z=Z+T|0,A=H(A^Z,16),b=b+A|0,T=H(T^b,12),Z=Z+T|0,A=H(A^Z,8),b=b+A|0,T=H(T^b,7),L=L+x|0,k=H(k^L,16),E=E+k|0,x=H(x^E,12),L=L+x|0,k=H(k^L,8),E=E+k|0,x=H(x^E,7),q=q+$|0,k=H(k^q,16),b=b+k|0,$=H($^b,12),q=q+$|0,k=H(k^q,8),b=b+k|0,$=H($^b,7),j=j+T|0,B=H(B^j,16),E=E+B|0,T=H(T^E,12),j=j+T|0,B=H(B^j,8),E=E+B|0,T=H(T^E,7),Z=Z+x|0,w=H(w^Z,16),p=p+w|0,x=H(x^p,12),Z=Z+x|0,w=H(w^Z,8),p=p+w|0,x=H(x^p,7),L=L+z|0,A=H(A^L,16),h=h+A|0,z=H(z^h,12),L=L+z|0,A=H(A^L,8),h=h+A|0,z=H(z^h,7);let C=0;r[C++]=s+q|0,r[C++]=a+j|0,r[C++]=c+Z|0,r[C++]=l+L|0,r[C++]=d+z|0,r[C++]=g+$|0,r[C++]=u+T|0,r[C++]=f+x|0,r[C++]=y+p|0,r[C++]=m+h|0,r[C++]=v+b|0,r[C++]=R+E|0,r[C++]=O+B|0,r[C++]=I+w|0,r[C++]=N+A|0,r[C++]=_+k|0}function Kl(t,e,n,r){let o=t[0],i=t[1],s=t[2],a=t[3],c=e[0],l=e[1],d=e[2],g=e[3],u=e[4],f=e[5],y=e[6],m=e[7],v=n[0],R=n[1],O=n[2],I=n[3];for(let _=0;_<20;_+=2)o=o+c|0,v=H(v^o,16),u=u+v|0,c=H(c^u,12),o=o+c|0,v=H(v^o,8),u=u+v|0,c=H(c^u,7),i=i+l|0,R=H(R^i,16),f=f+R|0,l=H(l^f,12),i=i+l|0,R=H(R^i,8),f=f+R|0,l=H(l^f,7),s=s+d|0,O=H(O^s,16),y=y+O|0,d=H(d^y,12),s=s+d|0,O=H(O^s,8),y=y+O|0,d=H(d^y,7),a=a+g|0,I=H(I^a,16),m=m+I|0,g=H(g^m,12),a=a+g|0,I=H(I^a,8),m=m+I|0,g=H(g^m,7),o=o+l|0,I=H(I^o,16),y=y+I|0,l=H(l^y,12),o=o+l|0,I=H(I^o,8),y=y+I|0,l=H(l^y,7),i=i+d|0,v=H(v^i,16),m=m+v|0,d=H(d^m,12),i=i+d|0,v=H(v^i,8),m=m+v|0,d=H(d^m,7),s=s+g|0,R=H(R^s,16),u=u+R|0,g=H(g^u,12),s=s+g|0,R=H(R^s,8),u=u+R|0,g=H(g^u,7),a=a+c|0,O=H(O^a,16),f=f+O|0,c=H(c^f,12),a=a+c|0,O=H(O^a,8),f=f+O|0,c=H(c^f,7);let N=0;r[N++]=o,r[N++]=i,r[N++]=s,r[N++]=a,r[N++]=v,r[N++]=R,r[N++]=O,r[N++]=I}var ut=co(ks,{counterRight:!1,counterLength:4,allowShortKeys:!1}),zl=co(ks,{counterRight:!1,counterLength:8,extendNonceFn:Kl,allowShortKeys:!1});var jl=new Uint8Array(16),vs=(t,e)=>{t.update(e);let n=e.length%16;n&&t.update(jl.subarray(n))},Zl=new Uint8Array(32);function Ss(t,e,n,r,o){o!==void 0&&se(o,void 0,"AAD");let i=t(e,n,Zl),s=bs(r.length,o?o.length:0,!0),a=Es.create(i);o&&vs(a,o),vs(a,r),a.update(s);let c=a.digest();return Oe(i,s),c}var Bs=t=>(e,n,r)=>({encrypt(i,s){let a=i.length;s=so(a+16,s,!1),s.set(i);let c=s.subarray(0,-16);t(e,n,c,c,1);let l=Ss(t,e,n,c,r);return s.set(l,a),Oe(l),s},decrypt(i,s){s=so(i.length-16,s,!1);let a=i.subarray(0,-16),c=i.subarray(-16),l=Ss(t,e,n,a,r);if(!Lt(c,l))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),t(e,n,s,s,1),Oe(l),s}}),Oh=io({blockSize:64,nonceLength:12,tagLength:16},Bs(ut)),Ph=io({blockSize:64,nonceLength:24,tagLength:16},Bs(zl));function Wn(t,e,n){return st(t),n===void 0&&(n=new Uint8Array(t.outputLen)),Ce(t,n,e)}var uo=Uint8Array.of(0),As=Uint8Array.of();function Yn(t,e,n,r=32){st(t),we(r,"length");let o=t.outputLen;if(r>255*o)throw new Error("Length must be <= 255*HashLen");let i=Math.ceil(r/o);n===void 0?n=As:Y(n,void 0,"info");let s=new Uint8Array(i*o),a=Ce.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let d=0;d<i;d++)uo[0]=d+1,c.update(d===0?As:l).update(n).update(uo).digestInto(l),s.set(l,o*d),a._cloneInto(c);return a.destroy(),c.destroy(),Ie(l,uo),s.slice(0,r)}function po(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Gl(t){if(!po(t))throw new Error("Uint8Array expected")}function Ls(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(n=>typeof n=="string"):e.every(n=>Number.isSafeInteger(n)):!1}function Wl(t){if(typeof t!="function")throw new Error("function expected");return!0}function ft(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function yo(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function fo(t){if(!Array.isArray(t))throw new Error("array expected")}function Xn(t,e){if(!Ls(!0,e))throw new Error(`${t}: array of strings expected`)}function Is(t,e){if(!Ls(!1,e))throw new Error(`${t}: array of numbers expected`)}function Ns(...t){let e=i=>i,n=(i,s)=>a=>i(s(a)),r=t.map(i=>i.encode).reduceRight(n,e),o=t.map(i=>i.decode).reduce(n,e);return{encode:r,decode:o}}function _s(t){let e=typeof t=="string"?t.split(""):t,n=e.length;Xn("alphabet",e);let r=new Map(e.map((o,i)=>[o,i]));return{encode:o=>(fo(o),o.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${t}`);return e[i]})),decode:o=>(fo(o),o.map(i=>{ft("alphabet.decode",i);let s=r.get(i);if(s===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${t}`);return s}))}}function Us(t=""){return ft("join",t),{encode:e=>(Xn("join.decode",e),e.join(t)),decode:e=>(ft("join.decode",e),e.split(t))}}function Yl(t,e="="){return yo(t),ft("padding",e),{encode(n){for(Xn("padding.encode",n);n.length*t%8;)n.push(e);return n},decode(n){Xn("padding.decode",n);let r=n.length;if(r*t%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;r>0&&n[r-1]===e;r--)if((r-1)*t%8===0)throw new Error("padding: invalid, string has too much padding");return n.slice(0,r)}}}var Os=(t,e)=>e===0?t:Os(e,t%e),Fn=(t,e)=>t+(e-Os(t,e)),Jn=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function ho(t,e,n,r){if(fo(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(Fn(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${Fn(e,n)}`);let o=0,i=0,s=Jn[e],a=Jn[n]-1,c=[];for(let l of t){if(yo(l),l>=s)throw new Error(`convertRadix2: invalid data word=${l} from=${e}`);if(o=o<<e|l,i+e>32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${e}`);for(i+=e;i>=n;i-=n)c.push((o>>i-n&a)>>>0);let d=Jn[i];if(d===void 0)throw new Error("invalid carry");o&=d-1}if(o=o<<n-i&a,!r&&i>=e)throw new Error("Excess padding");if(!r&&o>0)throw new Error(`Non-zero padding: ${o}`);return r&&i>0&&c.push(o>>>0),c}function Ps(t,e=!1){if(yo(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Fn(8,t)>32||Fn(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!po(n))throw new Error("radix2.encode input should be Uint8Array");return ho(Array.from(n),8,t,!e)},decode:n=>(Is("radix2.decode",n),Uint8Array.from(ho(n,t,8,e)))}}function Rs(t){return Wl(t),function(...e){try{return t.apply(null,e)}catch{}}}var Jl=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",Xl=(t,e)=>{ft("base64",t);let n=e?/^[A-Za-z0-9=_-]+$/:/^[A-Za-z0-9=+/]+$/,r=e?"base64url":"base64";if(t.length>0&&!n.test(t))throw new Error("invalid base64");return Uint8Array.fromBase64(t,{alphabet:r,lastChunkHandling:"strict"})},Nt=Jl?{encode(t){return Gl(t),t.toBase64()},decode(t){return Xl(t,!1)}}:Ns(Ps(6),_s("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Yl(6),Us(""));var go=Ns(_s("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Us("")),Cs=[996825010,642813549,513874426,1027748829,705979059];function cn(t){let e=t>>25,n=(t&33554431)<<5;for(let r=0;r<Cs.length;r++)(e>>r&1)===1&&(n^=Cs[r]);return n}function Ts(t,e,n=1){let r=t.length,o=1;for(let i=0;i<r;i++){let s=t.charCodeAt(i);if(s<33||s>126)throw new Error(`Invalid prefix (${t})`);o=cn(o)^s>>5}o=cn(o);for(let i=0;i<r;i++)o=cn(o)^t.charCodeAt(i)&31;for(let i of e)o=cn(o)^i;for(let i=0;i<6;i++)o=cn(o);return o^=n,go.encode(ho([o%Jn[30]],30,5,!1))}function Fl(t){let e=t==="bech32"?1:734539939,n=Ps(5),r=n.decode,o=n.encode,i=Rs(r);function s(g,u,f=90){ft("bech32.encode prefix",g),po(u)&&(u=Array.from(u)),Is("bech32.encode",u);let y=g.length;if(y===0)throw new TypeError(`Invalid prefix length ${y}`);let m=y+7+u.length;if(f!==!1&&m>f)throw new TypeError(`Length ${m} exceeds limit ${f}`);let v=g.toLowerCase(),R=Ts(v,u,e);return`${v}1${go.encode(u)}${R}`}function a(g,u=90){ft("bech32.decode input",g);let f=g.length;if(f<8||u!==!1&&f>u)throw new TypeError(`invalid string length: ${f} (${g}). Expected (8..${u})`);let y=g.toLowerCase();if(g!==y&&g!==g.toUpperCase())throw new Error("String must be lowercase or uppercase");let m=y.lastIndexOf("1");if(m===0||m===-1)throw new Error('Letter "1" must be present between prefix and data only');let v=y.slice(0,m),R=y.slice(m+1);if(R.length<6)throw new Error("Data must be at least 6 characters long");let O=go.decode(R).slice(0,-6),I=Ts(v,O,e);if(!R.endsWith(I))throw new Error(`Invalid checksum in ${g}: expected "${I}"`);return{prefix:v,words:O}}let c=Rs(a);function l(g){let{prefix:u,words:f}=a(g,!1);return{prefix:u,words:f,bytes:r(f)}}function d(g,u){return s(g,o(u))}return{encode:s,decode:a,encodeFromBytes:d,decodeToBytes:l,decodeUnsafe:c,fromWords:r,fromWordsUnsafe:i,toWords:o}}var bo=Fl("bech32");var dt=Symbol("verified"),Ql=t=>t instanceof Object;function eu(t){if(!Ql(t)||typeof t.kind!="number"||typeof t.content!="string"||typeof t.created_at!="number"||typeof t.pubkey!="string"||!t.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(t.tags))return!1;for(let e=0;e<t.tags.length;e++){let n=t.tags[e];if(!Array.isArray(n))return!1;for(let r=0;r<n.length;r++)if(typeof n[r]!="string")return!1}return!0}var tu=new TextDecoder("utf-8"),vo=new TextEncoder;function ln(t){try{t.indexOf("://")===-1&&(t="wss://"+t);let e=new URL(t);return e.protocol==="http:"?e.protocol="ws:":e.protocol==="https:"&&(e.protocol="wss:"),e.pathname=e.pathname.replace(/\/+/g,"/"),e.pathname.endsWith("/")&&(e.pathname=e.pathname.slice(0,-1)),(e.port==="80"&&e.protocol==="ws:"||e.port==="443"&&e.protocol==="wss:")&&(e.port=""),e.searchParams.sort(),e.hash="",e.toString()}catch{throw new Error(`Invalid URL: ${t}`)}}var nu=class{generateSecretKey(){return xe.utils.randomSecretKey()}getPublicKey(t){return ee(xe.getPublicKey(t))}finalizeEvent(t,e){let n=t;return n.pubkey=ee(xe.getPublicKey(e)),n.id=mo(n),n.sig=ee(xe.sign(ne(mo(n)),e)),n[dt]=!0,n}verifyEvent(t){if(typeof t[dt]=="boolean")return t[dt];try{let e=mo(t);if(e!==t.id)return t[dt]=!1,!1;let n=xe.verify(ne(t.sig),ne(e),ne(t.pubkey));return t[dt]=n,n}catch{return t[dt]=!1,!1}}};function ru(t){if(!eu(t))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content])}function mo(t){let e=ue(vo.encode(ru(t)));return ee(e)}var Qn=new nu,jh=Qn.generateSecretKey,Hs=Qn.getPublicKey,ou=Qn.finalizeEvent,qs=Qn.verifyEvent,So=1,ko=4294967295,Bo=65536;function wo(t,e){let n=zn.getSharedSecret(t,ne("02"+e)).subarray(1,33);return Wn(ue,n,vo.encode("nip44-v2"))}function Ds(t,e){let n=Yn(ue,t,e,76);return{chacha_key:n.subarray(0,32),chacha_nonce:n.subarray(32,44),hmac_key:n.subarray(44,76)}}function $s(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("expected positive integer");if(t<=32)return 32;let e=2**(Math.floor(Math.log2(t-1))+1),n=e<=256?32:e/8;return n*(Math.floor((t-1)/n)+1)}function iu(t){if(!Number.isSafeInteger(t)||t<So||t>65535)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");let e=new Uint8Array(2);return new DataView(e.buffer).setUint16(0,t,!1),e}function su(t){if(!Number.isSafeInteger(t)||t<Bo||t>ko)throw new Error("invalid plaintext size: must be between 65536 and 4294967295 bytes");let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!1),e}function au(t){let e=vo.encode(t),n=e.length;if(n<So||n>ko)throw new Error("invalid plaintext size: must be between 1 and 4294967295 bytes");let r=n>=Bo?te(new Uint8Array([0,0]),su(n)):iu(n),o=new Uint8Array($s(n)-n);return te(r,e,o)}function cu(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=e.getUint16(0),r,o;if(n===0){if(r=e.getUint32(2),r<Bo)throw new Error("invalid padding");o=6}else r=n,o=2;let i=t.subarray(o,o+r);if(r<So||r>ko||i.length!==r||t.length!==o+$s(r))throw new Error("invalid padding");return tu.decode(i)}function Vs(t,e,n){if(n.length!==32)throw new Error("AAD associated data must be 32 bytes");let r=te(n,e);return Ce(ue,t,r)}function lu(t){if(typeof t!="string")throw new Error("payload must be a valid string");let e=t.length;if(e<132)throw new Error("invalid payload length: "+e);if(t[0]==="#")throw new Error("unknown encryption version");let n;try{n=Nt.decode(t)}catch(i){throw new Error("invalid base64: "+i.message)}let r=n.length;if(r<99)throw new Error("invalid data length: "+r);let o=n[0];if(o!==2)throw new Error("unknown encryption version "+o);return{nonce:n.subarray(1,33),ciphertext:n.subarray(33,-32),mac:n.subarray(-32)}}function uu(t,e,n=ke(32)){let{chacha_key:r,chacha_nonce:o,hmac_key:i}=Ds(e,n),s=au(t),a=ut(r,o,s),c=Vs(i,a,n);return Nt.encode(te(new Uint8Array([2]),n,a,c))}function Ms(t,e){let{nonce:n,ciphertext:r,mac:o}=lu(t),{chacha_key:i,chacha_nonce:s,hmac_key:a}=Ds(e,n),c=Vs(a,r,n);if(!Lt(c,o))throw new Error("invalid MAC");let l=ut(i,s,r);return cu(l)}var fu=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,du;try{du=fetch}catch{}var hu=22242,xo=24133;function gu(t,e){if(t.ids&&t.ids.indexOf(e.id)===-1||t.kinds&&t.kinds.indexOf(e.kind)===-1||t.authors&&t.authors.indexOf(e.pubkey)===-1)return!1;for(let n in t)if(n[0]==="#"){let r=n.slice(1),o=t[`#${r}`];if(o&&!e.tags.find(([i,s])=>i===n.slice(1)&&o.indexOf(s)!==-1))return!1}return!(t.since&&e.created_at<t.since||t.until&&e.created_at>t.until)}function pu(t,e){for(let n=0;n<t.length;n++)if(gu(t[n],e))return!0;return!1}function yu(t,e){let n=e.length+3,r=t.indexOf(`"${e}":`)+n,o=t.slice(r).indexOf('"')+r+1;return t.slice(o,o+64)}function bu(t){let e=t.slice(0,22).indexOf('"EVENT"');if(e===-1)return null;let n=t.slice(e+7+1).indexOf('"');if(n===-1)return null;let r=e+7+1+n,o=t.slice(r+1,80).indexOf('"');if(o===-1)return null;let i=r+1+o;return t.slice(r+1,i)}function mu(t,e){return{kind:hu,created_at:Math.floor(Date.now()/1e3),tags:[["relay",t],["challenge",e]],content:""}}var Eo=class extends Error{constructor(t,e){super(`Tried to send message '${t} on a closed connection to ${e}.`),this.name="SendingOnClosedConnection"}},Ks=class{constructor(t,e){S(this,"url");S(this,"_connected",!1);S(this,"onclose",null);S(this,"onnotice",t=>console.debug(`NOTICE from ${this.url}: ${t}`));S(this,"onauth");S(this,"baseEoseTimeout",4400);S(this,"publishTimeout",4400);S(this,"pingFrequency",29e3);S(this,"pingTimeout",2e4);S(this,"resubscribeBackoff",[1e4,1e4,1e4,2e4,2e4,3e4,6e4]);S(this,"openSubs",new Map);S(this,"enablePing");S(this,"enableReconnect");S(this,"idleSince",Date.now());S(this,"ongoingOperations",0);S(this,"reconnectTimeoutHandle");S(this,"pingIntervalHandle");S(this,"reconnectAttempts",0);S(this,"skipReconnection",!1);S(this,"connectionPromise");S(this,"openCountRequests",new Map);S(this,"openEventPublishes",new Map);S(this,"ws");S(this,"challenge");S(this,"authPromise");S(this,"serial",0);S(this,"verifyEvent");S(this,"_WebSocket");this.url=ln(t),this.verifyEvent=e.verifyEvent,this._WebSocket=e.websocketImplementation||WebSocket,this.enablePing=e.enablePing,this.enableReconnect=e.enableReconnect||!1}static async connect(t,e){let n=new Ks(t,e);return await n.connect(e),n}closeAllSubscriptions(t){for(let[e,n]of this.openSubs)n.close(t);this.openSubs.clear();for(let[e,n]of this.openEventPublishes)n.reject(new Error(t));this.openEventPublishes.clear();for(let[e,n]of this.openCountRequests)n.reject(new Error(t));this.openCountRequests.clear()}get connected(){return this._connected}async reconnect(){let t=this.resubscribeBackoff[Math.min(this.reconnectAttempts,this.resubscribeBackoff.length-1)];this.reconnectAttempts++,this.reconnectTimeoutHandle=setTimeout(async()=>{try{await this.connect()}catch{}},t)}handleHardClose(t){this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this._connected=!1,this.connectionPromise=void 0,this.idleSince=void 0,this.enableReconnect&&!this.skipReconnection?this.reconnect():(this.onclose?.(),this.closeAllSubscriptions(t))}async connect(t){let e;return this.connectionPromise?this.connectionPromise:(this.challenge=void 0,this.authPromise=void 0,this.skipReconnection=!1,this.connectionPromise=new Promise((n,r)=>{t?.timeout&&(e=setTimeout(()=>{r("connection timed out"),this.connectionPromise=void 0,this.skipReconnection=!0,this.onclose?.(),this.handleHardClose("relay connection timed out")},t.timeout)),t?.abort&&(t.abort.onabort=r);try{this.ws=new this._WebSocket(this.url)}catch(o){clearTimeout(e),r(o);return}this.ws.onopen=()=>{this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),clearTimeout(e),this._connected=!0;let o=this.reconnectAttempts>0;this.reconnectAttempts=0;for(let i of this.openSubs.values()){if(i.eosed=!1,o)for(let s=0;s<i.filters.length;s++)i.lastEmitted&&(i.filters[s].since=i.lastEmitted+1);i.fire()}this.enablePing&&(this.pingIntervalHandle=setInterval(()=>this.pingpong(),this.pingFrequency)),n()},this.ws.onerror=()=>{clearTimeout(e),r("connection failed"),this.connectionPromise=void 0,this.skipReconnection=!0,this.onclose?.(),this.handleHardClose("relay connection failed")},this.ws.onclose=o=>{clearTimeout(e),r(o.message||"websocket closed"),this.handleHardClose("relay connection closed")},this.ws.onmessage=this._onmessage.bind(this)}),this.connectionPromise)}waitForPingPong(){return new Promise(t=>{this.ws.once("pong",()=>t(!0)),this.ws.ping()})}waitForDummyReq(){return new Promise((t,e)=>{if(!this.connectionPromise)return e(new Error(`no connection to ${this.url}, can't ping`));try{let n=this.subscribe([{ids:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],limit:0}],{label:"<forced-ping>",oneose:()=>{t(!0),n.close()},onclose(){t(!0)},eoseTimeout:this.pingTimeout+1e3})}catch(n){e(n)}})}async pingpong(){this.ws?.readyState===1&&(await Promise.any([this.ws&&this.ws.ping&&this.ws.once?this.waitForPingPong():this.waitForDummyReq(),new Promise(e=>setTimeout(()=>e(!1),this.pingTimeout))])||this.ws?.readyState===this._WebSocket.OPEN&&this.ws?.close())}async send(t){if(!this.connectionPromise)throw new Eo(t,this.url);this.connectionPromise.then(()=>{this.ws?.send(t)})}async auth(t){let e=this.challenge;if(!e)throw new Error("can't perform auth, no challenge was received");return this.authPromise?this.authPromise:(this.authPromise=new Promise(async(n,r)=>{try{let o=await t(mu(this.url,e)),i=setTimeout(()=>{let s=this.openEventPublishes.get(o.id);s&&(s.reject(new Error("auth timed out")),this.openEventPublishes.delete(o.id))},this.publishTimeout);this.openEventPublishes.set(o.id,{resolve:n,reject:r,timeout:i}),this.send('["AUTH",'+JSON.stringify(o)+"]")}catch(o){console.warn("subscribe auth function failed:",o)}}),this.authPromise)}async publish(t){this.idleSince=void 0,this.ongoingOperations++;let e=new Promise((n,r)=>{let o=setTimeout(()=>{let i=this.openEventPublishes.get(t.id);i&&(i.reject(new Error("publish timed out")),this.openEventPublishes.delete(t.id))},this.publishTimeout);this.openEventPublishes.set(t.id,{resolve:n,reject:r,timeout:o})});return this.send('["EVENT",'+JSON.stringify(t)+"]"),this.ongoingOperations--,this.ongoingOperations===0&&(this.idleSince=Date.now()),e}async count(t,e){this.serial++;let n=e?.id||"count:"+this.serial,r=new Promise((o,i)=>{this.openCountRequests.set(n,{resolve:o,reject:i})});return this.send('["COUNT","'+n+'",'+JSON.stringify(t).substring(1)),r}subscribe(t,e){e.label!=="<forced-ping>"&&(this.idleSince=void 0,this.ongoingOperations++);let n=this.prepareSubscription(t,e);return n.fire(),e.abort&&(e.abort.onabort=()=>n.close(String(e.abort.reason||"<aborted>"))),n}prepareSubscription(t,e){this.serial++;let n=e.id||(e.label?e.label+":":"sub:")+this.serial,r=new wu(this,n,t,e);return this.openSubs.set(n,r),r}close(){this.skipReconnection=!0,this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this.closeAllSubscriptions("relay connection closed by us"),this._connected=!1,this.idleSince=void 0,this.onclose?.(),this.ws?.readyState===this._WebSocket.OPEN&&this.ws?.close()}_onmessage(t){let e=t.data;if(!e)return;let n=bu(e);if(n){let r=this.openSubs.get(n);if(!r)return;let o=yu(e,"id"),i=r.alreadyHaveEvent?.(o);if(r.receivedEvent?.(this,o),i)return}try{let r=JSON.parse(e);switch(r[0]){case"EVENT":{let o=this.openSubs.get(r[1]),i=r[2];this.verifyEvent(i)&&pu(o.filters,i)?o.onevent(i):o.oninvalidevent?.(i),(!o.lastEmitted||o.lastEmitted<i.created_at)&&(o.lastEmitted=i.created_at);return}case"COUNT":{let o=r[1],i=r[2],s=this.openCountRequests.get(o);s&&(s.resolve(i.count),this.openCountRequests.delete(o));return}case"EOSE":{let o=this.openSubs.get(r[1]);if(!o)return;o.receivedEose();return}case"OK":{let o=r[1],i=r[2],s=r[3],a=this.openEventPublishes.get(o);a&&(clearTimeout(a.timeout),i?a.resolve(s):a.reject(new Error(s)),this.openEventPublishes.delete(o));return}case"CLOSED":{let o=r[1],i=this.openSubs.get(o);if(!i)return;i.closed=!0,i.close(r[2]);return}case"NOTICE":{this.onnotice(r[1]);return}case"AUTH":{this.challenge=r[1],this.onauth&&this.auth(this.onauth).catch(o=>{if(!(o instanceof Eo))throw o});return}default:{this.openSubs.get(r[1])?.oncustom?.(r);return}}}catch(r){try{let[o,i,s]=JSON.parse(e);console.warn(`[nostr] relay ${this.url} error processing message:`,r,s)}catch{console.warn(`[nostr] relay ${this.url} error processing message:`,r)}return}}},wu=class{constructor(t,e,n,r){S(this,"relay");S(this,"id");S(this,"lastEmitted");S(this,"closed",!1);S(this,"eosed",!1);S(this,"filters");S(this,"alreadyHaveEvent");S(this,"receivedEvent");S(this,"onevent");S(this,"oninvalidevent");S(this,"oneose");S(this,"onclose");S(this,"oncustom");S(this,"eoseTimeout");S(this,"eoseTimeoutHandle");if(n.length===0)throw new Error("subscription can't be created with zero filters");this.relay=t,this.filters=n,this.id=e,this.alreadyHaveEvent=r.alreadyHaveEvent,this.receivedEvent=r.receivedEvent,this.eoseTimeout=r.eoseTimeout||t.baseEoseTimeout,this.oneose=r.oneose,this.onclose=r.onclose,this.oninvalidevent=r.oninvalidevent,this.onevent=r.onevent||(o=>{console.warn(`onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,o)})}fire(){this.relay.send('["REQ","'+this.id+'",'+JSON.stringify(this.filters).substring(1)),this.eoseTimeoutHandle=setTimeout(this.receivedEose.bind(this),this.eoseTimeout)}receivedEose(){this.eosed||(clearTimeout(this.eoseTimeoutHandle),this.eosed=!0,this.oneose?.())}close(t="closed by caller"){if(!this.closed&&this.relay.connected){try{this.relay.send('["CLOSE",'+JSON.stringify(this.id)+"]")}catch(e){if(!(e instanceof Eo))throw e}this.closed=!0}this.relay.openSubs.delete(this.id),this.relay.ongoingOperations--,this.relay.ongoingOperations===0&&(this.relay.idleSince=Date.now()),this.onclose?.(t)}},xu=t=>(t[dt]=!0,!0),Eu=class{constructor(t){S(this,"relays",new Map);S(this,"seenOn",new Map);S(this,"trackRelays",!1);S(this,"verifyEvent");S(this,"enablePing");S(this,"enableReconnect");S(this,"automaticallyAuth");S(this,"trustedRelayURLs",new Set);S(this,"onRelayConnectionFailure");S(this,"onRelayConnectionSuccess");S(this,"allowConnectingToRelay");S(this,"maxWaitForConnection");S(this,"_WebSocket");this.verifyEvent=t.verifyEvent,this._WebSocket=t.websocketImplementation,this.enablePing=t.enablePing,this.enableReconnect=t.enableReconnect||!1,this.automaticallyAuth=t.automaticallyAuth,this.onRelayConnectionFailure=t.onRelayConnectionFailure,this.onRelayConnectionSuccess=t.onRelayConnectionSuccess,this.allowConnectingToRelay=t.allowConnectingToRelay,this.maxWaitForConnection=t.maxWaitForConnection||3e3}async ensureRelay(t,e){t=ln(t);let n=this.relays.get(t);if(n||(n=new Ks(t,{verifyEvent:this.trustedRelayURLs.has(t)?xu:this.verifyEvent,websocketImplementation:this._WebSocket,enablePing:this.enablePing,enableReconnect:this.enableReconnect}),n.onclose=()=>{this.relays.delete(t)},this.relays.set(t,n)),this.automaticallyAuth){let r=this.automaticallyAuth(t);r&&(n.onauth=r)}try{await n.connect({timeout:e?.connectionTimeout,abort:e?.abort})}catch(r){throw this.relays.delete(t),r}return n}close(t){t.map(ln).forEach(e=>{this.relays.get(e)?.close(),this.relays.delete(e)})}subscribe(t,e,n){let r=[],o=[];for(let i=0;i<t.length;i++){let s=ln(t[i]);r.find(a=>a.url===s)||o.indexOf(s)===-1&&(o.push(s),r.push({url:s,filter:e}))}return this.subscribeMap(r,n)}subscribeMany(t,e,n){return this.subscribe(t,e,n)}subscribeMap(t,e){let n=new Map;for(let u of t){let{url:f,filter:y}=u;n.has(f)||n.set(f,[]),n.get(f).push(y)}let r=Array.from(n.entries()).map(([u,f])=>({url:u,filters:f}));this.trackRelays&&(e.receivedEvent=(u,f)=>{let y=this.seenOn.get(f);y||(y=new Set,this.seenOn.set(f,y)),y.add(u)});let o=new Set,i=[],s=[],a=u=>{s[u]||(s[u]=!0,s.filter(f=>f).length===r.length&&(e.oneose?.(),a=()=>{}))},c=[],l=(u,f)=>{c[u]||(a(u),c[u]=f,c.filter(y=>y).length===r.length&&(e.onclose?.(c),l=()=>{}))},d=u=>{if(e.alreadyHaveEvent?.(u))return!0;let f=o.has(u);return o.add(u),f},g=Promise.all(r.map(async({url:u,filters:f},y)=>{if(this.allowConnectingToRelay?.(u,["read",f])===!1){l(y,"connection skipped by allowConnectingToRelay");return}let m;try{m=await this.ensureRelay(u,{connectionTimeout:this.maxWaitForConnection<(e.maxWait||0)?Math.max(e.maxWait*.8,e.maxWait-1e3):this.maxWaitForConnection,abort:e.abort})}catch(R){this.onRelayConnectionFailure?.(u),l(y,R?.message||String(R));return}this.onRelayConnectionSuccess?.(u);let v=m.subscribe(f,{...e,oneose:()=>a(y),onclose:R=>{R.startsWith("auth-required: ")&&e.onauth?m.auth(e.onauth).then(()=>{m.subscribe(f,{...e,oneose:()=>a(y),onclose:O=>{l(y,O)},alreadyHaveEvent:d,eoseTimeout:e.maxWait,abort:e.abort})}).catch(O=>{l(y,`auth was required and attempted, but failed with: ${O}`)}):l(y,R)},alreadyHaveEvent:d,eoseTimeout:e.maxWait,abort:e.abort});i.push(v)}));return{async close(u){await g,i.forEach(f=>{f.close(u)})}}}subscribeEose(t,e,n){let r;return r=this.subscribe(t,e,{...n,oneose(){let o="closed automatically on eose";r?r.close(o):n.onclose?.(t.map(i=>o))}}),r}subscribeManyEose(t,e,n){return this.subscribeEose(t,e,n)}async querySync(t,e,n){return new Promise(async r=>{let o=[];this.subscribeEose(t,e,{...n,onevent(i){o.push(i)},onclose(i){r(o)}})})}async get(t,e,n){e.limit=1;let r=await this.querySync(t,e,n);return r.sort((o,i)=>i.created_at-o.created_at),r[0]||null}publish(t,e,n){return t.map(ln).map(async(r,o,i)=>{if(i.indexOf(r)!==o)return Promise.reject("duplicate url");if(this.allowConnectingToRelay?.(r,["write",e])===!1)return Promise.reject("connection skipped by allowConnectingToRelay");let s;try{s=await this.ensureRelay(r,{connectionTimeout:this.maxWaitForConnection<(n?.maxWait||0)?Math.max(n.maxWait*.8,n.maxWait-1e3):this.maxWaitForConnection,abort:n?.abort})}catch(a){return this.onRelayConnectionFailure?.(r),"connection failure: "+String(a)}return s.publish(e).catch(async a=>{if(a instanceof Error&&a.message.startsWith("auth-required: ")&&n?.onauth)return await s.auth(n.onauth),s.publish(e);throw a}).then(a=>{if(this.trackRelays){let c=this.seenOn.get(e.id);c||(c=new Set,this.seenOn.set(e.id,c)),c.add(s)}return a})})}listConnectionStatus(){let t=new Map;return this.relays.forEach((e,n)=>t.set(n,e.connected)),t}destroy(){this.relays.forEach(t=>t.close()),this.relays=new Map}pruneIdleRelays(t=1e4){let e=[];for(let[n,r]of this.relays)r.idleSince&&Date.now()-r.idleSince>=t&&(this.relays.delete(n),e.push(n),r.close());return e}},zs;try{zs=WebSocket}catch{}var vu=class extends Eu{constructor(t){super({verifyEvent:qs,websocketImplementation:zs,maxWaitForConnection:3e3,...t})}},js;try{js=fetch}catch{}var Su=/^bunker:\/\/([0-9a-f]{64})\??([?\/\w:.=&%-]*)$/;async function Zs(t){let e=t.match(Su);if(e)try{let n=e[1],r=new URLSearchParams(e[2]);return{pubkey:n,relays:r.getAll("relay"),secret:r.get("secret")}}catch{}return ku(t)}async function ku(t){let e=t.match(fu);if(!e)return null;let[n,r="_",o]=e;try{let i=`https://${o}/.well-known/nostr.json?name=${r}`,s=await(await js(i,{redirect:"error"})).json(),a=s.names[r],c=s.nip46[a]||[];return{pubkey:a,relays:c,secret:null}}catch{return null}}var _t=class{constructor(t,e){S(this,"params");S(this,"pool");S(this,"subCloser");S(this,"isOpen");S(this,"serial");S(this,"idPrefix");S(this,"listeners");S(this,"waitingForAuth");S(this,"secretKey");S(this,"conversationKey");S(this,"bp");S(this,"cachedPubKey");this.params=e,this.pool=e.pool||new vu,this.secretKey=t,this.isOpen=!1,this.idPrefix=Math.random().toString(36).substring(7),this.serial=0,this.listeners={},this.waitingForAuth={}}static fromBunker(t,e,n={}){if(e.relays.length===0)throw new Error("no relays specified for this bunker");let r=new _t(t,n);return r.conversationKey=wo(t,e.pubkey),r.bp=e,r.setupSubscription(),r}static async fromURI(t,e,n={},r=3e5){let o=new _t(t,n),i=new URL(e),s=Hs(t);return new Promise((a,c)=>{let l=!1,d=o.pool.subscribe(i.searchParams.getAll("relay"),{kinds:[xo],"#p":[s],limit:0},{onevent:async g=>{try{let u=wo(t,g.pubkey),f=Ms(g.content,u);JSON.parse(f).result===i.searchParams.get("secret")&&(d.close(),o.bp={pubkey:g.pubkey,relays:i.searchParams.getAll("relay"),secret:i.searchParams.get("secret")},o.conversationKey=wo(t,g.pubkey),o.setupSubscription(),l=!0,n.skipSwitchRelays||await Promise.race([new Promise(m=>setTimeout(m,1e3)),o.switchRelays()]),a(o))}catch(u){console.warn("failed to process potential connection event",u)}},onclose:()=>{l||c(new Error("subscription closed before connection was established."))},maxWait:typeof r=="number"?r:void 0,abort:typeof r!="number"?r:void 0})})}setupSubscription(){let t=this.listeners,e=this.waitingForAuth,n=this.conversationKey;this.subCloser=this.pool.subscribe(this.bp.relays,{kinds:[xo],authors:[this.bp.pubkey],"#p":[Hs(this.secretKey)],limit:0},{onevent:async r=>{let o=JSON.parse(Ms(r.content,n)),{id:i,result:s,error:a}=o;if(s==="auth_url"&&e[i]){delete e[i],this.params.onauth?this.params.onauth(a):console.warn(`nostr-tools/nip46: remote signer ${this.bp.pubkey} tried to send an "auth_url"='${a}' but there was no onauth() callback configured.`);return}let c=t[i];c&&(a?c.reject(a):s&&c.resolve(s),delete t[i])},onclose:()=>{this.subCloser=void 0}}),this.isOpen=!0}async switchRelays(){try{let t=await this.sendRequest("switch_relays",[]),e=JSON.parse(t);if(!e||JSON.stringify(e.sort())===JSON.stringify(this.bp.relays))return!1;this.bp.relays=e;let n=this.subCloser;return setTimeout(()=>{n.close()},5e3),this.subCloser=void 0,this.setupSubscription(),!0}catch{return!1}}async close(){this.isOpen=!1,this.subCloser.close()}async sendRequest(t,e){return new Promise(async(n,r)=>{try{if(!this.isOpen)throw new Error("this signer is not open anymore, create a new one");this.subCloser||this.setupSubscription(),this.serial++;let o=`${this.idPrefix}-${this.serial}`,i=uu(JSON.stringify({id:o,method:t,params:e}),this.conversationKey),s=ou({kind:xo,tags:[["p",this.bp.pubkey]],content:i,created_at:Math.floor(Date.now()/1e3)},this.secretKey);this.listeners[o]={resolve:n,reject:r},this.waitingForAuth[o]=!0,await Promise.any(this.pool.publish(this.bp.relays,s))}catch(o){r(o)}})}async ping(){let t=await this.sendRequest("ping",[]);if(t!=="pong")throw new Error(`result is not pong: ${t}`)}async connect(){await this.sendRequest("connect",[this.bp.pubkey,this.bp.secret||""])}async getPublicKey(){return this.cachedPubKey||(this.cachedPubKey=await this.sendRequest("get_public_key",[])),this.cachedPubKey}async signEvent(t){let e=await this.sendRequest("sign_event",[JSON.stringify(t)]),n=JSON.parse(e);if(qs(n))return n;throw new Error(`event returned from bunker is improperly signed: ${JSON.stringify(n)}`)}async nip04Encrypt(t,e){return await this.sendRequest("nip04_encrypt",[t,e])}async nip04Decrypt(t,e){return await this.sendRequest("nip04_decrypt",[t,e])}async nip44Encrypt(t,e){return await this.sendRequest("nip44_encrypt",[t,e])}async nip44Decrypt(t,e){return await this.sendRequest("nip44_decrypt",[t,e])}};var Ut=Symbol("verified"),Bu=t=>t instanceof Object;function Au(t){if(!Bu(t)||typeof t.kind!="number"||typeof t.content!="string"||typeof t.created_at!="number"||typeof t.pubkey!="string"||!t.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(t.tags))return!1;for(let e=0;e<t.tags.length;e++){let n=t.tags[e];if(!Array.isArray(n))return!1;for(let r=0;r<n.length;r++)if(typeof n[r]!="string")return!1}return!0}var d0=new TextDecoder("utf-8"),Ru=new TextEncoder,Cu=class{generateSecretKey(){return xe.utils.randomSecretKey()}getPublicKey(t){return ee(xe.getPublicKey(t))}finalizeEvent(t,e){let n=t;return n.pubkey=ee(xe.getPublicKey(e)),n.id=Ao(n),n.sig=ee(xe.sign(ne(Ao(n)),e)),n[Ut]=!0,n}verifyEvent(t){if(typeof t[Ut]=="boolean")return t[Ut];try{let e=Ao(t);if(e!==t.id)return t[Ut]=!1,!1;let n=xe.verify(ne(t.sig),ne(e),ne(t.pubkey));return t[Ut]=n,n}catch{return t[Ut]=!1,!1}}};function Tu(t){if(!Au(t))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content])}function Ao(t){let e=ue(Ru.encode(Tu(t)));return ee(e)}var er=new Cu,h0=er.generateSecretKey,Gs=er.getPublicKey,Ws=er.finalizeEvent,g0=er.verifyEvent;var tr=new TextDecoder("utf-8"),w0=new TextEncoder;var Lu=5e3;function Ys(t){let{prefix:e,words:n}=bo.decode(t,Lu),r=new Uint8Array(bo.fromWords(n));switch(e){case"nprofile":{let o=Ro(r);if(!o[0]?.[0])throw new Error("missing TLV 0 for nprofile");if(o[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:ee(o[0][0]),relays:o[1]?o[1].map(i=>tr.decode(i)):[]}}}case"nevent":{let o=Ro(r);if(!o[0]?.[0])throw new Error("missing TLV 0 for nevent");if(o[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");if(o[2]&&o[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(o[3]&&o[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:ee(o[0][0]),relays:o[1]?o[1].map(i=>tr.decode(i)):[],author:o[2]?.[0]?ee(o[2][0]):void 0,kind:o[3]?.[0]?parseInt(ee(o[3][0]),16):void 0}}}case"naddr":{let o=Ro(r);if(!o[0]?.[0])throw new Error("missing TLV 0 for naddr");if(!o[2]?.[0])throw new Error("missing TLV 2 for naddr");if(o[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(!o[3]?.[0])throw new Error("missing TLV 3 for naddr");if(o[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:tr.decode(o[0][0]),pubkey:ee(o[2][0]),kind:parseInt(ee(o[3][0]),16),relays:o[1]?o[1].map(i=>tr.decode(i)):[]}}}case"nsec":return{type:e,data:r};case"npub":case"note":return{type:e,data:ee(r)};default:throw new Error(`unknown prefix ${e}`)}}function Ro(t){let e={},n=t;for(;n.length>0;){let r=n[0],o=n[1],i=n.slice(2,2+o);if(n=n.slice(2+o),i.length<o)throw new Error(`not enough data to read on TLV ${r}`);e[r]=e[r]||[],e[r].push(i)}return e}var Iu=new TextDecoder("utf-8"),Js=new TextEncoder,Co=1,To=4294967295,Lo=65536;function Ot(t,e){let n=zn.getSharedSecret(t,ne("02"+e)).subarray(1,33);return Wn(ue,n,Js.encode("nip44-v2"))}function Xs(t,e){let n=Yn(ue,t,e,76);return{chacha_key:n.subarray(0,32),chacha_nonce:n.subarray(32,44),hmac_key:n.subarray(44,76)}}function Fs(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("expected positive integer");if(t<=32)return 32;let e=2**(Math.floor(Math.log2(t-1))+1),n=e<=256?32:e/8;return n*(Math.floor((t-1)/n)+1)}function Nu(t){if(!Number.isSafeInteger(t)||t<Co||t>65535)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");let e=new Uint8Array(2);return new DataView(e.buffer).setUint16(0,t,!1),e}function _u(t){if(!Number.isSafeInteger(t)||t<Lo||t>To)throw new Error("invalid plaintext size: must be between 65536 and 4294967295 bytes");let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!1),e}function Uu(t){let e=Js.encode(t),n=e.length;if(n<Co||n>To)throw new Error("invalid plaintext size: must be between 1 and 4294967295 bytes");let r=n>=Lo?te(new Uint8Array([0,0]),_u(n)):Nu(n),o=new Uint8Array(Fs(n)-n);return te(r,e,o)}function Ou(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=e.getUint16(0),r,o;if(n===0){if(r=e.getUint32(2),r<Lo)throw new Error("invalid padding");o=6}else r=n,o=2;let i=t.subarray(o,o+r);if(r<Co||r>To||i.length!==r||t.length!==o+Fs(r))throw new Error("invalid padding");return Iu.decode(i)}function Qs(t,e,n){if(n.length!==32)throw new Error("AAD associated data must be 32 bytes");let r=te(n,e);return Ce(ue,t,r)}function Pu(t){if(typeof t!="string")throw new Error("payload must be a valid string");let e=t.length;if(e<132)throw new Error("invalid payload length: "+e);if(t[0]==="#")throw new Error("unknown encryption version");let n;try{n=Nt.decode(t)}catch(i){throw new Error("invalid base64: "+i.message)}let r=n.length;if(r<99)throw new Error("invalid data length: "+r);let o=n[0];if(o!==2)throw new Error("unknown encryption version "+o);return{nonce:n.subarray(1,33),ciphertext:n.subarray(33,-32),mac:n.subarray(-32)}}function ea(t,e,n=ke(32)){let{chacha_key:r,chacha_nonce:o,hmac_key:i}=Xs(e,n),s=Uu(t),a=ut(r,o,s),c=Qs(i,a,n);return Nt.encode(te(new Uint8Array([2]),n,a,c))}function un(t,e){let{nonce:n,ciphertext:r,mac:o}=Pu(t),{chacha_key:i,chacha_nonce:s,hmac_key:a}=Xs(e,n),c=Qs(a,r,n);if(!Lt(c,o))throw new Error("invalid MAC");let l=ut(i,s,r);return Ou(l)}function fn(){return typeof window<"u"&&!!window.nostr&&typeof window.nostr.signEvent=="function"}var Io=class{constructor(e,n){this.pubkey=e;this.provider=n;this.method="nip07";this.capabilities={canSignEvents:!0,hasNip44:!!n.nip44},n.nip44&&(this.nip44={encrypt:(r,o)=>n.nip44.encrypt(r,o),decrypt:(r,o)=>n.nip44.decrypt(r,o)})}async signEvent(e){return this.provider.signEvent(e)}async close(){}};async function dn(){if(!fn())throw new Error("no-nip07-provider");let t=window.nostr,e=await t.getPublicKey();if(!/^[0-9a-f]{64}$/i.test(e))throw new Error("invalid-pubkey-from-nip07");return new Io(e.toLowerCase(),t)}var nr=class{constructor(e,n,r,o){this.pubkey=e;this.bunker=n;this.bunkerUri=r;this.clientSecretKey=o;this.method="bunker";this.capabilities={canSignEvents:!0,hasNip44:!0};this.nip44={encrypt:(i,s)=>n.nip44Encrypt(i,s),decrypt:(i,s)=>n.nip44Decrypt(i,s)}}async signEvent(e){let{pubkey:n,...r}=e,o={kind:r.kind,content:r.content,created_at:r.created_at??Math.floor(Date.now()/1e3),tags:r.tags??[]};return await this.bunker.signEvent(o)}async close(){await this.bunker.close()}};async function ta(t){let{uri:e,clientSecretKey:n,abortSignal:r}=t;if(n.length!==32)throw new Error("invalid-client-secret-key");let o=r?await _t.fromURI(n,e,void 0,r):await _t.fromURI(n,e),i=await o.getPublicKey();if(!/^[0-9a-f]{64}$/i.test(i))throw await o.close().catch(()=>{}),new Error("invalid-pubkey-from-bunker");return new nr(i.toLowerCase(),o,e,n)}function na(t){let{clientPubkeyHex:e,relayUrl:n,secret:r}=t;if(!/^[0-9a-f]{64}$/i.test(e))throw new Error("invalid-client-pubkey");if(!/^wss?:\/\//.test(n))throw new Error("invalid-relay-url");let o=new URLSearchParams({relay:n,secret:r});return t.perms&&t.perms.length>0&&o.set("perms",t.perms.join(",")),t.appName&&o.set("name",t.appName),t.appUrl&&o.set("url",t.appUrl),`nostrconnect://${e}?${o.toString()}`}async function Hu(t,e,n){let r,o=new Promise((i,s)=>{r=setTimeout(()=>{n.close().catch(()=>{}),s(new Error("bunker-connect-timeout"))},e)});try{return await Promise.race([t,o])}finally{r!==void 0&&clearTimeout(r)}}async function Ht(t){let e=t.uri.trim();if(!e)throw new Error("empty-bunker-uri");let n=await Zs(e);if(!n)throw new Error("invalid-bunker-uri");let r=t.clientSecretKey??Mu();if(r.length!==32)throw new Error("invalid-client-secret-key");let o=_t.fromBunker(r,n,{onauth:t.onauth}),i=(async()=>(await o.connect(),o.getPublicKey()))(),s=t.timeoutMs&&t.timeoutMs>0?await Hu(i,t.timeoutMs,o):await i;if(!/^[0-9a-f]{64}$/i.test(s))throw await o.close().catch(()=>{}),new Error("invalid-pubkey-from-bunker");return new nr(s.toLowerCase(),o,e,r)}function Mu(){let t=new Uint8Array(32);return crypto.getRandomValues(t),t}var No=class{constructor(e,n){this.pubkey=e;this.privkey=n;this.method="nsec";this.capabilities={canSignEvents:!0,hasNip44:!0};this.nip44={encrypt:async(r,o)=>ea(o,Ot(this.privkey,r)),decrypt:async(r,o)=>un(o,Ot(this.privkey,r))}}async signEvent(e){let n={kind:e.kind,content:e.content,created_at:e.created_at??Math.floor(Date.now()/1e3),tags:e.tags??[]};return Ws(n,this.privkey)}async close(){this.privkey.fill(0)}};function ra(t){let e=t.trim();if(!e)throw new Error("empty-nsec");let n;if(e.startsWith("nsec1")){let o=Ys(e);if(o.type!=="nsec")throw new Error("not-an-nsec");n=o.data}else if(/^[0-9a-f]{64}$/i.test(e)){n=new Uint8Array(32);for(let o=0;o<32;o++)n[o]=parseInt(e.slice(o*2,o*2+2),16)}else throw new Error("invalid-nsec-format");if(n.length!==32)throw new Error("invalid-nsec-length");let r=Gs(n);if(!/^[0-9a-f]{64}$/i.test(r))throw new Error("invalid-pubkey-from-nsec");return new No(r.toLowerCase(),n)}var Ee=class{constructor(e,n){this.pubkey=e;this.authEvent=n;this.method="redirect";this.capabilities={canSignEvents:!1,hasNip44:!1}}async signEvent(e){throw new Error("signer-auth-only: this session was established via redirect and cannot sign new events. Install a NIP-07 extension (bark, Alby) or paste a bunker URI to upgrade.")}async close(){}},Pt=class{constructor(e,n,r,o,i,s=!0){this.pubkey=e;this.authEvent=n;this.upgrade=r;this.bunkerUri=o;this.clientSecretKey=i;this.method="bunker";this.capabilities={canSignEvents:s,hasNip44:s},this.upgrade.then(a=>{a&&(this.capabilities.canSignEvents=!0,this.capabilities.hasNip44=!0)}),this.nip44={encrypt:async(a,c)=>(await this.live()).nip44.encrypt(a,c),decrypt:async(a,c)=>(await this.live()).nip44.decrypt(a,c)}}async live(){let e=await this.upgrade;if(!e)throw new Error("signer-auth-only: the redirect bunker handoff did not connect, so this session cannot sign. Reconnect the signer or paste a bunker URI to upgrade.");return e}async signEvent(e){return(await this.live()).signEvent(e)}async close(){let e=await this.upgrade.catch(()=>null);e&&await e.close().catch(()=>{})}};function Pe(t){try{return typeof localStorage<"u"?localStorage.getItem(t):null}catch{return null}}function He(t,e){try{typeof localStorage<"u"&&localStorage.setItem(t,e)}catch{}}function Ye(t){try{typeof localStorage<"u"&&localStorage.removeItem(t)}catch{}}function oa(t){He(F.pubkey,t.pubkey),He(F.method,t.method),He(F.authEvent,t.authEventJson),t.bunkerUri!==void 0&&He(F.bunkerUri,t.bunkerUri),t.bunkerClientSkHex!==void 0&&He(F.bunkerClientSk,t.bunkerClientSkHex),t.expiresAt!==void 0&&He(F.expiresAt,String(t.expiresAt)),t.displayName!==void 0&&He(F.displayName,t.displayName)}function ia(){let t=Pe(F.pubkey),e=Pe(F.method),n=Pe(F.authEvent);if(!t||!e||!n||!/^[0-9a-f]{64}$/i.test(t)||e!=="nip07"&&e!=="redirect"&&e!=="bunker"&&e!=="amber")return null;let r;try{if(r=JSON.parse(n),typeof r!="object"||r===null||r.pubkey!==t)return null}catch{return null}let o=Pe(F.expiresAt),i=o?Number(o):void 0;if(i!==void 0&&Number.isFinite(i)&&Date.now()>i)return Je(),null;let s={pubkey:t,method:e,authEventJson:n},a=Pe(F.bunkerUri),c=Pe(F.bunkerClientSk),l=Pe(F.displayName);return a&&(s.bunkerUri=a),c&&(s.bunkerClientSkHex=c),i!==void 0&&Number.isFinite(i)&&(s.expiresAt=i),l&&(s.displayName=l),s}function Je(){Ye(F.pubkey),Ye(F.method),Ye(F.authEvent),Ye(F.bunkerUri),Ye(F.bunkerClientSk),Ye(F.expiresAt),Ye(F.displayName)}function ht(){let t=Pe(F.clientSk);if(t&&/^[0-9a-f]{64}$/i.test(t))try{return qu(t)}catch{}let e=new Uint8Array(32);return crypto.getRandomValues(e),He(F.clientSk,_o(e)),e}function rr(t){He(F.pendingRedirect,JSON.stringify(t))}function or(){let t=Pe(F.pendingRedirect);if(!t)return null;try{let e=JSON.parse(t),n=e.challenge,r=e.origin,o=e.appName,i=e.createdAt;return typeof n!="string"||!/^[0-9a-f]{64}$/i.test(n)||typeof r!="string"||r.length===0||typeof o!="string"||o.length===0||typeof i!="number"||!Number.isFinite(i)?null:{challenge:n,origin:r,appName:o,createdAt:i}}catch{return null}}function ir(){Ye(F.pendingRedirect)}function _o(t){let e="";for(let n=0;n<t.length;n++)e+=t[n].toString(16).padStart(2,"0");return e}function qu(t){if(t.length%2!==0)throw new Error("odd-hex-length");let e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n++)e[n]=parseInt(t.slice(n*2,n*2+2),16);return e}function sr(){return typeof navigator>"u"?!1:/android/i.test(navigator.userAgent)}var sa=/^[0-9a-f]{64}$/i;function Du(t){return{kind:21236,content:"",created_at:Math.floor(Date.now()/1e3),tags:[["challenge",t.challenge],["origin",t.origin],["app",t.appName]]}}function $u(t){let e=Du(t),n=JSON.stringify(e),r=typeof btoa=="function"?btoa(n):Buffer.from(n,"utf-8").toString("base64"),o=t.redirectCallback??`${t.origin}/?signet_amber=1`,i=new URLSearchParams({type:"sign_event",compressionType:"base64",returnType:"event",callbackUrl:o});return`nostrsigner:${r}?${i.toString()}`}function aa(t){if(typeof window>"u")throw new Error("signet-login: amber mode requires a browser environment");let e={challenge:t.challenge,origin:t.origin,appName:t.appName,createdAt:Date.now()};return rr(e),window.location.href=$u(t),new Promise(()=>{})}function Vu(){if(typeof window>"u")return;let t=new URL(window.location.href),e=!1;for(let r of["event","signet_amber","error"])t.searchParams.has(r)&&(t.searchParams.delete(r),e=!0);if(!e)return;let n=t.pathname+(t.search?t.search:"")+t.hash;try{window.history.replaceState(window.history.state,document.title,n)}catch{}}function ca(){if(typeof window>"u")return{kind:"no-callback"};let t=new URLSearchParams(window.location.search);if(!(t.has("signet_amber")||t.has("event")))return{kind:"no-callback"};let n=g=>(ir(),Vu(),g);if(t.get("error")==="denied")return n({kind:"denied"});let r=or();if(!r)return n({kind:"invalid",reason:"no-pending-state"});if(r.origin!==window.location.origin)return n({kind:"invalid",reason:"origin-mismatch"});if(Date.now()-r.createdAt>Ln)return n({kind:"invalid",reason:"pending-stale"});let o=t.get("event");if(!o)return n({kind:"invalid",reason:"no-event-param"});let i;try{let g;try{g=typeof atob=="function"?atob(o):Buffer.from(o,"base64").toString("utf-8")}catch{g=o}i=JSON.parse(g)}catch{return n({kind:"invalid",reason:"event-malformed"})}if(typeof i!="object"||i===null)return n({kind:"invalid",reason:"event-not-object"});let s=i;if(typeof s.id!="string"||!sa.test(s.id)||typeof s.pubkey!="string"||!sa.test(s.pubkey)||typeof s.sig!="string"||!/^[0-9a-f]{128}$/i.test(s.sig)||typeof s.created_at!="number"||!Array.isArray(s.tags)||s.kind!==21236||typeof s.content!="string")return n({kind:"invalid",reason:"event-shape-invalid"});let a=s.tags.find(g=>Array.isArray(g)&&g[0]==="challenge");if(!a||a[1]!==r.challenge)return n({kind:"invalid",reason:"challenge-mismatch"});let c={id:s.id.toLowerCase(),pubkey:s.pubkey.toLowerCase(),kind:21236,created_at:s.created_at,tags:s.tags,content:s.content,sig:s.sig.toLowerCase()},l=new Ee(c.pubkey,c),d={pubkey:c.pubkey,method:"amber",signer:l,authEvent:c};return n({kind:"session",session:d})}var gt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function pt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function hn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Ae(t,...e){if(!pt(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function ar(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");hn(t.outputLen),hn(t.blockLen)}function qt(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function ua(t,e){Ae(t);let n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function yt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function cr(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Re(t,e){return t<<32-e|t>>>e}var fa=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ku=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function le(t){if(Ae(t),fa)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Ku[t[n]];return e}var Me={_0:48,_9:57,A:65,F:70,a:97,f:102};function la(t){if(t>=Me._0&&t<=Me._9)return t-Me._0;if(t>=Me.A&&t<=Me.F)return t-(Me.A-10);if(t>=Me.a&&t<=Me.f)return t-(Me.a-10)}function bt(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(fa)return Uint8Array.fromHex(t);let e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let o=0,i=0;o<n;o++,i+=2){let s=la(t.charCodeAt(i)),a=la(t.charCodeAt(i+1));if(s===void 0||a===void 0){let c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}r[o]=s*16+a}return r}function lr(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function gn(t){return typeof t=="string"&&(t=lr(t)),Ae(t),t}function pe(...t){let e=0;for(let r=0;r<t.length;r++){let o=t[r];Ae(o),e+=o.length}let n=new Uint8Array(e);for(let r=0,o=0;r<t.length;r++){let i=t[r];n.set(i,o),o+=i.length}return n}var Mt=class{};function da(t){let e=r=>t().update(gn(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function mt(t=32){if(gt&&typeof gt.getRandomValues=="function")return gt.getRandomValues(new Uint8Array(t));if(gt&&typeof gt.randomBytes=="function")return Uint8Array.from(gt.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function zu(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);let o=BigInt(32),i=BigInt(4294967295),s=Number(n>>o&i),a=Number(n&i),c=r?4:0,l=r?0:4;t.setUint32(e+c,s,r),t.setUint32(e+l,a,r)}function ha(t,e,n){return t&e^~t&n}function ga(t,e,n){return t&e^t&n^e&n}var ur=class extends Mt{constructor(e,n,r,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=cr(this.buffer)}update(e){qt(this),e=gn(e),Ae(e);let{view:n,buffer:r,blockLen:o}=this,i=e.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=cr(e);for(;o<=i-s;s+=o)this.process(c,s);continue}r.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){qt(this),ua(e,this),this.finished=!0;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,yt(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(r,0),s=0);for(let g=s;g<o;g++)n[g]=0;zu(r,o-8,BigInt(this.length*8),i),this.process(r,0);let a=cr(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let g=0;g<l;g++)a.setUint32(4*g,d[g],i)}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:i,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=i,e.length=o,e.pos=a,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}},qe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ju=Uint32Array.from([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]),Xe=new Uint32Array(64),fr=class extends ur{constructor(e=32){super(64,e,8,!1),this.A=qe[0]|0,this.B=qe[1]|0,this.C=qe[2]|0,this.D=qe[3]|0,this.E=qe[4]|0,this.F=qe[5]|0,this.G=qe[6]|0,this.H=qe[7]|0}get(){let{A:e,B:n,C:r,D:o,E:i,F:s,G:a,H:c}=this;return[e,n,r,o,i,s,a,c]}set(e,n,r,o,i,s,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,n){for(let g=0;g<16;g++,n+=4)Xe[g]=e.getUint32(n,!1);for(let g=16;g<64;g++){let u=Xe[g-15],f=Xe[g-2],y=Re(u,7)^Re(u,18)^u>>>3,m=Re(f,17)^Re(f,19)^f>>>10;Xe[g]=m+Xe[g-7]+y+Xe[g-16]|0}let{A:r,B:o,C:i,D:s,E:a,F:c,G:l,H:d}=this;for(let g=0;g<64;g++){let u=Re(a,6)^Re(a,11)^Re(a,25),f=d+u+ha(a,c,l)+ju[g]+Xe[g]|0,m=(Re(r,2)^Re(r,13)^Re(r,22))+ga(r,o,i)|0;d=l,l=c,c=a,a=s+f|0,s=i,i=o,o=r,r=f+m|0}r=r+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(r,o,i,s,a,c,l,d)}roundClean(){yt(Xe)}destroy(){this.set(0,0,0,0,0,0,0,0),yt(this.buffer)}};var Dt=da(()=>new fr);var dr=class extends Mt{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,ar(e);let r=gn(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,i=new Uint8Array(o);i.set(r.length>o?e.create().update(r).digest():r);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=e.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),yt(i)}update(e){return qt(this),this.iHash.update(e),this}digestInto(e){qt(this),Ae(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:n,iHash:r,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Uo=(t,e,n)=>new dr(t,e).update(n).digest();Uo.create=(t,e)=>new dr(t,e);var Ho=BigInt(0),Po=BigInt(1);function pn(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function Fe(t,e,n=""){let r=pt(t),o=t?.length,i=e!==void 0;if(!r||i&&o!==e){let s=n&&`"${n}" `,a=i?` of length ${e}`:"",c=r?`length=${o}`:`type=${typeof t}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return t}function yn(t){let e=t.toString(16);return e.length&1?"0"+e:e}function pa(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Ho:BigInt("0x"+t)}function De(t){return pa(le(t))}function Mo(t){return Ae(t),pa(le(Uint8Array.from(t).reverse()))}function $t(t,e){return bt(t.toString(16).padStart(e*2,"0"))}function qo(t,e){return $t(t,e).reverse()}function re(t,e,n){let r;if(typeof e=="string")try{r=bt(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(pt(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");let o=r.length;if(typeof n=="number"&&o!==n)throw new Error(t+" of length "+n+" expected, got "+o);return r}var Oo=t=>typeof t=="bigint"&&Ho<=t;function bn(t,e,n){return Oo(t)&&Oo(e)&&Oo(n)&&e<=t&&t<n}function ya(t,e,n,r){if(!bn(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function hr(t){let e;for(e=0;t>Ho;t>>=Po,e+=1);return e}var Qe=t=>(Po<<BigInt(t))-Po;function ba(t,e,n){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");let r=f=>new Uint8Array(f),o=f=>Uint8Array.of(f),i=r(t),s=r(t),a=0,c=()=>{i.fill(1),s.fill(0),a=0},l=(...f)=>n(s,i,...f),d=(f=r(0))=>{s=l(o(0),f),i=l(),f.length!==0&&(s=l(o(1),f),i=l())},g=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,y=[];for(;f<e;){i=l();let m=i.slice();y.push(m),f+=i.length}return pe(...y)};return(f,y)=>{c(),d(f);let m;for(;!(m=y(g()));)d();return c(),m}}function mn(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(o,i,s){let a=t[o];if(s&&a===void 0)return;let c=typeof a;if(c!==i||a===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${c}`)}Object.entries(e).forEach(([o,i])=>r(o,i,!1)),Object.entries(n).forEach(([o,i])=>r(o,i,!0))}function Do(t){let e=new WeakMap;return(n,...r)=>{let o=e.get(n);if(o!==void 0)return o;let i=t(n,...r);return e.set(n,i),i}}var ge=BigInt(0),de=BigInt(1),wt=BigInt(2),xa=BigInt(3),Ea=BigInt(4),va=BigInt(5),Zu=BigInt(7),Sa=BigInt(8),Gu=BigInt(9),ka=BigInt(16);function be(t,e){let n=t%e;return n>=ge?n:e+n}function me(t,e,n){let r=t;for(;e-- >ge;)r*=r,r%=n;return r}function ma(t,e){if(t===ge)throw new Error("invert: expected non-zero number");if(e<=ge)throw new Error("invert: expected positive modulus, got "+e);let n=be(t,e),r=e,o=ge,i=de,s=de,a=ge;for(;n!==ge;){let l=r/n,d=r%n,g=o-s*l,u=i-a*l;r=n,n=d,o=s,i=a,s=g,a=u}if(r!==de)throw new Error("invert: does not exist");return be(o,e)}function $o(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function Ba(t,e){let n=(t.ORDER+de)/Ea,r=t.pow(e,n);return $o(t,r,e),r}function Wu(t,e){let n=(t.ORDER-va)/Sa,r=t.mul(e,wt),o=t.pow(r,n),i=t.mul(e,o),s=t.mul(t.mul(i,wt),o),a=t.mul(i,t.sub(s,t.ONE));return $o(t,a,e),a}function Yu(t){let e=et(t),n=Aa(t),r=n(e,e.neg(e.ONE)),o=n(e,r),i=n(e,e.neg(r)),s=(t+Zu)/ka;return(a,c)=>{let l=a.pow(c,s),d=a.mul(l,r),g=a.mul(l,o),u=a.mul(l,i),f=a.eql(a.sqr(d),c),y=a.eql(a.sqr(g),c);l=a.cmov(l,d,f),d=a.cmov(u,g,y);let m=a.eql(a.sqr(d),c),v=a.cmov(l,d,m);return $o(a,v,c),v}}function Aa(t){if(t<xa)throw new Error("sqrt is not defined for small field");let e=t-de,n=0;for(;e%wt===ge;)e/=wt,n++;let r=wt,o=et(t);for(;wa(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Ba;let i=o.pow(r,e),s=(e+de)/wt;return function(c,l){if(c.is0(l))return l;if(wa(c,l)!==1)throw new Error("Cannot find square root");let d=n,g=c.mul(c.ONE,i),u=c.pow(l,e),f=c.pow(l,s);for(;!c.eql(u,c.ONE);){if(c.is0(u))return c.ZERO;let y=1,m=c.sqr(u);for(;!c.eql(m,c.ONE);)if(y++,m=c.sqr(m),y===d)throw new Error("Cannot find square root");let v=de<<BigInt(d-y-1),R=c.pow(g,v);d=y,g=c.sqr(R),u=c.mul(u,g),f=c.mul(f,R)}return f}}function Ju(t){return t%Ea===xa?Ba:t%Sa===va?Wu:t%ka===Gu?Yu(t):Aa(t)}var Xu=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Vo(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=Xu.reduce((r,o)=>(r[o]="function",r),e);return mn(t,n),t}function Fu(t,e,n){if(n<ge)throw new Error("invalid exponent, negatives unsupported");if(n===ge)return t.ONE;if(n===de)return e;let r=t.ONE,o=e;for(;n>ge;)n&de&&(r=t.mul(r,o)),o=t.sqr(o),n>>=de;return r}function gr(t,e,n=!1){let r=new Array(e.length).fill(n?t.ZERO:void 0),o=e.reduce((s,a,c)=>t.is0(a)?s:(r[c]=s,t.mul(s,a)),t.ONE),i=t.inv(o);return e.reduceRight((s,a,c)=>t.is0(a)?s:(r[c]=t.mul(s,r[c]),t.mul(s,a)),i),r}function wa(t,e){let n=(t.ORDER-de)/wt,r=t.pow(e,n),o=t.eql(r,t.ONE),i=t.eql(r,t.ZERO),s=t.eql(r,t.neg(t.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function pr(t,e){e!==void 0&&hn(e);let n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function et(t,e,n=!1,r={}){if(t<=ge)throw new Error("invalid field: expected ORDER > 0, got "+t);let o,i,s=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");let u=e;u.BITS&&(o=u.BITS),u.sqrt&&(i=u.sqrt),typeof u.isLE=="boolean"&&(n=u.isLE),typeof u.modFromBytes=="boolean"&&(s=u.modFromBytes),a=u.allowedLengths}else typeof e=="number"&&(o=e),r.sqrt&&(i=r.sqrt);let{nBitLength:c,nByteLength:l}=pr(t,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d,g=Object.freeze({ORDER:t,isLE:n,BITS:c,BYTES:l,MASK:Qe(c),ZERO:ge,ONE:de,allowedLengths:a,create:u=>be(u,t),isValid:u=>{if(typeof u!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof u);return ge<=u&&u<t},is0:u=>u===ge,isValidNot0:u=>!g.is0(u)&&g.isValid(u),isOdd:u=>(u&de)===de,neg:u=>be(-u,t),eql:(u,f)=>u===f,sqr:u=>be(u*u,t),add:(u,f)=>be(u+f,t),sub:(u,f)=>be(u-f,t),mul:(u,f)=>be(u*f,t),pow:(u,f)=>Fu(g,u,f),div:(u,f)=>be(u*ma(f,t),t),sqrN:u=>u*u,addN:(u,f)=>u+f,subN:(u,f)=>u-f,mulN:(u,f)=>u*f,inv:u=>ma(u,t),sqrt:i||(u=>(d||(d=Ju(t)),d(g,u))),toBytes:u=>n?qo(u,l):$t(u,l),fromBytes:(u,f=!0)=>{if(a){if(!a.includes(u.length)||u.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+u.length);let m=new Uint8Array(l);m.set(u,n?0:m.length-u.length),u=m}if(u.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+u.length);let y=n?Mo(u):De(u);if(s&&(y=be(y,t)),!f&&!g.isValid(y))throw new Error("invalid field element: outside of range 0..ORDER");return y},invertBatch:u=>gr(g,u),cmov:(u,f,y)=>y?f:u});return Object.freeze(g)}function Ra(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function Ko(t){let e=Ra(t);return e+Math.ceil(e/2)}function yr(t,e,n=!1){let r=t.length,o=Ra(e),i=Ko(e);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let s=n?Mo(t):De(t),a=be(s,e-de)+de;return n?qo(a,o):$t(a,o)}var Vt=BigInt(0),xt=BigInt(1);function wn(t,e){let n=e.negate();return t?n:e}function mr(t,e){let n=gr(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function Ia(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function zo(t,e){Ia(t,e);let n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,i=Qe(t),s=BigInt(t);return{windows:n,windowSize:r,mask:i,maxNumber:o,shiftBy:s}}function Ca(t,e,n){let{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n,a=Number(t&o),c=t>>s;a>r&&(a-=i,c+=xt);let l=e*r,d=l+Math.abs(a)-1,g=a===0,u=a<0,f=e%2!==0;return{nextN:c,offset:d,isZero:g,isNeg:u,isNegF:f,offsetF:l}}function Qu(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function ef(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}var jo=new WeakMap,Na=new WeakMap;function Zo(t){return Na.get(t)||1}function Ta(t){if(t!==Vt)throw new Error("invalid wNAF")}var br=class{constructor(e,n){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>Vt;)n&xt&&(r=r.add(o)),o=o.double(),n>>=xt;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=zo(n,this.bits),i=[],s=e,a=s;for(let c=0;c<r;c++){a=s,i.push(a);for(let l=1;l<o;l++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,s=zo(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:d,isNeg:g,isNegF:u,offsetF:f}=Ca(r,a,s);r=c,d?i=i.add(wn(u,n[f])):o=o.add(wn(g,n[l]))}return Ta(r),{p:o,f:i}}wNAFUnsafe(e,n,r,o=this.ZERO){let i=zo(e,this.bits);for(let s=0;s<i.windows&&r!==Vt;s++){let{nextN:a,offset:c,isZero:l,isNeg:d}=Ca(r,s,i);if(r=a,!l){let g=n[c];o=o.add(d?g.negate():g)}}return Ta(r),o}getPrecomputes(e,n,r){let o=jo.get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),jo.set(n,o))),o}cached(e,n,r){let o=Zo(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){let i=Zo(e);return i===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),n,o)}createCache(e,n){Ia(n,this.bits),Na.set(e,n),jo.delete(e)}hasCache(e){return Zo(e)!==1}};function _a(t,e,n,r){let o=e,i=t.ZERO,s=t.ZERO;for(;n>Vt||r>Vt;)n&xt&&(i=i.add(o)),r&xt&&(s=s.add(o)),o=o.double(),n>>=xt,r>>=xt;return{p1:i,p2:s}}function Ua(t,e,n,r){Qu(n,t),ef(r,e);let o=n.length,i=r.length;if(o!==i)throw new Error("arrays of points and scalars must have equal length");let s=t.ZERO,a=hr(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let l=Qe(c),d=new Array(Number(l)+1).fill(s),g=Math.floor((e.BITS-1)/c)*c,u=s;for(let f=g;f>=0;f-=c){d.fill(s);for(let m=0;m<i;m++){let v=r[m],R=Number(v>>BigInt(f)&l);d[R]=d[R].add(n[m])}let y=s;for(let m=d.length-1,v=s;m>0;m--)v=v.add(d[m]),y=y.add(v);if(u=u.add(y),f!==0)for(let m=0;m<c;m++)u=u.double()}return u}function La(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Vo(e),e}else return et(t,{isLE:n})}function Oa(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>Vt))throw new Error(`CURVE.${c} must be positive bigint`)}let o=La(e.p,n.Fp,r),i=La(e.n,n.Fn,r),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:i}}var Pa=(t,e)=>(t+(t>=0?e:-e)/Ha)/e;function tf(t,e,n){let[[r,o],[i,s]]=e,a=Pa(s*t,n),c=Pa(-o*t,n),l=t-a*r-c*i,d=-a*o-c*s,g=l<Ve,u=d<Ve;g&&(l=-l),u&&(d=-d);let f=Qe(Math.ceil(hr(n)/2))+Kt;if(l<Ve||l>=f||d<Ve||d>=f)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:g,k1:l,k2neg:u,k2:d}}function Wo(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Go(t,e){let n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return pn(n.lowS,"lowS"),pn(n.prehash,"prehash"),n.format!==void 0&&Wo(n.format),n}var Yo=class extends Error{constructor(e=""){super(e)}},$e={Err:Yo,_tlv:{encode:(t,e)=>{let{Err:n}=$e;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");let r=e.length/2,o=yn(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");let i=r>127?yn(o.length/2|128):"";return yn(t)+i+o+e},decode(t,e){let{Err:n}=$e,r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");let o=e[r++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");let l=e.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(let d of l)s=s<<8|d;if(r+=c,s<128)throw new n("tlv.decode(long): not minimal encoding")}let a=e.subarray(r,r+s);if(a.length!==s)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+s)}}},_int:{encode(t){let{Err:e}=$e;if(t<Ve)throw new e("integer: negative integers are not allowed");let n=yn(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){let{Err:e}=$e;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return De(t)}},toSig(t){let{Err:e,_int:n,_tlv:r}=$e,o=re("signature",t),{v:i,l:s}=r.decode(48,o);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=r.decode(2,i),{v:l,l:d}=r.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(t){let{_tlv:e,_int:n}=$e,r=e.encode(2,n.encode(t.r)),o=e.encode(2,n.encode(t.s)),i=r+o;return e.encode(48,i)}},Ve=BigInt(0),Kt=BigInt(1),Ha=BigInt(2),wr=BigInt(3),nf=BigInt(4);function tt(t,e){let{BYTES:n}=t,r;if(typeof e=="bigint")r=e;else{let o=re("private key",e);try{r=t.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof e}`)}}if(!t.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function rf(t,e={}){let n=Oa("weierstrass",t,e),{Fp:r,Fn:o}=n,i=n.CURVE,{h:s,n:a}=i;mn(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=e;if(c&&(!r.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=qa(r,o);function d(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function g(T,x,p){let{x:h,y:b}=x.toAffine(),E=r.toBytes(h);if(pn(p,"isCompressed"),p){d();let B=!r.isOdd(b);return pe(Ma(B),E)}else return pe(Uint8Array.of(4),E,r.toBytes(b))}function u(T){Fe(T,void 0,"Point");let{publicKey:x,publicKeyUncompressed:p}=l,h=T.length,b=T[0],E=T.subarray(1);if(h===x&&(b===2||b===3)){let B=r.fromBytes(E);if(!r.isValid(B))throw new Error("bad point: is not on curve, wrong x");let w=m(B),A;try{A=r.sqrt(w)}catch(P){let D=P instanceof Error?": "+P.message:"";throw new Error("bad point: is not on curve, sqrt error"+D)}d();let k=r.isOdd(A);return(b&1)===1!==k&&(A=r.neg(A)),{x:B,y:A}}else if(h===p&&b===4){let B=r.BYTES,w=r.fromBytes(E.subarray(0,B)),A=r.fromBytes(E.subarray(B,B*2));if(!v(w,A))throw new Error("bad point: is not on curve");return{x:w,y:A}}else throw new Error(`bad point: got length ${h}, expected compressed=${x} or uncompressed=${p}`)}let f=e.toBytes||g,y=e.fromBytes||u;function m(T){let x=r.sqr(T),p=r.mul(x,T);return r.add(r.add(p,r.mul(T,i.a)),i.b)}function v(T,x){let p=r.sqr(x),h=m(T);return r.eql(p,h)}if(!v(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let R=r.mul(r.pow(i.a,wr),nf),O=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(R,O)))throw new Error("bad curve params: a or b");function I(T,x,p=!1){if(!r.isValid(x)||p&&r.is0(x))throw new Error(`bad point coordinate ${T}`);return x}function N(T){if(!(T instanceof L))throw new Error("ProjectivePoint expected")}function _(T){if(!c||!c.basises)throw new Error("no endo");return tf(T,c.basises,o.ORDER)}let q=Do((T,x)=>{let{X:p,Y:h,Z:b}=T;if(r.eql(b,r.ONE))return{x:p,y:h};let E=T.is0();x==null&&(x=E?r.ONE:r.inv(b));let B=r.mul(p,x),w=r.mul(h,x),A=r.mul(b,x);if(E)return{x:r.ZERO,y:r.ZERO};if(!r.eql(A,r.ONE))throw new Error("invZ was invalid");return{x:B,y:w}}),j=Do(T=>{if(T.is0()){if(e.allowInfinityPoint&&!r.is0(T.Y))return;throw new Error("bad point: ZERO")}let{x,y:p}=T.toAffine();if(!r.isValid(x)||!r.isValid(p))throw new Error("bad point: x or y not field elements");if(!v(x,p))throw new Error("bad point: equation left != right");if(!T.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Z(T,x,p,h,b){return p=new L(r.mul(p.X,T),p.Y,p.Z),x=wn(h,x),p=wn(b,p),x.add(p)}class L{constructor(x,p,h){this.X=I("x",x),this.Y=I("y",p,!0),this.Z=I("z",h),Object.freeze(this)}static CURVE(){return i}static fromAffine(x){let{x:p,y:h}=x||{};if(!x||!r.isValid(p)||!r.isValid(h))throw new Error("invalid affine point");if(x instanceof L)throw new Error("projective point not allowed");return r.is0(p)&&r.is0(h)?L.ZERO:new L(p,h,r.ONE)}static fromBytes(x){let p=L.fromAffine(y(Fe(x,void 0,"point")));return p.assertValidity(),p}static fromHex(x){return L.fromBytes(re("pointHex",x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,p=!0){return $.createCache(this,x),p||this.multiply(wr),this}assertValidity(){j(this)}hasEvenY(){let{y:x}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(x)}equals(x){N(x);let{X:p,Y:h,Z:b}=this,{X:E,Y:B,Z:w}=x,A=r.eql(r.mul(p,w),r.mul(E,b)),k=r.eql(r.mul(h,w),r.mul(B,b));return A&&k}negate(){return new L(this.X,r.neg(this.Y),this.Z)}double(){let{a:x,b:p}=i,h=r.mul(p,wr),{X:b,Y:E,Z:B}=this,w=r.ZERO,A=r.ZERO,k=r.ZERO,C=r.mul(b,b),P=r.mul(E,E),D=r.mul(B,B),M=r.mul(b,E);return M=r.add(M,M),k=r.mul(b,B),k=r.add(k,k),w=r.mul(x,k),A=r.mul(h,D),A=r.add(w,A),w=r.sub(P,A),A=r.add(P,A),A=r.mul(w,A),w=r.mul(M,w),k=r.mul(h,k),D=r.mul(x,D),M=r.sub(C,D),M=r.mul(x,M),M=r.add(M,k),k=r.add(C,C),C=r.add(k,C),C=r.add(C,D),C=r.mul(C,M),A=r.add(A,C),D=r.mul(E,B),D=r.add(D,D),C=r.mul(D,M),w=r.sub(w,C),k=r.mul(D,P),k=r.add(k,k),k=r.add(k,k),new L(w,A,k)}add(x){N(x);let{X:p,Y:h,Z:b}=this,{X:E,Y:B,Z:w}=x,A=r.ZERO,k=r.ZERO,C=r.ZERO,P=i.a,D=r.mul(i.b,wr),M=r.mul(p,E),U=r.mul(h,B),V=r.mul(b,w),W=r.add(p,h),K=r.add(E,B);W=r.mul(W,K),K=r.add(M,U),W=r.sub(W,K),K=r.add(p,b);let G=r.add(E,w);return K=r.mul(K,G),G=r.add(M,V),K=r.sub(K,G),G=r.add(h,b),A=r.add(B,w),G=r.mul(G,A),A=r.add(U,V),G=r.sub(G,A),C=r.mul(P,K),A=r.mul(D,V),C=r.add(A,C),A=r.sub(U,C),C=r.add(U,C),k=r.mul(A,C),U=r.add(M,M),U=r.add(U,M),V=r.mul(P,V),K=r.mul(D,K),U=r.add(U,V),V=r.sub(M,V),V=r.mul(P,V),K=r.add(K,V),M=r.mul(U,K),k=r.add(k,M),M=r.mul(G,K),A=r.mul(W,A),A=r.sub(A,M),M=r.mul(W,U),C=r.mul(G,C),C=r.add(C,M),new L(A,k,C)}subtract(x){return this.add(x.negate())}is0(){return this.equals(L.ZERO)}multiply(x){let{endo:p}=e;if(!o.isValidNot0(x))throw new Error("invalid scalar: out of range");let h,b,E=B=>$.cached(this,B,w=>mr(L,w));if(p){let{k1neg:B,k1:w,k2neg:A,k2:k}=_(x),{p:C,f:P}=E(w),{p:D,f:M}=E(k);b=P.add(M),h=Z(p.beta,C,D,B,A)}else{let{p:B,f:w}=E(x);h=B,b=w}return mr(L,[h,b])[0]}multiplyUnsafe(x){let{endo:p}=e,h=this;if(!o.isValid(x))throw new Error("invalid scalar: out of range");if(x===Ve||h.is0())return L.ZERO;if(x===Kt)return h;if($.hasCache(this))return this.multiply(x);if(p){let{k1neg:b,k1:E,k2neg:B,k2:w}=_(x),{p1:A,p2:k}=_a(L,h,E,w);return Z(p.beta,A,k,b,B)}else return $.unsafe(h,x)}multiplyAndAddUnsafe(x,p,h){let b=this.multiplyUnsafe(p).add(x.multiplyUnsafe(h));return b.is0()?void 0:b}toAffine(x){return q(this,x)}isTorsionFree(){let{isTorsionFree:x}=e;return s===Kt?!0:x?x(L,this):$.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:x}=e;return s===Kt?this:x?x(L,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(x=!0){return pn(x,"isCompressed"),this.assertValidity(),f(L,this,x)}toHex(x=!0){return le(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(x=!0){return this.toBytes(x)}_setWindowSize(x){this.precompute(x)}static normalizeZ(x){return mr(L,x)}static msm(x,p){return Ua(L,o,x,p)}static fromPrivateKey(x){return L.BASE.multiply(tt(o,x))}}L.BASE=new L(i.Gx,i.Gy,r.ONE),L.ZERO=new L(r.ZERO,r.ONE,r.ZERO),L.Fp=r,L.Fn=o;let z=o.BITS,$=new br(L,e.endo?Math.ceil(z/2):z);return L.BASE.precompute(8),L}function Ma(t){return Uint8Array.of(t?2:3)}function qa(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function of(t,e={}){let{Fn:n}=t,r=e.randomBytes||mt,o=Object.assign(qa(t.Fp,n),{seed:Ko(n.ORDER)});function i(f){try{return!!tt(n,f)}catch{return!1}}function s(f,y){let{publicKey:m,publicKeyUncompressed:v}=o;try{let R=f.length;return y===!0&&R!==m||y===!1&&R!==v?!1:!!t.fromBytes(f)}catch{return!1}}function a(f=r(o.seed)){return yr(Fe(f,o.seed,"seed"),n.ORDER)}function c(f,y=!0){return t.BASE.multiply(tt(n,f)).toBytes(y)}function l(f){let y=a(f);return{secretKey:y,publicKey:c(y)}}function d(f){if(typeof f=="bigint")return!1;if(f instanceof t)return!0;let{secretKey:y,publicKey:m,publicKeyUncompressed:v}=o;if(n.allowedLengths||y===m)return;let R=re("key",f).length;return R===m||R===v}function g(f,y,m=!0){if(d(f)===!0)throw new Error("first arg must be private key");if(d(y)===!1)throw new Error("second arg must be public key");let v=tt(n,f);return t.fromHex(y).multiply(v).toBytes(m)}return Object.freeze({getPublicKey:c,getSharedSecret:g,keygen:l,Point:t,utils:{isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:f=>tt(n,f),precompute(f=8,y=t.BASE){return y.precompute(f,!1)}},lengths:o})}function sf(t,e,n={}){ar(e),mn(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=n.randomBytes||mt,o=n.hmac||((p,...h)=>Uo(e,p,pe(...h))),{Fp:i,Fn:s}=t,{ORDER:a,BITS:c}=s,{keygen:l,getPublicKey:d,getSharedSecret:g,utils:u,lengths:f}=of(t,n),y={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function v(p){let h=a>>Kt;return p>h}function R(p,h){if(!s.isValidNot0(h))throw new Error(`invalid signature ${p}: out of range 1..Point.Fn.ORDER`);return h}function O(p,h){Wo(h);let b=f.signature,E=h==="compact"?b:h==="recovered"?b+1:void 0;return Fe(p,E,`${h} signature`)}class I{constructor(h,b,E){this.r=R("r",h),this.s=R("s",b),E!=null&&(this.recovery=E),Object.freeze(this)}static fromBytes(h,b=m){O(h,b);let E;if(b==="der"){let{r:k,s:C}=$e.toSig(Fe(h));return new I(k,C)}b==="recovered"&&(E=h[0],b="compact",h=h.subarray(1));let B=s.BYTES,w=h.subarray(0,B),A=h.subarray(B,B*2);return new I(s.fromBytes(w),s.fromBytes(A),E)}static fromHex(h,b){return this.fromBytes(bt(h),b)}addRecoveryBit(h){return new I(this.r,this.s,h)}recoverPublicKey(h){let b=i.ORDER,{r:E,s:B,recovery:w}=this;if(w==null||![0,1,2,3].includes(w))throw new Error("recovery id invalid");if(a*Ha<b&&w>1)throw new Error("recovery id is ambiguous for h>1 curve");let k=w===2||w===3?E+a:E;if(!i.isValid(k))throw new Error("recovery id 2 or 3 invalid");let C=i.toBytes(k),P=t.fromBytes(pe(Ma((w&1)===0),C)),D=s.inv(k),M=_(re("msgHash",h)),U=s.create(-M*D),V=s.create(B*D),W=t.BASE.multiplyUnsafe(U).add(P.multiplyUnsafe(V));if(W.is0())throw new Error("point at infinify");return W.assertValidity(),W}hasHighS(){return v(this.s)}toBytes(h=m){if(Wo(h),h==="der")return bt($e.hexFromSig(this));let b=s.toBytes(this.r),E=s.toBytes(this.s);if(h==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return pe(Uint8Array.of(this.recovery),b,E)}return pe(b,E)}toHex(h){return le(this.toBytes(h))}assertValidity(){}static fromCompact(h){return I.fromBytes(re("sig",h),"compact")}static fromDER(h){return I.fromBytes(re("sig",h),"der")}normalizeS(){return this.hasHighS()?new I(this.r,s.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return le(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return le(this.toBytes("compact"))}}let N=n.bits2int||function(h){if(h.length>8192)throw new Error("input is too large");let b=De(h),E=h.length*8-c;return E>0?b>>BigInt(E):b},_=n.bits2int_modN||function(h){return s.create(N(h))},q=Qe(c);function j(p){return ya("num < 2^"+c,p,Ve,q),s.toBytes(p)}function Z(p,h){return Fe(p,void 0,"message"),h?Fe(e(p),void 0,"prehashed message"):p}function L(p,h,b){if(["recovered","canonical"].some(U=>U in b))throw new Error("sign() legacy options not supported");let{lowS:E,prehash:B,extraEntropy:w}=Go(b,y);p=Z(p,B);let A=_(p),k=tt(s,h),C=[j(k),j(A)];if(w!=null&&w!==!1){let U=w===!0?r(f.secretKey):w;C.push(re("extraEntropy",U))}let P=pe(...C),D=A;function M(U){let V=N(U);if(!s.isValidNot0(V))return;let W=s.inv(V),K=t.BASE.multiply(V).toAffine(),G=s.create(K.x);if(G===Ve)return;let oe=s.create(W*s.create(D+G*k));if(oe===Ve)return;let Xt=(K.x===G?0:2)|Number(K.y&Kt),Ft=oe;return E&&v(oe)&&(Ft=s.neg(oe),Xt^=1),new I(G,Ft,Xt)}return{seed:P,k2sig:M}}function z(p,h,b={}){p=re("message",p);let{seed:E,k2sig:B}=L(p,h,b);return ba(e.outputLen,s.BYTES,o)(E,B)}function $(p){let h,b=typeof p=="string"||pt(p),E=!b&&p!==null&&typeof p=="object"&&typeof p.r=="bigint"&&typeof p.s=="bigint";if(!b&&!E)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(E)h=new I(p.r,p.s);else if(b){try{h=I.fromBytes(re("sig",p),"der")}catch(B){if(!(B instanceof $e.Err))throw B}if(!h)try{h=I.fromBytes(re("sig",p),"compact")}catch{return!1}}return h||!1}function T(p,h,b,E={}){let{lowS:B,prehash:w,format:A}=Go(E,y);if(b=re("publicKey",b),h=Z(re("message",h),w),"strict"in E)throw new Error("options.strict was renamed to lowS");let k=A===void 0?$(p):I.fromBytes(re("sig",p),A);if(k===!1)return!1;try{let C=t.fromBytes(b);if(B&&k.hasHighS())return!1;let{r:P,s:D}=k,M=_(h),U=s.inv(D),V=s.create(M*U),W=s.create(P*U),K=t.BASE.multiplyUnsafe(V).add(C.multiplyUnsafe(W));return K.is0()?!1:s.create(K.x)===P}catch{return!1}}function x(p,h,b={}){let{prehash:E}=Go(b,y);return h=Z(h,E),I.fromBytes(p,"recovered").recoverPublicKey(h).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:g,utils:u,lengths:f,Point:t,sign:z,verify:T,recoverPublicKey:x,Signature:I,hash:e})}function af(t){let e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp,r=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(s=>Math.ceil(s/2)))):void 0,o=et(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),i={Fp:n,Fn:o,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:i}}function cf(t){let{CURVE:e,curveOpts:n}=af(t),r={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:n,hash:t.hash,ecdsaOpts:r}}function lf(t,e){let n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,pr(n.Fn.ORDER,n.Fn.BITS))})}function Da(t){let{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:o}=cf(t),i=rf(e,n),s=sf(i,r,o);return lf(t,s)}function $a(t,e){let n=r=>Da({...t,hash:r});return{...n(e),create:n}}var zt={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},uf={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},ff=BigInt(0),Va=BigInt(1),Jo=BigInt(2);function df(t){let e=zt.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,d=l*l*t%e,g=me(d,n,e)*d%e,u=me(g,n,e)*d%e,f=me(u,Jo,e)*l%e,y=me(f,o,e)*f%e,m=me(y,i,e)*y%e,v=me(m,a,e)*m%e,R=me(v,c,e)*v%e,O=me(R,a,e)*m%e,I=me(O,n,e)*d%e,N=me(I,s,e)*y%e,_=me(N,r,e)*l%e,q=me(_,Jo,e);if(!xr.eql(xr.sqr(q),t))throw new Error("Cannot find square root");return q}var xr=et(zt.p,{sqrt:df}),ja=$a({...zt,Fp:xr,lowS:!0,endo:uf},Dt),Ka={};function Er(t,...e){let n=Ka[t];if(n===void 0){let r=Dt(lr(t));n=pe(r,r),Ka[t]=n}return Dt(pe(n,...e))}var Fo=t=>t.toBytes(!0).slice(1),jt=ja.Point,Qo=t=>t%Jo===ff;function Xo(t){let{Fn:e,BASE:n}=jt,r=tt(e,t),o=n.multiply(r);return{scalar:Qo(o.y)?r:e.neg(r),bytes:Fo(o)}}function Za(t){let e=xr;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x \u2265 p");let n=e.create(t*t),r=e.create(n*t+BigInt(7)),o=e.sqrt(r);Qo(o)||(o=e.neg(o));let i=jt.fromAffine({x:t,y:o});return i.assertValidity(),i}var xn=De;function Ga(...t){return jt.Fn.create(xn(Er("BIP0340/challenge",...t)))}function za(t){return Xo(t).bytes}function hf(t,e,n=mt(32)){let{Fn:r}=jt,o=re("message",t),{bytes:i,scalar:s}=Xo(e),a=re("auxRand",n,32),c=r.toBytes(s^xn(Er("BIP0340/aux",a))),l=Er("BIP0340/nonce",c,i,o),{bytes:d,scalar:g}=Xo(l),u=Ga(d,i,o),f=new Uint8Array(64);if(f.set(d,0),f.set(r.toBytes(r.create(g+u*s)),32),!Wa(f,o,i))throw new Error("sign: Invalid signature produced");return f}function Wa(t,e,n){let{Fn:r,BASE:o}=jt,i=re("signature",t,64),s=re("message",e),a=re("publicKey",n,32);try{let c=Za(xn(a)),l=xn(i.subarray(0,32));if(!bn(l,Va,zt.p))return!1;let d=xn(i.subarray(32,64));if(!bn(d,Va,zt.n))return!1;let g=Ga(r.toBytes(l),Fo(c),s),u=o.multiplyUnsafe(d).add(c.multiplyUnsafe(r.neg(g))),{x:f,y}=u.toAffine();return!(u.is0()||!Qo(y)||f!==l)}catch{return!1}}var Te=(()=>{let n=(o=mt(48))=>yr(o,zt.n);ja.utils.randomSecretKey;function r(o){let i=n(o);return{secretKey:i,publicKey:za(i)}}return{keygen:r,getPublicKey:za,sign:hf,verify:Wa,Point:jt,utils:{randomSecretKey:n,randomPrivateKey:n,taggedHash:Er,lift_x:Za,pointToBytes:Fo,numberToBytesBE:$t,bytesToNumberBE:De,mod:be},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();var ei=Dt;function gf(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function pf(){let t=new Uint8Array(16);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function vr(t,e){let n=t.find(r=>r[0]===e);return n?n[1]:void 0}function Ke(t){let e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n++)e[n]=parseInt(t.substr(n*2,2),16);return e}async function yf(t){if(!t.id||!t.pubkey||!t.sig||!t.tags||t.kind!==30470||!/^[0-9a-f]{128}$/i.test(t.sig)||!/^[0-9a-f]{64}$/i.test(t.pubkey)||!/^[0-9a-f]{64}$/i.test(t.id)||t.tags.length>100||t.content.length>65536||t.tags.some(s=>s.some(a=>a.length>1024)))return!1;let e=t.tags.map(s=>s[0]);if(!e.includes("tier")||!e.includes("age-range")||!e.includes("entity-type"))return!1;let n=JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content]),r=new TextEncoder,o=ei(r.encode(n));if(le(o)!==t.id.toLowerCase())return!1;try{let s=Ke(t.sig),a=Ke(t.id),c=Ke(t.pubkey);return Te.verify(s,a,c)}catch{return!1}}function bf(t,e){if(t===e||t==="18+"&&e==="18+")return!0;let n=["0-3","4-7","8-12","13-17","18+"],r=n.indexOf(t),o=n.indexOf(e);return r===-1||o===-1?!1:e==="18+"?t==="18+":t===e}async function mf(t,e){if(e==null||!/^https:\/\//i.test(e)||!/^[0-9a-f]{64}$/i.test(t))return null;try{let n=await fetch(`${e}/status/${t}`,{signal:AbortSignal.timeout(5e3)});if(!n.ok)return null;let r=await n.json();if(typeof r!="object"||r===null)return null;let o=r;return{confirmed:o.confirmed===!0,method:["A","B","C","D"].includes(o.method)?o.method:null,profession:typeof o.profession=="string"?o.profession:void 0,jurisdiction:typeof o.jurisdiction=="string"?o.jurisdiction:void 0}}catch{return null}}async function wf(t,e){if(!["0-3","4-7","8-12","13-17","18+"].includes(t))return{verified:!1,ageRange:null,tier:null,entityType:null,credentialId:null,verifierPubkey:null,verifierConfirmed:null,verifierMethod:null,issuedAt:null,expiresAt:null,error:"invalid-age-range"};let r={requiredAgeRange:t,relayUrl:e?.relayUrl||"wss://relay.damus.io",theme:e?.theme||"auto",timeout:e?.timeout||12e4,verifierCheckUrl:e?.verifierCheckUrl!==void 0?e.verifierCheckUrl:"https://verify.signet.forgesworn.dev",acceptUnconfirmed:e?.acceptUnconfirmed||!1,...e};r.timeout=Math.max(5e3,Math.min(r.timeout??12e4,6e5));let o=pf(),i={type:"signet-verify-request",requestId:o,requiredAgeRange:r.requiredAgeRange,relayUrl:r.relayUrl,timestamp:Math.floor(Date.now()/1e3)},s=JSON.stringify(i),a=btoa(s);return new Promise(c=>{let l=document.createElement("style");l.textContent="#signet-verify-dialog::backdrop{background:rgba(0,0,0,0.7)}",document.head.appendChild(l);let d=r.theme==="dark"||r.theme==="auto"&&window.matchMedia("(prefers-color-scheme: dark)").matches,g=d?"#1a1a2e":"#ffffff",u=d?"#e0e0e0":"#1a1a2e",f=d?"#888":"#666",y=document.createElement("dialog");y.id="signet-verify-dialog",y.style.cssText=`border:none;border-radius:16px;padding:32px;max-width:380px;width:90%;text-align:center;box-shadow:0 20px 60px rgba(0,0,0,0.3);background:${g};color:${u};font-family:system-ui,-apple-system,sans-serif;`,y.innerHTML=`
|
|
8
|
+
`;return typeof r=="function"&&r(null,u),u}});var Jc=X(Rn=>{var yd=Fa(),ki=Kc(),Yc=jc(),bd=Wc();function Bi(t,e,n,r,o){let i=[].slice.call(arguments,1),s=i.length,a=typeof i[s-1]=="function";if(!a&&!yd())throw new Error("Callback required as last argument");if(a){if(s<2)throw new Error("Too few arguments provided");s===2?(o=n,n=e,e=r=void 0):s===3&&(e.getContext&&typeof o>"u"?(o=r,r=void 0):(o=r,r=n,n=e,e=void 0))}else{if(s<1)throw new Error("Too few arguments provided");return s===1?(n=e,e=r=void 0):s===2&&!e.getContext&&(r=n,n=e,e=void 0),new Promise(function(c,l){try{let d=ki.create(n,r);c(t(d,e,r))}catch(d){l(d)}})}try{let c=ki.create(n,r);o(null,t(c,e,r))}catch(c){o(c)}}Rn.create=ki.create;Rn.toCanvas=Bi.bind(null,Yc.render);Rn.toDataURL=Bi.bind(null,Yc.renderToDataURL);Rn.toString=Bi.bind(null,function(t,e,n){return bd.render(t,n)})});var Id={};ul(Id,{handleCallback:()=>tl,handleRedirectCallback:()=>nl,isAndroid:()=>sr,login:()=>Qc,logout:()=>rl,restoreSession:()=>el});var je={relayUrl:"wss://relay.damus.io",signetAppOrigin:"https://mysignet.app",timeout:12e4,theme:"auto",persist:!0,mode:"relay"},Tn=300*1e3,F={pubkey:"signet:login.pubkey",method:"signet:login.method",authEvent:"signet:login.authEvent",bunkerUri:"signet:login.bunkerUri",bunkerClientSk:"signet:login.bunkerClientSk",clientSk:"signet:login.clientSk",expiresAt:"signet:login.expiresAt",displayName:"signet:login.displayName",pendingRedirect:"signet:login.pendingRedirect"};function Qt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function we(t,e=""){if(!Number.isSafeInteger(t)||t<0){let n=e&&`"${e}" `;throw new Error(`${n}expected integer >= 0, got ${t}`)}}function Y(t,e,n=""){let r=Qt(t),o=t?.length,i=e!==void 0;if(!r||i&&o!==e){let s=n&&`"${n}" `,a=i?` of length ${e}`:"",c=r?`length=${o}`:`type=${typeof t}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return t}function st(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash must wrapped by utils.createHasher");we(t.outputLen),we(t.blockLen)}function At(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Li(t,e){Y(t,void 0,"digestInto() output");let n=e.outputLen;if(t.length<n)throw new Error('"digestInto() output" expected to be of length >='+n)}function Ie(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Ln(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Se(t,e){return t<<32-e|t>>>e}var Ii=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",hl=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ee(t){if(Y(t),Ii)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=hl[t[n]];return e}var Le={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ti(t){if(t>=Le._0&&t<=Le._9)return t-Le._0;if(t>=Le.A&&t<=Le.F)return t-(Le.A-10);if(t>=Le.a&&t<=Le.f)return t-(Le.a-10)}function ne(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Ii)return Uint8Array.fromHex(t);let e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let o=0,i=0;o<n;o++,i+=2){let s=Ti(t.charCodeAt(i)),a=Ti(t.charCodeAt(i+1));if(s===void 0||a===void 0){let c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}r[o]=s*16+a}return r}function te(...t){let e=0;for(let r=0;r<t.length;r++){let o=t[r];Y(o),e+=o.length}let n=new Uint8Array(e);for(let r=0,o=0;r<t.length;r++){let i=t[r];n.set(i,o),o+=i.length}return n}function Ni(t,e={}){let n=(o,i)=>t(i).update(o).digest(),r=t(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.create=o=>t(o),Object.assign(n,e),Object.freeze(n)}function ke(t=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(t))}var _i=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function Ui(t,e,n){return t&e^~t&n}function Oi(t,e,n){return t&e^t&n^e&n}var In=class{constructor(e,n,r,o){S(this,"blockLen");S(this,"outputLen");S(this,"padOffset");S(this,"isLE");S(this,"buffer");S(this,"view");S(this,"finished",!1);S(this,"length",0);S(this,"pos",0);S(this,"destroyed",!1);this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Ln(this.buffer)}update(e){At(this),Y(e);let{view:n,buffer:r,blockLen:o}=this,i=e.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=Ln(e);for(;o<=i-s;s+=o)this.process(c,s);continue}r.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){At(this),Li(e,this),this.finished=!0;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,Ie(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(r,0),s=0);for(let g=s;g<o;g++)n[g]=0;r.setBigUint64(o-8,BigInt(this.length*8),i),this.process(r,0);let a=Ln(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let g=0;g<l;g++)a.setUint32(4*g,d[g],i)}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:i,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=i,e.length=o,e.pos=a,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}},Ne=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var gl=Uint32Array.from([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]),Ze=new Uint32Array(64),Or=class extends In{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:n,C:r,D:o,E:i,F:s,G:a,H:c}=this;return[e,n,r,o,i,s,a,c]}set(e,n,r,o,i,s,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,n){for(let g=0;g<16;g++,n+=4)Ze[g]=e.getUint32(n,!1);for(let g=16;g<64;g++){let u=Ze[g-15],f=Ze[g-2],y=Se(u,7)^Se(u,18)^u>>>3,m=Se(f,17)^Se(f,19)^f>>>10;Ze[g]=m+Ze[g-7]+y+Ze[g-16]|0}let{A:r,B:o,C:i,D:s,E:a,F:c,G:l,H:d}=this;for(let g=0;g<64;g++){let u=Se(a,6)^Se(a,11)^Se(a,25),f=d+u+Ui(a,c,l)+gl[g]+Ze[g]|0,m=(Se(r,2)^Se(r,13)^Se(r,22))+Oi(r,o,i)|0;d=l,l=c,c=a,a=s+f|0,s=i,i=o,o=r,r=f+m|0}r=r+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(r,o,i,s,a,c,l,d)}roundClean(){Ie(Ze)}destroy(){this.set(0,0,0,0,0,0,0,0),Ie(this.buffer)}},Pr=class extends Or{constructor(){super(32);S(this,"A",Ne[0]|0);S(this,"B",Ne[1]|0);S(this,"C",Ne[2]|0);S(this,"D",Ne[3]|0);S(this,"E",Ne[4]|0);S(this,"F",Ne[5]|0);S(this,"G",Ne[6]|0);S(this,"H",Ne[7]|0)}};var ue=Ni(()=>new Pr,_i(1));var Mr=BigInt(0),Hr=BigInt(1);function en(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}" `;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function Pi(t){if(typeof t=="bigint"){if(!Nn(t))throw new Error("positive bigint expected, got "+t)}else we(t);return t}function tn(t){let e=Pi(t).toString(16);return e.length&1?"0"+e:e}function Hi(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Mr:BigInt("0x"+t)}function Ge(t){return Hi(ee(t))}function qr(t){return Hi(ee(pl(Y(t)).reverse()))}function _n(t,e){we(e),t=Pi(t);let n=ne(t.toString(16).padStart(e*2,"0"));if(n.length!==e)throw new Error("number too large");return n}function Dr(t,e){return _n(t,e).reverse()}function pl(t){return Uint8Array.from(t)}function Mi(t){return Uint8Array.from(t,(e,n)=>{let r=e.charCodeAt(0);if(e.length!==1||r>127)throw new Error(`string contains non-ASCII character "${t[n]}" with code ${r} at position ${n}`);return r})}var Nn=t=>typeof t=="bigint"&&Mr<=t;function yl(t,e,n){return Nn(t)&&Nn(e)&&Nn(n)&&e<=t&&t<n}function qi(t,e,n,r){if(!yl(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function $r(t){let e;for(e=0;t>Mr;t>>=Hr,e+=1);return e}var nn=t=>(Hr<<BigInt(t))-Hr;function Di(t,e,n){if(we(t,"hashLen"),we(e,"qByteLen"),typeof n!="function")throw new Error("hmacFn must be a function");let r=v=>new Uint8Array(v),o=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1e3,c=r(t),l=r(t),d=0,g=()=>{c.fill(1),l.fill(0),d=0},u=(...v)=>n(l,te(c,...v)),f=(v=o)=>{l=u(i,v),c=u(),v.length!==0&&(l=u(s,v),c=u())},y=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let v=0,R=[];for(;v<e;){c=u();let O=c.slice();R.push(O),v+=c.length}return te(...R)};return(v,R)=>{g(),f(v);let O;for(;!(O=R(y()));)f();return g(),O}}function rn(t,e={},n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(i,s,a){let c=t[i];if(a&&c===void 0)return;let l=typeof c;if(l!==s||c===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${l}`)}let o=(i,s)=>Object.entries(i).forEach(([a,c])=>r(a,c,s));o(e,!1),o(n,!0)}function Vr(t){let e=new WeakMap;return(n,...r)=>{let o=e.get(n);if(o!==void 0)return o;let i=t(n,...r);return e.set(n,i),i}}var he=BigInt(0),fe=BigInt(1),at=BigInt(2),Ki=BigInt(3),zi=BigInt(4),ji=BigInt(5),bl=BigInt(7),Zi=BigInt(8),ml=BigInt(9),Gi=BigInt(16);function Be(t,e){let n=t%e;return n>=he?n:e+n}function ye(t,e,n){let r=t;for(;e-- >he;)r*=r,r%=n;return r}function $i(t,e){if(t===he)throw new Error("invert: expected non-zero number");if(e<=he)throw new Error("invert: expected positive modulus, got "+e);let n=Be(t,e),r=e,o=he,i=fe,s=fe,a=he;for(;n!==he;){let l=r/n,d=r%n,g=o-s*l,u=i-a*l;r=n,n=d,o=s,i=a,s=g,a=u}if(r!==fe)throw new Error("invert: does not exist");return Be(o,e)}function zr(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function Wi(t,e){let n=(t.ORDER+fe)/zi,r=t.pow(e,n);return zr(t,r,e),r}function wl(t,e){let n=(t.ORDER-ji)/Zi,r=t.mul(e,at),o=t.pow(r,n),i=t.mul(e,o),s=t.mul(t.mul(i,at),o),a=t.mul(i,t.sub(s,t.ONE));return zr(t,a,e),a}function xl(t){let e=Rt(t),n=Yi(t),r=n(e,e.neg(e.ONE)),o=n(e,r),i=n(e,e.neg(r)),s=(t+bl)/Gi;return(a,c)=>{let l=a.pow(c,s),d=a.mul(l,r),g=a.mul(l,o),u=a.mul(l,i),f=a.eql(a.sqr(d),c),y=a.eql(a.sqr(g),c);l=a.cmov(l,d,f),d=a.cmov(u,g,y);let m=a.eql(a.sqr(d),c),v=a.cmov(l,d,m);return zr(a,v,c),v}}function Yi(t){if(t<Ki)throw new Error("sqrt is not defined for small field");let e=t-fe,n=0;for(;e%at===he;)e/=at,n++;let r=at,o=Rt(t);for(;Vi(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Wi;let i=o.pow(r,e),s=(e+fe)/at;return function(c,l){if(c.is0(l))return l;if(Vi(c,l)!==1)throw new Error("Cannot find square root");let d=n,g=c.mul(c.ONE,i),u=c.pow(l,e),f=c.pow(l,s);for(;!c.eql(u,c.ONE);){if(c.is0(u))return c.ZERO;let y=1,m=c.sqr(u);for(;!c.eql(m,c.ONE);)if(y++,m=c.sqr(m),y===d)throw new Error("Cannot find square root");let v=fe<<BigInt(d-y-1),R=c.pow(g,v);d=y,g=c.sqr(R),u=c.mul(u,g),f=c.mul(f,R)}return f}}function El(t){return t%zi===Ki?Wi:t%Zi===ji?wl:t%Gi===ml?xl(t):Yi(t)}var vl=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function jr(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},n=vl.reduce((r,o)=>(r[o]="function",r),e);return rn(t,n),t}function Sl(t,e,n){if(n<he)throw new Error("invalid exponent, negatives unsupported");if(n===he)return t.ONE;if(n===fe)return e;let r=t.ONE,o=e;for(;n>he;)n&fe&&(r=t.mul(r,o)),o=t.sqr(o),n>>=fe;return r}function Un(t,e,n=!1){let r=new Array(e.length).fill(n?t.ZERO:void 0),o=e.reduce((s,a,c)=>t.is0(a)?s:(r[c]=s,t.mul(s,a)),t.ONE),i=t.inv(o);return e.reduceRight((s,a,c)=>t.is0(a)?s:(r[c]=t.mul(s,r[c]),t.mul(s,a)),i),r}function Vi(t,e){let n=(t.ORDER-fe)/at,r=t.pow(e,n),o=t.eql(r,t.ONE),i=t.eql(r,t.ZERO),s=t.eql(r,t.neg(t.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function kl(t,e){e!==void 0&&we(e);let n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}var Kr=class{constructor(e,n={}){S(this,"ORDER");S(this,"BITS");S(this,"BYTES");S(this,"isLE");S(this,"ZERO",he);S(this,"ONE",fe);S(this,"_lengths");S(this,"_sqrt");S(this,"_mod");if(e<=he)throw new Error("invalid field: expected ORDER > 0, got "+e);let r;this.isLE=!1,n!=null&&typeof n=="object"&&(typeof n.BITS=="number"&&(r=n.BITS),typeof n.sqrt=="function"&&(this.sqrt=n.sqrt),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=n.allowedLengths?.slice()),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));let{nBitLength:o,nByteLength:i}=kl(e,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return Be(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return he<=e&&e<this.ORDER}is0(e){return e===he}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&fe)===fe}neg(e){return Be(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return Be(e*e,this.ORDER)}add(e,n){return Be(e+n,this.ORDER)}sub(e,n){return Be(e-n,this.ORDER)}mul(e,n){return Be(e*n,this.ORDER)}pow(e,n){return Sl(this,e,n)}div(e,n){return Be(e*$i(n,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return $i(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=El(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Dr(e,this.BYTES):_n(e,this.BYTES)}fromBytes(e,n=!1){Y(e);let{_lengths:r,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(r){if(!r.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,i?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=i?qr(e):Ge(e);if(a&&(c=Be(c,s)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Un(this,e)}cmov(e,n,r){return r?n:e}};function Rt(t,e={}){return new Kr(t,e)}function Ji(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function Zr(t){let e=Ji(t);return e+Math.ceil(e/2)}function On(t,e,n=!1){Y(t);let r=t.length,o=Ji(e),i=Zr(e);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let s=n?qr(t):Ge(t),a=Be(s,e-fe)+fe;return n?Dr(a,o):_n(a,o)}var Ct=BigInt(0),ct=BigInt(1);function on(t,e){let n=e.negate();return t?n:e}function Jr(t,e){let n=Un(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function es(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Gr(t,e){es(t,e);let n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,i=nn(t),s=BigInt(t);return{windows:n,windowSize:r,mask:i,maxNumber:o,shiftBy:s}}function Xi(t,e,n){let{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n,a=Number(t&o),c=t>>s;a>r&&(a-=i,c+=ct);let l=e*r,d=l+Math.abs(a)-1,g=a===0,u=a<0,f=e%2!==0;return{nextN:c,offset:d,isZero:g,isNeg:u,isNegF:f,offsetF:l}}var Wr=new WeakMap,ts=new WeakMap;function Yr(t){return ts.get(t)||1}function Fi(t){if(t!==Ct)throw new Error("invalid wNAF")}var Pn=class{constructor(e,n){S(this,"BASE");S(this,"ZERO");S(this,"Fn");S(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>Ct;)n&ct&&(r=r.add(o)),o=o.double(),n>>=ct;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=Gr(n,this.bits),i=[],s=e,a=s;for(let c=0;c<r;c++){a=s,i.push(a);for(let l=1;l<o;l++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,s=Gr(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:d,isNeg:g,isNegF:u,offsetF:f}=Xi(r,a,s);r=c,d?i=i.add(on(u,n[f])):o=o.add(on(g,n[l]))}return Fi(r),{p:o,f:i}}wNAFUnsafe(e,n,r,o=this.ZERO){let i=Gr(e,this.bits);for(let s=0;s<i.windows&&r!==Ct;s++){let{nextN:a,offset:c,isZero:l,isNeg:d}=Xi(r,s,i);if(r=a,!l){let g=n[c];o=o.add(d?g.negate():g)}}return Fi(r),o}getPrecomputes(e,n,r){let o=Wr.get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),Wr.set(n,o))),o}cached(e,n,r){let o=Yr(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){let i=Yr(e);return i===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),n,o)}createCache(e,n){es(n,this.bits),ts.set(e,n),Wr.delete(e)}hasCache(e){return Yr(e)!==1}};function ns(t,e,n,r){let o=e,i=t.ZERO,s=t.ZERO;for(;n>Ct||r>Ct;)n&ct&&(i=i.add(o)),r&ct&&(s=s.add(o)),o=o.double(),n>>=ct,r>>=ct;return{p1:i,p2:s}}function Qi(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return jr(e),e}else return Rt(t,{isLE:n})}function rs(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>Ct))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Qi(e.p,n.Fp,r),i=Qi(e.n,n.Fn,r),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:i}}function Hn(t,e){return function(r){let o=t(r);return{secretKey:o,publicKey:e(o)}}}var Mn=class{constructor(e,n){S(this,"oHash");S(this,"iHash");S(this,"blockLen");S(this,"outputLen");S(this,"finished",!1);S(this,"destroyed",!1);if(st(e),Y(n,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,o=new Uint8Array(r);o.set(n.length>r?e.create().update(n).digest():n);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),Ie(o)}update(e){return At(this),this.iHash.update(e),this}digestInto(e){At(this),Y(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:n,iHash:r,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ce=(t,e,n)=>new Mn(t,e).update(n).digest();Ce.create=(t,e)=>new Mn(t,e);var os=(t,e)=>(t+(t>=0?e:-e)/is)/e;function Bl(t,e,n){let[[r,o],[i,s]]=e,a=os(s*t,n),c=os(-o*t,n),l=t-a*r-c*i,d=-a*o-c*s,g=l<_e,u=d<_e;g&&(l=-l),u&&(d=-d);let f=nn(Math.ceil($r(n)/2))+Tt;if(l<_e||l>=f||d<_e||d>=f)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:g,k1:l,k2neg:u,k2:d}}function Fr(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Xr(t,e){let n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return en(n.lowS,"lowS"),en(n.prehash,"prehash"),n.format!==void 0&&Fr(n.format),n}var Qr=class extends Error{constructor(e=""){super(e)}},We={Err:Qr,_tlv:{encode:(t,e)=>{let{Err:n}=We;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");let r=e.length/2,o=tn(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");let i=r>127?tn(o.length/2|128):"";return tn(t)+i+o+e},decode(t,e){let{Err:n}=We,r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");let o=e[r++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");let l=e.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(let d of l)s=s<<8|d;if(r+=c,s<128)throw new n("tlv.decode(long): not minimal encoding")}let a=e.subarray(r,r+s);if(a.length!==s)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+s)}}},_int:{encode(t){let{Err:e}=We;if(t<_e)throw new e("integer: negative integers are not allowed");let n=tn(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){let{Err:e}=We;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Ge(t)}},toSig(t){let{Err:e,_int:n,_tlv:r}=We,o=Y(t,void 0,"signature"),{v:i,l:s}=r.decode(48,o);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=r.decode(2,i),{v:l,l:d}=r.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(t){let{_tlv:e,_int:n}=We,r=e.encode(2,n.encode(t.r)),o=e.encode(2,n.encode(t.s)),i=r+o;return e.encode(48,i)}},_e=BigInt(0),Tt=BigInt(1),is=BigInt(2),qn=BigInt(3),Al=BigInt(4);function ss(t,e={}){let n=rs("weierstrass",t,e),{Fp:r,Fn:o}=n,i=n.CURVE,{h:s,n:a}=i;rn(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!r.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=cs(r,o);function d(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function g(x,p,h){let{x:b,y:E}=p.toAffine(),B=r.toBytes(b);if(en(h,"isCompressed"),h){d();let w=!r.isOdd(E);return te(as(w),B)}else return te(Uint8Array.of(4),B,r.toBytes(E))}function u(x){Y(x,void 0,"Point");let{publicKey:p,publicKeyUncompressed:h}=l,b=x.length,E=x[0],B=x.subarray(1);if(b===p&&(E===2||E===3)){let w=r.fromBytes(B);if(!r.isValid(w))throw new Error("bad point: is not on curve, wrong x");let A=m(w),k;try{k=r.sqrt(A)}catch(D){let M=D instanceof Error?": "+D.message:"";throw new Error("bad point: is not on curve, sqrt error"+M)}d();let C=r.isOdd(k);return(E&1)===1!==C&&(k=r.neg(k)),{x:w,y:k}}else if(b===h&&E===4){let w=r.BYTES,A=r.fromBytes(B.subarray(0,w)),k=r.fromBytes(B.subarray(w,w*2));if(!v(A,k))throw new Error("bad point: is not on curve");return{x:A,y:k}}else throw new Error(`bad point: got length ${b}, expected compressed=${p} or uncompressed=${h}`)}let f=e.toBytes||g,y=e.fromBytes||u;function m(x){let p=r.sqr(x),h=r.mul(p,x);return r.add(r.add(h,r.mul(x,i.a)),i.b)}function v(x,p){let h=r.sqr(p),b=m(x);return r.eql(h,b)}if(!v(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let R=r.mul(r.pow(i.a,qn),Al),O=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(R,O)))throw new Error("bad curve params: a or b");function I(x,p,h=!1){if(!r.isValid(p)||h&&r.is0(p))throw new Error(`bad point coordinate ${x}`);return p}function N(x){if(!(x instanceof L))throw new Error("Weierstrass Point expected")}function _(x){if(!c||!c.basises)throw new Error("no endo");return Bl(x,c.basises,o.ORDER)}let q=Vr((x,p)=>{let{X:h,Y:b,Z:E}=x;if(r.eql(E,r.ONE))return{x:h,y:b};let B=x.is0();p==null&&(p=B?r.ONE:r.inv(E));let w=r.mul(h,p),A=r.mul(b,p),k=r.mul(E,p);if(B)return{x:r.ZERO,y:r.ZERO};if(!r.eql(k,r.ONE))throw new Error("invZ was invalid");return{x:w,y:A}}),j=Vr(x=>{if(x.is0()){if(e.allowInfinityPoint&&!r.is0(x.Y))return;throw new Error("bad point: ZERO")}let{x:p,y:h}=x.toAffine();if(!r.isValid(p)||!r.isValid(h))throw new Error("bad point: x or y not field elements");if(!v(p,h))throw new Error("bad point: equation left != right");if(!x.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Z(x,p,h,b,E){return h=new L(r.mul(h.X,x),h.Y,h.Z),p=on(b,p),h=on(E,h),p.add(h)}let T=class T{constructor(p,h,b){S(this,"X");S(this,"Y");S(this,"Z");this.X=I("x",p),this.Y=I("y",h,!0),this.Z=I("z",b),Object.freeze(this)}static CURVE(){return i}static fromAffine(p){let{x:h,y:b}=p||{};if(!p||!r.isValid(h)||!r.isValid(b))throw new Error("invalid affine point");if(p instanceof T)throw new Error("projective point not allowed");return r.is0(h)&&r.is0(b)?T.ZERO:new T(h,b,r.ONE)}static fromBytes(p){let h=T.fromAffine(y(Y(p,void 0,"point")));return h.assertValidity(),h}static fromHex(p){return T.fromBytes(ne(p))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,h=!0){return $.createCache(this,p),h||this.multiply(qn),this}assertValidity(){j(this)}hasEvenY(){let{y:p}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(p)}equals(p){N(p);let{X:h,Y:b,Z:E}=this,{X:B,Y:w,Z:A}=p,k=r.eql(r.mul(h,A),r.mul(B,E)),C=r.eql(r.mul(b,A),r.mul(w,E));return k&&C}negate(){return new T(this.X,r.neg(this.Y),this.Z)}double(){let{a:p,b:h}=i,b=r.mul(h,qn),{X:E,Y:B,Z:w}=this,A=r.ZERO,k=r.ZERO,C=r.ZERO,P=r.mul(E,E),D=r.mul(B,B),M=r.mul(w,w),U=r.mul(E,B);return U=r.add(U,U),C=r.mul(E,w),C=r.add(C,C),A=r.mul(p,C),k=r.mul(b,M),k=r.add(A,k),A=r.sub(D,k),k=r.add(D,k),k=r.mul(A,k),A=r.mul(U,A),C=r.mul(b,C),M=r.mul(p,M),U=r.sub(P,M),U=r.mul(p,U),U=r.add(U,C),C=r.add(P,P),P=r.add(C,P),P=r.add(P,M),P=r.mul(P,U),k=r.add(k,P),M=r.mul(B,w),M=r.add(M,M),P=r.mul(M,U),A=r.sub(A,P),C=r.mul(M,D),C=r.add(C,C),C=r.add(C,C),new T(A,k,C)}add(p){N(p);let{X:h,Y:b,Z:E}=this,{X:B,Y:w,Z:A}=p,k=r.ZERO,C=r.ZERO,P=r.ZERO,D=i.a,M=r.mul(i.b,qn),U=r.mul(h,B),V=r.mul(b,w),W=r.mul(E,A),K=r.add(h,b),G=r.add(B,w);K=r.mul(K,G),G=r.add(U,V),K=r.sub(K,G),G=r.add(h,E);let oe=r.add(B,A);return G=r.mul(G,oe),oe=r.add(U,W),G=r.sub(G,oe),oe=r.add(b,E),k=r.add(w,A),oe=r.mul(oe,k),k=r.add(V,W),oe=r.sub(oe,k),P=r.mul(D,G),k=r.mul(M,W),P=r.add(k,P),k=r.sub(V,P),P=r.add(V,P),C=r.mul(k,P),V=r.add(U,U),V=r.add(V,U),W=r.mul(D,W),G=r.mul(M,G),V=r.add(V,W),W=r.sub(U,W),W=r.mul(D,W),G=r.add(G,W),U=r.mul(V,G),C=r.add(C,U),U=r.mul(oe,G),k=r.mul(K,k),k=r.sub(k,U),U=r.mul(K,V),P=r.mul(oe,P),P=r.add(P,U),new T(k,C,P)}subtract(p){return this.add(p.negate())}is0(){return this.equals(T.ZERO)}multiply(p){let{endo:h}=e;if(!o.isValidNot0(p))throw new Error("invalid scalar: out of range");let b,E,B=w=>$.cached(this,w,A=>Jr(T,A));if(h){let{k1neg:w,k1:A,k2neg:k,k2:C}=_(p),{p:P,f:D}=B(A),{p:M,f:U}=B(C);E=D.add(U),b=Z(h.beta,P,M,w,k)}else{let{p:w,f:A}=B(p);b=w,E=A}return Jr(T,[b,E])[0]}multiplyUnsafe(p){let{endo:h}=e,b=this;if(!o.isValid(p))throw new Error("invalid scalar: out of range");if(p===_e||b.is0())return T.ZERO;if(p===Tt)return b;if($.hasCache(this))return this.multiply(p);if(h){let{k1neg:E,k1:B,k2neg:w,k2:A}=_(p),{p1:k,p2:C}=ns(T,b,B,A);return Z(h.beta,k,C,E,w)}else return $.unsafe(b,p)}toAffine(p){return q(this,p)}isTorsionFree(){let{isTorsionFree:p}=e;return s===Tt?!0:p?p(T,this):$.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:p}=e;return s===Tt?this:p?p(T,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(p=!0){return en(p,"isCompressed"),this.assertValidity(),f(T,this,p)}toHex(p=!0){return ee(this.toBytes(p))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};S(T,"BASE",new T(i.Gx,i.Gy,r.ONE)),S(T,"ZERO",new T(r.ZERO,r.ONE,r.ZERO)),S(T,"Fp",r),S(T,"Fn",o);let L=T,z=o.BITS,$=new Pn(L,e.endo?Math.ceil(z/2):z);return L.BASE.precompute(8),L}function as(t){return Uint8Array.of(t?2:3)}function cs(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Rl(t,e={}){let{Fn:n}=t,r=e.randomBytes||ke,o=Object.assign(cs(t.Fp,n),{seed:Zr(n.ORDER)});function i(f){try{let y=n.fromBytes(f);return n.isValidNot0(y)}catch{return!1}}function s(f,y){let{publicKey:m,publicKeyUncompressed:v}=o;try{let R=f.length;return y===!0&&R!==m||y===!1&&R!==v?!1:!!t.fromBytes(f)}catch{return!1}}function a(f=r(o.seed)){return On(Y(f,o.seed,"seed"),n.ORDER)}function c(f,y=!0){return t.BASE.multiply(n.fromBytes(f)).toBytes(y)}function l(f){let{secretKey:y,publicKey:m,publicKeyUncompressed:v}=o;if(!Qt(f)||"_lengths"in n&&n._lengths||y===m)return;let R=Y(f,void 0,"key").length;return R===m||R===v}function d(f,y,m=!0){if(l(f)===!0)throw new Error("first arg must be private key");if(l(y)===!1)throw new Error("second arg must be public key");let v=n.fromBytes(f);return t.fromBytes(y).multiply(v).toBytes(m)}let g={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},u=Hn(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:u,Point:t,utils:g,lengths:o})}function ls(t,e,n={}){st(e),rn(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),n=Object.assign({},n);let r=n.randomBytes||ke,o=n.hmac||((p,h)=>Ce(e,p,h)),{Fp:i,Fn:s}=t,{ORDER:a,BITS:c}=s,{keygen:l,getPublicKey:d,getSharedSecret:g,utils:u,lengths:f}=Rl(t,n),y={prehash:!0,lowS:typeof n.lowS=="boolean"?n.lowS:!0,format:"compact",extraEntropy:!1},m=a*is<i.ORDER;function v(p){let h=a>>Tt;return p>h}function R(p,h){if(!s.isValidNot0(h))throw new Error(`invalid signature ${p}: out of range 1..Point.Fn.ORDER`);return h}function O(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function I(p,h){Fr(h);let b=f.signature,E=h==="compact"?b:h==="recovered"?b+1:void 0;return Y(p,E)}class N{constructor(h,b,E){S(this,"r");S(this,"s");S(this,"recovery");if(this.r=R("r",h),this.s=R("s",b),E!=null){if(O(),![0,1,2,3].includes(E))throw new Error("invalid recovery id");this.recovery=E}Object.freeze(this)}static fromBytes(h,b=y.format){I(h,b);let E;if(b==="der"){let{r:k,s:C}=We.toSig(Y(h));return new N(k,C)}b==="recovered"&&(E=h[0],b="compact",h=h.subarray(1));let B=f.signature/2,w=h.subarray(0,B),A=h.subarray(B,B*2);return new N(s.fromBytes(w),s.fromBytes(A),E)}static fromHex(h,b){return this.fromBytes(ne(h),b)}assertRecovery(){let{recovery:h}=this;if(h==null)throw new Error("invalid recovery id: must be present");return h}addRecoveryBit(h){return new N(this.r,this.s,h)}recoverPublicKey(h){let{r:b,s:E}=this,B=this.assertRecovery(),w=B===2||B===3?b+a:b;if(!i.isValid(w))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let A=i.toBytes(w),k=t.fromBytes(te(as((B&1)===0),A)),C=s.inv(w),P=q(Y(h,void 0,"msgHash")),D=s.create(-P*C),M=s.create(E*C),U=t.BASE.multiplyUnsafe(D).add(k.multiplyUnsafe(M));if(U.is0())throw new Error("invalid recovery: point at infinify");return U.assertValidity(),U}hasHighS(){return v(this.s)}toBytes(h=y.format){if(Fr(h),h==="der")return ne(We.hexFromSig(this));let{r:b,s:E}=this,B=s.toBytes(b),w=s.toBytes(E);return h==="recovered"?(O(),te(Uint8Array.of(this.assertRecovery()),B,w)):te(B,w)}toHex(h){return ee(this.toBytes(h))}}let _=n.bits2int||function(h){if(h.length>8192)throw new Error("input is too large");let b=Ge(h),E=h.length*8-c;return E>0?b>>BigInt(E):b},q=n.bits2int_modN||function(h){return s.create(_(h))},j=nn(c);function Z(p){return qi("num < 2^"+c,p,_e,j),s.toBytes(p)}function L(p,h){return Y(p,void 0,"message"),h?Y(e(p),void 0,"prehashed message"):p}function z(p,h,b){let{lowS:E,prehash:B,extraEntropy:w}=Xr(b,y);p=L(p,B);let A=q(p),k=s.fromBytes(h);if(!s.isValidNot0(k))throw new Error("invalid private key");let C=[Z(k),Z(A)];if(w!=null&&w!==!1){let U=w===!0?r(f.secretKey):w;C.push(Y(U,void 0,"extraEntropy"))}let P=te(...C),D=A;function M(U){let V=_(U);if(!s.isValidNot0(V))return;let W=s.inv(V),K=t.BASE.multiply(V).toAffine(),G=s.create(K.x);if(G===_e)return;let oe=s.create(W*s.create(D+G*k));if(oe===_e)return;let Jt=(K.x===G?0:2)|Number(K.y&Tt),Xt=oe;return E&&v(oe)&&(Xt=s.neg(oe),Jt^=1),new N(G,Xt,m?void 0:Jt)}return{seed:P,k2sig:M}}function $(p,h,b={}){let{seed:E,k2sig:B}=z(p,h,b);return Di(e.outputLen,s.BYTES,o)(E,B).toBytes(b.format)}function T(p,h,b,E={}){let{lowS:B,prehash:w,format:A}=Xr(E,y);if(b=Y(b,void 0,"publicKey"),h=L(h,w),!Qt(p)){let k=p instanceof N?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+k)}I(p,A);try{let k=N.fromBytes(p,A),C=t.fromBytes(b);if(B&&k.hasHighS())return!1;let{r:P,s:D}=k,M=q(h),U=s.inv(D),V=s.create(M*U),W=s.create(P*U),K=t.BASE.multiplyUnsafe(V).add(C.multiplyUnsafe(W));return K.is0()?!1:s.create(K.x)===P}catch{return!1}}function x(p,h,b={}){let{prehash:E}=Xr(b,y);return h=L(h,E),N.fromBytes(p,"recovered").recoverPublicKey(h).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:g,utils:u,lengths:f,Point:t,sign:$,verify:T,recoverPublicKey:x,Signature:N,hash:e})}var Vn={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Cl={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Tl=BigInt(0),eo=BigInt(2);function Ll(t){let e=Vn.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,d=l*l*t%e,g=ye(d,n,e)*d%e,u=ye(g,n,e)*d%e,f=ye(u,eo,e)*l%e,y=ye(f,o,e)*f%e,m=ye(y,i,e)*y%e,v=ye(m,a,e)*m%e,R=ye(v,c,e)*v%e,O=ye(R,a,e)*m%e,I=ye(O,n,e)*d%e,N=ye(I,s,e)*y%e,_=ye(N,r,e)*l%e,q=ye(_,eo,e);if(!Dn.eql(Dn.sqr(q),t))throw new Error("Cannot find square root");return q}var Dn=Rt(Vn.p,{sqrt:Ll}),lt=ss(Vn,{Fp:Dn,endo:Cl}),Kn=ls(lt,ue),us={};function $n(t,...e){let n=us[t];if(n===void 0){let r=ue(Mi(t));n=te(r,r),us[t]=n}return ue(te(n,...e))}var no=t=>t.toBytes(!0).slice(1),ro=t=>t%eo===Tl;function to(t){let{Fn:e,BASE:n}=lt,r=e.fromBytes(t),o=n.multiply(r);return{scalar:ro(o.y)?r:e.neg(r),bytes:no(o)}}function ds(t){let e=Dn;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x \u2265 p");let n=e.create(t*t),r=e.create(n*t+BigInt(7)),o=e.sqrt(r);ro(o)||(o=e.neg(o));let i=lt.fromAffine({x:t,y:o});return i.assertValidity(),i}var sn=Ge;function hs(...t){return lt.Fn.create(sn($n("BIP0340/challenge",...t)))}function fs(t){return to(t).bytes}function Il(t,e,n=ke(32)){let{Fn:r}=lt,o=Y(t,void 0,"message"),{bytes:i,scalar:s}=to(e),a=Y(n,32,"auxRand"),c=r.toBytes(s^sn($n("BIP0340/aux",a))),l=$n("BIP0340/nonce",c,i,o),{bytes:d,scalar:g}=to(l),u=hs(d,i,o),f=new Uint8Array(64);if(f.set(d,0),f.set(r.toBytes(r.create(g+u*s)),32),!gs(f,o,i))throw new Error("sign: Invalid signature produced");return f}function gs(t,e,n){let{Fp:r,Fn:o,BASE:i}=lt,s=Y(t,64,"signature"),a=Y(e,void 0,"message"),c=Y(n,32,"publicKey");try{let l=ds(sn(c)),d=sn(s.subarray(0,32));if(!r.isValidNot0(d))return!1;let g=sn(s.subarray(32,64));if(!o.isValidNot0(g))return!1;let u=hs(o.toBytes(d),no(l),a),f=i.multiplyUnsafe(g).add(l.multiplyUnsafe(o.neg(u))),{x:y,y:m}=f.toAffine();return!(f.is0()||!ro(m)||y!==d)}catch{return!1}}var xe=(()=>{let n=(r=ke(48))=>On(r,Vn.n);return{keygen:Hn(n,fs),getPublicKey:fs,sign:Il,verify:gs,Point:lt,utils:{randomSecretKey:n,taggedHash:$n,lift_x:ds,pointToBytes:no},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();function Nl(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function zn(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function jn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function se(t,e,n=""){let r=Nl(t),o=t?.length,i=e!==void 0;if(!r||i&&o!==e){let s=n&&`"${n}" `,a=i?` of length ${e}`:"",c=r?`length=${o}`:`type=${typeof t}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return t}function oo(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function ps(t,e){se(t,void 0,"output");let n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function Ue(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Oe(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function _l(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}var Ul=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ys(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function Lt(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}var io=(t,e)=>{function n(r,...o){if(se(r,void 0,"key"),!Ul)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){let d=o[0];se(d,t.varSizeNonce?void 0:t.nonceLength,"nonce")}let i=t.tagLength;i&&o[1]!==void 0&&se(o[1],void 0,"AAD");let s=e(r,...o),a=(d,g)=>{if(g!==void 0){if(d!==2)throw new Error("cipher output not supported");se(g,void 0,"output")}},c=!1;return{encrypt(d,g){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,se(d),a(s.encrypt.length,g),s.encrypt(d,g)},decrypt(d,g){if(se(d),i&&d.length<i)throw new Error('"ciphertext" expected length bigger than tagLength='+i);return a(s.decrypt.length,g),s.decrypt(d,g)}}}return Object.assign(n,t),n};function so(t,e,n=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error('"output" expected Uint8Array of length '+t+", got: "+e.length);if(n&&!Ol(e))throw new Error("invalid output, must be aligned");return e}function bs(t,e,n){zn(n);let r=new Uint8Array(16),o=_l(r);return o.setBigUint64(0,BigInt(e),n),o.setBigUint64(8,BigInt(t),n),r}function Ol(t){return t.byteOffset%4===0}function It(t){return Uint8Array.from(t)}var ws=t=>Uint8Array.from(t.split(""),e=>e.charCodeAt(0)),Pl=ws("expand 16-byte k"),Hl=ws("expand 32-byte k"),Ml=Ue(Pl),ql=Ue(Hl);function H(t,e){return t<<e|t>>>32-e}function ao(t){return t.byteOffset%4===0}var Zn=64,Dl=16,xs=2**32-1,ms=Uint32Array.of();function $l(t,e,n,r,o,i,s,a){let c=o.length,l=new Uint8Array(Zn),d=Ue(l),g=ao(o)&&ao(i),u=g?Ue(o):ms,f=g?Ue(i):ms;for(let y=0;y<c;s++){if(t(e,n,r,d,s,a),s>=xs)throw new Error("arx: counter overflow");let m=Math.min(Zn,c-y);if(g&&m===Zn){let v=y/4;if(y%4!==0)throw new Error("arx: invalid block position");for(let R=0,O;R<Dl;R++)O=v+R,f[O]=u[O]^d[R];y+=Zn;continue}for(let v=0,R;v<m;v++)R=y+v,i[R]=o[R]^l[v];y+=m}}function co(t,e){let{allowShortKeys:n,extendNonceFn:r,counterLength:o,counterRight:i,rounds:s}=ys({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return jn(o),jn(s),zn(i),zn(n),(a,c,l,d,g=0)=>{se(a,void 0,"key"),se(c,void 0,"nonce"),se(l,void 0,"data");let u=l.length;if(d===void 0&&(d=new Uint8Array(u)),se(d,void 0,"output"),jn(g),g<0||g>=xs)throw new Error("arx: counter overflow");if(d.length<u)throw new Error(`arx: output (${d.length}) is shorter than data (${u})`);let f=[],y=a.length,m,v;if(y===32)f.push(m=It(a)),v=ql;else if(y===16&&n)m=new Uint8Array(32),m.set(a),m.set(a,16),v=Ml,f.push(m);else throw se(a,32,"arx key"),new Error("invalid key size");ao(c)||f.push(c=It(c));let R=Ue(m);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(v,R,Ue(c.subarray(0,16)),R),c=c.subarray(16)}let O=16-o;if(O!==c.length)throw new Error(`arx: nonce must be ${O} or 16 bytes`);if(O!==12){let N=new Uint8Array(12);N.set(c,i?0:12-c.length),c=N,f.push(c)}let I=Ue(c);return $l(t,v,R,I,l,d,g,s),Oe(...f),d}}function ce(t,e){return t[e++]&255|(t[e++]&255)<<8}var lo=class{constructor(e){S(this,"blockLen",16);S(this,"outputLen",16);S(this,"buffer",new Uint8Array(16));S(this,"r",new Uint16Array(10));S(this,"h",new Uint16Array(10));S(this,"pad",new Uint16Array(8));S(this,"pos",0);S(this,"finished",!1);e=It(se(e,32,"key"));let n=ce(e,0),r=ce(e,2),o=ce(e,4),i=ce(e,6),s=ce(e,8),a=ce(e,10),c=ce(e,12),l=ce(e,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|o<<6)&7939,this.r[3]=(o>>>7|i<<9)&8191,this.r[4]=(i>>>4|s<<12)&255,this.r[5]=s>>>1&8190,this.r[6]=(s>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let d=0;d<8;d++)this.pad[d]=ce(e,16+2*d)}process(e,n,r=!1){let o=r?0:2048,{h:i,r:s}=this,a=s[0],c=s[1],l=s[2],d=s[3],g=s[4],u=s[5],f=s[6],y=s[7],m=s[8],v=s[9],R=ce(e,n+0),O=ce(e,n+2),I=ce(e,n+4),N=ce(e,n+6),_=ce(e,n+8),q=ce(e,n+10),j=ce(e,n+12),Z=ce(e,n+14),L=i[0]+(R&8191),z=i[1]+((R>>>13|O<<3)&8191),$=i[2]+((O>>>10|I<<6)&8191),T=i[3]+((I>>>7|N<<9)&8191),x=i[4]+((N>>>4|_<<12)&8191),p=i[5]+(_>>>1&8191),h=i[6]+((_>>>14|q<<2)&8191),b=i[7]+((q>>>11|j<<5)&8191),E=i[8]+((j>>>8|Z<<8)&8191),B=i[9]+(Z>>>5|o),w=0,A=w+L*a+z*(5*v)+$*(5*m)+T*(5*y)+x*(5*f);w=A>>>13,A&=8191,A+=p*(5*u)+h*(5*g)+b*(5*d)+E*(5*l)+B*(5*c),w+=A>>>13,A&=8191;let k=w+L*c+z*a+$*(5*v)+T*(5*m)+x*(5*y);w=k>>>13,k&=8191,k+=p*(5*f)+h*(5*u)+b*(5*g)+E*(5*d)+B*(5*l),w+=k>>>13,k&=8191;let C=w+L*l+z*c+$*a+T*(5*v)+x*(5*m);w=C>>>13,C&=8191,C+=p*(5*y)+h*(5*f)+b*(5*u)+E*(5*g)+B*(5*d),w+=C>>>13,C&=8191;let P=w+L*d+z*l+$*c+T*a+x*(5*v);w=P>>>13,P&=8191,P+=p*(5*m)+h*(5*y)+b*(5*f)+E*(5*u)+B*(5*g),w+=P>>>13,P&=8191;let D=w+L*g+z*d+$*l+T*c+x*a;w=D>>>13,D&=8191,D+=p*(5*v)+h*(5*m)+b*(5*y)+E*(5*f)+B*(5*u),w+=D>>>13,D&=8191;let M=w+L*u+z*g+$*d+T*l+x*c;w=M>>>13,M&=8191,M+=p*a+h*(5*v)+b*(5*m)+E*(5*y)+B*(5*f),w+=M>>>13,M&=8191;let U=w+L*f+z*u+$*g+T*d+x*l;w=U>>>13,U&=8191,U+=p*c+h*a+b*(5*v)+E*(5*m)+B*(5*y),w+=U>>>13,U&=8191;let V=w+L*y+z*f+$*u+T*g+x*d;w=V>>>13,V&=8191,V+=p*l+h*c+b*a+E*(5*v)+B*(5*m),w+=V>>>13,V&=8191;let W=w+L*m+z*y+$*f+T*u+x*g;w=W>>>13,W&=8191,W+=p*d+h*l+b*c+E*a+B*(5*v),w+=W>>>13,W&=8191;let K=w+L*v+z*m+$*y+T*f+x*u;w=K>>>13,K&=8191,K+=p*g+h*d+b*l+E*c+B*a,w+=K>>>13,K&=8191,w=(w<<2)+w|0,w=w+A|0,A=w&8191,w=w>>>13,k+=w,i[0]=A,i[1]=k,i[2]=C,i[3]=P,i[4]=D,i[5]=M,i[6]=U,i[7]=V,i[8]=W,i[9]=K}finalize(){let{h:e,pad:n}=this,r=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,r[0]=e[0]+5,o=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+o,o=r[a]>>>13,r[a]&=8191;r[9]-=8192;let i=(o^1)-1;for(let a=0;a<10;a++)r[a]&=i;i=~i;for(let a=0;a<10;a++)e[a]=e[a]&i|r[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let s=e[0]+n[0];e[0]=s&65535;for(let a=1;a<8;a++)s=(e[a]+n[a]|0)+(s>>>16)|0,e[a]=s&65535;Oe(r)}update(e){oo(this),se(e),e=It(e);let{buffer:n,blockLen:r}=this,o=e.length;for(let i=0;i<o;){let s=Math.min(r-this.pos,o-i);if(s===r){for(;r<=o-i;i+=r)this.process(e,i);continue}n.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){Oe(this.h,this.r,this.buffer,this.pad)}digestInto(e){oo(this),ps(e,this),this.finished=!0;let{buffer:n,h:r}=this,{pos:o}=this;if(o){for(n[o++]=1;o<16;o++)n[o]=0;this.process(n,0,!0)}this.finalize();let i=0;for(let s=0;s<8;s++)e[i++]=r[s]>>>0,e[i++]=r[s]>>>8;return e}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let r=e.slice(0,n);return this.destroy(),r}};function Vl(t){let e=(r,o)=>t(o).update(r).digest(),n=t(new Uint8Array(32));return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}var Es=Vl(t=>new lo(t));function ks(t,e,n,r,o,i=20){let s=t[0],a=t[1],c=t[2],l=t[3],d=e[0],g=e[1],u=e[2],f=e[3],y=e[4],m=e[5],v=e[6],R=e[7],O=o,I=n[0],N=n[1],_=n[2],q=s,j=a,Z=c,L=l,z=d,$=g,T=u,x=f,p=y,h=m,b=v,E=R,B=O,w=I,A=N,k=_;for(let P=0;P<i;P+=2)q=q+z|0,B=H(B^q,16),p=p+B|0,z=H(z^p,12),q=q+z|0,B=H(B^q,8),p=p+B|0,z=H(z^p,7),j=j+$|0,w=H(w^j,16),h=h+w|0,$=H($^h,12),j=j+$|0,w=H(w^j,8),h=h+w|0,$=H($^h,7),Z=Z+T|0,A=H(A^Z,16),b=b+A|0,T=H(T^b,12),Z=Z+T|0,A=H(A^Z,8),b=b+A|0,T=H(T^b,7),L=L+x|0,k=H(k^L,16),E=E+k|0,x=H(x^E,12),L=L+x|0,k=H(k^L,8),E=E+k|0,x=H(x^E,7),q=q+$|0,k=H(k^q,16),b=b+k|0,$=H($^b,12),q=q+$|0,k=H(k^q,8),b=b+k|0,$=H($^b,7),j=j+T|0,B=H(B^j,16),E=E+B|0,T=H(T^E,12),j=j+T|0,B=H(B^j,8),E=E+B|0,T=H(T^E,7),Z=Z+x|0,w=H(w^Z,16),p=p+w|0,x=H(x^p,12),Z=Z+x|0,w=H(w^Z,8),p=p+w|0,x=H(x^p,7),L=L+z|0,A=H(A^L,16),h=h+A|0,z=H(z^h,12),L=L+z|0,A=H(A^L,8),h=h+A|0,z=H(z^h,7);let C=0;r[C++]=s+q|0,r[C++]=a+j|0,r[C++]=c+Z|0,r[C++]=l+L|0,r[C++]=d+z|0,r[C++]=g+$|0,r[C++]=u+T|0,r[C++]=f+x|0,r[C++]=y+p|0,r[C++]=m+h|0,r[C++]=v+b|0,r[C++]=R+E|0,r[C++]=O+B|0,r[C++]=I+w|0,r[C++]=N+A|0,r[C++]=_+k|0}function Kl(t,e,n,r){let o=t[0],i=t[1],s=t[2],a=t[3],c=e[0],l=e[1],d=e[2],g=e[3],u=e[4],f=e[5],y=e[6],m=e[7],v=n[0],R=n[1],O=n[2],I=n[3];for(let _=0;_<20;_+=2)o=o+c|0,v=H(v^o,16),u=u+v|0,c=H(c^u,12),o=o+c|0,v=H(v^o,8),u=u+v|0,c=H(c^u,7),i=i+l|0,R=H(R^i,16),f=f+R|0,l=H(l^f,12),i=i+l|0,R=H(R^i,8),f=f+R|0,l=H(l^f,7),s=s+d|0,O=H(O^s,16),y=y+O|0,d=H(d^y,12),s=s+d|0,O=H(O^s,8),y=y+O|0,d=H(d^y,7),a=a+g|0,I=H(I^a,16),m=m+I|0,g=H(g^m,12),a=a+g|0,I=H(I^a,8),m=m+I|0,g=H(g^m,7),o=o+l|0,I=H(I^o,16),y=y+I|0,l=H(l^y,12),o=o+l|0,I=H(I^o,8),y=y+I|0,l=H(l^y,7),i=i+d|0,v=H(v^i,16),m=m+v|0,d=H(d^m,12),i=i+d|0,v=H(v^i,8),m=m+v|0,d=H(d^m,7),s=s+g|0,R=H(R^s,16),u=u+R|0,g=H(g^u,12),s=s+g|0,R=H(R^s,8),u=u+R|0,g=H(g^u,7),a=a+c|0,O=H(O^a,16),f=f+O|0,c=H(c^f,12),a=a+c|0,O=H(O^a,8),f=f+O|0,c=H(c^f,7);let N=0;r[N++]=o,r[N++]=i,r[N++]=s,r[N++]=a,r[N++]=v,r[N++]=R,r[N++]=O,r[N++]=I}var ut=co(ks,{counterRight:!1,counterLength:4,allowShortKeys:!1}),zl=co(ks,{counterRight:!1,counterLength:8,extendNonceFn:Kl,allowShortKeys:!1});var jl=new Uint8Array(16),vs=(t,e)=>{t.update(e);let n=e.length%16;n&&t.update(jl.subarray(n))},Zl=new Uint8Array(32);function Ss(t,e,n,r,o){o!==void 0&&se(o,void 0,"AAD");let i=t(e,n,Zl),s=bs(r.length,o?o.length:0,!0),a=Es.create(i);o&&vs(a,o),vs(a,r),a.update(s);let c=a.digest();return Oe(i,s),c}var Bs=t=>(e,n,r)=>({encrypt(i,s){let a=i.length;s=so(a+16,s,!1),s.set(i);let c=s.subarray(0,-16);t(e,n,c,c,1);let l=Ss(t,e,n,c,r);return s.set(l,a),Oe(l),s},decrypt(i,s){s=so(i.length-16,s,!1);let a=i.subarray(0,-16),c=i.subarray(-16),l=Ss(t,e,n,a,r);if(!Lt(c,l))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),t(e,n,s,s,1),Oe(l),s}}),Oh=io({blockSize:64,nonceLength:12,tagLength:16},Bs(ut)),Ph=io({blockSize:64,nonceLength:24,tagLength:16},Bs(zl));function Gn(t,e,n){return st(t),n===void 0&&(n=new Uint8Array(t.outputLen)),Ce(t,n,e)}var uo=Uint8Array.of(0),As=Uint8Array.of();function Wn(t,e,n,r=32){st(t),we(r,"length");let o=t.outputLen;if(r>255*o)throw new Error("Length must be <= 255*HashLen");let i=Math.ceil(r/o);n===void 0?n=As:Y(n,void 0,"info");let s=new Uint8Array(i*o),a=Ce.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let d=0;d<i;d++)uo[0]=d+1,c.update(d===0?As:l).update(n).update(uo).digestInto(l),s.set(l,o*d),a._cloneInto(c);return a.destroy(),c.destroy(),Ie(l,uo),s.slice(0,r)}function po(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Gl(t){if(!po(t))throw new Error("Uint8Array expected")}function Ls(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(n=>typeof n=="string"):e.every(n=>Number.isSafeInteger(n)):!1}function Wl(t){if(typeof t!="function")throw new Error("function expected");return!0}function ft(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function yo(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function fo(t){if(!Array.isArray(t))throw new Error("array expected")}function Jn(t,e){if(!Ls(!0,e))throw new Error(`${t}: array of strings expected`)}function Is(t,e){if(!Ls(!1,e))throw new Error(`${t}: array of numbers expected`)}function Ns(...t){let e=i=>i,n=(i,s)=>a=>i(s(a)),r=t.map(i=>i.encode).reduceRight(n,e),o=t.map(i=>i.decode).reduce(n,e);return{encode:r,decode:o}}function _s(t){let e=typeof t=="string"?t.split(""):t,n=e.length;Jn("alphabet",e);let r=new Map(e.map((o,i)=>[o,i]));return{encode:o=>(fo(o),o.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${t}`);return e[i]})),decode:o=>(fo(o),o.map(i=>{ft("alphabet.decode",i);let s=r.get(i);if(s===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${t}`);return s}))}}function Us(t=""){return ft("join",t),{encode:e=>(Jn("join.decode",e),e.join(t)),decode:e=>(ft("join.decode",e),e.split(t))}}function Yl(t,e="="){return yo(t),ft("padding",e),{encode(n){for(Jn("padding.encode",n);n.length*t%8;)n.push(e);return n},decode(n){Jn("padding.decode",n);let r=n.length;if(r*t%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;r>0&&n[r-1]===e;r--)if((r-1)*t%8===0)throw new Error("padding: invalid, string has too much padding");return n.slice(0,r)}}}var Os=(t,e)=>e===0?t:Os(e,t%e),Xn=(t,e)=>t+(e-Os(t,e)),Yn=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function ho(t,e,n,r){if(fo(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(Xn(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${Xn(e,n)}`);let o=0,i=0,s=Yn[e],a=Yn[n]-1,c=[];for(let l of t){if(yo(l),l>=s)throw new Error(`convertRadix2: invalid data word=${l} from=${e}`);if(o=o<<e|l,i+e>32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${e}`);for(i+=e;i>=n;i-=n)c.push((o>>i-n&a)>>>0);let d=Yn[i];if(d===void 0)throw new Error("invalid carry");o&=d-1}if(o=o<<n-i&a,!r&&i>=e)throw new Error("Excess padding");if(!r&&o>0)throw new Error(`Non-zero padding: ${o}`);return r&&i>0&&c.push(o>>>0),c}function Ps(t,e=!1){if(yo(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Xn(8,t)>32||Xn(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!po(n))throw new Error("radix2.encode input should be Uint8Array");return ho(Array.from(n),8,t,!e)},decode:n=>(Is("radix2.decode",n),Uint8Array.from(ho(n,t,8,e)))}}function Rs(t){return Wl(t),function(...e){try{return t.apply(null,e)}catch{}}}var Jl=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",Xl=(t,e)=>{ft("base64",t);let n=e?/^[A-Za-z0-9=_-]+$/:/^[A-Za-z0-9=+/]+$/,r=e?"base64url":"base64";if(t.length>0&&!n.test(t))throw new Error("invalid base64");return Uint8Array.fromBase64(t,{alphabet:r,lastChunkHandling:"strict"})},Nt=Jl?{encode(t){return Gl(t),t.toBase64()},decode(t){return Xl(t,!1)}}:Ns(Ps(6),_s("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Yl(6),Us(""));var go=Ns(_s("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Us("")),Cs=[996825010,642813549,513874426,1027748829,705979059];function an(t){let e=t>>25,n=(t&33554431)<<5;for(let r=0;r<Cs.length;r++)(e>>r&1)===1&&(n^=Cs[r]);return n}function Ts(t,e,n=1){let r=t.length,o=1;for(let i=0;i<r;i++){let s=t.charCodeAt(i);if(s<33||s>126)throw new Error(`Invalid prefix (${t})`);o=an(o)^s>>5}o=an(o);for(let i=0;i<r;i++)o=an(o)^t.charCodeAt(i)&31;for(let i of e)o=an(o)^i;for(let i=0;i<6;i++)o=an(o);return o^=n,go.encode(ho([o%Yn[30]],30,5,!1))}function Fl(t){let e=t==="bech32"?1:734539939,n=Ps(5),r=n.decode,o=n.encode,i=Rs(r);function s(g,u,f=90){ft("bech32.encode prefix",g),po(u)&&(u=Array.from(u)),Is("bech32.encode",u);let y=g.length;if(y===0)throw new TypeError(`Invalid prefix length ${y}`);let m=y+7+u.length;if(f!==!1&&m>f)throw new TypeError(`Length ${m} exceeds limit ${f}`);let v=g.toLowerCase(),R=Ts(v,u,e);return`${v}1${go.encode(u)}${R}`}function a(g,u=90){ft("bech32.decode input",g);let f=g.length;if(f<8||u!==!1&&f>u)throw new TypeError(`invalid string length: ${f} (${g}). Expected (8..${u})`);let y=g.toLowerCase();if(g!==y&&g!==g.toUpperCase())throw new Error("String must be lowercase or uppercase");let m=y.lastIndexOf("1");if(m===0||m===-1)throw new Error('Letter "1" must be present between prefix and data only');let v=y.slice(0,m),R=y.slice(m+1);if(R.length<6)throw new Error("Data must be at least 6 characters long");let O=go.decode(R).slice(0,-6),I=Ts(v,O,e);if(!R.endsWith(I))throw new Error(`Invalid checksum in ${g}: expected "${I}"`);return{prefix:v,words:O}}let c=Rs(a);function l(g){let{prefix:u,words:f}=a(g,!1);return{prefix:u,words:f,bytes:r(f)}}function d(g,u){return s(g,o(u))}return{encode:s,decode:a,encodeFromBytes:d,decodeToBytes:l,decodeUnsafe:c,fromWords:r,fromWordsUnsafe:i,toWords:o}}var bo=Fl("bech32");var dt=Symbol("verified"),Ql=t=>t instanceof Object;function eu(t){if(!Ql(t)||typeof t.kind!="number"||typeof t.content!="string"||typeof t.created_at!="number"||typeof t.pubkey!="string"||!t.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(t.tags))return!1;for(let e=0;e<t.tags.length;e++){let n=t.tags[e];if(!Array.isArray(n))return!1;for(let r=0;r<n.length;r++)if(typeof n[r]!="string")return!1}return!0}var tu=new TextDecoder("utf-8"),vo=new TextEncoder;function cn(t){try{t.indexOf("://")===-1&&(t="wss://"+t);let e=new URL(t);return e.protocol==="http:"?e.protocol="ws:":e.protocol==="https:"&&(e.protocol="wss:"),e.pathname=e.pathname.replace(/\/+/g,"/"),e.pathname.endsWith("/")&&(e.pathname=e.pathname.slice(0,-1)),(e.port==="80"&&e.protocol==="ws:"||e.port==="443"&&e.protocol==="wss:")&&(e.port=""),e.searchParams.sort(),e.hash="",e.toString()}catch{throw new Error(`Invalid URL: ${t}`)}}var nu=class{generateSecretKey(){return xe.utils.randomSecretKey()}getPublicKey(t){return ee(xe.getPublicKey(t))}finalizeEvent(t,e){let n=t;return n.pubkey=ee(xe.getPublicKey(e)),n.id=mo(n),n.sig=ee(xe.sign(ne(mo(n)),e)),n[dt]=!0,n}verifyEvent(t){if(typeof t[dt]=="boolean")return t[dt];try{let e=mo(t);if(e!==t.id)return t[dt]=!1,!1;let n=xe.verify(ne(t.sig),ne(e),ne(t.pubkey));return t[dt]=n,n}catch{return t[dt]=!1,!1}}};function ru(t){if(!eu(t))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content])}function mo(t){let e=ue(vo.encode(ru(t)));return ee(e)}var Fn=new nu,jh=Fn.generateSecretKey,Hs=Fn.getPublicKey,ou=Fn.finalizeEvent,qs=Fn.verifyEvent,So=1,ko=4294967295,Bo=65536;function wo(t,e){let n=Kn.getSharedSecret(t,ne("02"+e)).subarray(1,33);return Gn(ue,n,vo.encode("nip44-v2"))}function Ds(t,e){let n=Wn(ue,t,e,76);return{chacha_key:n.subarray(0,32),chacha_nonce:n.subarray(32,44),hmac_key:n.subarray(44,76)}}function $s(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("expected positive integer");if(t<=32)return 32;let e=2**(Math.floor(Math.log2(t-1))+1),n=e<=256?32:e/8;return n*(Math.floor((t-1)/n)+1)}function iu(t){if(!Number.isSafeInteger(t)||t<So||t>65535)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");let e=new Uint8Array(2);return new DataView(e.buffer).setUint16(0,t,!1),e}function su(t){if(!Number.isSafeInteger(t)||t<Bo||t>ko)throw new Error("invalid plaintext size: must be between 65536 and 4294967295 bytes");let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!1),e}function au(t){let e=vo.encode(t),n=e.length;if(n<So||n>ko)throw new Error("invalid plaintext size: must be between 1 and 4294967295 bytes");let r=n>=Bo?te(new Uint8Array([0,0]),su(n)):iu(n),o=new Uint8Array($s(n)-n);return te(r,e,o)}function cu(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=e.getUint16(0),r,o;if(n===0){if(r=e.getUint32(2),r<Bo)throw new Error("invalid padding");o=6}else r=n,o=2;let i=t.subarray(o,o+r);if(r<So||r>ko||i.length!==r||t.length!==o+$s(r))throw new Error("invalid padding");return tu.decode(i)}function Vs(t,e,n){if(n.length!==32)throw new Error("AAD associated data must be 32 bytes");let r=te(n,e);return Ce(ue,t,r)}function lu(t){if(typeof t!="string")throw new Error("payload must be a valid string");let e=t.length;if(e<132)throw new Error("invalid payload length: "+e);if(t[0]==="#")throw new Error("unknown encryption version");let n;try{n=Nt.decode(t)}catch(i){throw new Error("invalid base64: "+i.message)}let r=n.length;if(r<99)throw new Error("invalid data length: "+r);let o=n[0];if(o!==2)throw new Error("unknown encryption version "+o);return{nonce:n.subarray(1,33),ciphertext:n.subarray(33,-32),mac:n.subarray(-32)}}function uu(t,e,n=ke(32)){let{chacha_key:r,chacha_nonce:o,hmac_key:i}=Ds(e,n),s=au(t),a=ut(r,o,s),c=Vs(i,a,n);return Nt.encode(te(new Uint8Array([2]),n,a,c))}function Ms(t,e){let{nonce:n,ciphertext:r,mac:o}=lu(t),{chacha_key:i,chacha_nonce:s,hmac_key:a}=Ds(e,n),c=Vs(a,r,n);if(!Lt(c,o))throw new Error("invalid MAC");let l=ut(i,s,r);return cu(l)}var fu=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,du;try{du=fetch}catch{}var hu=22242,xo=24133;function gu(t,e){if(t.ids&&t.ids.indexOf(e.id)===-1||t.kinds&&t.kinds.indexOf(e.kind)===-1||t.authors&&t.authors.indexOf(e.pubkey)===-1)return!1;for(let n in t)if(n[0]==="#"){let r=n.slice(1),o=t[`#${r}`];if(o&&!e.tags.find(([i,s])=>i===n.slice(1)&&o.indexOf(s)!==-1))return!1}return!(t.since&&e.created_at<t.since||t.until&&e.created_at>t.until)}function pu(t,e){for(let n=0;n<t.length;n++)if(gu(t[n],e))return!0;return!1}function yu(t,e){let n=e.length+3,r=t.indexOf(`"${e}":`)+n,o=t.slice(r).indexOf('"')+r+1;return t.slice(o,o+64)}function bu(t){let e=t.slice(0,22).indexOf('"EVENT"');if(e===-1)return null;let n=t.slice(e+7+1).indexOf('"');if(n===-1)return null;let r=e+7+1+n,o=t.slice(r+1,80).indexOf('"');if(o===-1)return null;let i=r+1+o;return t.slice(r+1,i)}function mu(t,e){return{kind:hu,created_at:Math.floor(Date.now()/1e3),tags:[["relay",t],["challenge",e]],content:""}}var Eo=class extends Error{constructor(t,e){super(`Tried to send message '${t} on a closed connection to ${e}.`),this.name="SendingOnClosedConnection"}},Ks=class{constructor(t,e){S(this,"url");S(this,"_connected",!1);S(this,"onclose",null);S(this,"onnotice",t=>console.debug(`NOTICE from ${this.url}: ${t}`));S(this,"onauth");S(this,"baseEoseTimeout",4400);S(this,"publishTimeout",4400);S(this,"pingFrequency",29e3);S(this,"pingTimeout",2e4);S(this,"resubscribeBackoff",[1e4,1e4,1e4,2e4,2e4,3e4,6e4]);S(this,"openSubs",new Map);S(this,"enablePing");S(this,"enableReconnect");S(this,"idleSince",Date.now());S(this,"ongoingOperations",0);S(this,"reconnectTimeoutHandle");S(this,"pingIntervalHandle");S(this,"reconnectAttempts",0);S(this,"skipReconnection",!1);S(this,"connectionPromise");S(this,"openCountRequests",new Map);S(this,"openEventPublishes",new Map);S(this,"ws");S(this,"challenge");S(this,"authPromise");S(this,"serial",0);S(this,"verifyEvent");S(this,"_WebSocket");this.url=cn(t),this.verifyEvent=e.verifyEvent,this._WebSocket=e.websocketImplementation||WebSocket,this.enablePing=e.enablePing,this.enableReconnect=e.enableReconnect||!1}static async connect(t,e){let n=new Ks(t,e);return await n.connect(e),n}closeAllSubscriptions(t){for(let[e,n]of this.openSubs)n.close(t);this.openSubs.clear();for(let[e,n]of this.openEventPublishes)n.reject(new Error(t));this.openEventPublishes.clear();for(let[e,n]of this.openCountRequests)n.reject(new Error(t));this.openCountRequests.clear()}get connected(){return this._connected}async reconnect(){let t=this.resubscribeBackoff[Math.min(this.reconnectAttempts,this.resubscribeBackoff.length-1)];this.reconnectAttempts++,this.reconnectTimeoutHandle=setTimeout(async()=>{try{await this.connect()}catch{}},t)}handleHardClose(t){this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this._connected=!1,this.connectionPromise=void 0,this.idleSince=void 0,this.enableReconnect&&!this.skipReconnection?this.reconnect():(this.onclose?.(),this.closeAllSubscriptions(t))}async connect(t){let e;return this.connectionPromise?this.connectionPromise:(this.challenge=void 0,this.authPromise=void 0,this.skipReconnection=!1,this.connectionPromise=new Promise((n,r)=>{t?.timeout&&(e=setTimeout(()=>{r("connection timed out"),this.connectionPromise=void 0,this.skipReconnection=!0,this.onclose?.(),this.handleHardClose("relay connection timed out")},t.timeout)),t?.abort&&(t.abort.onabort=r);try{this.ws=new this._WebSocket(this.url)}catch(o){clearTimeout(e),r(o);return}this.ws.onopen=()=>{this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),clearTimeout(e),this._connected=!0;let o=this.reconnectAttempts>0;this.reconnectAttempts=0;for(let i of this.openSubs.values()){if(i.eosed=!1,o)for(let s=0;s<i.filters.length;s++)i.lastEmitted&&(i.filters[s].since=i.lastEmitted+1);i.fire()}this.enablePing&&(this.pingIntervalHandle=setInterval(()=>this.pingpong(),this.pingFrequency)),n()},this.ws.onerror=()=>{clearTimeout(e),r("connection failed"),this.connectionPromise=void 0,this.skipReconnection=!0,this.onclose?.(),this.handleHardClose("relay connection failed")},this.ws.onclose=o=>{clearTimeout(e),r(o.message||"websocket closed"),this.handleHardClose("relay connection closed")},this.ws.onmessage=this._onmessage.bind(this)}),this.connectionPromise)}waitForPingPong(){return new Promise(t=>{this.ws.once("pong",()=>t(!0)),this.ws.ping()})}waitForDummyReq(){return new Promise((t,e)=>{if(!this.connectionPromise)return e(new Error(`no connection to ${this.url}, can't ping`));try{let n=this.subscribe([{ids:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],limit:0}],{label:"<forced-ping>",oneose:()=>{t(!0),n.close()},onclose(){t(!0)},eoseTimeout:this.pingTimeout+1e3})}catch(n){e(n)}})}async pingpong(){this.ws?.readyState===1&&(await Promise.any([this.ws&&this.ws.ping&&this.ws.once?this.waitForPingPong():this.waitForDummyReq(),new Promise(e=>setTimeout(()=>e(!1),this.pingTimeout))])||this.ws?.readyState===this._WebSocket.OPEN&&this.ws?.close())}async send(t){if(!this.connectionPromise)throw new Eo(t,this.url);this.connectionPromise.then(()=>{this.ws?.send(t)})}async auth(t){let e=this.challenge;if(!e)throw new Error("can't perform auth, no challenge was received");return this.authPromise?this.authPromise:(this.authPromise=new Promise(async(n,r)=>{try{let o=await t(mu(this.url,e)),i=setTimeout(()=>{let s=this.openEventPublishes.get(o.id);s&&(s.reject(new Error("auth timed out")),this.openEventPublishes.delete(o.id))},this.publishTimeout);this.openEventPublishes.set(o.id,{resolve:n,reject:r,timeout:i}),this.send('["AUTH",'+JSON.stringify(o)+"]")}catch(o){console.warn("subscribe auth function failed:",o)}}),this.authPromise)}async publish(t){this.idleSince=void 0,this.ongoingOperations++;let e=new Promise((n,r)=>{let o=setTimeout(()=>{let i=this.openEventPublishes.get(t.id);i&&(i.reject(new Error("publish timed out")),this.openEventPublishes.delete(t.id))},this.publishTimeout);this.openEventPublishes.set(t.id,{resolve:n,reject:r,timeout:o})});return this.send('["EVENT",'+JSON.stringify(t)+"]"),this.ongoingOperations--,this.ongoingOperations===0&&(this.idleSince=Date.now()),e}async count(t,e){this.serial++;let n=e?.id||"count:"+this.serial,r=new Promise((o,i)=>{this.openCountRequests.set(n,{resolve:o,reject:i})});return this.send('["COUNT","'+n+'",'+JSON.stringify(t).substring(1)),r}subscribe(t,e){e.label!=="<forced-ping>"&&(this.idleSince=void 0,this.ongoingOperations++);let n=this.prepareSubscription(t,e);return n.fire(),e.abort&&(e.abort.onabort=()=>n.close(String(e.abort.reason||"<aborted>"))),n}prepareSubscription(t,e){this.serial++;let n=e.id||(e.label?e.label+":":"sub:")+this.serial,r=new wu(this,n,t,e);return this.openSubs.set(n,r),r}close(){this.skipReconnection=!0,this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this.closeAllSubscriptions("relay connection closed by us"),this._connected=!1,this.idleSince=void 0,this.onclose?.(),this.ws?.readyState===this._WebSocket.OPEN&&this.ws?.close()}_onmessage(t){let e=t.data;if(!e)return;let n=bu(e);if(n){let r=this.openSubs.get(n);if(!r)return;let o=yu(e,"id"),i=r.alreadyHaveEvent?.(o);if(r.receivedEvent?.(this,o),i)return}try{let r=JSON.parse(e);switch(r[0]){case"EVENT":{let o=this.openSubs.get(r[1]),i=r[2];this.verifyEvent(i)&&pu(o.filters,i)?o.onevent(i):o.oninvalidevent?.(i),(!o.lastEmitted||o.lastEmitted<i.created_at)&&(o.lastEmitted=i.created_at);return}case"COUNT":{let o=r[1],i=r[2],s=this.openCountRequests.get(o);s&&(s.resolve(i.count),this.openCountRequests.delete(o));return}case"EOSE":{let o=this.openSubs.get(r[1]);if(!o)return;o.receivedEose();return}case"OK":{let o=r[1],i=r[2],s=r[3],a=this.openEventPublishes.get(o);a&&(clearTimeout(a.timeout),i?a.resolve(s):a.reject(new Error(s)),this.openEventPublishes.delete(o));return}case"CLOSED":{let o=r[1],i=this.openSubs.get(o);if(!i)return;i.closed=!0,i.close(r[2]);return}case"NOTICE":{this.onnotice(r[1]);return}case"AUTH":{this.challenge=r[1],this.onauth&&this.auth(this.onauth).catch(o=>{if(!(o instanceof Eo))throw o});return}default:{this.openSubs.get(r[1])?.oncustom?.(r);return}}}catch(r){try{let[o,i,s]=JSON.parse(e);console.warn(`[nostr] relay ${this.url} error processing message:`,r,s)}catch{console.warn(`[nostr] relay ${this.url} error processing message:`,r)}return}}},wu=class{constructor(t,e,n,r){S(this,"relay");S(this,"id");S(this,"lastEmitted");S(this,"closed",!1);S(this,"eosed",!1);S(this,"filters");S(this,"alreadyHaveEvent");S(this,"receivedEvent");S(this,"onevent");S(this,"oninvalidevent");S(this,"oneose");S(this,"onclose");S(this,"oncustom");S(this,"eoseTimeout");S(this,"eoseTimeoutHandle");if(n.length===0)throw new Error("subscription can't be created with zero filters");this.relay=t,this.filters=n,this.id=e,this.alreadyHaveEvent=r.alreadyHaveEvent,this.receivedEvent=r.receivedEvent,this.eoseTimeout=r.eoseTimeout||t.baseEoseTimeout,this.oneose=r.oneose,this.onclose=r.onclose,this.oninvalidevent=r.oninvalidevent,this.onevent=r.onevent||(o=>{console.warn(`onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,o)})}fire(){this.relay.send('["REQ","'+this.id+'",'+JSON.stringify(this.filters).substring(1)),this.eoseTimeoutHandle=setTimeout(this.receivedEose.bind(this),this.eoseTimeout)}receivedEose(){this.eosed||(clearTimeout(this.eoseTimeoutHandle),this.eosed=!0,this.oneose?.())}close(t="closed by caller"){if(!this.closed&&this.relay.connected){try{this.relay.send('["CLOSE",'+JSON.stringify(this.id)+"]")}catch(e){if(!(e instanceof Eo))throw e}this.closed=!0}this.relay.openSubs.delete(this.id),this.relay.ongoingOperations--,this.relay.ongoingOperations===0&&(this.relay.idleSince=Date.now()),this.onclose?.(t)}},xu=t=>(t[dt]=!0,!0),Eu=class{constructor(t){S(this,"relays",new Map);S(this,"seenOn",new Map);S(this,"trackRelays",!1);S(this,"verifyEvent");S(this,"enablePing");S(this,"enableReconnect");S(this,"automaticallyAuth");S(this,"trustedRelayURLs",new Set);S(this,"onRelayConnectionFailure");S(this,"onRelayConnectionSuccess");S(this,"allowConnectingToRelay");S(this,"maxWaitForConnection");S(this,"_WebSocket");this.verifyEvent=t.verifyEvent,this._WebSocket=t.websocketImplementation,this.enablePing=t.enablePing,this.enableReconnect=t.enableReconnect||!1,this.automaticallyAuth=t.automaticallyAuth,this.onRelayConnectionFailure=t.onRelayConnectionFailure,this.onRelayConnectionSuccess=t.onRelayConnectionSuccess,this.allowConnectingToRelay=t.allowConnectingToRelay,this.maxWaitForConnection=t.maxWaitForConnection||3e3}async ensureRelay(t,e){t=cn(t);let n=this.relays.get(t);if(n||(n=new Ks(t,{verifyEvent:this.trustedRelayURLs.has(t)?xu:this.verifyEvent,websocketImplementation:this._WebSocket,enablePing:this.enablePing,enableReconnect:this.enableReconnect}),n.onclose=()=>{this.relays.delete(t)},this.relays.set(t,n)),this.automaticallyAuth){let r=this.automaticallyAuth(t);r&&(n.onauth=r)}try{await n.connect({timeout:e?.connectionTimeout,abort:e?.abort})}catch(r){throw this.relays.delete(t),r}return n}close(t){t.map(cn).forEach(e=>{this.relays.get(e)?.close(),this.relays.delete(e)})}subscribe(t,e,n){let r=[],o=[];for(let i=0;i<t.length;i++){let s=cn(t[i]);r.find(a=>a.url===s)||o.indexOf(s)===-1&&(o.push(s),r.push({url:s,filter:e}))}return this.subscribeMap(r,n)}subscribeMany(t,e,n){return this.subscribe(t,e,n)}subscribeMap(t,e){let n=new Map;for(let u of t){let{url:f,filter:y}=u;n.has(f)||n.set(f,[]),n.get(f).push(y)}let r=Array.from(n.entries()).map(([u,f])=>({url:u,filters:f}));this.trackRelays&&(e.receivedEvent=(u,f)=>{let y=this.seenOn.get(f);y||(y=new Set,this.seenOn.set(f,y)),y.add(u)});let o=new Set,i=[],s=[],a=u=>{s[u]||(s[u]=!0,s.filter(f=>f).length===r.length&&(e.oneose?.(),a=()=>{}))},c=[],l=(u,f)=>{c[u]||(a(u),c[u]=f,c.filter(y=>y).length===r.length&&(e.onclose?.(c),l=()=>{}))},d=u=>{if(e.alreadyHaveEvent?.(u))return!0;let f=o.has(u);return o.add(u),f},g=Promise.all(r.map(async({url:u,filters:f},y)=>{if(this.allowConnectingToRelay?.(u,["read",f])===!1){l(y,"connection skipped by allowConnectingToRelay");return}let m;try{m=await this.ensureRelay(u,{connectionTimeout:this.maxWaitForConnection<(e.maxWait||0)?Math.max(e.maxWait*.8,e.maxWait-1e3):this.maxWaitForConnection,abort:e.abort})}catch(R){this.onRelayConnectionFailure?.(u),l(y,R?.message||String(R));return}this.onRelayConnectionSuccess?.(u);let v=m.subscribe(f,{...e,oneose:()=>a(y),onclose:R=>{R.startsWith("auth-required: ")&&e.onauth?m.auth(e.onauth).then(()=>{m.subscribe(f,{...e,oneose:()=>a(y),onclose:O=>{l(y,O)},alreadyHaveEvent:d,eoseTimeout:e.maxWait,abort:e.abort})}).catch(O=>{l(y,`auth was required and attempted, but failed with: ${O}`)}):l(y,R)},alreadyHaveEvent:d,eoseTimeout:e.maxWait,abort:e.abort});i.push(v)}));return{async close(u){await g,i.forEach(f=>{f.close(u)})}}}subscribeEose(t,e,n){let r;return r=this.subscribe(t,e,{...n,oneose(){let o="closed automatically on eose";r?r.close(o):n.onclose?.(t.map(i=>o))}}),r}subscribeManyEose(t,e,n){return this.subscribeEose(t,e,n)}async querySync(t,e,n){return new Promise(async r=>{let o=[];this.subscribeEose(t,e,{...n,onevent(i){o.push(i)},onclose(i){r(o)}})})}async get(t,e,n){e.limit=1;let r=await this.querySync(t,e,n);return r.sort((o,i)=>i.created_at-o.created_at),r[0]||null}publish(t,e,n){return t.map(cn).map(async(r,o,i)=>{if(i.indexOf(r)!==o)return Promise.reject("duplicate url");if(this.allowConnectingToRelay?.(r,["write",e])===!1)return Promise.reject("connection skipped by allowConnectingToRelay");let s;try{s=await this.ensureRelay(r,{connectionTimeout:this.maxWaitForConnection<(n?.maxWait||0)?Math.max(n.maxWait*.8,n.maxWait-1e3):this.maxWaitForConnection,abort:n?.abort})}catch(a){return this.onRelayConnectionFailure?.(r),"connection failure: "+String(a)}return s.publish(e).catch(async a=>{if(a instanceof Error&&a.message.startsWith("auth-required: ")&&n?.onauth)return await s.auth(n.onauth),s.publish(e);throw a}).then(a=>{if(this.trackRelays){let c=this.seenOn.get(e.id);c||(c=new Set,this.seenOn.set(e.id,c)),c.add(s)}return a})})}listConnectionStatus(){let t=new Map;return this.relays.forEach((e,n)=>t.set(n,e.connected)),t}destroy(){this.relays.forEach(t=>t.close()),this.relays=new Map}pruneIdleRelays(t=1e4){let e=[];for(let[n,r]of this.relays)r.idleSince&&Date.now()-r.idleSince>=t&&(this.relays.delete(n),e.push(n),r.close());return e}},zs;try{zs=WebSocket}catch{}var vu=class extends Eu{constructor(t){super({verifyEvent:qs,websocketImplementation:zs,maxWaitForConnection:3e3,...t})}},js;try{js=fetch}catch{}var Su=/^bunker:\/\/([0-9a-f]{64})\??([?\/\w:.=&%-]*)$/;async function Zs(t){let e=t.match(Su);if(e)try{let n=e[1],r=new URLSearchParams(e[2]);return{pubkey:n,relays:r.getAll("relay"),secret:r.get("secret")}}catch{}return ku(t)}async function ku(t){let e=t.match(fu);if(!e)return null;let[n,r="_",o]=e;try{let i=`https://${o}/.well-known/nostr.json?name=${r}`,s=await(await js(i,{redirect:"error"})).json(),a=s.names[r],c=s.nip46[a]||[];return{pubkey:a,relays:c,secret:null}}catch{return null}}var _t=class{constructor(t,e){S(this,"params");S(this,"pool");S(this,"subCloser");S(this,"isOpen");S(this,"serial");S(this,"idPrefix");S(this,"listeners");S(this,"waitingForAuth");S(this,"secretKey");S(this,"conversationKey");S(this,"bp");S(this,"cachedPubKey");this.params=e,this.pool=e.pool||new vu,this.secretKey=t,this.isOpen=!1,this.idPrefix=Math.random().toString(36).substring(7),this.serial=0,this.listeners={},this.waitingForAuth={}}static fromBunker(t,e,n={}){if(e.relays.length===0)throw new Error("no relays specified for this bunker");let r=new _t(t,n);return r.conversationKey=wo(t,e.pubkey),r.bp=e,r.setupSubscription(),r}static async fromURI(t,e,n={},r=3e5){let o=new _t(t,n),i=new URL(e),s=Hs(t);return new Promise((a,c)=>{let l=!1,d=o.pool.subscribe(i.searchParams.getAll("relay"),{kinds:[xo],"#p":[s],limit:0},{onevent:async g=>{try{let u=wo(t,g.pubkey),f=Ms(g.content,u);JSON.parse(f).result===i.searchParams.get("secret")&&(d.close(),o.bp={pubkey:g.pubkey,relays:i.searchParams.getAll("relay"),secret:i.searchParams.get("secret")},o.conversationKey=wo(t,g.pubkey),o.setupSubscription(),l=!0,n.skipSwitchRelays||await Promise.race([new Promise(m=>setTimeout(m,1e3)),o.switchRelays()]),a(o))}catch(u){console.warn("failed to process potential connection event",u)}},onclose:()=>{l||c(new Error("subscription closed before connection was established."))},maxWait:typeof r=="number"?r:void 0,abort:typeof r!="number"?r:void 0})})}setupSubscription(){let t=this.listeners,e=this.waitingForAuth,n=this.conversationKey;this.subCloser=this.pool.subscribe(this.bp.relays,{kinds:[xo],authors:[this.bp.pubkey],"#p":[Hs(this.secretKey)],limit:0},{onevent:async r=>{let o=JSON.parse(Ms(r.content,n)),{id:i,result:s,error:a}=o;if(s==="auth_url"&&e[i]){delete e[i],this.params.onauth?this.params.onauth(a):console.warn(`nostr-tools/nip46: remote signer ${this.bp.pubkey} tried to send an "auth_url"='${a}' but there was no onauth() callback configured.`);return}let c=t[i];c&&(a?c.reject(a):s&&c.resolve(s),delete t[i])},onclose:()=>{this.subCloser=void 0}}),this.isOpen=!0}async switchRelays(){try{let t=await this.sendRequest("switch_relays",[]),e=JSON.parse(t);if(!e||JSON.stringify(e.sort())===JSON.stringify(this.bp.relays))return!1;this.bp.relays=e;let n=this.subCloser;return setTimeout(()=>{n.close()},5e3),this.subCloser=void 0,this.setupSubscription(),!0}catch{return!1}}async close(){this.isOpen=!1,this.subCloser.close()}async sendRequest(t,e){return new Promise(async(n,r)=>{try{if(!this.isOpen)throw new Error("this signer is not open anymore, create a new one");this.subCloser||this.setupSubscription(),this.serial++;let o=`${this.idPrefix}-${this.serial}`,i=uu(JSON.stringify({id:o,method:t,params:e}),this.conversationKey),s=ou({kind:xo,tags:[["p",this.bp.pubkey]],content:i,created_at:Math.floor(Date.now()/1e3)},this.secretKey);this.listeners[o]={resolve:n,reject:r},this.waitingForAuth[o]=!0,await Promise.any(this.pool.publish(this.bp.relays,s))}catch(o){r(o)}})}async ping(){let t=await this.sendRequest("ping",[]);if(t!=="pong")throw new Error(`result is not pong: ${t}`)}async connect(){await this.sendRequest("connect",[this.bp.pubkey,this.bp.secret||""])}async getPublicKey(){return this.cachedPubKey||(this.cachedPubKey=await this.sendRequest("get_public_key",[])),this.cachedPubKey}async signEvent(t){let e=await this.sendRequest("sign_event",[JSON.stringify(t)]),n=JSON.parse(e);if(qs(n))return n;throw new Error(`event returned from bunker is improperly signed: ${JSON.stringify(n)}`)}async nip04Encrypt(t,e){return await this.sendRequest("nip04_encrypt",[t,e])}async nip04Decrypt(t,e){return await this.sendRequest("nip04_decrypt",[t,e])}async nip44Encrypt(t,e){return await this.sendRequest("nip44_encrypt",[t,e])}async nip44Decrypt(t,e){return await this.sendRequest("nip44_decrypt",[t,e])}};var Ut=Symbol("verified"),Bu=t=>t instanceof Object;function Au(t){if(!Bu(t)||typeof t.kind!="number"||typeof t.content!="string"||typeof t.created_at!="number"||typeof t.pubkey!="string"||!t.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(t.tags))return!1;for(let e=0;e<t.tags.length;e++){let n=t.tags[e];if(!Array.isArray(n))return!1;for(let r=0;r<n.length;r++)if(typeof n[r]!="string")return!1}return!0}var d0=new TextDecoder("utf-8"),Ru=new TextEncoder,Cu=class{generateSecretKey(){return xe.utils.randomSecretKey()}getPublicKey(t){return ee(xe.getPublicKey(t))}finalizeEvent(t,e){let n=t;return n.pubkey=ee(xe.getPublicKey(e)),n.id=Ao(n),n.sig=ee(xe.sign(ne(Ao(n)),e)),n[Ut]=!0,n}verifyEvent(t){if(typeof t[Ut]=="boolean")return t[Ut];try{let e=Ao(t);if(e!==t.id)return t[Ut]=!1,!1;let n=xe.verify(ne(t.sig),ne(e),ne(t.pubkey));return t[Ut]=n,n}catch{return t[Ut]=!1,!1}}};function Tu(t){if(!Au(t))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content])}function Ao(t){let e=ue(Ru.encode(Tu(t)));return ee(e)}var Qn=new Cu,h0=Qn.generateSecretKey,Gs=Qn.getPublicKey,Ws=Qn.finalizeEvent,g0=Qn.verifyEvent;var er=new TextDecoder("utf-8"),w0=new TextEncoder;var Lu=5e3;function Ys(t){let{prefix:e,words:n}=bo.decode(t,Lu),r=new Uint8Array(bo.fromWords(n));switch(e){case"nprofile":{let o=Ro(r);if(!o[0]?.[0])throw new Error("missing TLV 0 for nprofile");if(o[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:ee(o[0][0]),relays:o[1]?o[1].map(i=>er.decode(i)):[]}}}case"nevent":{let o=Ro(r);if(!o[0]?.[0])throw new Error("missing TLV 0 for nevent");if(o[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");if(o[2]&&o[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(o[3]&&o[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:ee(o[0][0]),relays:o[1]?o[1].map(i=>er.decode(i)):[],author:o[2]?.[0]?ee(o[2][0]):void 0,kind:o[3]?.[0]?parseInt(ee(o[3][0]),16):void 0}}}case"naddr":{let o=Ro(r);if(!o[0]?.[0])throw new Error("missing TLV 0 for naddr");if(!o[2]?.[0])throw new Error("missing TLV 2 for naddr");if(o[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(!o[3]?.[0])throw new Error("missing TLV 3 for naddr");if(o[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:er.decode(o[0][0]),pubkey:ee(o[2][0]),kind:parseInt(ee(o[3][0]),16),relays:o[1]?o[1].map(i=>er.decode(i)):[]}}}case"nsec":return{type:e,data:r};case"npub":case"note":return{type:e,data:ee(r)};default:throw new Error(`unknown prefix ${e}`)}}function Ro(t){let e={},n=t;for(;n.length>0;){let r=n[0],o=n[1],i=n.slice(2,2+o);if(n=n.slice(2+o),i.length<o)throw new Error(`not enough data to read on TLV ${r}`);e[r]=e[r]||[],e[r].push(i)}return e}var Iu=new TextDecoder("utf-8"),Js=new TextEncoder,Co=1,To=4294967295,Lo=65536;function Ot(t,e){let n=Kn.getSharedSecret(t,ne("02"+e)).subarray(1,33);return Gn(ue,n,Js.encode("nip44-v2"))}function Xs(t,e){let n=Wn(ue,t,e,76);return{chacha_key:n.subarray(0,32),chacha_nonce:n.subarray(32,44),hmac_key:n.subarray(44,76)}}function Fs(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("expected positive integer");if(t<=32)return 32;let e=2**(Math.floor(Math.log2(t-1))+1),n=e<=256?32:e/8;return n*(Math.floor((t-1)/n)+1)}function Nu(t){if(!Number.isSafeInteger(t)||t<Co||t>65535)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");let e=new Uint8Array(2);return new DataView(e.buffer).setUint16(0,t,!1),e}function _u(t){if(!Number.isSafeInteger(t)||t<Lo||t>To)throw new Error("invalid plaintext size: must be between 65536 and 4294967295 bytes");let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!1),e}function Uu(t){let e=Js.encode(t),n=e.length;if(n<Co||n>To)throw new Error("invalid plaintext size: must be between 1 and 4294967295 bytes");let r=n>=Lo?te(new Uint8Array([0,0]),_u(n)):Nu(n),o=new Uint8Array(Fs(n)-n);return te(r,e,o)}function Ou(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=e.getUint16(0),r,o;if(n===0){if(r=e.getUint32(2),r<Lo)throw new Error("invalid padding");o=6}else r=n,o=2;let i=t.subarray(o,o+r);if(r<Co||r>To||i.length!==r||t.length!==o+Fs(r))throw new Error("invalid padding");return Iu.decode(i)}function Qs(t,e,n){if(n.length!==32)throw new Error("AAD associated data must be 32 bytes");let r=te(n,e);return Ce(ue,t,r)}function Pu(t){if(typeof t!="string")throw new Error("payload must be a valid string");let e=t.length;if(e<132)throw new Error("invalid payload length: "+e);if(t[0]==="#")throw new Error("unknown encryption version");let n;try{n=Nt.decode(t)}catch(i){throw new Error("invalid base64: "+i.message)}let r=n.length;if(r<99)throw new Error("invalid data length: "+r);let o=n[0];if(o!==2)throw new Error("unknown encryption version "+o);return{nonce:n.subarray(1,33),ciphertext:n.subarray(33,-32),mac:n.subarray(-32)}}function ea(t,e,n=ke(32)){let{chacha_key:r,chacha_nonce:o,hmac_key:i}=Xs(e,n),s=Uu(t),a=ut(r,o,s),c=Qs(i,a,n);return Nt.encode(te(new Uint8Array([2]),n,a,c))}function ln(t,e){let{nonce:n,ciphertext:r,mac:o}=Pu(t),{chacha_key:i,chacha_nonce:s,hmac_key:a}=Xs(e,n),c=Qs(a,r,n);if(!Lt(c,o))throw new Error("invalid MAC");let l=ut(i,s,r);return Ou(l)}function un(){return typeof window<"u"&&!!window.nostr&&typeof window.nostr.signEvent=="function"}var Io=class{constructor(e,n){this.pubkey=e;this.provider=n;this.method="nip07";this.capabilities={canSignEvents:!0,hasNip44:!!n.nip44},n.nip44&&(this.nip44={encrypt:(r,o)=>n.nip44.encrypt(r,o),decrypt:(r,o)=>n.nip44.decrypt(r,o)})}async signEvent(e){return this.provider.signEvent(e)}async close(){}};async function fn(){if(!un())throw new Error("no-nip07-provider");let t=window.nostr,e=await t.getPublicKey();if(!/^[0-9a-f]{64}$/i.test(e))throw new Error("invalid-pubkey-from-nip07");return new Io(e.toLowerCase(),t)}var tr=class{constructor(e,n,r,o){this.pubkey=e;this.bunker=n;this.bunkerUri=r;this.clientSecretKey=o;this.method="bunker";this.capabilities={canSignEvents:!0,hasNip44:!0};this.nip44={encrypt:(i,s)=>n.nip44Encrypt(i,s),decrypt:(i,s)=>n.nip44Decrypt(i,s)}}async signEvent(e){let{pubkey:n,...r}=e,o={kind:r.kind,content:r.content,created_at:r.created_at??Math.floor(Date.now()/1e3),tags:r.tags??[]};return await this.bunker.signEvent(o)}async close(){await this.bunker.close()}};async function ta(t){let{uri:e,clientSecretKey:n,abortSignal:r}=t;if(n.length!==32)throw new Error("invalid-client-secret-key");let o=r?await _t.fromURI(n,e,void 0,r):await _t.fromURI(n,e),i=await o.getPublicKey();if(!/^[0-9a-f]{64}$/i.test(i))throw await o.close().catch(()=>{}),new Error("invalid-pubkey-from-bunker");return new tr(i.toLowerCase(),o,e,n)}function na(t){let{clientPubkeyHex:e,relayUrl:n,secret:r}=t;if(!/^[0-9a-f]{64}$/i.test(e))throw new Error("invalid-client-pubkey");if(!/^wss?:\/\//.test(n))throw new Error("invalid-relay-url");let o=new URLSearchParams({relay:n,secret:r});return t.perms&&t.perms.length>0&&o.set("perms",t.perms.join(",")),t.appName&&o.set("name",t.appName),t.appUrl&&o.set("url",t.appUrl),`nostrconnect://${e}?${o.toString()}`}async function Hu(t,e,n){let r,o=new Promise((i,s)=>{r=setTimeout(()=>{n.close().catch(()=>{}),s(new Error("bunker-connect-timeout"))},e)});try{return await Promise.race([t,o])}finally{r!==void 0&&clearTimeout(r)}}async function Pt(t){let e=t.uri.trim();if(!e)throw new Error("empty-bunker-uri");let n=await Zs(e);if(!n)throw new Error("invalid-bunker-uri");let r=t.clientSecretKey??Mu();if(r.length!==32)throw new Error("invalid-client-secret-key");let o=_t.fromBunker(r,n,{onauth:t.onauth}),i=(async()=>(await o.connect(),o.getPublicKey()))(),s=t.timeoutMs&&t.timeoutMs>0?await Hu(i,t.timeoutMs,o):await i;if(!/^[0-9a-f]{64}$/i.test(s))throw await o.close().catch(()=>{}),new Error("invalid-pubkey-from-bunker");return new tr(s.toLowerCase(),o,e,r)}function Mu(){let t=new Uint8Array(32);return crypto.getRandomValues(t),t}var No=class{constructor(e,n){this.pubkey=e;this.privkey=n;this.method="nsec";this.capabilities={canSignEvents:!0,hasNip44:!0};this.nip44={encrypt:async(r,o)=>ea(o,Ot(this.privkey,r)),decrypt:async(r,o)=>ln(o,Ot(this.privkey,r))}}async signEvent(e){let n={kind:e.kind,content:e.content,created_at:e.created_at??Math.floor(Date.now()/1e3),tags:e.tags??[]};return Ws(n,this.privkey)}async close(){this.privkey.fill(0)}};function ra(t){let e=t.trim();if(!e)throw new Error("empty-nsec");let n;if(e.startsWith("nsec1")){let o=Ys(e);if(o.type!=="nsec")throw new Error("not-an-nsec");n=o.data}else if(/^[0-9a-f]{64}$/i.test(e)){n=new Uint8Array(32);for(let o=0;o<32;o++)n[o]=parseInt(e.slice(o*2,o*2+2),16)}else throw new Error("invalid-nsec-format");if(n.length!==32)throw new Error("invalid-nsec-length");let r=Gs(n);if(!/^[0-9a-f]{64}$/i.test(r))throw new Error("invalid-pubkey-from-nsec");return new No(r.toLowerCase(),n)}var Ee=class{constructor(e,n){this.pubkey=e;this.authEvent=n;this.method="redirect";this.capabilities={canSignEvents:!1,hasNip44:!1}}async signEvent(e){throw new Error("signer-auth-only: this session was established via redirect and cannot sign new events. Install a NIP-07 extension (bark, Alby) or paste a bunker URI to upgrade.")}async close(){}},nr=class{constructor(e,n,r,o,i,s=!0){this.pubkey=e;this.authEvent=n;this.upgrade=r;this.bunkerUri=o;this.clientSecretKey=i;this.method="bunker";this.capabilities={canSignEvents:s,hasNip44:s},this.upgrade.then(a=>{a&&(this.capabilities.canSignEvents=!0,this.capabilities.hasNip44=!0)}),this.nip44={encrypt:async(a,c)=>(await this.live()).nip44.encrypt(a,c),decrypt:async(a,c)=>(await this.live()).nip44.decrypt(a,c)}}async live(){let e=await this.upgrade;if(!e)throw new Error("signer-auth-only: the redirect bunker handoff did not connect, so this session cannot sign. Reconnect the signer or paste a bunker URI to upgrade.");return e}async signEvent(e){return(await this.live()).signEvent(e)}async close(){let e=await this.upgrade.catch(()=>null);e&&await e.close().catch(()=>{})}};function Pe(t){try{return typeof localStorage<"u"?localStorage.getItem(t):null}catch{return null}}function He(t,e){try{typeof localStorage<"u"&&localStorage.setItem(t,e)}catch{}}function Ye(t){try{typeof localStorage<"u"&&localStorage.removeItem(t)}catch{}}function oa(t){He(F.pubkey,t.pubkey),He(F.method,t.method),He(F.authEvent,t.authEventJson),t.bunkerUri!==void 0&&He(F.bunkerUri,t.bunkerUri),t.bunkerClientSkHex!==void 0&&He(F.bunkerClientSk,t.bunkerClientSkHex),t.expiresAt!==void 0&&He(F.expiresAt,String(t.expiresAt)),t.displayName!==void 0&&He(F.displayName,t.displayName)}function ia(){let t=Pe(F.pubkey),e=Pe(F.method),n=Pe(F.authEvent);if(!t||!e||!n||!/^[0-9a-f]{64}$/i.test(t)||e!=="nip07"&&e!=="redirect"&&e!=="bunker"&&e!=="amber")return null;let r;try{if(r=JSON.parse(n),typeof r!="object"||r===null||r.pubkey!==t)return null}catch{return null}let o=Pe(F.expiresAt),i=o?Number(o):void 0;if(i!==void 0&&Number.isFinite(i)&&Date.now()>i)return Je(),null;let s={pubkey:t,method:e,authEventJson:n},a=Pe(F.bunkerUri),c=Pe(F.bunkerClientSk),l=Pe(F.displayName);return a&&(s.bunkerUri=a),c&&(s.bunkerClientSkHex=c),i!==void 0&&Number.isFinite(i)&&(s.expiresAt=i),l&&(s.displayName=l),s}function Je(){Ye(F.pubkey),Ye(F.method),Ye(F.authEvent),Ye(F.bunkerUri),Ye(F.bunkerClientSk),Ye(F.expiresAt),Ye(F.displayName)}function ht(){let t=Pe(F.clientSk);if(t&&/^[0-9a-f]{64}$/i.test(t))try{return qu(t)}catch{}let e=new Uint8Array(32);return crypto.getRandomValues(e),He(F.clientSk,_o(e)),e}function rr(t){He(F.pendingRedirect,JSON.stringify(t))}function or(){let t=Pe(F.pendingRedirect);if(!t)return null;try{let e=JSON.parse(t),n=e.challenge,r=e.origin,o=e.appName,i=e.createdAt;return typeof n!="string"||!/^[0-9a-f]{64}$/i.test(n)||typeof r!="string"||r.length===0||typeof o!="string"||o.length===0||typeof i!="number"||!Number.isFinite(i)?null:{challenge:n,origin:r,appName:o,createdAt:i}}catch{return null}}function ir(){Ye(F.pendingRedirect)}function _o(t){let e="";for(let n=0;n<t.length;n++)e+=t[n].toString(16).padStart(2,"0");return e}function qu(t){if(t.length%2!==0)throw new Error("odd-hex-length");let e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n++)e[n]=parseInt(t.slice(n*2,n*2+2),16);return e}function sr(){return typeof navigator>"u"?!1:/android/i.test(navigator.userAgent)}var sa=/^[0-9a-f]{64}$/i;function Du(t){return{kind:21236,content:"",created_at:Math.floor(Date.now()/1e3),tags:[["challenge",t.challenge],["origin",t.origin],["app",t.appName]]}}function $u(t){let e=Du(t),n=JSON.stringify(e),r=typeof btoa=="function"?btoa(n):Buffer.from(n,"utf-8").toString("base64"),o=t.redirectCallback??`${t.origin}/?signet_amber=1`,i=new URLSearchParams({type:"sign_event",compressionType:"base64",returnType:"event",callbackUrl:o});return`nostrsigner:${r}?${i.toString()}`}function aa(t){if(typeof window>"u")throw new Error("signet-login: amber mode requires a browser environment");let e={challenge:t.challenge,origin:t.origin,appName:t.appName,createdAt:Date.now()};return rr(e),window.location.href=$u(t),new Promise(()=>{})}function Vu(){if(typeof window>"u")return;let t=new URL(window.location.href),e=!1;for(let r of["event","signet_amber","error"])t.searchParams.has(r)&&(t.searchParams.delete(r),e=!0);if(!e)return;let n=t.pathname+(t.search?t.search:"")+t.hash;try{window.history.replaceState(window.history.state,document.title,n)}catch{}}function ca(){if(typeof window>"u")return{kind:"no-callback"};let t=new URLSearchParams(window.location.search);if(!(t.has("signet_amber")||t.has("event")))return{kind:"no-callback"};let n=g=>(ir(),Vu(),g);if(t.get("error")==="denied")return n({kind:"denied"});let r=or();if(!r)return n({kind:"invalid",reason:"no-pending-state"});if(r.origin!==window.location.origin)return n({kind:"invalid",reason:"origin-mismatch"});if(Date.now()-r.createdAt>Tn)return n({kind:"invalid",reason:"pending-stale"});let o=t.get("event");if(!o)return n({kind:"invalid",reason:"no-event-param"});let i;try{let g;try{g=typeof atob=="function"?atob(o):Buffer.from(o,"base64").toString("utf-8")}catch{g=o}i=JSON.parse(g)}catch{return n({kind:"invalid",reason:"event-malformed"})}if(typeof i!="object"||i===null)return n({kind:"invalid",reason:"event-not-object"});let s=i;if(typeof s.id!="string"||!sa.test(s.id)||typeof s.pubkey!="string"||!sa.test(s.pubkey)||typeof s.sig!="string"||!/^[0-9a-f]{128}$/i.test(s.sig)||typeof s.created_at!="number"||!Array.isArray(s.tags)||s.kind!==21236||typeof s.content!="string")return n({kind:"invalid",reason:"event-shape-invalid"});let a=s.tags.find(g=>Array.isArray(g)&&g[0]==="challenge");if(!a||a[1]!==r.challenge)return n({kind:"invalid",reason:"challenge-mismatch"});let c={id:s.id.toLowerCase(),pubkey:s.pubkey.toLowerCase(),kind:21236,created_at:s.created_at,tags:s.tags,content:s.content,sig:s.sig.toLowerCase()},l=new Ee(c.pubkey,c),d={pubkey:c.pubkey,method:"amber",signer:l,authEvent:c};return n({kind:"session",session:d})}var gt=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function pt(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function dn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Ae(t,...e){if(!pt(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function ar(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");dn(t.outputLen),dn(t.blockLen)}function Mt(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function ua(t,e){Ae(t);let n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function yt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function cr(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Re(t,e){return t<<32-e|t>>>e}var fa=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ku=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function le(t){if(Ae(t),fa)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Ku[t[n]];return e}var Me={_0:48,_9:57,A:65,F:70,a:97,f:102};function la(t){if(t>=Me._0&&t<=Me._9)return t-Me._0;if(t>=Me.A&&t<=Me.F)return t-(Me.A-10);if(t>=Me.a&&t<=Me.f)return t-(Me.a-10)}function bt(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(fa)return Uint8Array.fromHex(t);let e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let o=0,i=0;o<n;o++,i+=2){let s=la(t.charCodeAt(i)),a=la(t.charCodeAt(i+1));if(s===void 0||a===void 0){let c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}r[o]=s*16+a}return r}function lr(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function hn(t){return typeof t=="string"&&(t=lr(t)),Ae(t),t}function pe(...t){let e=0;for(let r=0;r<t.length;r++){let o=t[r];Ae(o),e+=o.length}let n=new Uint8Array(e);for(let r=0,o=0;r<t.length;r++){let i=t[r];n.set(i,o),o+=i.length}return n}var Ht=class{};function da(t){let e=r=>t().update(hn(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function mt(t=32){if(gt&&typeof gt.getRandomValues=="function")return gt.getRandomValues(new Uint8Array(t));if(gt&&typeof gt.randomBytes=="function")return Uint8Array.from(gt.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function zu(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);let o=BigInt(32),i=BigInt(4294967295),s=Number(n>>o&i),a=Number(n&i),c=r?4:0,l=r?0:4;t.setUint32(e+c,s,r),t.setUint32(e+l,a,r)}function ha(t,e,n){return t&e^~t&n}function ga(t,e,n){return t&e^t&n^e&n}var ur=class extends Ht{constructor(e,n,r,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(e),this.view=cr(this.buffer)}update(e){Mt(this),e=hn(e),Ae(e);let{view:n,buffer:r,blockLen:o}=this,i=e.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=cr(e);for(;o<=i-s;s+=o)this.process(c,s);continue}r.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Mt(this),ua(e,this),this.finished=!0;let{buffer:n,view:r,blockLen:o,isLE:i}=this,{pos:s}=this;n[s++]=128,yt(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(r,0),s=0);for(let g=s;g<o;g++)n[g]=0;zu(r,o-8,BigInt(this.length*8),i),this.process(r,0);let a=cr(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let g=0;g<l;g++)a.setUint32(4*g,d[g],i)}digest(){let{buffer:e,outputLen:n}=this;this.digestInto(e);let r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:n,buffer:r,length:o,finished:i,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=i,e.length=o,e.pos=a,o%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}},qe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var ju=Uint32Array.from([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]),Xe=new Uint32Array(64),fr=class extends ur{constructor(e=32){super(64,e,8,!1),this.A=qe[0]|0,this.B=qe[1]|0,this.C=qe[2]|0,this.D=qe[3]|0,this.E=qe[4]|0,this.F=qe[5]|0,this.G=qe[6]|0,this.H=qe[7]|0}get(){let{A:e,B:n,C:r,D:o,E:i,F:s,G:a,H:c}=this;return[e,n,r,o,i,s,a,c]}set(e,n,r,o,i,s,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,n){for(let g=0;g<16;g++,n+=4)Xe[g]=e.getUint32(n,!1);for(let g=16;g<64;g++){let u=Xe[g-15],f=Xe[g-2],y=Re(u,7)^Re(u,18)^u>>>3,m=Re(f,17)^Re(f,19)^f>>>10;Xe[g]=m+Xe[g-7]+y+Xe[g-16]|0}let{A:r,B:o,C:i,D:s,E:a,F:c,G:l,H:d}=this;for(let g=0;g<64;g++){let u=Re(a,6)^Re(a,11)^Re(a,25),f=d+u+ha(a,c,l)+ju[g]+Xe[g]|0,m=(Re(r,2)^Re(r,13)^Re(r,22))+ga(r,o,i)|0;d=l,l=c,c=a,a=s+f|0,s=i,i=o,o=r,r=f+m|0}r=r+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(r,o,i,s,a,c,l,d)}roundClean(){yt(Xe)}destroy(){this.set(0,0,0,0,0,0,0,0),yt(this.buffer)}};var qt=da(()=>new fr);var dr=class extends Ht{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,ar(e);let r=hn(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,i=new Uint8Array(o);i.set(r.length>o?e.create().update(r).digest():r);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=e.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),yt(i)}update(e){return Mt(this),this.iHash.update(e),this}digestInto(e){Mt(this),Ae(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:n,iHash:r,finished:o,destroyed:i,blockLen:s,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Uo=(t,e,n)=>new dr(t,e).update(n).digest();Uo.create=(t,e)=>new dr(t,e);var Ho=BigInt(0),Po=BigInt(1);function gn(t,e=""){if(typeof t!="boolean"){let n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function Fe(t,e,n=""){let r=pt(t),o=t?.length,i=e!==void 0;if(!r||i&&o!==e){let s=n&&`"${n}" `,a=i?` of length ${e}`:"",c=r?`length=${o}`:`type=${typeof t}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return t}function pn(t){let e=t.toString(16);return e.length&1?"0"+e:e}function pa(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Ho:BigInt("0x"+t)}function De(t){return pa(le(t))}function Mo(t){return Ae(t),pa(le(Uint8Array.from(t).reverse()))}function Dt(t,e){return bt(t.toString(16).padStart(e*2,"0"))}function qo(t,e){return Dt(t,e).reverse()}function re(t,e,n){let r;if(typeof e=="string")try{r=bt(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(pt(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");let o=r.length;if(typeof n=="number"&&o!==n)throw new Error(t+" of length "+n+" expected, got "+o);return r}var Oo=t=>typeof t=="bigint"&&Ho<=t;function yn(t,e,n){return Oo(t)&&Oo(e)&&Oo(n)&&e<=t&&t<n}function ya(t,e,n,r){if(!yn(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function hr(t){let e;for(e=0;t>Ho;t>>=Po,e+=1);return e}var Qe=t=>(Po<<BigInt(t))-Po;function ba(t,e,n){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");let r=f=>new Uint8Array(f),o=f=>Uint8Array.of(f),i=r(t),s=r(t),a=0,c=()=>{i.fill(1),s.fill(0),a=0},l=(...f)=>n(s,i,...f),d=(f=r(0))=>{s=l(o(0),f),i=l(),f.length!==0&&(s=l(o(1),f),i=l())},g=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,y=[];for(;f<e;){i=l();let m=i.slice();y.push(m),f+=i.length}return pe(...y)};return(f,y)=>{c(),d(f);let m;for(;!(m=y(g()));)d();return c(),m}}function bn(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(o,i,s){let a=t[o];if(s&&a===void 0)return;let c=typeof a;if(c!==i||a===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${c}`)}Object.entries(e).forEach(([o,i])=>r(o,i,!1)),Object.entries(n).forEach(([o,i])=>r(o,i,!0))}function Do(t){let e=new WeakMap;return(n,...r)=>{let o=e.get(n);if(o!==void 0)return o;let i=t(n,...r);return e.set(n,i),i}}var ge=BigInt(0),de=BigInt(1),wt=BigInt(2),xa=BigInt(3),Ea=BigInt(4),va=BigInt(5),Zu=BigInt(7),Sa=BigInt(8),Gu=BigInt(9),ka=BigInt(16);function be(t,e){let n=t%e;return n>=ge?n:e+n}function me(t,e,n){let r=t;for(;e-- >ge;)r*=r,r%=n;return r}function ma(t,e){if(t===ge)throw new Error("invert: expected non-zero number");if(e<=ge)throw new Error("invert: expected positive modulus, got "+e);let n=be(t,e),r=e,o=ge,i=de,s=de,a=ge;for(;n!==ge;){let l=r/n,d=r%n,g=o-s*l,u=i-a*l;r=n,n=d,o=s,i=a,s=g,a=u}if(r!==de)throw new Error("invert: does not exist");return be(o,e)}function $o(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function Ba(t,e){let n=(t.ORDER+de)/Ea,r=t.pow(e,n);return $o(t,r,e),r}function Wu(t,e){let n=(t.ORDER-va)/Sa,r=t.mul(e,wt),o=t.pow(r,n),i=t.mul(e,o),s=t.mul(t.mul(i,wt),o),a=t.mul(i,t.sub(s,t.ONE));return $o(t,a,e),a}function Yu(t){let e=et(t),n=Aa(t),r=n(e,e.neg(e.ONE)),o=n(e,r),i=n(e,e.neg(r)),s=(t+Zu)/ka;return(a,c)=>{let l=a.pow(c,s),d=a.mul(l,r),g=a.mul(l,o),u=a.mul(l,i),f=a.eql(a.sqr(d),c),y=a.eql(a.sqr(g),c);l=a.cmov(l,d,f),d=a.cmov(u,g,y);let m=a.eql(a.sqr(d),c),v=a.cmov(l,d,m);return $o(a,v,c),v}}function Aa(t){if(t<xa)throw new Error("sqrt is not defined for small field");let e=t-de,n=0;for(;e%wt===ge;)e/=wt,n++;let r=wt,o=et(t);for(;wa(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Ba;let i=o.pow(r,e),s=(e+de)/wt;return function(c,l){if(c.is0(l))return l;if(wa(c,l)!==1)throw new Error("Cannot find square root");let d=n,g=c.mul(c.ONE,i),u=c.pow(l,e),f=c.pow(l,s);for(;!c.eql(u,c.ONE);){if(c.is0(u))return c.ZERO;let y=1,m=c.sqr(u);for(;!c.eql(m,c.ONE);)if(y++,m=c.sqr(m),y===d)throw new Error("Cannot find square root");let v=de<<BigInt(d-y-1),R=c.pow(g,v);d=y,g=c.sqr(R),u=c.mul(u,g),f=c.mul(f,R)}return f}}function Ju(t){return t%Ea===xa?Ba:t%Sa===va?Wu:t%ka===Gu?Yu(t):Aa(t)}var Xu=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Vo(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=Xu.reduce((r,o)=>(r[o]="function",r),e);return bn(t,n),t}function Fu(t,e,n){if(n<ge)throw new Error("invalid exponent, negatives unsupported");if(n===ge)return t.ONE;if(n===de)return e;let r=t.ONE,o=e;for(;n>ge;)n&de&&(r=t.mul(r,o)),o=t.sqr(o),n>>=de;return r}function gr(t,e,n=!1){let r=new Array(e.length).fill(n?t.ZERO:void 0),o=e.reduce((s,a,c)=>t.is0(a)?s:(r[c]=s,t.mul(s,a)),t.ONE),i=t.inv(o);return e.reduceRight((s,a,c)=>t.is0(a)?s:(r[c]=t.mul(s,r[c]),t.mul(s,a)),i),r}function wa(t,e){let n=(t.ORDER-de)/wt,r=t.pow(e,n),o=t.eql(r,t.ONE),i=t.eql(r,t.ZERO),s=t.eql(r,t.neg(t.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function pr(t,e){e!==void 0&&dn(e);let n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function et(t,e,n=!1,r={}){if(t<=ge)throw new Error("invalid field: expected ORDER > 0, got "+t);let o,i,s=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");let u=e;u.BITS&&(o=u.BITS),u.sqrt&&(i=u.sqrt),typeof u.isLE=="boolean"&&(n=u.isLE),typeof u.modFromBytes=="boolean"&&(s=u.modFromBytes),a=u.allowedLengths}else typeof e=="number"&&(o=e),r.sqrt&&(i=r.sqrt);let{nBitLength:c,nByteLength:l}=pr(t,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d,g=Object.freeze({ORDER:t,isLE:n,BITS:c,BYTES:l,MASK:Qe(c),ZERO:ge,ONE:de,allowedLengths:a,create:u=>be(u,t),isValid:u=>{if(typeof u!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof u);return ge<=u&&u<t},is0:u=>u===ge,isValidNot0:u=>!g.is0(u)&&g.isValid(u),isOdd:u=>(u&de)===de,neg:u=>be(-u,t),eql:(u,f)=>u===f,sqr:u=>be(u*u,t),add:(u,f)=>be(u+f,t),sub:(u,f)=>be(u-f,t),mul:(u,f)=>be(u*f,t),pow:(u,f)=>Fu(g,u,f),div:(u,f)=>be(u*ma(f,t),t),sqrN:u=>u*u,addN:(u,f)=>u+f,subN:(u,f)=>u-f,mulN:(u,f)=>u*f,inv:u=>ma(u,t),sqrt:i||(u=>(d||(d=Ju(t)),d(g,u))),toBytes:u=>n?qo(u,l):Dt(u,l),fromBytes:(u,f=!0)=>{if(a){if(!a.includes(u.length)||u.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+u.length);let m=new Uint8Array(l);m.set(u,n?0:m.length-u.length),u=m}if(u.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+u.length);let y=n?Mo(u):De(u);if(s&&(y=be(y,t)),!f&&!g.isValid(y))throw new Error("invalid field element: outside of range 0..ORDER");return y},invertBatch:u=>gr(g,u),cmov:(u,f,y)=>y?f:u});return Object.freeze(g)}function Ra(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function Ko(t){let e=Ra(t);return e+Math.ceil(e/2)}function yr(t,e,n=!1){let r=t.length,o=Ra(e),i=Ko(e);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let s=n?Mo(t):De(t),a=be(s,e-de)+de;return n?qo(a,o):Dt(a,o)}var $t=BigInt(0),xt=BigInt(1);function mn(t,e){let n=e.negate();return t?n:e}function mr(t,e){let n=gr(t.Fp,e.map(r=>r.Z));return e.map((r,o)=>t.fromAffine(r.toAffine(n[o])))}function Ia(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function zo(t,e){Ia(t,e);let n=Math.ceil(e/t)+1,r=2**(t-1),o=2**t,i=Qe(t),s=BigInt(t);return{windows:n,windowSize:r,mask:i,maxNumber:o,shiftBy:s}}function Ca(t,e,n){let{windowSize:r,mask:o,maxNumber:i,shiftBy:s}=n,a=Number(t&o),c=t>>s;a>r&&(a-=i,c+=xt);let l=e*r,d=l+Math.abs(a)-1,g=a===0,u=a<0,f=e%2!==0;return{nextN:c,offset:d,isZero:g,isNeg:u,isNegF:f,offsetF:l}}function Qu(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function ef(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}var jo=new WeakMap,Na=new WeakMap;function Zo(t){return Na.get(t)||1}function Ta(t){if(t!==$t)throw new Error("invalid wNAF")}var br=class{constructor(e,n){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n}_unsafeLadder(e,n,r=this.ZERO){let o=e;for(;n>$t;)n&xt&&(r=r.add(o)),o=o.double(),n>>=xt;return r}precomputeWindow(e,n){let{windows:r,windowSize:o}=zo(n,this.bits),i=[],s=e,a=s;for(let c=0;c<r;c++){a=s,i.push(a);for(let l=1;l<o;l++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,s=zo(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:d,isNeg:g,isNegF:u,offsetF:f}=Ca(r,a,s);r=c,d?i=i.add(mn(u,n[f])):o=o.add(mn(g,n[l]))}return Ta(r),{p:o,f:i}}wNAFUnsafe(e,n,r,o=this.ZERO){let i=zo(e,this.bits);for(let s=0;s<i.windows&&r!==$t;s++){let{nextN:a,offset:c,isZero:l,isNeg:d}=Ca(r,s,i);if(r=a,!l){let g=n[c];o=o.add(d?g.negate():g)}}return Ta(r),o}getPrecomputes(e,n,r){let o=jo.get(n);return o||(o=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(o=r(o)),jo.set(n,o))),o}cached(e,n,r){let o=Zo(e);return this.wNAF(o,this.getPrecomputes(o,e,r),n)}unsafe(e,n,r,o){let i=Zo(e);return i===1?this._unsafeLadder(e,n,o):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),n,o)}createCache(e,n){Ia(n,this.bits),Na.set(e,n),jo.delete(e)}hasCache(e){return Zo(e)!==1}};function _a(t,e,n,r){let o=e,i=t.ZERO,s=t.ZERO;for(;n>$t||r>$t;)n&xt&&(i=i.add(o)),r&xt&&(s=s.add(o)),o=o.double(),n>>=xt,r>>=xt;return{p1:i,p2:s}}function Ua(t,e,n,r){Qu(n,t),ef(r,e);let o=n.length,i=r.length;if(o!==i)throw new Error("arrays of points and scalars must have equal length");let s=t.ZERO,a=hr(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let l=Qe(c),d=new Array(Number(l)+1).fill(s),g=Math.floor((e.BITS-1)/c)*c,u=s;for(let f=g;f>=0;f-=c){d.fill(s);for(let m=0;m<i;m++){let v=r[m],R=Number(v>>BigInt(f)&l);d[R]=d[R].add(n[m])}let y=s;for(let m=d.length-1,v=s;m>0;m--)v=v.add(d[m]),y=y.add(v);if(u=u.add(y),f!==0)for(let m=0;m<c;m++)u=u.double()}return u}function La(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Vo(e),e}else return et(t,{isLE:n})}function Oa(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>$t))throw new Error(`CURVE.${c} must be positive bigint`)}let o=La(e.p,n.Fp,r),i=La(e.n,n.Fn,r),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:i}}var Pa=(t,e)=>(t+(t>=0?e:-e)/Ha)/e;function tf(t,e,n){let[[r,o],[i,s]]=e,a=Pa(s*t,n),c=Pa(-o*t,n),l=t-a*r-c*i,d=-a*o-c*s,g=l<Ve,u=d<Ve;g&&(l=-l),u&&(d=-d);let f=Qe(Math.ceil(hr(n)/2))+Vt;if(l<Ve||l>=f||d<Ve||d>=f)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:g,k1:l,k2neg:u,k2:d}}function Wo(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Go(t,e){let n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return gn(n.lowS,"lowS"),gn(n.prehash,"prehash"),n.format!==void 0&&Wo(n.format),n}var Yo=class extends Error{constructor(e=""){super(e)}},$e={Err:Yo,_tlv:{encode:(t,e)=>{let{Err:n}=$e;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");let r=e.length/2,o=pn(r);if(o.length/2&128)throw new n("tlv.encode: long form length too big");let i=r>127?pn(o.length/2|128):"";return pn(t)+i+o+e},decode(t,e){let{Err:n}=$e,r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");let o=e[r++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");let l=e.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(let d of l)s=s<<8|d;if(r+=c,s<128)throw new n("tlv.decode(long): not minimal encoding")}let a=e.subarray(r,r+s);if(a.length!==s)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+s)}}},_int:{encode(t){let{Err:e}=$e;if(t<Ve)throw new e("integer: negative integers are not allowed");let n=pn(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){let{Err:e}=$e;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return De(t)}},toSig(t){let{Err:e,_int:n,_tlv:r}=$e,o=re("signature",t),{v:i,l:s}=r.decode(48,o);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=r.decode(2,i),{v:l,l:d}=r.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(t){let{_tlv:e,_int:n}=$e,r=e.encode(2,n.encode(t.r)),o=e.encode(2,n.encode(t.s)),i=r+o;return e.encode(48,i)}},Ve=BigInt(0),Vt=BigInt(1),Ha=BigInt(2),wr=BigInt(3),nf=BigInt(4);function tt(t,e){let{BYTES:n}=t,r;if(typeof e=="bigint")r=e;else{let o=re("private key",e);try{r=t.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof e}`)}}if(!t.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function rf(t,e={}){let n=Oa("weierstrass",t,e),{Fp:r,Fn:o}=n,i=n.CURVE,{h:s,n:a}=i;bn(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=e;if(c&&(!r.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=qa(r,o);function d(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function g(T,x,p){let{x:h,y:b}=x.toAffine(),E=r.toBytes(h);if(gn(p,"isCompressed"),p){d();let B=!r.isOdd(b);return pe(Ma(B),E)}else return pe(Uint8Array.of(4),E,r.toBytes(b))}function u(T){Fe(T,void 0,"Point");let{publicKey:x,publicKeyUncompressed:p}=l,h=T.length,b=T[0],E=T.subarray(1);if(h===x&&(b===2||b===3)){let B=r.fromBytes(E);if(!r.isValid(B))throw new Error("bad point: is not on curve, wrong x");let w=m(B),A;try{A=r.sqrt(w)}catch(P){let D=P instanceof Error?": "+P.message:"";throw new Error("bad point: is not on curve, sqrt error"+D)}d();let k=r.isOdd(A);return(b&1)===1!==k&&(A=r.neg(A)),{x:B,y:A}}else if(h===p&&b===4){let B=r.BYTES,w=r.fromBytes(E.subarray(0,B)),A=r.fromBytes(E.subarray(B,B*2));if(!v(w,A))throw new Error("bad point: is not on curve");return{x:w,y:A}}else throw new Error(`bad point: got length ${h}, expected compressed=${x} or uncompressed=${p}`)}let f=e.toBytes||g,y=e.fromBytes||u;function m(T){let x=r.sqr(T),p=r.mul(x,T);return r.add(r.add(p,r.mul(T,i.a)),i.b)}function v(T,x){let p=r.sqr(x),h=m(T);return r.eql(p,h)}if(!v(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let R=r.mul(r.pow(i.a,wr),nf),O=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(R,O)))throw new Error("bad curve params: a or b");function I(T,x,p=!1){if(!r.isValid(x)||p&&r.is0(x))throw new Error(`bad point coordinate ${T}`);return x}function N(T){if(!(T instanceof L))throw new Error("ProjectivePoint expected")}function _(T){if(!c||!c.basises)throw new Error("no endo");return tf(T,c.basises,o.ORDER)}let q=Do((T,x)=>{let{X:p,Y:h,Z:b}=T;if(r.eql(b,r.ONE))return{x:p,y:h};let E=T.is0();x==null&&(x=E?r.ONE:r.inv(b));let B=r.mul(p,x),w=r.mul(h,x),A=r.mul(b,x);if(E)return{x:r.ZERO,y:r.ZERO};if(!r.eql(A,r.ONE))throw new Error("invZ was invalid");return{x:B,y:w}}),j=Do(T=>{if(T.is0()){if(e.allowInfinityPoint&&!r.is0(T.Y))return;throw new Error("bad point: ZERO")}let{x,y:p}=T.toAffine();if(!r.isValid(x)||!r.isValid(p))throw new Error("bad point: x or y not field elements");if(!v(x,p))throw new Error("bad point: equation left != right");if(!T.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Z(T,x,p,h,b){return p=new L(r.mul(p.X,T),p.Y,p.Z),x=mn(h,x),p=mn(b,p),x.add(p)}class L{constructor(x,p,h){this.X=I("x",x),this.Y=I("y",p,!0),this.Z=I("z",h),Object.freeze(this)}static CURVE(){return i}static fromAffine(x){let{x:p,y:h}=x||{};if(!x||!r.isValid(p)||!r.isValid(h))throw new Error("invalid affine point");if(x instanceof L)throw new Error("projective point not allowed");return r.is0(p)&&r.is0(h)?L.ZERO:new L(p,h,r.ONE)}static fromBytes(x){let p=L.fromAffine(y(Fe(x,void 0,"point")));return p.assertValidity(),p}static fromHex(x){return L.fromBytes(re("pointHex",x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,p=!0){return $.createCache(this,x),p||this.multiply(wr),this}assertValidity(){j(this)}hasEvenY(){let{y:x}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(x)}equals(x){N(x);let{X:p,Y:h,Z:b}=this,{X:E,Y:B,Z:w}=x,A=r.eql(r.mul(p,w),r.mul(E,b)),k=r.eql(r.mul(h,w),r.mul(B,b));return A&&k}negate(){return new L(this.X,r.neg(this.Y),this.Z)}double(){let{a:x,b:p}=i,h=r.mul(p,wr),{X:b,Y:E,Z:B}=this,w=r.ZERO,A=r.ZERO,k=r.ZERO,C=r.mul(b,b),P=r.mul(E,E),D=r.mul(B,B),M=r.mul(b,E);return M=r.add(M,M),k=r.mul(b,B),k=r.add(k,k),w=r.mul(x,k),A=r.mul(h,D),A=r.add(w,A),w=r.sub(P,A),A=r.add(P,A),A=r.mul(w,A),w=r.mul(M,w),k=r.mul(h,k),D=r.mul(x,D),M=r.sub(C,D),M=r.mul(x,M),M=r.add(M,k),k=r.add(C,C),C=r.add(k,C),C=r.add(C,D),C=r.mul(C,M),A=r.add(A,C),D=r.mul(E,B),D=r.add(D,D),C=r.mul(D,M),w=r.sub(w,C),k=r.mul(D,P),k=r.add(k,k),k=r.add(k,k),new L(w,A,k)}add(x){N(x);let{X:p,Y:h,Z:b}=this,{X:E,Y:B,Z:w}=x,A=r.ZERO,k=r.ZERO,C=r.ZERO,P=i.a,D=r.mul(i.b,wr),M=r.mul(p,E),U=r.mul(h,B),V=r.mul(b,w),W=r.add(p,h),K=r.add(E,B);W=r.mul(W,K),K=r.add(M,U),W=r.sub(W,K),K=r.add(p,b);let G=r.add(E,w);return K=r.mul(K,G),G=r.add(M,V),K=r.sub(K,G),G=r.add(h,b),A=r.add(B,w),G=r.mul(G,A),A=r.add(U,V),G=r.sub(G,A),C=r.mul(P,K),A=r.mul(D,V),C=r.add(A,C),A=r.sub(U,C),C=r.add(U,C),k=r.mul(A,C),U=r.add(M,M),U=r.add(U,M),V=r.mul(P,V),K=r.mul(D,K),U=r.add(U,V),V=r.sub(M,V),V=r.mul(P,V),K=r.add(K,V),M=r.mul(U,K),k=r.add(k,M),M=r.mul(G,K),A=r.mul(W,A),A=r.sub(A,M),M=r.mul(W,U),C=r.mul(G,C),C=r.add(C,M),new L(A,k,C)}subtract(x){return this.add(x.negate())}is0(){return this.equals(L.ZERO)}multiply(x){let{endo:p}=e;if(!o.isValidNot0(x))throw new Error("invalid scalar: out of range");let h,b,E=B=>$.cached(this,B,w=>mr(L,w));if(p){let{k1neg:B,k1:w,k2neg:A,k2:k}=_(x),{p:C,f:P}=E(w),{p:D,f:M}=E(k);b=P.add(M),h=Z(p.beta,C,D,B,A)}else{let{p:B,f:w}=E(x);h=B,b=w}return mr(L,[h,b])[0]}multiplyUnsafe(x){let{endo:p}=e,h=this;if(!o.isValid(x))throw new Error("invalid scalar: out of range");if(x===Ve||h.is0())return L.ZERO;if(x===Vt)return h;if($.hasCache(this))return this.multiply(x);if(p){let{k1neg:b,k1:E,k2neg:B,k2:w}=_(x),{p1:A,p2:k}=_a(L,h,E,w);return Z(p.beta,A,k,b,B)}else return $.unsafe(h,x)}multiplyAndAddUnsafe(x,p,h){let b=this.multiplyUnsafe(p).add(x.multiplyUnsafe(h));return b.is0()?void 0:b}toAffine(x){return q(this,x)}isTorsionFree(){let{isTorsionFree:x}=e;return s===Vt?!0:x?x(L,this):$.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:x}=e;return s===Vt?this:x?x(L,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(x=!0){return gn(x,"isCompressed"),this.assertValidity(),f(L,this,x)}toHex(x=!0){return le(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(x=!0){return this.toBytes(x)}_setWindowSize(x){this.precompute(x)}static normalizeZ(x){return mr(L,x)}static msm(x,p){return Ua(L,o,x,p)}static fromPrivateKey(x){return L.BASE.multiply(tt(o,x))}}L.BASE=new L(i.Gx,i.Gy,r.ONE),L.ZERO=new L(r.ZERO,r.ONE,r.ZERO),L.Fp=r,L.Fn=o;let z=o.BITS,$=new br(L,e.endo?Math.ceil(z/2):z);return L.BASE.precompute(8),L}function Ma(t){return Uint8Array.of(t?2:3)}function qa(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function of(t,e={}){let{Fn:n}=t,r=e.randomBytes||mt,o=Object.assign(qa(t.Fp,n),{seed:Ko(n.ORDER)});function i(f){try{return!!tt(n,f)}catch{return!1}}function s(f,y){let{publicKey:m,publicKeyUncompressed:v}=o;try{let R=f.length;return y===!0&&R!==m||y===!1&&R!==v?!1:!!t.fromBytes(f)}catch{return!1}}function a(f=r(o.seed)){return yr(Fe(f,o.seed,"seed"),n.ORDER)}function c(f,y=!0){return t.BASE.multiply(tt(n,f)).toBytes(y)}function l(f){let y=a(f);return{secretKey:y,publicKey:c(y)}}function d(f){if(typeof f=="bigint")return!1;if(f instanceof t)return!0;let{secretKey:y,publicKey:m,publicKeyUncompressed:v}=o;if(n.allowedLengths||y===m)return;let R=re("key",f).length;return R===m||R===v}function g(f,y,m=!0){if(d(f)===!0)throw new Error("first arg must be private key");if(d(y)===!1)throw new Error("second arg must be public key");let v=tt(n,f);return t.fromHex(y).multiply(v).toBytes(m)}return Object.freeze({getPublicKey:c,getSharedSecret:g,keygen:l,Point:t,utils:{isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:f=>tt(n,f),precompute(f=8,y=t.BASE){return y.precompute(f,!1)}},lengths:o})}function sf(t,e,n={}){ar(e),bn(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=n.randomBytes||mt,o=n.hmac||((p,...h)=>Uo(e,p,pe(...h))),{Fp:i,Fn:s}=t,{ORDER:a,BITS:c}=s,{keygen:l,getPublicKey:d,getSharedSecret:g,utils:u,lengths:f}=of(t,n),y={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function v(p){let h=a>>Vt;return p>h}function R(p,h){if(!s.isValidNot0(h))throw new Error(`invalid signature ${p}: out of range 1..Point.Fn.ORDER`);return h}function O(p,h){Wo(h);let b=f.signature,E=h==="compact"?b:h==="recovered"?b+1:void 0;return Fe(p,E,`${h} signature`)}class I{constructor(h,b,E){this.r=R("r",h),this.s=R("s",b),E!=null&&(this.recovery=E),Object.freeze(this)}static fromBytes(h,b=m){O(h,b);let E;if(b==="der"){let{r:k,s:C}=$e.toSig(Fe(h));return new I(k,C)}b==="recovered"&&(E=h[0],b="compact",h=h.subarray(1));let B=s.BYTES,w=h.subarray(0,B),A=h.subarray(B,B*2);return new I(s.fromBytes(w),s.fromBytes(A),E)}static fromHex(h,b){return this.fromBytes(bt(h),b)}addRecoveryBit(h){return new I(this.r,this.s,h)}recoverPublicKey(h){let b=i.ORDER,{r:E,s:B,recovery:w}=this;if(w==null||![0,1,2,3].includes(w))throw new Error("recovery id invalid");if(a*Ha<b&&w>1)throw new Error("recovery id is ambiguous for h>1 curve");let k=w===2||w===3?E+a:E;if(!i.isValid(k))throw new Error("recovery id 2 or 3 invalid");let C=i.toBytes(k),P=t.fromBytes(pe(Ma((w&1)===0),C)),D=s.inv(k),M=_(re("msgHash",h)),U=s.create(-M*D),V=s.create(B*D),W=t.BASE.multiplyUnsafe(U).add(P.multiplyUnsafe(V));if(W.is0())throw new Error("point at infinify");return W.assertValidity(),W}hasHighS(){return v(this.s)}toBytes(h=m){if(Wo(h),h==="der")return bt($e.hexFromSig(this));let b=s.toBytes(this.r),E=s.toBytes(this.s);if(h==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return pe(Uint8Array.of(this.recovery),b,E)}return pe(b,E)}toHex(h){return le(this.toBytes(h))}assertValidity(){}static fromCompact(h){return I.fromBytes(re("sig",h),"compact")}static fromDER(h){return I.fromBytes(re("sig",h),"der")}normalizeS(){return this.hasHighS()?new I(this.r,s.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return le(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return le(this.toBytes("compact"))}}let N=n.bits2int||function(h){if(h.length>8192)throw new Error("input is too large");let b=De(h),E=h.length*8-c;return E>0?b>>BigInt(E):b},_=n.bits2int_modN||function(h){return s.create(N(h))},q=Qe(c);function j(p){return ya("num < 2^"+c,p,Ve,q),s.toBytes(p)}function Z(p,h){return Fe(p,void 0,"message"),h?Fe(e(p),void 0,"prehashed message"):p}function L(p,h,b){if(["recovered","canonical"].some(U=>U in b))throw new Error("sign() legacy options not supported");let{lowS:E,prehash:B,extraEntropy:w}=Go(b,y);p=Z(p,B);let A=_(p),k=tt(s,h),C=[j(k),j(A)];if(w!=null&&w!==!1){let U=w===!0?r(f.secretKey):w;C.push(re("extraEntropy",U))}let P=pe(...C),D=A;function M(U){let V=N(U);if(!s.isValidNot0(V))return;let W=s.inv(V),K=t.BASE.multiply(V).toAffine(),G=s.create(K.x);if(G===Ve)return;let oe=s.create(W*s.create(D+G*k));if(oe===Ve)return;let Jt=(K.x===G?0:2)|Number(K.y&Vt),Xt=oe;return E&&v(oe)&&(Xt=s.neg(oe),Jt^=1),new I(G,Xt,Jt)}return{seed:P,k2sig:M}}function z(p,h,b={}){p=re("message",p);let{seed:E,k2sig:B}=L(p,h,b);return ba(e.outputLen,s.BYTES,o)(E,B)}function $(p){let h,b=typeof p=="string"||pt(p),E=!b&&p!==null&&typeof p=="object"&&typeof p.r=="bigint"&&typeof p.s=="bigint";if(!b&&!E)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(E)h=new I(p.r,p.s);else if(b){try{h=I.fromBytes(re("sig",p),"der")}catch(B){if(!(B instanceof $e.Err))throw B}if(!h)try{h=I.fromBytes(re("sig",p),"compact")}catch{return!1}}return h||!1}function T(p,h,b,E={}){let{lowS:B,prehash:w,format:A}=Go(E,y);if(b=re("publicKey",b),h=Z(re("message",h),w),"strict"in E)throw new Error("options.strict was renamed to lowS");let k=A===void 0?$(p):I.fromBytes(re("sig",p),A);if(k===!1)return!1;try{let C=t.fromBytes(b);if(B&&k.hasHighS())return!1;let{r:P,s:D}=k,M=_(h),U=s.inv(D),V=s.create(M*U),W=s.create(P*U),K=t.BASE.multiplyUnsafe(V).add(C.multiplyUnsafe(W));return K.is0()?!1:s.create(K.x)===P}catch{return!1}}function x(p,h,b={}){let{prehash:E}=Go(b,y);return h=Z(h,E),I.fromBytes(p,"recovered").recoverPublicKey(h).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:g,utils:u,lengths:f,Point:t,sign:z,verify:T,recoverPublicKey:x,Signature:I,hash:e})}function af(t){let e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp,r=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(s=>Math.ceil(s/2)))):void 0,o=et(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),i={Fp:n,Fn:o,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:i}}function cf(t){let{CURVE:e,curveOpts:n}=af(t),r={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:n,hash:t.hash,ecdsaOpts:r}}function lf(t,e){let n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,pr(n.Fn.ORDER,n.Fn.BITS))})}function Da(t){let{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:o}=cf(t),i=rf(e,n),s=sf(i,r,o);return lf(t,s)}function $a(t,e){let n=r=>Da({...t,hash:r});return{...n(e),create:n}}var Kt={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},uf={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},ff=BigInt(0),Va=BigInt(1),Jo=BigInt(2);function df(t){let e=Kt.p,n=BigInt(3),r=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,d=l*l*t%e,g=me(d,n,e)*d%e,u=me(g,n,e)*d%e,f=me(u,Jo,e)*l%e,y=me(f,o,e)*f%e,m=me(y,i,e)*y%e,v=me(m,a,e)*m%e,R=me(v,c,e)*v%e,O=me(R,a,e)*m%e,I=me(O,n,e)*d%e,N=me(I,s,e)*y%e,_=me(N,r,e)*l%e,q=me(_,Jo,e);if(!xr.eql(xr.sqr(q),t))throw new Error("Cannot find square root");return q}var xr=et(Kt.p,{sqrt:df}),ja=$a({...Kt,Fp:xr,lowS:!0,endo:uf},qt),Ka={};function Er(t,...e){let n=Ka[t];if(n===void 0){let r=qt(lr(t));n=pe(r,r),Ka[t]=n}return qt(pe(n,...e))}var Fo=t=>t.toBytes(!0).slice(1),zt=ja.Point,Qo=t=>t%Jo===ff;function Xo(t){let{Fn:e,BASE:n}=zt,r=tt(e,t),o=n.multiply(r);return{scalar:Qo(o.y)?r:e.neg(r),bytes:Fo(o)}}function Za(t){let e=xr;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x \u2265 p");let n=e.create(t*t),r=e.create(n*t+BigInt(7)),o=e.sqrt(r);Qo(o)||(o=e.neg(o));let i=zt.fromAffine({x:t,y:o});return i.assertValidity(),i}var wn=De;function Ga(...t){return zt.Fn.create(wn(Er("BIP0340/challenge",...t)))}function za(t){return Xo(t).bytes}function hf(t,e,n=mt(32)){let{Fn:r}=zt,o=re("message",t),{bytes:i,scalar:s}=Xo(e),a=re("auxRand",n,32),c=r.toBytes(s^wn(Er("BIP0340/aux",a))),l=Er("BIP0340/nonce",c,i,o),{bytes:d,scalar:g}=Xo(l),u=Ga(d,i,o),f=new Uint8Array(64);if(f.set(d,0),f.set(r.toBytes(r.create(g+u*s)),32),!Wa(f,o,i))throw new Error("sign: Invalid signature produced");return f}function Wa(t,e,n){let{Fn:r,BASE:o}=zt,i=re("signature",t,64),s=re("message",e),a=re("publicKey",n,32);try{let c=Za(wn(a)),l=wn(i.subarray(0,32));if(!yn(l,Va,Kt.p))return!1;let d=wn(i.subarray(32,64));if(!yn(d,Va,Kt.n))return!1;let g=Ga(r.toBytes(l),Fo(c),s),u=o.multiplyUnsafe(d).add(c.multiplyUnsafe(r.neg(g))),{x:f,y}=u.toAffine();return!(u.is0()||!Qo(y)||f!==l)}catch{return!1}}var Te=(()=>{let n=(o=mt(48))=>yr(o,Kt.n);ja.utils.randomSecretKey;function r(o){let i=n(o);return{secretKey:i,publicKey:za(i)}}return{keygen:r,getPublicKey:za,sign:hf,verify:Wa,Point:zt,utils:{randomSecretKey:n,randomPrivateKey:n,taggedHash:Er,lift_x:Za,pointToBytes:Fo,numberToBytesBE:Dt,bytesToNumberBE:De,mod:be},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();var ei=qt;function gf(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function pf(){let t=new Uint8Array(16);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function vr(t,e){let n=t.find(r=>r[0]===e);return n?n[1]:void 0}function Ke(t){let e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n++)e[n]=parseInt(t.substr(n*2,2),16);return e}async function yf(t){if(!t.id||!t.pubkey||!t.sig||!t.tags||t.kind!==30470||!/^[0-9a-f]{128}$/i.test(t.sig)||!/^[0-9a-f]{64}$/i.test(t.pubkey)||!/^[0-9a-f]{64}$/i.test(t.id)||t.tags.length>100||t.content.length>65536||t.tags.some(s=>s.some(a=>a.length>1024)))return!1;let e=t.tags.map(s=>s[0]);if(!e.includes("tier")||!e.includes("age-range")||!e.includes("entity-type"))return!1;let n=JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content]),r=new TextEncoder,o=ei(r.encode(n));if(le(o)!==t.id.toLowerCase())return!1;try{let s=Ke(t.sig),a=Ke(t.id),c=Ke(t.pubkey);return Te.verify(s,a,c)}catch{return!1}}function bf(t,e){if(t===e||t==="18+"&&e==="18+")return!0;let n=["0-3","4-7","8-12","13-17","18+"],r=n.indexOf(t),o=n.indexOf(e);return r===-1||o===-1?!1:e==="18+"?t==="18+":t===e}async function mf(t,e){if(e==null||!/^https:\/\//i.test(e)||!/^[0-9a-f]{64}$/i.test(t))return null;try{let n=await fetch(`${e}/status/${t}`,{signal:AbortSignal.timeout(5e3)});if(!n.ok)return null;let r=await n.json();if(typeof r!="object"||r===null)return null;let o=r;return{confirmed:o.confirmed===!0,method:["A","B","C","D"].includes(o.method)?o.method:null,profession:typeof o.profession=="string"?o.profession:void 0,jurisdiction:typeof o.jurisdiction=="string"?o.jurisdiction:void 0}}catch{return null}}async function wf(t,e){if(!["0-3","4-7","8-12","13-17","18+"].includes(t))return{verified:!1,ageRange:null,tier:null,entityType:null,credentialId:null,verifierPubkey:null,verifierConfirmed:null,verifierMethod:null,issuedAt:null,expiresAt:null,error:"invalid-age-range"};let r={requiredAgeRange:t,relayUrl:e?.relayUrl||"wss://relay.damus.io",theme:e?.theme||"auto",timeout:e?.timeout||12e4,verifierCheckUrl:e?.verifierCheckUrl!==void 0?e.verifierCheckUrl:"https://verify.signet.forgesworn.dev",acceptUnconfirmed:e?.acceptUnconfirmed||!1,...e};r.timeout=Math.max(5e3,Math.min(r.timeout??12e4,6e5));let o=pf(),i={type:"signet-verify-request",requestId:o,requiredAgeRange:r.requiredAgeRange,relayUrl:r.relayUrl,timestamp:Math.floor(Date.now()/1e3)},s=JSON.stringify(i),a=btoa(s);return new Promise(c=>{let l=document.createElement("style");l.textContent="#signet-verify-dialog::backdrop{background:rgba(0,0,0,0.7)}",document.head.appendChild(l);let d=r.theme==="dark"||r.theme==="auto"&&window.matchMedia("(prefers-color-scheme: dark)").matches,g=d?"#1a1a2e":"#ffffff",u=d?"#e0e0e0":"#1a1a2e",f=d?"#888":"#666",y=document.createElement("dialog");y.id="signet-verify-dialog",y.style.cssText=`border:none;border-radius:16px;padding:32px;max-width:380px;width:90%;text-align:center;box-shadow:0 20px 60px rgba(0,0,0,0.3);background:${g};color:${u};font-family:system-ui,-apple-system,sans-serif;`,y.innerHTML=`
|
|
9
9
|
<h2 style="margin:0 0 8px;font-size:1.3rem;">Verify your age with Signet</h2>
|
|
10
10
|
<p style="margin:0 0 24px;color:${f};font-size:0.9rem;">Scan this QR code with your Signet app to prove you are ${gf(t)}. No personal data is shared.</p>
|
|
11
11
|
<div id="signet-qr" style="display:flex;justify-content:center;margin-bottom:24px;"></div>
|
|
12
12
|
<p style="margin:0 0 16px;color:${f};font-size:0.8rem;">Waiting for verification...</p>
|
|
13
13
|
<button id="signet-cancel" style="background:none;border:1px solid ${f};color:${u};padding:10px 24px;border-radius:8px;cursor:pointer;font-size:0.9rem;">Cancel</button>
|
|
14
|
-
`,document.body.appendChild(y),y.showModal();let m=y.querySelector("#signet-qr");if(m){let R=document.createElement("div");R.style.cssText=`width:200px;height:200px;background:${d?"#2a2a3e":"#f0f0f0"};border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:0.75rem;color:${f};word-break:break-all;padding:12px;`,R.textContent=`signet:verify:${a.slice(0,40)}...`,m.appendChild(R)}let v=new BroadcastChannel("signet-verify-"+o);y.querySelector("#signet-cancel")?.addEventListener("click",()=>{v.close(),y.close(),y.remove(),l.remove(),c({verified:!1,ageRange:null,tier:null,entityType:null,credentialId:null,verifierPubkey:null,verifierConfirmed:null,verifierMethod:null,issuedAt:null,expiresAt:null,error:"cancelled"})}),v.onmessage=async R=>{let O=R.data;if(typeof O!="object"||O===null)return;let I=O;if(I.type!=="signet-verify-response"||I.requestId!==o||!I.credential||typeof I.credential!="object"||!Array.isArray(I.credential.tags))return;let N=I.credential,_=await yf(N),q=vr(N.tags,"age-range"),j=vr(N.tags,"tier"),Z=vr(N.tags,"entity-type"),L=vr(N.tags,"expires"),z=q?bf(q,r.requiredAgeRange):!1,$=await mf(N.pubkey,r.verifierCheckUrl),T=$?.confirmed??null,x=$?.method??null,p=r.acceptUnconfirmed||T===!0;y.close(),y.remove(),l.remove(),v.close();let h=j?parseInt(j,10):null,b=L?parseInt(L,10):null,E=Math.floor(Date.now()/1e3),B=b===null||!isNaN(b)&&b>E,w;_?B?z?p||(w=T===!1?"verifier-not-confirmed":"verifier-check-unavailable"):w="age-range-not-met":w="credential-expired":w="invalid-credential",c({verified:_&&B&&z&&p,ageRange:q||null,tier:h!==null&&!isNaN(h)?h:null,entityType:Z||null,credentialId:N.id,verifierPubkey:N.pubkey,verifierConfirmed:T,verifierMethod:x,issuedAt:N.created_at,expiresAt:b!==null&&!isNaN(b)?b:null,error:w})},setTimeout(()=>{y.close(),y.remove(),l.remove(),v.close(),c({verified:!1,ageRange:null,tier:null,entityType:null,credentialId:null,verifierPubkey:null,verifierConfirmed:null,verifierMethod:null,issuedAt:null,expiresAt:null,error:"timeout"})},r.timeout)})}function ti(t){let e=JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content]),n=ei(new TextEncoder().encode(e));return le(n)}async function xf(t,e){try{let n=Ot(e,t.pubkey),r=un(t.content,n),o=JSON.parse(r);if(typeof o!="object"||o===null)return null;let i=o;if(i.kind!==13||typeof i.pubkey!="string"||!/^[0-9a-f]{64}$/i.test(i.pubkey)||typeof i.created_at!="number"||!Array.isArray(i.tags)||typeof i.content!="string"||typeof i.id!="string"||!/^[0-9a-f]{64}$/i.test(i.id)||typeof i.sig!="string"||!/^[0-9a-f]{128}$/i.test(i.sig)||ti({pubkey:i.pubkey,created_at:i.created_at,kind:13,tags:i.tags,content:i.content})!==i.id.toLowerCase())return null;let a=Ke(i.sig),c=Ke(i.id),l=Ke(i.pubkey);if(!Te.verify(a,c,l))return null;let d=Ot(e,i.pubkey),g=un(i.content,d),u=JSON.parse(g);if(typeof u!="object"||u===null)return null;let f=u;if(typeof f.pubkey!="string"||f.pubkey!==i.pubkey||typeof f.kind!="number"||typeof f.created_at!="number"||!Array.isArray(f.tags)||typeof f.content!="string")return null;let y=typeof f.id=="string"?f.id:ti({pubkey:f.pubkey,created_at:f.created_at,kind:f.kind,tags:f.tags,content:f.content});return{pubkey:f.pubkey,id:y,kind:f.kind,created_at:f.created_at,tags:f.tags,content:f.content}}catch{return null}}function Ef(t){if(typeof t!="string")return;let e=t.replace(/[\x00-\x1f\x7f-\x9f\u200b-\u200f\u2028-\u202e\u2066-\u2069]/g,"").trim().slice(0,64);return e.length>0?e:void 0}async function ni(t){if(!/^[0-9a-f]{64}$/i.test(t.requestId))throw new Error("invalid-request-id");if(!(t.sessionPrivKey instanceof Uint8Array)||t.sessionPrivKey.length!==32)throw new Error("invalid-session-privkey");if(!/^wss:\/\//i.test(t.relayUrl)&&!/^ws:\/\/(localhost|127\.0\.0\.1)([:\/]|$)/i.test(t.relayUrl))throw new Error("invalid-relay-url");if(typeof t.expectedOrigin!="string"||t.expectedOrigin.length===0)throw new Error("invalid-expected-origin");let e=le(Te.getPublicKey(t.sessionPrivKey)),n=Math.max(5e3,Math.min(t.timeout??12e4,6e5)),r=t.requestId.toLowerCase(),o=t.expectedOrigin;return new Promise((i,s)=>{let a=`sa-${Math.random().toString(36).slice(2,12)}`,c=!1,l;try{l=new WebSocket(t.relayUrl)}catch{s(new Error("relay-error"));return}let d=u=>{if(!c){c=!0,clearTimeout(g);try{l.close()}catch{}u()}},g=setTimeout(()=>{d(()=>s(new Error("timeout")))},n);l.onopen=()=>{let u=Math.floor(Date.now()/1e3)-60;l.send(JSON.stringify(["REQ",a,{kinds:[1059],"#p":[e],since:u}]))},l.onmessage=async u=>{if(c)return;let f;try{f=JSON.parse(typeof u.data=="string"?u.data:"")}catch{return}if(!Array.isArray(f)||f[0]!=="EVENT"||f[1]!==a)return;let y=f[2];if(typeof y!="object"||y===null)return;let m=y;if(m.kind!==1059||typeof m.pubkey!="string"||typeof m.content!="string")return;let v=await xf({pubkey:m.pubkey,content:m.content},t.sessionPrivKey);if(!v||v.kind!==29999)return;let R=v.tags.find(h=>h[0]==="session");if(!R||R[1]!==r)return;let O=v.tags.find(h=>h[0]==="status");if(O?.[1]==="rejected"){d(()=>s(new Error("denied")));return}if(O?.[1]!=="approved"||Math.abs(Date.now()/1e3-v.created_at)>300)return;let N;try{let h=JSON.parse(v.content);if(typeof h!="object"||h===null)return;N=h}catch{return}if(N.type!=="signet-auth-response"||N.requestId!==r||typeof N.authEvent!="object"||N.authEvent===null)return;let _=N.authEvent;if(typeof _.id!="string"||!/^[0-9a-f]{64}$/i.test(_.id)||typeof _.pubkey!="string"||!/^[0-9a-f]{64}$/i.test(_.pubkey)||typeof _.sig!="string"||!/^[0-9a-f]{128}$/i.test(_.sig)||_.kind!==21236||typeof _.created_at!="number"||!Array.isArray(_.tags)||typeof _.content!="string"||_.pubkey.toLowerCase()!==v.pubkey.toLowerCase()||ti({pubkey:_.pubkey,created_at:_.created_at,kind:21236,tags:_.tags,content:_.content})!==_.id.toLowerCase())return;let j=!1;try{let h=Ke(_.sig),b=Ke(_.id),E=Ke(_.pubkey);j=Te.verify(h,b,E)}catch{j=!1}if(!j)return;let Z=_.tags,L=Z.find(h=>Array.isArray(h)&&h[0]==="challenge");if(!L||typeof L[1]!="string"||L[1].toLowerCase()!==r)return;let z=Z.find(h=>Array.isArray(h)&&h[0]==="origin");if(!z||z[1]!==o||Math.abs(Date.now()/1e3-_.created_at)>300)return;let T={id:_.id.toLowerCase(),pubkey:_.pubkey.toLowerCase(),kind:21236,created_at:_.created_at,tags:Z,content:_.content,sig:_.sig},x=Ef(N.displayName),p=typeof N.bunkerUri=="string"&&/^bunker:\/\//i.test(N.bunkerUri)?N.bunkerUri:void 0;d(()=>i({pubkey:T.pubkey,authEvent:T,credential:N.credential,...x!==void 0?{displayName:x}:{},...p!==void 0?{bunkerUri:p}:{},createdAt:T.created_at}))},l.onerror=()=>{d(()=>s(new Error("relay-error")))}})}typeof window<"u"&&(window.Signet={verifyAge:wf,waitForAuthResponse:ni});var Ya=/^[0-9a-f]{64}$/i,vf=/^[0-9a-f]{128}$/i;function Sf(t){let e=t.redirectCallback??`${t.origin}/`,n=new URLSearchParams({auth:"1",challenge:t.challenge,origin:t.origin,name:t.appName,callback:e,t:String(Math.floor(Date.now()/1e3))});return`${t.signetAppOrigin}/?${n.toString()}`}function Sr(t){if(typeof window>"u")throw new Error("signet-login: redirect mode requires a browser environment");let e={challenge:t.challenge,origin:t.origin,appName:t.appName,createdAt:Date.now()};rr(e);let n=Sf(t);return window.location.href=n,new Promise(()=>{})}function kf(){if(typeof window>"u")return;let t=new URL(window.location.href),e=["pubkey","npub","signature","eventId","error","warnings","fromNP","display_name","t","bunker","avatar_hash","avatar_url","avatar_key"],n=!1;for(let o of e)t.searchParams.has(o)&&(t.searchParams.delete(o),n=!0);if(!n)return;let r=t.pathname+(t.search?t.search:"")+t.hash;try{window.history.replaceState(window.history.state,document.title,r)}catch{}}function Ja(){if(typeof window>"u")return{kind:"no-callback"};let t=new URLSearchParams(window.location.search),e=t.get("error"),n=t.get("pubkey"),r=t.get("signature"),o=t.get("eventId");if(!e&&!n&&!r&&!o)return{kind:"no-callback"};let i=or(),s=q=>(ir(),kf(),q);if(e==="denied")return s({kind:"denied"});if(!i)return s({kind:"invalid",reason:"no-pending-state"});if(i.origin!==window.location.origin)return s({kind:"invalid",reason:"origin-mismatch"});if(Date.now()-i.createdAt>Ln)return s({kind:"invalid",reason:"pending-stale"});if(!n||!Ya.test(n))return s({kind:"invalid",reason:"pubkey-malformed"});if(!r||!vf.test(r))return s({kind:"invalid",reason:"signature-malformed"});if(!o||!Ya.test(o))return s({kind:"invalid",reason:"eventId-malformed"});let a,c=t.get("t");if(c&&/^\d+$/.test(c)){let q=Number(c);if(!Number.isFinite(q))return s({kind:"invalid",reason:"t-malformed"});a=q}else a=Math.floor(Date.now()/1e3),typeof console<"u"&&console.warn("signet-login: redirect callback missing `t` param \u2014 auth event created_at approximated. Server-side verification may reject. Upgrade signet-app to emit `t` in the redirect URL.");let l=n.toLowerCase(),d=r.toLowerCase(),g=o.toLowerCase(),u=[["challenge",i.challenge],["origin",i.origin]],f=t.get("avatar_hash"),y=t.get("avatar_url"),m=t.get("avatar_key");f&&/^[0-9a-f]{64}$/i.test(f)&&u.push(["avatar_hash",f]),y&&y.length<=500&&u.push(["avatar_url",y]),m&&/^[0-9a-f]{64}$/i.test(m)&&u.push(["avatar_key",m]);let v={id:g,pubkey:l,kind:21236,created_at:a,tags:u,content:"",sig:d},R=t.get("display_name")||void 0,O=new Ee(l,v),I={pubkey:l,method:"redirect",signer:O,authEvent:v};R&&(I.displayName=R);let N=t.get("bunker"),_;return N&&N.length>=9&&N.length<=8192&&N.slice(0,9).toLowerCase()==="bunker://"&&(_=N),s(_?{kind:"session",session:I,bunkerUri:_}:{kind:"session",session:I})}var Ri=fl(Jc(),1),md=8e3;function Ai(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function wd(){let t=new Uint8Array(32);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function Bt(t){return t==="dark"?!0:t==="light"?!1:typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches}function xd(t){let e=document.createElement("style");e.textContent="#signet-login-dialog::backdrop{background:rgba(0,0,0,0.7)}",document.head.appendChild(e);let n=Bt(t),r=n?"#1a1a2e":"#ffffff",o=n?"#e0e0e0":"#1a1a2e",i=document.createElement("dialog");i.id="signet-login-dialog",i.style.cssText=`border:none;border-radius:16px;padding:32px;max-width:380px;width:90%;text-align:center;box-shadow:0 20px 60px rgba(0,0,0,0.3);background:${r};color:${o};font-family:system-ui,-apple-system,sans-serif;`,document.body.appendChild(i),i.showModal();let s=()=>Array.from(i.querySelectorAll("button")).filter(u=>{if(u.disabled||!u.isConnected)return!1;let f=window.getComputedStyle(u);return f.display!=="none"&&f.visibility!=="hidden"}),a=()=>document.activeElement instanceof HTMLButtonElement&&i.contains(document.activeElement)?document.activeElement:null,c=0,l=()=>{let u=s();u.length!==0&&(c=Math.min(Math.max(c,0),u.length-1),u[c].focus())},d=u=>{if(!i.isConnected||!i.open)return;let f=u.target;if(f&&(f.tagName==="INPUT"||f.tagName==="TEXTAREA")&&u.isTrusted)return;let y=s();if(y.length===0)return;let m=u.key||u.code,v=u.code||u.key,R=m==="ArrowDown"||v==="ArrowDown"||m==="ArrowRight"||v==="ArrowRight"?1:m==="ArrowUp"||v==="ArrowUp"||m==="ArrowLeft"||v==="ArrowLeft"?-1:0;if(R){u.preventDefault(),u.stopImmediatePropagation();let O=a(),I=O?y.indexOf(O):-1;c=((I>=0?I:c)+R+y.length)%y.length,y[c].focus();return}u.isTrusted||(u.key==="Enter"||u.key===" "||u.code==="Space"||u.code==="Enter"?(u.preventDefault(),u.stopImmediatePropagation(),y[Math.min(Math.max(c,0),y.length-1)].click()):(u.key==="Escape"||u.code==="Escape")&&(u.preventDefault(),u.stopImmediatePropagation(),(i.querySelector('[data-action="back"]')??i.querySelector('[data-action="cancel"],[data-choice="cancel"]'))?.click()))};window.addEventListener("keydown",d,!0);let g=new MutationObserver(()=>{c=0,l()});return g.observe(i,{childList:!0}),l(),{dialog:i,style:e,cleanupNav:()=>{window.removeEventListener("keydown",d,!0),g.disconnect()}}}function Ed(t){t.cleanupNav?.();try{t.dialog.close()}catch{}t.dialog.remove(),t.style.remove()}function ae(t,e=!1){return e?"background:#2c3e8f;color:white;border:0;padding:12px 16px;border-radius:8px;cursor:pointer;font-size:0.95rem;width:100%;margin-bottom:8px;text-align:left;display:flex;align-items:center;gap:12px;":`background:transparent;color:${t?"#e0e0e0":"#1a1a2e"};border:1px solid ${t?"#3a3a4e":"#d0d0d0"};padding:12px 16px;border-radius:8px;cursor:pointer;font-size:0.95rem;width:100%;margin-bottom:8px;text-align:left;display:flex;align-items:center;gap:12px;`}function vd(t,e,n){let r=Bt(n),o=r?"#888":"#666",i=fn(),s=sr();return t.dialog.innerHTML=`
|
|
14
|
+
`,document.body.appendChild(y),y.showModal();let m=y.querySelector("#signet-qr");if(m){let R=document.createElement("div");R.style.cssText=`width:200px;height:200px;background:${d?"#2a2a3e":"#f0f0f0"};border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:0.75rem;color:${f};word-break:break-all;padding:12px;`,R.textContent=`signet:verify:${a.slice(0,40)}...`,m.appendChild(R)}let v=new BroadcastChannel("signet-verify-"+o);y.querySelector("#signet-cancel")?.addEventListener("click",()=>{v.close(),y.close(),y.remove(),l.remove(),c({verified:!1,ageRange:null,tier:null,entityType:null,credentialId:null,verifierPubkey:null,verifierConfirmed:null,verifierMethod:null,issuedAt:null,expiresAt:null,error:"cancelled"})}),v.onmessage=async R=>{let O=R.data;if(typeof O!="object"||O===null)return;let I=O;if(I.type!=="signet-verify-response"||I.requestId!==o||!I.credential||typeof I.credential!="object"||!Array.isArray(I.credential.tags))return;let N=I.credential,_=await yf(N),q=vr(N.tags,"age-range"),j=vr(N.tags,"tier"),Z=vr(N.tags,"entity-type"),L=vr(N.tags,"expires"),z=q?bf(q,r.requiredAgeRange):!1,$=await mf(N.pubkey,r.verifierCheckUrl),T=$?.confirmed??null,x=$?.method??null,p=r.acceptUnconfirmed||T===!0;y.close(),y.remove(),l.remove(),v.close();let h=j?parseInt(j,10):null,b=L?parseInt(L,10):null,E=Math.floor(Date.now()/1e3),B=b===null||!isNaN(b)&&b>E,w;_?B?z?p||(w=T===!1?"verifier-not-confirmed":"verifier-check-unavailable"):w="age-range-not-met":w="credential-expired":w="invalid-credential",c({verified:_&&B&&z&&p,ageRange:q||null,tier:h!==null&&!isNaN(h)?h:null,entityType:Z||null,credentialId:N.id,verifierPubkey:N.pubkey,verifierConfirmed:T,verifierMethod:x,issuedAt:N.created_at,expiresAt:b!==null&&!isNaN(b)?b:null,error:w})},setTimeout(()=>{y.close(),y.remove(),l.remove(),v.close(),c({verified:!1,ageRange:null,tier:null,entityType:null,credentialId:null,verifierPubkey:null,verifierConfirmed:null,verifierMethod:null,issuedAt:null,expiresAt:null,error:"timeout"})},r.timeout)})}function ti(t){let e=JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content]),n=ei(new TextEncoder().encode(e));return le(n)}async function xf(t,e){try{let n=Ot(e,t.pubkey),r=ln(t.content,n),o=JSON.parse(r);if(typeof o!="object"||o===null)return null;let i=o;if(i.kind!==13||typeof i.pubkey!="string"||!/^[0-9a-f]{64}$/i.test(i.pubkey)||typeof i.created_at!="number"||!Array.isArray(i.tags)||typeof i.content!="string"||typeof i.id!="string"||!/^[0-9a-f]{64}$/i.test(i.id)||typeof i.sig!="string"||!/^[0-9a-f]{128}$/i.test(i.sig)||ti({pubkey:i.pubkey,created_at:i.created_at,kind:13,tags:i.tags,content:i.content})!==i.id.toLowerCase())return null;let a=Ke(i.sig),c=Ke(i.id),l=Ke(i.pubkey);if(!Te.verify(a,c,l))return null;let d=Ot(e,i.pubkey),g=ln(i.content,d),u=JSON.parse(g);if(typeof u!="object"||u===null)return null;let f=u;if(typeof f.pubkey!="string"||f.pubkey!==i.pubkey||typeof f.kind!="number"||typeof f.created_at!="number"||!Array.isArray(f.tags)||typeof f.content!="string")return null;let y=typeof f.id=="string"?f.id:ti({pubkey:f.pubkey,created_at:f.created_at,kind:f.kind,tags:f.tags,content:f.content});return{pubkey:f.pubkey,id:y,kind:f.kind,created_at:f.created_at,tags:f.tags,content:f.content}}catch{return null}}function Ef(t){if(typeof t!="string")return;let e=t.replace(/[\x00-\x1f\x7f-\x9f\u200b-\u200f\u2028-\u202e\u2066-\u2069]/g,"").trim().slice(0,64);return e.length>0?e:void 0}async function ni(t){if(!/^[0-9a-f]{64}$/i.test(t.requestId))throw new Error("invalid-request-id");if(!(t.sessionPrivKey instanceof Uint8Array)||t.sessionPrivKey.length!==32)throw new Error("invalid-session-privkey");if(!/^wss:\/\//i.test(t.relayUrl)&&!/^ws:\/\/(localhost|127\.0\.0\.1)([:\/]|$)/i.test(t.relayUrl))throw new Error("invalid-relay-url");if(typeof t.expectedOrigin!="string"||t.expectedOrigin.length===0)throw new Error("invalid-expected-origin");let e=le(Te.getPublicKey(t.sessionPrivKey)),n=Math.max(5e3,Math.min(t.timeout??12e4,6e5)),r=t.requestId.toLowerCase(),o=t.expectedOrigin;return new Promise((i,s)=>{let a=`sa-${Math.random().toString(36).slice(2,12)}`,c=!1,l;try{l=new WebSocket(t.relayUrl)}catch{s(new Error("relay-error"));return}let d=u=>{if(!c){c=!0,clearTimeout(g);try{l.close()}catch{}u()}},g=setTimeout(()=>{d(()=>s(new Error("timeout")))},n);l.onopen=()=>{let u=Math.floor(Date.now()/1e3)-60;l.send(JSON.stringify(["REQ",a,{kinds:[1059],"#p":[e],since:u}]))},l.onmessage=async u=>{if(c)return;let f;try{f=JSON.parse(typeof u.data=="string"?u.data:"")}catch{return}if(!Array.isArray(f)||f[0]!=="EVENT"||f[1]!==a)return;let y=f[2];if(typeof y!="object"||y===null)return;let m=y;if(m.kind!==1059||typeof m.pubkey!="string"||typeof m.content!="string")return;let v=await xf({pubkey:m.pubkey,content:m.content},t.sessionPrivKey);if(!v||v.kind!==29999)return;let R=v.tags.find(h=>h[0]==="session");if(!R||R[1]!==r)return;let O=v.tags.find(h=>h[0]==="status");if(O?.[1]==="rejected"){d(()=>s(new Error("denied")));return}if(O?.[1]!=="approved"||Math.abs(Date.now()/1e3-v.created_at)>300)return;let N;try{let h=JSON.parse(v.content);if(typeof h!="object"||h===null)return;N=h}catch{return}if(N.type!=="signet-auth-response"||N.requestId!==r||typeof N.authEvent!="object"||N.authEvent===null)return;let _=N.authEvent;if(typeof _.id!="string"||!/^[0-9a-f]{64}$/i.test(_.id)||typeof _.pubkey!="string"||!/^[0-9a-f]{64}$/i.test(_.pubkey)||typeof _.sig!="string"||!/^[0-9a-f]{128}$/i.test(_.sig)||_.kind!==21236||typeof _.created_at!="number"||!Array.isArray(_.tags)||typeof _.content!="string"||_.pubkey.toLowerCase()!==v.pubkey.toLowerCase()||ti({pubkey:_.pubkey,created_at:_.created_at,kind:21236,tags:_.tags,content:_.content})!==_.id.toLowerCase())return;let j=!1;try{let h=Ke(_.sig),b=Ke(_.id),E=Ke(_.pubkey);j=Te.verify(h,b,E)}catch{j=!1}if(!j)return;let Z=_.tags,L=Z.find(h=>Array.isArray(h)&&h[0]==="challenge");if(!L||typeof L[1]!="string"||L[1].toLowerCase()!==r)return;let z=Z.find(h=>Array.isArray(h)&&h[0]==="origin");if(!z||z[1]!==o||Math.abs(Date.now()/1e3-_.created_at)>300)return;let T={id:_.id.toLowerCase(),pubkey:_.pubkey.toLowerCase(),kind:21236,created_at:_.created_at,tags:Z,content:_.content,sig:_.sig},x=Ef(N.displayName),p=typeof N.bunkerUri=="string"&&/^bunker:\/\//i.test(N.bunkerUri)?N.bunkerUri:void 0;d(()=>i({pubkey:T.pubkey,authEvent:T,credential:N.credential,...x!==void 0?{displayName:x}:{},...p!==void 0?{bunkerUri:p}:{},createdAt:T.created_at}))},l.onerror=()=>{d(()=>s(new Error("relay-error")))}})}typeof window<"u"&&(window.Signet={verifyAge:wf,waitForAuthResponse:ni});var Ya=/^[0-9a-f]{64}$/i,vf=/^[0-9a-f]{128}$/i;function Sf(t){let e=t.redirectCallback??`${t.origin}/`,n=new URLSearchParams({auth:"1",challenge:t.challenge,origin:t.origin,name:t.appName,callback:e,t:String(Math.floor(Date.now()/1e3))});return`${t.signetAppOrigin}/?${n.toString()}`}function Sr(t){if(typeof window>"u")throw new Error("signet-login: redirect mode requires a browser environment");let e={challenge:t.challenge,origin:t.origin,appName:t.appName,createdAt:Date.now()};rr(e);let n=Sf(t);return window.location.href=n,new Promise(()=>{})}function kf(){if(typeof window>"u")return;let t=new URL(window.location.href),e=["pubkey","npub","signature","eventId","error","warnings","fromNP","display_name","t","bunker","avatar_hash","avatar_url","avatar_key"],n=!1;for(let o of e)t.searchParams.has(o)&&(t.searchParams.delete(o),n=!0);if(!n)return;let r=t.pathname+(t.search?t.search:"")+t.hash;try{window.history.replaceState(window.history.state,document.title,r)}catch{}}function Ja(){if(typeof window>"u")return{kind:"no-callback"};let t=new URLSearchParams(window.location.search),e=t.get("error"),n=t.get("pubkey"),r=t.get("signature"),o=t.get("eventId");if(!e&&!n&&!r&&!o)return{kind:"no-callback"};let i=or(),s=q=>(ir(),kf(),q);if(e==="denied")return s({kind:"denied"});if(!i)return s({kind:"invalid",reason:"no-pending-state"});if(i.origin!==window.location.origin)return s({kind:"invalid",reason:"origin-mismatch"});if(Date.now()-i.createdAt>Tn)return s({kind:"invalid",reason:"pending-stale"});if(!n||!Ya.test(n))return s({kind:"invalid",reason:"pubkey-malformed"});if(!r||!vf.test(r))return s({kind:"invalid",reason:"signature-malformed"});if(!o||!Ya.test(o))return s({kind:"invalid",reason:"eventId-malformed"});let a,c=t.get("t");if(c&&/^\d+$/.test(c)){let q=Number(c);if(!Number.isFinite(q))return s({kind:"invalid",reason:"t-malformed"});a=q}else a=Math.floor(Date.now()/1e3),typeof console<"u"&&console.warn("signet-login: redirect callback missing `t` param \u2014 auth event created_at approximated. Server-side verification may reject. Upgrade signet-app to emit `t` in the redirect URL.");let l=n.toLowerCase(),d=r.toLowerCase(),g=o.toLowerCase(),u=[["challenge",i.challenge],["origin",i.origin]],f=t.get("avatar_hash"),y=t.get("avatar_url"),m=t.get("avatar_key");f&&/^[0-9a-f]{64}$/i.test(f)&&u.push(["avatar_hash",f]),y&&y.length<=500&&u.push(["avatar_url",y]),m&&/^[0-9a-f]{64}$/i.test(m)&&u.push(["avatar_key",m]);let v={id:g,pubkey:l,kind:21236,created_at:a,tags:u,content:"",sig:d},R=t.get("display_name")||void 0,O=new Ee(l,v),I={pubkey:l,method:"redirect",signer:O,authEvent:v};R&&(I.displayName=R);let N=t.get("bunker"),_;return N&&N.length>=9&&N.length<=8192&&N.slice(0,9).toLowerCase()==="bunker://"&&(_=N),s(_?{kind:"session",session:I,bunkerUri:_}:{kind:"session",session:I})}var Ri=fl(Jc(),1),md=8e3;function Ai(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function wd(){let t=new Uint8Array(32);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function Bt(t){return t==="dark"?!0:t==="light"?!1:typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches}function xd(t){let e=document.createElement("style");e.textContent="#signet-login-dialog::backdrop{background:rgba(0,0,0,0.7)}",document.head.appendChild(e);let n=Bt(t),r=n?"#1a1a2e":"#ffffff",o=n?"#e0e0e0":"#1a1a2e",i=document.createElement("dialog");i.id="signet-login-dialog",i.style.cssText=`border:none;border-radius:16px;padding:32px;max-width:380px;width:90%;text-align:center;box-shadow:0 20px 60px rgba(0,0,0,0.3);background:${r};color:${o};font-family:system-ui,-apple-system,sans-serif;`,document.body.appendChild(i),i.showModal();let s=()=>Array.from(i.querySelectorAll("button")).filter(u=>{if(u.disabled||!u.isConnected)return!1;let f=window.getComputedStyle(u);return f.display!=="none"&&f.visibility!=="hidden"}),a=()=>document.activeElement instanceof HTMLButtonElement&&i.contains(document.activeElement)?document.activeElement:null,c=0,l=()=>{let u=s();u.length!==0&&(c=Math.min(Math.max(c,0),u.length-1),u[c].focus())},d=u=>{if(!i.isConnected||!i.open)return;let f=u.target;if(f&&(f.tagName==="INPUT"||f.tagName==="TEXTAREA")&&u.isTrusted)return;let y=s();if(y.length===0)return;let m=u.key||u.code,v=u.code||u.key,R=m==="ArrowDown"||v==="ArrowDown"||m==="ArrowRight"||v==="ArrowRight"?1:m==="ArrowUp"||v==="ArrowUp"||m==="ArrowLeft"||v==="ArrowLeft"?-1:0;if(R){u.preventDefault(),u.stopImmediatePropagation();let O=a(),I=O?y.indexOf(O):-1;c=((I>=0?I:c)+R+y.length)%y.length,y[c].focus();return}u.isTrusted||(u.key==="Enter"||u.key===" "||u.code==="Space"||u.code==="Enter"?(u.preventDefault(),u.stopImmediatePropagation(),y[Math.min(Math.max(c,0),y.length-1)].click()):(u.key==="Escape"||u.code==="Escape")&&(u.preventDefault(),u.stopImmediatePropagation(),(i.querySelector('[data-action="back"]')??i.querySelector('[data-action="cancel"],[data-choice="cancel"]'))?.click()))};window.addEventListener("keydown",d,!0);let g=new MutationObserver(()=>{c=0,l()});return g.observe(i,{childList:!0}),l(),{dialog:i,style:e,cleanupNav:()=>{window.removeEventListener("keydown",d,!0),g.disconnect()}}}function Ed(t){t.cleanupNav?.();try{t.dialog.close()}catch{}t.dialog.remove(),t.style.remove()}function ae(t,e=!1){return e?"background:#2c3e8f;color:white;border:0;padding:12px 16px;border-radius:8px;cursor:pointer;font-size:0.95rem;width:100%;margin-bottom:8px;text-align:left;display:flex;align-items:center;gap:12px;":`background:transparent;color:${t?"#e0e0e0":"#1a1a2e"};border:1px solid ${t?"#3a3a4e":"#d0d0d0"};padding:12px 16px;border-radius:8px;cursor:pointer;font-size:0.95rem;width:100%;margin-bottom:8px;text-align:left;display:flex;align-items:center;gap:12px;`}function vd(t,e,n){let r=Bt(n),o=r?"#888":"#666",i=un(),s=sr();return t.dialog.innerHTML=`
|
|
15
15
|
<h2 style="margin:0 0 8px;font-size:1.3rem;">Sign in to ${Ai(e)}</h2>
|
|
16
16
|
<p style="margin:0 0 24px;color:${o};font-size:0.9rem;">Choose how you want to sign in. Your keys never leave your control.</p>
|
|
17
17
|
<div style="display:flex;flex-direction:column;">
|
|
@@ -36,7 +36,7 @@ Minimum version required to store current data is: `+i+`.
|
|
|
36
36
|
<button data-action="cancel" style="${ae(n)}width:auto;flex:0 0 auto;padding:8px 16px;">Cancel</button>
|
|
37
37
|
</div>
|
|
38
38
|
<style>@keyframes signet-login-spin{to{transform:rotate(360deg)}}</style>
|
|
39
|
-
`;let i=t.dialog.querySelector("#signet-login-nip07-elapsed"),s=0,a=window.setInterval(()=>{s+=1,i&&(i.textContent=`Waiting for your signer (${s}s)\u2026`)},1e3),c=new Promise(l=>{t.dialog.querySelector('[data-action="back"]')?.addEventListener("click",()=>l(null)),t.dialog.querySelector('[data-action="cancel"]')?.addEventListener("click",()=>l(null))});try{let l=await Promise.race([
|
|
39
|
+
`;let i=t.dialog.querySelector("#signet-login-nip07-elapsed"),s=0,a=window.setInterval(()=>{s+=1,i&&(i.textContent=`Waiting for your signer (${s}s)\u2026`)},1e3),c=new Promise(l=>{t.dialog.querySelector('[data-action="back"]')?.addEventListener("click",()=>l(null)),t.dialog.querySelector('[data-action="cancel"]')?.addEventListener("click",()=>l(null))});try{let l=await Promise.race([fn(),c]);if(!l)return null;let d=await Promise.race([l.signEvent({kind:21236,content:"",tags:[["challenge",e.challenge],["origin",e.origin],["app",e.appName]]}),c]);if(!d){try{await l.close()}catch{}return null}return{pubkey:l.pubkey,authEvent:d}}catch(l){return i&&(i.textContent=`\u2717 ${l instanceof Error?l.message:String(l)}`,i.style.color="#d04848"),await Promise.race([new Promise(d=>setTimeout(d,2500)),c]),null}finally{window.clearInterval(a)}}async function kd(t,e){let n=Bt(e.theme),r=n?"#888":"#666",o=Te.utils.randomPrivateKey(),i=le(Te.getPublicKey(o)),s=new URLSearchParams({auth:"1",challenge:e.challenge,origin:e.origin,name:e.appName,callback:e.redirectCallback??`${e.origin}/`,t:String(Math.floor(Date.now()/1e3)),relay:e.relayUrl,sessionPubkey:i}),a=`${e.signetAppOrigin}/?${s.toString()}`;t.dialog.innerHTML=`
|
|
40
40
|
<h2 style="margin:0 0 8px;font-size:1.2rem;">Sign in with Signet</h2>
|
|
41
41
|
<p style="margin:0 0 16px;color:${r};font-size:0.85rem;">Open the link on your phone, or scan the QR if rendered.</p>
|
|
42
42
|
<div style="background:${n?"#0f0f1f":"#f5f5f8"};border-radius:8px;padding:16px;margin-bottom:16px;">
|
|
@@ -57,7 +57,7 @@ Minimum version required to store current data is: `+i+`.
|
|
|
57
57
|
<button data-action="back" style="${ae(n)}width:auto;flex:0 0 auto;padding:8px 16px;">\u2190 Back</button>
|
|
58
58
|
<button data-action="connect" style="${ae(n,!0)}width:auto;flex:1;padding:8px 16px;text-align:center;">Connect</button>
|
|
59
59
|
</div>
|
|
60
|
-
`,new Promise(s=>{let a=!1,c=u=>{a||(a=!0,s(u))},l=t.dialog.querySelector("#signet-login-bunker-input"),d=t.dialog.querySelector("#signet-login-bunker-status"),g=t.dialog.querySelector('[data-action="connect"]');t.dialog.querySelector('[data-action="back"]')?.addEventListener("click",()=>{c(null)}),g?.addEventListener("click",async()=>{let u=l?.value.trim()??"";if(!u){d&&(d.textContent="Please paste a bunker URI.");return}d&&(d.textContent="Connecting\u2026",d.style.color=""),g.disabled=!0;try{let f=await
|
|
60
|
+
`,new Promise(s=>{let a=!1,c=u=>{a||(a=!0,s(u))},l=t.dialog.querySelector("#signet-login-bunker-input"),d=t.dialog.querySelector("#signet-login-bunker-status"),g=t.dialog.querySelector('[data-action="connect"]');t.dialog.querySelector('[data-action="back"]')?.addEventListener("click",()=>{c(null)}),g?.addEventListener("click",async()=>{let u=l?.value.trim()??"";if(!u){d&&(d.textContent="Please paste a bunker URI.");return}d&&(d.textContent="Connecting\u2026",d.style.color=""),g.disabled=!0;try{let f=await Pt({uri:u,clientSecretKey:ht()});c(f)}catch(f){d&&(d.textContent=`\u2717 ${f instanceof Error?f.message:String(f)}`,d.style.color="#d04848"),g.disabled=!1}})})}async function Ad(t,e){let n=Bt(e.theme),r=n?"#888":"#666",o=ht(),i=le(Te.getPublicKey(o)),s=le(Te.utils.randomPrivateKey()).slice(0,32),a=na({clientPubkeyHex:i,relayUrl:e.relayUrl,secret:s,perms:["sign_event","nip44_encrypt","nip44_decrypt"],appName:e.appName,appUrl:e.origin});t.dialog.innerHTML=`
|
|
61
61
|
<h2 style="margin:0 0 8px;font-size:1.2rem;">Connect a Nostr signer</h2>
|
|
62
62
|
<p style="margin:0 0 16px;color:${r};font-size:0.85rem;">Scan or paste this into your signer (nsec.app, Amber, Keychat\u2026). The connection happens over your relay.</p>
|
|
63
63
|
<div style="background:${n?"#0f0f1f":"#f5f5f8"};border-radius:8px;padding:16px;margin-bottom:16px;">
|
|
@@ -79,7 +79,7 @@ Minimum version required to store current data is: `+i+`.
|
|
|
79
79
|
<button data-action="back" style="${ae(n)}width:auto;flex:0 0 auto;padding:8px 16px;">\u2190 Back</button>
|
|
80
80
|
<button data-action="connect" style="${ae(n,!0)}width:auto;flex:1;padding:8px 16px;text-align:center;">Sign in</button>
|
|
81
81
|
</div>
|
|
82
|
-
`,new Promise(s=>{let a=!1,c=u=>{a||(a=!0,s(u))},l=t.dialog.querySelector("#signet-login-nsec-input"),d=t.dialog.querySelector("#signet-login-nsec-status"),g=t.dialog.querySelector('[data-action="connect"]');t.dialog.querySelector('[data-action="back"]')?.addEventListener("click",()=>{l&&(l.value=""),c(null)}),g?.addEventListener("click",()=>{let u=l?.value??"";if(!u.trim()){d&&(d.textContent="Please paste an nsec.");return}try{let f=ra(u);l&&(l.value=""),c(f)}catch(f){d&&(d.textContent=`\u2717 ${f instanceof Error?f.message:String(f)}`,d.style.color="#d04848")}})})}function Cd(t){let e=t.challenge??wd();if(!/^[0-9a-f]{64}$/i.test(e))throw new Error("challenge-must-be-64-hex");let n=typeof window<"u"?window.location.origin:"http://localhost",r=Math.max(5e3,Math.min(t.timeout??je.timeout,6e5)),o={appName:t.appName,challenge:e.toLowerCase(),origin:n,relayUrl:t.relayUrl??je.relayUrl,theme:t.theme??je.theme,timeout:r,signetAppOrigin:t.signetAppOrigin??je.signetAppOrigin};return t.preferredMethod!==void 0&&(o.preferredMethod=t.preferredMethod),t.redirectCallback!==void 0&&(o.redirectCallback=t.redirectCallback),o}async function Xc(t){if(!t.appName||t.appName.length===0)throw new Error("appName-required");if(t.appName.length>64)throw new Error("appName-too-long");let e=Cd(t),n=xd(e.theme),r=!1,o=new Promise(i=>{n.dialog.addEventListener("cancel",()=>{r=!0,i(null)})});try{for(;;){let i=e.preferredMethod?e.preferredMethod:await Promise.race([vd(n,e.appName,e.theme),o]);if(r||i===null||i==="cancel")return null;if(i==="nip07"){let s=await Promise.race([Sd(n,e),o]);if(r)return null;if(!s){if(e.preferredMethod)return null;continue}let a=await
|
|
82
|
+
`,new Promise(s=>{let a=!1,c=u=>{a||(a=!0,s(u))},l=t.dialog.querySelector("#signet-login-nsec-input"),d=t.dialog.querySelector("#signet-login-nsec-status"),g=t.dialog.querySelector('[data-action="connect"]');t.dialog.querySelector('[data-action="back"]')?.addEventListener("click",()=>{l&&(l.value=""),c(null)}),g?.addEventListener("click",()=>{let u=l?.value??"";if(!u.trim()){d&&(d.textContent="Please paste an nsec.");return}try{let f=ra(u);l&&(l.value=""),c(f)}catch(f){d&&(d.textContent=`\u2717 ${f instanceof Error?f.message:String(f)}`,d.style.color="#d04848")}})})}function Cd(t){let e=t.challenge??wd();if(!/^[0-9a-f]{64}$/i.test(e))throw new Error("challenge-must-be-64-hex");let n=typeof window<"u"?window.location.origin:"http://localhost",r=Math.max(5e3,Math.min(t.timeout??je.timeout,6e5)),o={appName:t.appName,challenge:e.toLowerCase(),origin:n,relayUrl:t.relayUrl??je.relayUrl,theme:t.theme??je.theme,timeout:r,signetAppOrigin:t.signetAppOrigin??je.signetAppOrigin};return t.preferredMethod!==void 0&&(o.preferredMethod=t.preferredMethod),t.redirectCallback!==void 0&&(o.redirectCallback=t.redirectCallback),o}async function Xc(t){if(!t.appName||t.appName.length===0)throw new Error("appName-required");if(t.appName.length>64)throw new Error("appName-too-long");let e=Cd(t),n=xd(e.theme),r=!1,o=new Promise(i=>{n.dialog.addEventListener("cancel",()=>{r=!0,i(null)})});try{for(;;){let i=e.preferredMethod?e.preferredMethod:await Promise.race([vd(n,e.appName,e.theme),o]);if(r||i===null||i==="cancel")return null;if(i==="nip07"){let s=await Promise.race([Sd(n,e),o]);if(r)return null;if(!s){if(e.preferredMethod)return null;continue}let a=await fn();return{pubkey:s.pubkey,method:"nip07",signer:a,authEvent:s.authEvent}}if(i==="redirect")return await Sr({appName:e.appName,challenge:e.challenge,origin:e.origin,signetAppOrigin:e.signetAppOrigin,...e.redirectCallback!==void 0?{redirectCallback:e.redirectCallback}:{}}),null;if(i==="amber")return await aa({appName:e.appName,challenge:e.challenge,origin:e.origin,...e.redirectCallback!==void 0?{redirectCallback:e.redirectCallback}:{}}),null;if(i==="qr"){let s=await Promise.race([kd(n,e),o]);if(r)return null;if(!s){if(e.preferredMethod)return null;continue}let a=new Ee(s.pubkey,s.authEvent),c="redirect";if(s.bunkerUri){let d=ht(),g=s.pubkey,u=n.dialog.querySelector("#signet-login-status");u&&(u.textContent="Connecting signer...");try{let f=await Pt({uri:s.bunkerUri,clientSecretKey:d,timeoutMs:md});if(f.pubkey.toLowerCase()!==g.toLowerCase()){if(console.warn("[signet-login] QR upgrade: bunker pubkey mismatch \u2014 cannot sign",{connected:f.pubkey,expected:g}),f.close().catch(()=>{}),u&&(u.textContent="Signer connected with the wrong public key.",u.style.color="#d04848"),await Promise.race([new Promise(y=>setTimeout(y,2500)),o]),r||e.preferredMethod)return null;continue}a=f}catch(f){if(console.warn("[signet-login] QR upgrade: createBunkerSigner failed \u2014 signer did not become live.",f),u&&(u.textContent=`Signer connection failed: ${f instanceof Error?f.message:String(f)}`,u.style.color="#d04848"),await Promise.race([new Promise(y=>setTimeout(y,2500)),o]),r||e.preferredMethod)return null;continue}c="bunker"}else console.warn("[signet-login] QR login carried no bunkerUri \u2014 auth-only ephemeral (cannot sign). The signer device must have its NIP-46 server enabled to hand back a bunker:// URI.");let l={pubkey:s.pubkey,method:c,signer:a,authEvent:s.authEvent};return s.displayName&&(l.displayName=s.displayName),l}if(i==="bunker"){let s=await Promise.race([Bd(n,e),o]);if(r)return null;if(!s){if(e.preferredMethod)return null;continue}let a=await s.signEvent({kind:21236,content:"",tags:[["challenge",e.challenge],["origin",e.origin],["app",e.appName]]});return{pubkey:s.pubkey,method:"bunker",signer:s,authEvent:a}}if(i==="nostrconnect"){let s=await Promise.race([Ad(n,e),o]);if(r)return null;if(!s){if(e.preferredMethod)return null;continue}let a=await s.signEvent({kind:21236,content:"",tags:[["challenge",e.challenge],["origin",e.origin],["app",e.appName]]});return{pubkey:s.pubkey,method:"bunker",signer:s,authEvent:a}}if(i==="nsec"){let s=await Promise.race([Rd(n,e),o]);if(r)return null;if(!s){if(e.preferredMethod)return null;continue}let a=await s.signEvent({kind:21236,content:"",tags:[["challenge",e.challenge],["origin",e.origin],["app",e.appName]]});return{pubkey:s.pubkey,method:"nsec",signer:s,authEvent:a}}}}finally{Ed(n)}}function Fc(t){let e={};typeof window<"u"&&new URLSearchParams(window.location.search).forEach((o,i)=>{e[i]=o});let n=typeof window<"u"&&!!window.opener&&window.opener!==window;if(n){try{window.opener.postMessage({type:"signet-login-callback",params:e},"*")}catch{}if(t?.closeAfterPost??!0)try{window.close()}catch{}}return{params:e,isPopup:n}}var Td=8e3;async function Qc(t){if(t.mode==="redirect"){if(typeof window>"u")throw new Error("signet-login: redirect mode requires a browser environment");let n=t.challenge??Ld();if(!/^[0-9a-f]{64}$/i.test(n))throw new Error("challenge-must-be-64-hex");if(!t.appName||t.appName.length===0)throw new Error("appName-required");if(t.appName.length>64)throw new Error("appName-too-long");return Sr({appName:t.appName,challenge:n.toLowerCase(),origin:window.location.origin,signetAppOrigin:t.signetAppOrigin??je.signetAppOrigin,...t.redirectCallback!==void 0?{redirectCallback:t.redirectCallback}:{}})}let e=await Xc(t);return e?(t.persist!==!1&&Cn(e),e):null}function Ld(){let t=new Uint8Array(32);return crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}async function el(t){let e=ia();if(!e)return null;let n;try{n=JSON.parse(e.authEventJson)}catch{return Je(),null}if(e.method==="nip07"){if(!un()){let i=new Ee(e.pubkey,n);return{pubkey:e.pubkey,method:"redirect",signer:i,authEvent:n}}try{let i=await fn();return i.pubkey!==e.pubkey?(Je(),null):{pubkey:e.pubkey,method:"nip07",signer:i,authEvent:n}}catch{return Je(),null}}if(e.method==="bunker"){if(t?.reconnectBunker===!1){let i=new Ee(e.pubkey,n);return{pubkey:e.pubkey,method:"redirect",signer:i,authEvent:n}}if(!e.bunkerUri||!e.bunkerClientSkHex)return console.warn("[signet-login] restore: stored bunker session has no reconnect creds (bunkerUri/clientSk) \u2014 it was an auth-only login. Clearing."),Je(),null;try{let i=await Pt({uri:e.bunkerUri,clientSecretKey:ht()});return i.pubkey!==e.pubkey?(console.warn("[signet-login] restore: reconnected bunker pubkey mismatch \u2014 clearing session",{connected:i.pubkey,expected:e.pubkey}),await i.close(),Je(),null):{pubkey:e.pubkey,method:"bunker",signer:i,authEvent:n}}catch(i){return console.warn("[signet-login] restore: bunker reconnect failed \u2014 keeping creds for the next retry (NOT clearing). The signer device should still recognise us on reconnect.",i),null}}let r=new Ee(e.pubkey,n),o={pubkey:e.pubkey,method:e.method,signer:r,authEvent:n};return e.displayName&&(o.displayName=e.displayName),o}var tl=Fc;async function nl(){let t=ca();if(t.kind==="session")return Cn(t.session),t;if(t.kind!=="no-callback")return t;let e=Ja();if(e.kind!=="session")return e;if(e.bunkerUri){let n=e.session.pubkey,r=e.session.authEvent,o=e.session.displayName,i=ht(),s=Pt({uri:e.bunkerUri,clientSecretKey:i,timeoutMs:Td}).then(c=>{if(c.pubkey.toLowerCase()!==n.toLowerCase())return console.warn("[signet-login] redirect upgrade: bunker pubkey mismatch \u2014 staying auth-only (cannot sign)",{connected:c.pubkey,expected:n}),c.close().catch(()=>{}),null;let l={pubkey:n,method:"bunker",signer:c,authEvent:r};return o&&(l.displayName=o),Cn(l),c}).catch(c=>(console.warn("[signet-login] redirect upgrade: createBunkerSigner failed \u2014 staying auth-only (no live signing). Reconnect/relay issue or signer device unreachable.",c),null)),a={pubkey:n,method:"bunker",signer:new nr(n,r,s,e.bunkerUri,i,!1),authEvent:r};return o&&(a.displayName=o),Cn(a),{kind:"session",session:a}}return console.warn("[signet-login] redirect login carried no bunkerUri \u2014 auth-only ephemeral (cannot sign). The signer device must enable its NIP-46 server to return a bunker:// URI."),Cn(e.session),e}async function rl(t){if(t)try{await t.signer.close()}catch{}Je()}function Cn(t){if(t.method==="nsec")return;let e={pubkey:t.pubkey,method:t.method,authEventJson:JSON.stringify(t.authEvent)};if(t.method==="bunker"){let n=t.signer;n.bunkerUri&&n.clientSecretKey instanceof Uint8Array&&(e.bunkerUri=n.bunkerUri,e.bunkerClientSkHex=_o(n.clientSecretKey))}t.expiresAt!==void 0&&(e.expiresAt=t.expiresAt),t.displayName!==void 0&&(e.displayName=t.displayName),oa(e)}if(typeof window<"u"){let e=window.Signet??{};Object.assign(e,{login:Qc,restoreSession:el,logout:rl,handleCallback:tl,handleRedirectCallback:nl}),window.Signet=e}return dl(Id);})();
|
|
83
83
|
/*! Bundled license information:
|
|
84
84
|
|
|
85
85
|
@noble/hashes/utils.js:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "signet-login",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.9",
|
|
4
4
|
"description": "Sign in with Signet — drop-in login SDK for Nostr-aware websites. NIP-07, bunker URI, and Signet redirect/QR in one unified API.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/signet-login.js",
|