@bsv/authsocket-client
Version:
Mutually Authenticated Web Sockets Client
2 lines • 206 kB
JavaScript
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.bsv=t():e.bsv=t()}(this,()=>(()=>{"use strict";const e={d:(t,n)=>{if(Array.isArray(n))for(var r=0;r<n.length;){var i=n[r++],s=n[r++];e.o(t,i)?0===s&&r++:0===s?Object.defineProperty(t,i,{enumerable:!0,value:n[r++]}):Object.defineProperty(t,i,{enumerable:!0,get:s})}else for(var i in n)e.o(n,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:n[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}};let t={};e.r(t),e.d(t,{AuthSocketClient:()=>Ni,SocketClientTransport:()=>r,decodeAuthSocketEventPayload:()=>xi});var n={};e.r(n),e.d(n,{Decoder:()=>pe,Encoder:()=>be,PacketType:()=>le,isPacketValid:()=>we,protocol:()=>ue});var r=class{socket;onDataCallback;maxPendingMessages;onError;pendingMessages=0;failed=!1;constructor(e,t={}){this.socket=e;const n=t.maxPendingMessages??32;if(!Number.isSafeInteger(n)||n<1)throw new RangeError("maxPendingMessages must be a positive safe integer");this.maxPendingMessages=n,this.onError=t.onError,this.socket.on("authMessage",e=>this.processMessage(e))}async send(e){this.socket.emit("authMessage",e)}async onData(e){this.onDataCallback=e}async processMessage(e){if(!this.failed&&void 0!==this.onDataCallback)if(this.pendingMessages>=this.maxPendingMessages)this.fail(new Error("Authentication message concurrency limit exceeded"));else{this.pendingMessages+=1;try{await this.onDataCallback(e)}catch(e){this.fail(e)}finally{this.pendingMessages-=1}}}fail(e){if(!this.failed){this.failed=!0,Promise.resolve().then(async()=>await(this.onError?.(e))).catch(()=>{});try{this.socket.disconnect()}catch{}}}};const i=Object.create(null);i.open="0",i.close="1",i.ping="2",i.pong="3",i.message="4",i.upgrade="5",i.noop="6";const s=Object.create(null);Object.keys(i).forEach(e=>{s[i[e]]=e});const a={type:"error",data:"parser error"},o="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),c="function"==typeof ArrayBuffer,d=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,f=({type:e,data:t},n,r)=>o&&t instanceof Blob?n?r(t):h(t,r):c&&(t instanceof ArrayBuffer||d(t))?n?r(t):h(new Blob([t]),r):r(i[e]+(t||"")),h=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function u(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let l;const b="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<64;e++)b["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(e)]=e;const p="function"==typeof ArrayBuffer,g=(e,t)=>{if("string"!=typeof e)return{type:"message",data:m(e,t)};const n=e.charAt(0);return"b"===n?{type:"message",data:y(e.substring(1),t)}:s[n]?e.length>1?{type:s[n],data:e.substring(1)}:{type:s[n]}:a},y=(e,t)=>{if(p){const n=(e=>{let t,n,r,i,s,a=.75*e.length,o=e.length,c=0;"="===e[e.length-1]&&(a--,"="===e[e.length-2]&&a--);const d=new ArrayBuffer(a),f=new Uint8Array(d);for(t=0;t<o;t+=4)n=b[e.charCodeAt(t)],r=b[e.charCodeAt(t+1)],i=b[e.charCodeAt(t+2)],s=b[e.charCodeAt(t+3)],f[c++]=n<<2|r>>4,f[c++]=(15&r)<<4|i>>2,f[c++]=(3&i)<<6|63&s;return d})(e);return m(n,t)}return{base64:!0,data:e}},m=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,w=String.fromCharCode(30);let v;function _(e){return e.reduce((e,t)=>e+t.length,0)}function S(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let i=0;i<t;i++)n[i]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function I(e){if(e)return function(e){for(var t in I.prototype)e[t]=I.prototype[t];return e}(e)}I.prototype.on=I.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},I.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},I.prototype.off=I.prototype.removeListener=I.prototype.removeAllListeners=I.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+e];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var i=0;i<r.length;i++)if((n=r[i])===t||n.fn===t){r.splice(i,1);break}return 0===r.length&&delete this._callbacks["$"+e],this},I.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){r=0;for(var i=(n=n.slice(0)).length;r<i;++r)n[r].apply(this,t)}return this},I.prototype.emitReserved=I.prototype.emit,I.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},I.prototype.hasListeners=function(e){return!!this.listeners(e).length};const A="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),E="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function x(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}const k=E.setTimeout,N=E.clearTimeout;function R(e,t){t.useNativeTimers?(e.setTimeoutFn=k.bind(E),e.clearTimeoutFn=N.bind(E)):(e.setTimeoutFn=E.setTimeout.bind(E),e.clearTimeoutFn=E.clearTimeout.bind(E))}function B(e){return"string"==typeof e?function(e){let t=0,n=0;for(let r=0,i=e.length;r<i;r++)t=e.charCodeAt(r),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}(e):Math.ceil(1.33*(e.byteLength||e.size))}function C(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class T extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class L extends I{constructor(e){super(),this.writable=!1,R(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new T(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=g(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&443!==Number(this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}(e);return t.length?"?"+t:""}}class M extends L{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const n=e.split(w),r=[];for(let e=0;e<n.length;e++){const i=g(n[e],t);if(r.push(i),"error"===i.type)break}return r})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const n=e.length,r=new Array(n);let i=0;e.forEach((e,s)=>{f(e,!1,e=>{r[s]=e,++i===n&&t(r.join(w))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=C()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let K=!1;try{K="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){}const D=K;function P(){}class U extends M{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let n=location.port;n||(n=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}class O extends I{constructor(e,t,n){super(),this.createRequest=e,R(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=void 0!==n.data?n.data:null,this._create()}_create(){var e;const t=x(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(t);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&n.setRequestHeader(e,this._opts.extraHeaders[e])}}catch(e){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{n.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this._opts.cookieJar)||void 0===e||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var e;3===n.readyState&&(null===(e=this._opts.cookieJar)||void 0===e||e.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.send(this._data)}catch(e){return void this.setTimeoutFn(()=>{this._onError(e)},0)}"undefined"!=typeof document&&(this._index=O.requestsCount++,O.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=P,e)try{this._xhr.abort()}catch(e){}"undefined"!=typeof document&&delete O.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}function q(){for(let e in O.requests)O.requests.hasOwnProperty(e)&&O.requests[e].abort()}O.requestsCount=0,O.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",q):"function"==typeof addEventListener&&addEventListener("onpagehide"in E?"pagehide":"unload",q,!1));const F=function(){const e=z({xdomain:!1});return e&&null!==e.responseType}();function z(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||D))return new XMLHttpRequest}catch(e){}if(!t)try{return new(E[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}const V="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class H extends L{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=V?{}:x(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;f(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch(e){}r&&A(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=C()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const j=E.WebSocket||E.MozWebSocket,W={websocket:class extends H{createSocket(e,t,n){return V?new j(e,t,n):t?new j(e,t):new j(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends L{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=function(e,t){v||(v=new TextDecoder);const n=[];let r=0,i=-1,s=!1;return new TransformStream({transform(o,c){for(n.push(o);;){if(0===r){if(_(n)<1)break;const e=S(n,1);s=!(128&~e[0]),i=127&e[0],r=i<126?3:126===i?1:2}else if(1===r){if(_(n)<2)break;const e=S(n,2);i=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),r=3}else if(2===r){if(_(n)<8)break;const e=S(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),s=t.getUint32(0);if(s>Math.pow(2,21)-1){c.enqueue(a);break}i=s*Math.pow(2,32)+t.getUint32(4),r=3}else{if(_(n)<i)break;const e=S(n,i);c.enqueue(g(s?e:v.decode(e),t)),r=0}if(0===i||i>e){c.enqueue(a);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),r=new TransformStream({transform(e,t){!function(e,t){o&&e.data instanceof Blob?e.data.arrayBuffer().then(u).then(t):c&&(e.data instanceof ArrayBuffer||d(e.data))?t(u(e.data)):f(e,!1,e=>{l||(l=new TextEncoder),t(l.encode(e))})}(e,n=>{const r=n.length;let i;if(r<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,r);else if(r<65536){i=new Uint8Array(3);const e=new DataView(i.buffer);e.setUint8(0,126),e.setUint16(1,r)}else{i=new Uint8Array(9);const e=new DataView(i.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(r))}e.data&&"string"!=typeof e.data&&(i[0]|=128),t.enqueue(i),t.enqueue(n)})}});r.readable.pipeTo(e.writable),this._writer=r.writable.getWriter();const i=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),i())}).catch(e=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this._writer.write(s).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],r=t===e.length-1;this._writer.write(n).then(()=>{r&&A(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends U{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=F&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new O(z,this.uri(),e)}}},$=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,G=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Z(e){if(e.length>8e3)throw"URI too long";const t=e,n=e.indexOf("["),r=e.indexOf("]");-1!=n&&-1!=r&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let i=$.exec(e||""),s={},a=14;for(;a--;)s[G[a]]=i[a]||"";return-1!=n&&-1!=r&&(s.source=t,s.host=s.host.substring(1,s.host.length-1).replace(/;/g,":"),s.authority=s.authority.replace("[","").replace("]","").replace(/;/g,":"),s.ipv6uri=!0),s.pathNames=function(e,t){const n=t.replace(/\/{2,9}/g,"/").split("/");return"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1),"/"==t.slice(-1)&&n.splice(n.length-1,1),n}(0,s.path),s.queryKey=function(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,r){t&&(n[t]=r)}),n}(0,s.query),s}const X="function"==typeof addEventListener&&"function"==typeof removeEventListener,Y=[];X&&addEventListener("offline",()=>{Y.forEach(e=>e())},!1);class J extends I{constructor(e,t){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){const n=Z(e);t.hostname=n.host,t.secure="https"===n.protocol||"wss"===n.protocol,t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=Z(t.host).host);R(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{const t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},n=e.split("&");for(let e=0,r=n.length;e<r;e++){let r=n[e].split("=");t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}return t}(this.opts.query)),X&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Y.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const e=this.opts.rememberUpgrade&&J.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",J.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const n=this.writeBuffer[t].data;if(n&&(e+=B(n)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,A(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,r){if("function"==typeof t&&(r=t,t=void 0),"function"==typeof n&&(r=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const i={type:e,data:t,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(J.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),X&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=Y.indexOf(this._offlineEventListener);-1!==e&&Y.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}J.protocol=4;class Q extends J{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;J.priorWebsocketSuccess=!1;const r=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!n)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;J.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(d(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function i(){n||(n=!0,d(),t.close(),t=null)}const s=e=>{const n=new Error("probe error: "+e);n.transport=t.name,i(),this.emitReserved("upgradeError",n)};function a(){s("transport closed")}function o(){s("socket closed")}function c(e){t&&e.name!==t.name&&i()}const d=()=>{t.removeListener("open",r),t.removeListener("error",s),t.removeListener("close",a),this.off("close",o),this.off("upgrading",c)};t.once("open",r),t.once("error",s),t.once("close",a),this.once("close",o),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}class ee extends Q{constructor(e,t={}){const n="object"==typeof e,r=n?{...e}:{...t};(!r.transports||r.transports&&"string"==typeof r.transports[0])&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(e=>W[e]).filter(e=>!!e)),super(n?r:e,r)}}const te="function"==typeof ArrayBuffer,ne=Object.prototype.toString,re="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===ne.call(Blob),ie="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===ne.call(File);function se(e){return te&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||re&&e instanceof Blob||ie&&e instanceof File}function ae(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(ae(e[t]))return!0;return!1}if(se(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return ae(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&ae(e[t]))return!0;return!1}function oe(e){const t=[],n=e.data,r=e;return r.data=ce(n,t),r.attachments=t.length,{packet:r,buffers:t}}function ce(e,t,n){if(!e)return e;if(se(e)){const n={_placeholder:!0,num:t.length};return t.push(e),n}if(Array.isArray(e)){const n=new Array(e.length);for(let r=0;r<e.length;r++)n[r]=ce(e[r],t);return n}if("object"==typeof e&&!(e instanceof Date)){if(e.toJSON&&"function"==typeof e.toJSON&&!n)return ce(e.toJSON(),t,!0);const r={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=ce(e[n],t));return r}return e}function de(e,t){return e.data=fe(e.data,t),delete e.attachments,e}function fe(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=fe(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=fe(e[n],t));return e}const he=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],ue=5;var le;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(le||(le={}));class be{constructor(e){this.replacer=e}encode(e){return e.type!==le.EVENT&&e.type!==le.ACK||!ae(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===le.EVENT?le.BINARY_EVENT:le.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==le.BINARY_EVENT&&e.type!==le.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=oe(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}}class pe extends I{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},"function"==typeof e?{reviver:e}:e)}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===le.BINARY_EVENT;n||t.type===le.BINARY_ACK?(t.type=n?le.EVENT:le.ACK,this.reconstructor=new ge(t)):super.emitReserved("decoded",t)}else{if(!se(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(void 0===le[n.type])throw new Error("unknown packet type "+n.type);if(n.type===le.BINARY_EVENT||n.type===le.BINARY_ACK){const r=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const i=e.substring(r,t);if(i!=Number(i)||"-"!==e.charAt(t))throw new Error("Illegal attachments");const s=Number(i);if(!ye(s)||s<1)throw new Error("Illegal attachments");if(s>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=s}if("/"===e.charAt(t+1)){const r=t+1;for(;++t&&","!==e.charAt(t)&&t!==e.length;);n.nsp=e.substring(r,t)}else n.nsp="/";const r=e.charAt(t+1);if(""!==r&&Number(r)==r){const r=t+1;for(;++t;){const n=e.charAt(t);if(null==n||Number(n)!=n){--t;break}if(t===e.length)break}n.id=Number(e.substring(r,t+1))}if(e.charAt(++t)){const r=this.tryParse(e.substr(t));if(!pe.isPayloadValid(n.type,r))throw new Error("invalid payload");n.data=r}return n}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case le.CONNECT:return me(t);case le.DISCONNECT:return void 0===t;case le.CONNECT_ERROR:return"string"==typeof t||me(t);case le.EVENT:case le.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===he.indexOf(t[0]));case le.ACK:case le.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ge{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=de(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const ye=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function me(e){return"[object Object]"===Object.prototype.toString.call(e)}function we(e){return"string"==typeof e.nsp&&(void 0===(t=e.id)||ye(t))&&function(e,t){switch(e){case le.CONNECT:return void 0===t||me(t);case le.DISCONNECT:return void 0===t;case le.EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===he.indexOf(t[0]));case le.ACK:return Array.isArray(t);case le.CONNECT_ERROR:return"string"==typeof t||me(t);default:return!1}}(e.type,e.data);var t}function ve(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const _e=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Se extends I{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[ve(e,"open",this.onopen.bind(this)),ve(e,"packet",this.onpacket.bind(this)),ve(e,"error",this.onerror.bind(this)),ve(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,r,i;if(_e.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const s={type:le.EVENT,data:t,options:{}};if(s.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,n=t.pop();this._registerAckCallback(e,n),s.id=e}const a=null===(r=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===r?void 0:r.writable,o=this.connected&&!(null===(i=this.io.engine)||void 0===i?void 0:i._hasPingExpired());return this.flags.volatile&&!a||(o?(this.notifyOutgoingListeners(s),this.packet(s)):this.sendBuffer.push(s)),this.flags={},this}_registerAckCallback(e,t){var n;const r=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===r)return void(this.acks[e]=t);const i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},r),s=(...e)=>{this.io.clearTimeoutFn(i),t.apply(this,e)};s.withError=!0,this.acks[e]=s}emitWithAck(e,...t){return new Promise((n,r)=>{const i=(e,t)=>e?r(e):n(t);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...r)=>(this._queue[0],null!==e?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...r)),n.pending=!1,this._drainQueue())),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:le.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){const t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case le.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case le.EVENT:case le.BINARY_EVENT:this.onevent(e);break;case le.ACK:case le.BINARY_ACK:this.onack(e);break;case le.DISCONNECT:this.ondisconnect();break;case le.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...r){n||(n=!0,t.packet({type:le.ACK,id:e,data:r}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:le.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}function Ie(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Ie.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+n:e-n}return 0|Math.min(e,this.max)},Ie.prototype.reset=function(){this.attempts=0},Ie.prototype.setMin=function(e){this.ms=e},Ie.prototype.setMax=function(e){this.max=e},Ie.prototype.setJitter=function(e){this.jitter=e};class Ae extends I{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,R(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(r=t.randomizationFactor)&&void 0!==r?r:.5),this.backoff=new Ie({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||n;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new ee(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const r=ve(t,"open",function(){n.onopen(),e&&e()}),i=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},s=ve(t,"error",i);if(!1!==this._timeout){const e=this._timeout,n=this.setTimeoutFn(()=>{r(),i(new Error("timeout")),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(r),this.subs.push(s),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(ve(e,"ping",this.onping.bind(this)),ve(e,"data",this.ondata.bind(this)),ve(e,"error",this.onerror.bind(this)),ve(e,"close",this.onclose.bind(this)),ve(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){A(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new Se(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const e of t)if(this.nsps[e].active)return;this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),null===(n=this.engine)||void 0===n||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const Ee={};function xe(e,t){"object"==typeof e&&(t=e,e=void 0);const n=function(e,t="",n){let r=e;n=n||"undefined"!=typeof location&&location,null==e&&(e=n.protocol+"//"+n.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==n?n.protocol+"//"+e:"https://"+e),r=Z(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";const i=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port+t,r.href=r.protocol+"://"+i+(n&&n.port===r.port?"":":"+r.port),r}(e,(t=t||{}).path||"/socket.io"),r=n.source,i=n.id,s=n.path,a=Ee[i]&&s in Ee[i].nsps;let o;return t.forceNew||t["force new connection"]||!1===t.multiplex||a?o=new Ae(r,t):(Ee[i]||(Ee[i]=new Ae(r,t)),o=Ee[i]),n.query&&!t.query&&(t.query=n.queryKey),o.socket(n.path,t)}Object.assign(xe,{Manager:Ae,Socket:Se,io:xe,connect:xe});const ke=globalThis.Buffer,Ne=null!=ke&&"function"==typeof ke.from,Re=new Int8Array(256).fill(-1);for(let e=0;e<10;e++)Re[48+e]=e;for(let e=0;e<6;e++)Re[65+e]=10+e,Re[97+e]=10+e;class Be{static zeros=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"];static groupSizes=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5];static groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];static wordSize=26;static WORD_SIZE_BIGINT=BigInt(Be.wordSize);static WORD_MASK=(1n<<Be.WORD_SIZE_BIGINT)-1n;static MAX_SAFE_INTEGER_BIGINT=BigInt(Number.MAX_SAFE_INTEGER);static MIN_SAFE_INTEGER_BIGINT=BigInt(Number.MIN_SAFE_INTEGER);static MAX_IMULN_ARG=67108863;static MAX_NUMBER_CONSTRUCTOR_MAG_BIGINT=(1n<<53n)-1n;static MAX_NOMINAL_WORD_LENGTH=1048576;_magnitude=0n;_sign=0;_nominalWordLength=1;red=null;get negative(){return this._sign}set negative(e){this.assert(0===e||1===e,"Negative property must be 0 or 1");const t=1===e?1:0;0n===this._magnitude?this._sign=0:this._sign=t}get _computedWordsArray(){if(0n===this._magnitude)return[0];const e=[];let t=this._magnitude;for(;t>0n;)e.push(Number(t&Be.WORD_MASK)),t>>=Be.WORD_SIZE_BIGINT;return e.length>0?e:[0]}get words(){if(!Number.isSafeInteger(this._nominalWordLength)||this._nominalWordLength<1||this._nominalWordLength>Be.MAX_NOMINAL_WORD_LENGTH)throw new Error("BigNumber word length exceeds the supported limit");const e=this._computedWordsArray;if(this._nominalWordLength<=e.length)return e;const t=Array.from({length:this._nominalWordLength}).fill(0);for(let n=0;n<e.length;n++)t[n]=e[n];return t}set words(e){const t=this._sign;let n=0n;const r=e.length>0?e.length:1;for(let t=r-1;t>=0;t--){const r=e[t]??0;n=n<<Be.WORD_SIZE_BIGINT|BigInt(r&Number(Be.WORD_MASK))}this._magnitude=n,this._sign=t,this._nominalWordLength=r,this.normSign()}get length(){return Math.max(1,this._nominalWordLength)}static isBN(e){return e instanceof Be||null!==e&&"object"==typeof e&&e.constructor?.wordSize===Be.wordSize&&Array.isArray(e.words)}static max(e,t){return e.cmp(t)>0?e:t}static min(e,t){return e.cmp(t)<0?e:t}constructor(e=0,t=10,n="be"){if(e??=0,"bigint"==typeof e)return this._initializeState(e<0n?-e:e,e<0n?1:0),void this.normSign();const r="le"===t||"be"===t,i=r?10:t,s=r?t:n;"number"!=typeof e?Array.isArray(e)?this.initArray(e,s):"string"!=typeof e?0!==e?this.assert(!1,"Unsupported input type for BigNumber constructor"):this._initializeState(0n,0):this._initFromString(e,i,s):this.initNumber(e,s)}_initFromString(e,t,n){"hex"===t&&(t=16),this.assert("number"==typeof t&&t===Math.trunc(t)&&t>=2&&t<=36,"Base must be an integer between 2 and 36");const r=e.toString().replace(/\s+/g,"");let i=0,s=0;r.startsWith("-")?(i++,s=1):r.startsWith("+")&&i++;const a=r.substring(i);if(0===a.length)return this._initializeState(0n,1===s&&r.startsWith("-")?1:0),void this.normSign();16===t?this._initFromHexString(a,s,n):this._initFromNonHexString(a,t,s,n)}_initFromHexString(e,t,n){if("le"===n){const n=[];let r=e;r.length%2!=0&&(r="0"+r);for(let e=0;e<r.length;e+=2){const t=r.substring(e,e+2),i=Number.parseInt(t,16);if(Number.isNaN(i))throw new Error("Invalid character in "+r);n.push(i)}this.initArray(n,"le"),this._sign=t,this.normSign()}else{let n;try{n=BigInt("0x"+e)}catch{throw new Error("Invalid character in "+e)}this._initializeState(n,t),this.normSign()}}_initFromNonHexString(e,t,n,r){try{if(this._parseBaseString(e,t),this._sign=n,this.normSign(),"le"===r){const e=this._sign;this.initArray(this.toArray("be"),"le"),this._sign=e,this.normSign()}}catch(e){const t=e;if(t.message.includes("Invalid character in string")||t.message.includes("Invalid digit for base")||t.message.startsWith("Invalid character:"))throw new Error("Invalid character");throw t}}_bigIntToStringInBase(e,t){if(0n===e)return"0";if(t<2||t>36)throw new Error("Base must be between 2 and 36");let n="",r=e>0n?e:-e;const i=BigInt(t);for(;r>0n;)n="0123456789abcdefghijklmnopqrstuvwxyz"[Number(r%i)]+n,r/=i;return n}_parseBaseString(e,t){this._magnitude=0n;const n=BigInt(t);let r=Be.groupSizes[t],i=BigInt(Be.groupBases[t]);0!==r&&0n!==i||(r=Math.floor(Math.log(67108863)/Math.log(t)),0===r&&(r=1),i=n**BigInt(r));let s=0;const a=e.length;let o=a%r;if(0===o&&a>0&&(o=r),o>0){const n=e.substring(s,s+o);this._magnitude=BigInt(this._parseBaseWord(n,t)),s+=o}for(;s<a;){const n=e.substring(s,s+r),a=BigInt(this._parseBaseWord(n,t));this._magnitude=this._magnitude*i+a,s+=r}this._finishInitialization()}_parseBaseWord(e,t){let n=0;for(let r=0;r<e.length;r++){const i=e.codePointAt(r);let s;if(i>=48&&i<=57)s=i-48;else if(i>=65&&i<=90)s=i-65+10;else{if(!(i>=97&&i<=122))throw new Error("Invalid character: "+e[r]);s=i-97+10}if(s>=t)throw new Error("Invalid character");n=n*t+s}return n}_initializeState(e,t){this._magnitude=e,this._sign=0n===e?0:t,this._finishInitialization()}_finishInitialization(){if(0n===this._magnitude)this._nominalWordLength=1,this._sign=0;else{const e=this._magnitude.toString(2).length;this._nominalWordLength=Math.max(1,Math.ceil(e/Be.wordSize))}}assert(e,t="Assertion failed"){if(!e)throw new Error(t)}initNumber(e,t="be"){if(this.assert(BigInt(Math.abs(e))<=Be.MAX_NUMBER_CONSTRUCTOR_MAG_BIGINT,"The number is larger than 2 ^ 53 (unsafe)"),this.assert(e%1==0,"Number must be an integer for BigNumber conversion"),this._initializeState(BigInt(Math.abs(e)),e<0?1:0),"le"===t){const e=this._sign,t=this.toArray("be");this.initArray(t,"le"),this._sign=e,this.normSign()}return this}initArray(e,t){if(0===e.length)return this._initializeState(0n,0),this;let n=0n;if("be"===t)for(const t of e)n=n<<8n|BigInt(255&t);else for(let t=e.length-1;t>=0;t--)n=n<<8n|BigInt(255&e[t]);return this._initializeState(n,0),this}copy(e){e._magnitude=this._magnitude,e._sign=this._sign,e._nominalWordLength=this._nominalWordLength,e.red=this.red}static move(e,t){e._magnitude=t._magnitude,e._sign=t._sign,e._nominalWordLength=t._nominalWordLength,e.red=t.red}clone(){const e=new Be(0n);return this.copy(e),e}expand(e){return this.assert(Number.isSafeInteger(e)&&e>=0&&e<=Be.MAX_NOMINAL_WORD_LENGTH,"Expand size must be a non-negative safe integer within the supported word limit"),this._nominalWordLength=Math.max(this._nominalWordLength,e,1),this}strip(){return this._finishInitialization(),this.normSign()}normSign(){return 0n===this._magnitude&&(this._sign=0),this}inspect(){return(null===this.red?"<BN: ":"<BN-R: ")+this.toString(16)+">"}_getMinimalHex(){return 0n===this._magnitude?"0":this._magnitude.toString(16)}_toHexString(e){let t=this._getMinimalHex();if(e>1)for("0"!==t&&t.length%2!=0&&(t="0"+t);t.length%e!==0;)t="0"+t;return(this.isNeg()?"-":"")+t}toString(e=10,t=1){if(16===e||"hex"===e)return this._toHexString(t);if("number"!=typeof e||e<2||e>36||e%1!=0)throw new Error("Base should be an integer between 2 and 36");return this.toBaseString(e,t)}toBaseString(e,t){if(0n===this._magnitude)return Be._paddedZero(t);let n=Be.groupSizes[e],r=BigInt(Be.groupBases[e]);0!==n&&0n!==r||(n=Math.floor(Math.log(Number.MAX_SAFE_INTEGER)/Math.log(e)),0===n&&(n=1),r=BigInt(e)**BigInt(n));let i="",s=this._magnitude;for(;s>0n;){const t=s%r;s/=r;const a=this._bigIntToStringInBase(t,e);i=(s>0n?this._zeroPaddedChunk(a,n):a)+i}if(t>0)for(;i.length<t;)i="0"+i;return(1===this._sign?"-":"")+i}static _paddedZero(e){let t="0";if(e>1)for(;t.length<e;)t="0"+t;return t}_zeroPaddedChunk(e,t){const n=t-e.length;return n<=0?e:n<Be.zeros.length?Be.zeros[n]+e:"0".repeat(n)+e}toNumber(){const e=this._getSignedValue();if(e>Be.MAX_SAFE_INTEGER_BIGINT||e<Be.MIN_SAFE_INTEGER_BIGINT)throw new Error("Number can only safely store up to 53 bits");return Number(e)}toBigInt(){return this._getSignedValue()}toJSON(){const e=this._getMinimalHex();return(this.isNeg()?"-":"")+e}toArrayLikeGeneric(e,t){let n=this._magnitude,r=t?0:e.length-1;const i=t?1:-1;for(const t of e){if(0n===n&&r>=0&&r<e.length)e[r]=0;else{if(!(r>=0&&r<e.length))break;e[r]=Number(0xffn&n)}n>>=8n,r+=i}}toArray(e="be",t){this.strip();const n=this.byteLength(),r=t??Math.max(1,n);this.assert(n<=r,"byte array longer than desired length"),this.assert(r>0,"Requested array length <= 0");const i=Array.from({length:r}).fill(0);return 0n===this._magnitude&&r>0?i:0n===this._magnitude&&0===r?[]:(this.toArrayLikeGeneric(i,"le"===e),i)}bitLength(){return 0n===this._magnitude?0:this._magnitude.toString(2).length}static toBitArray(e){const t=e.bitLength();if(0===t)return[];const n=Array.from({length:t}),r=e._magnitude;for(let e=0;e<t;e++)n[e]=0n==(r>>BigInt(e)&1n)?0:1;return n}toBitArray(){return Be.toBitArray(this)}zeroBits(){if(0n===this._magnitude)return 0;let e=0,t=this._magnitude;for(;0n==(1n&t)&&0n!==t;)e++,t>>=1n;return e}byteLength(){return 0n===this._magnitude?0:Math.ceil(this.bitLength()/8)}_getSignedValue(){return 1===this._sign?-this._magnitude:this._magnitude}_setValueFromSigned(e){e<0n?(this._magnitude=-e,this._sign=1):(this._magnitude=e,this._sign=0),this._finishInitialization(),this.normSign()}toTwos(e){this.assert(e>=0);const t=BigInt(e);let n=this._getSignedValue();1===this._sign&&0n!==this._magnitude&&(n=(1n<<t)+n),n&=(1n<<t)-1n;const r=new Be(0n);return r._initializeState(n,0),r}fromTwos(e){this.assert(e>=0);const t=BigInt(e),n=this._magnitude;if(e>0&&0n!=(n>>t-1n&1n)&&0===this._sign){const e=n-(1n<<t),r=new Be(0n);return r._setValueFromSigned(e),r}return this.clone()}isNeg(){return 1===this._sign&&0n!==this._magnitude}neg(){return this.clone().ineg()}ineg(){return 0n!==this._magnitude&&(this._sign=1===this._sign?0:1),this}_iuop(e,t,n=!1){const r=t(this._magnitude,e._magnitude);let i=this._nominalWordLength;return n&&(i=Math.max(this.length,e.length)),this._magnitude=r,this._finishInitialization(),n&&(this._nominalWordLength=Math.max(this._nominalWordLength,i)),this.strip()}iuor(e){return this._iuop(e,(e,t)=>e|t)}iuand(e){return this._iuop(e,(e,t)=>e&t)}iuxor(e){return this._iuop(e,(e,t)=>e^t,!0)}_iop(e,t,n=!1){return this.assert(0===this._sign&&0===e._sign),this._iuop(e,t,n)}ior(e){return this._iop(e,(e,t)=>e|t)}iand(e){return this._iop(e,(e,t)=>e&t)}ixor(e){return this._iop(e,(e,t)=>e^t,!0)}_uop_new(e,t){return this.length>=e.length?this.clone()[t](e):e.clone()[t](this)}or(e){return this.assert(0===this._sign&&0===e._sign),this._uop_new(e,"iuor")}uor(e){return this._uop_new(e,"iuor")}and(e){return this.assert(0===this._sign&&0===e._sign),this._uop_new(e,"iuand")}uand(e){return this._uop_new(e,"iuand")}xor(e){return this.assert(0===this._sign&&0===e._sign),this._uop_new(e,"iuxor")}uxor(e){return this._uop_new(e,"iuxor")}inotn(e){this.assert("number"==typeof e&&e>=0);const t=(1n<<BigInt(e))-1n;this._magnitude=~this._magnitude&t;const n=0===e?1:Math.ceil(e/Be.wordSize);return this._nominalWordLength=Math.max(1,n),this.strip(),this._nominalWordLength=Math.max(this._nominalWordLength,Math.max(1,n)),this}notn(e){return this.clone().inotn(e)}setn(e,t){this.assert("number"==typeof e&&e>=0);const n=BigInt(e);1===t||!0===t?this._magnitude|=1n<<n:this._magnitude&=~(1n<<n);const r=Math.floor(e/Be.wordSize)+1;return this._nominalWordLength=Math.max(this._nominalWordLength,r),this._finishInitialization(),this.strip()}iadd(e){return this._setValueFromSigned(this._getSignedValue()+e._getSignedValue()),this}add(e){const t=new Be(0n);return t._setValueFromSigned(this._getSignedValue()+e._getSignedValue()),t}isub(e){return this._setValueFromSigned(this._getSignedValue()-e._getSignedValue()),this}sub(e){const t=new Be(0n);return t._setValueFromSigned(this._getSignedValue()-e._getSignedValue()),t}mul(e){const t=new Be(0n);return t._magnitude=this._magnitude*e._magnitude,t._sign=0n===t._magnitude?0:this._sign^e._sign,t._nominalWordLength=this.length+e.length,t.red=null,t.normSign()}imul(e){return this._magnitude*=e._magnitude,this._sign=0n===this._magnitude?0:this._sign^e._sign,this._nominalWordLength=this.length+e.length,this.red=null,this.normSign()}imuln(e){return this.assert("number"==typeof e,"Assertion failed"),this.assert(Math.abs(e)<=Be.MAX_IMULN_ARG,"Assertion failed"),this._setValueFromSigned(this._getSignedValue()*BigInt(e)),this}muln(e){return this.clone().imuln(e)}sqr(){const e=new Be(0n);return e._magnitude=this._magnitude*this._magnitude,e._sign=0,e._nominalWordLength=2*this.length,e.red=null,e}isqr(){return this._magnitude*=this._magnitude,this._sign=0,this._nominalWordLength=2*this.length,this.red=null,this}pow(e){if(this.assert(0===e._sign,"Exponent for pow must be non-negative"),e.isZero())return new Be(1n);const t=new Be(1n),n=this.clone(),r=e.clone(),i=n.isNeg(),s=r.isOdd();for(i&&n.ineg();!r.isZero();)r.isOdd()&&t.imul(n),n.isqr(),r.iushrn(1);return i&&s&&t.ineg(),t}static normalizeNonNegativeBigInt(e,t){if("number"==typeof e){if(!Number.isFinite(e)||!Number.isInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return BigInt(e)}if(e<0n)throw new Error(`${t} must be a non-negative integer`);return e}iushln(e){const t=Be.normalizeNonNegativeBigInt(e,"Shift bits");return 0n===t?this:(this._magnitude<<=t,this._finishInitialization(),this.strip())}ishln(e){return this.assert(0===this._sign,"ishln requires positive number"),this.iushln(e)}iushrn(e,t,n){const r=Be.normalizeNonNegativeBigInt(e,"Shift bits");if(0n===r)return null!=n&&n._initializeState(0n,0),this;if(null!=n){const e=(1n<<r)-1n,t=this._magnitude&e;n._initializeState(t,0)}return this._magnitude>>=r,this._finishInitialization(),this.strip()}ishrn(e,t,n){return this.assert(0===this._sign,"ishrn requires positive number"),this.iushrn(e,t,n)}shln(e){return this.clone().ishln(e)}ushln(e){return this.clone().iushln(e)}shrn(e){return this.clone().ishrn(e)}ushrn(e){return this.clone().iushrn(e)}testn(e){return this.assert("number"==typeof e&&e>=0),0n!=(this._magnitude>>BigInt(e)&1n)}imaskn(e){this.assert("number"==typeof e&&e>=0),this.assert(0===this._sign,"imaskn works only with positive numbers");const t=BigInt(e),n=0n===t?0n:(1n<<t)-1n;this._magnitude&=n;const r=0===e?1:Math.max(1,Math.ceil(e/Be.wordSize));return this._nominalWordLength=r,this._finishInitialization(),this._nominalWordLength=Math.max(this._nominalWordLength,r),this.strip()}maskn(e){return this.clone().imaskn(e)}iaddn(e){return this.assert("number"==typeof e),this.assert(Math.abs(e)<=Be.MAX_IMULN_ARG,"num is too large"),this._setValueFromSigned(this._getSignedValue()+BigInt(e)),this}_iaddn(e){return this.iaddn(e)}isubn(e){return this.assert("number"==typeof e),this.assert(Math.abs(e)<=Be.MAX_IMULN_ARG,"Assertion failed"),this._setValueFromSigned(this._getSignedValue()-BigInt(e)),this}addn(e){return this.clone().iaddn(e)}subn(e){return this.clone().isubn(e)}iabs(){return this._sign=0,this}abs(){return this.clone().iabs()}divmod(e,t,n){if(this.assert(!e.isZero(),"Division by zero"),this.isZero()){const e=new Be(0n);return{div:"mod"===t?null:e,mod:"div"===t?null:e}}const r=this._getSignedValue(),i=e._getSignedValue(),s="mod"!==t?r/i:null,a=this._computeMod(r,i,t,n);return{div:this._bigNumberFromSigned(s),mod:this._bigNumberFromSigned(a)}}_computeMod(e,t,n,r){if("div"===n)return null;let i=e%t;return!0===r&&i<0n&&(i+=t<0n?-t:t),i}_bigNumberFromSigned(e){if(null===e)return null;const t=new Be(0n);return t._setValueFromSigned(e),t}div(e){return this.divmod(e,"div",!1).div}mod(e){return this.divmod(e,"mod",!1).mod}umod(e){return this.divmod(e,"mod",!0).mod}divRound(e){this.assert(!e.isZero());const t=this._getSignedValue(),n=e._getSignedValue();let r=t/n;const i=t%n;if(0n===i){const e=new Be(0n);return e._setValueFromSigned(r),e}2n*(i<0n?-i:i)>=(n<0n?-n:n)&&(t>0n&&n>0n||t<0n&&n<0n?r+=1n:r-=1n);const s=new Be(0n);return s._setValueFromSigned(r),s}modrn(e){this.assert(0!==e,"Division by zero in modrn");const t=BigInt(Math.abs(e));if(0n===t)throw new Error("Division by zero in modrn");const n=this._magnitude%t;return Number(e<0?-n:n)}idivn(e){return this.assert(0!==e),this.assert(Math.abs(e)<=Be.MAX_IMULN_ARG,"num is too large"),this._setValueFromSigned(this._getSignedValue()/BigInt(e)),this}divn(e){return this.clone().idivn(e)}egcd(e){this.assert(0===e._sign,"p must not be negative"),this.assert(!e.isZero(),"p must not be zero");let t=this._getSignedValue(),n=e._magnitude,r=1n,i=0n,s=0n,a=1n;for(;0n!==n;){const e=t/n;let o=n;n=t%n,t=o,o=i,i=r-e*i,r=o,o=a,a=s-e*a,s=o}const o=new Be(0n);o._setValueFromSigned(r);const c=new Be(0n);c._setValueFromSigned(s);const d=new Be(0n);return d._initializeState(t<0n?-t:t,0),{a:o,b:c,gcd:d}}gcd(e){let t=this._magnitude,n=e._magnitude;if(0n===t){const e=new Be(0n);return e._setValueFromSigned(n),e.iabs()}if(0n===n){const e=new Be(0n);return e._setValueFromSigned(t),e.iabs()}for(;0n!==n;){const e=t%n;t=n,n=e}const r=new Be(0n);return r._initializeState(t,0),r}invm(e){this.assert(!e.isZero()&&0===e._sign,"Modulus for invm must be positive and non-zero");const t=this.egcd(e);if(!t.gcd.eqn(1))throw new Error("Inverse does not exist (numbers are not coprime).");return t.a.umod(e)}isEven(){return this._magnitude%2n==0n}isOdd(){return this._magnitude%2n==1n}andln(e){return this.assert(e>=0),Number(this._magnitude&BigInt(e))}bincn(e){this.assert("number"==typeof e&&e>=0);const t=1n<<BigInt(e);return this._setValueFromSigned(this._getSignedValue()+t),this}isZero(){return 0n===this._magnitude}cmpn(e){this.assert(Math.abs(e)<=Be.MAX_IMULN_ARG,"Number is too big");const t=this._getSignedValue(),n=BigInt(e);return t<n?-1:t>n?1:0}cmp(e){const t=this._getSignedValue(),n=e._getSignedValue();return t<n?-1:t>n?1:0}ucmp(e){return this._magnitude<e._magnitude?-1:this._magnitude>e._magnitude?1:0}gtn(e){return 1===this.cmpn(e)}gt(e){return 1===this.cmp(e)}gten(e){return this.cmpn(e)>=0}gte(e){return this.cmp(e)>=0}ltn(e){return-1===this.cmpn(e)}lt(e){return-1===this.cmp(e)}lten(e){return this.cmpn(e)<=0}lte(e){return this.cmp(e)<=0}eqn(e){return 0===this.cmpn(e)}eq(e){return 0===this.cmp(e)}toRed(e){return this.assert(null==this.red,"Already a number in reduction context"),this.assert(0===this._sign,"toRed works only with positives"),e.convertTo(this).forceRed(e)}fromRed(){return this.assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)}forceRed(e){return this.red=e,this}redAdd(e){return this.assert(this.red,"redAdd works only with red numbers"),this.red.add(this,e)}redIAdd(e){return this.assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)}redSub(e){return this.assert(this.red,"redSub works only with red numbers"),this.red.sub(this,e)}redISub(e){return this.assert(this.red,"redISub works only with red numbers"),this.red.isub(this,e)}redShl(e){return this.assert(this.red,"redShl works only with red numbers"),this.red.shl(this,e)}redMul(e){return this.assert(this.red,"redMul works only with red numbers"),this.red.verify2(this,e),this.red.mul(this,e)}redIMul(e){return this.assert(this.red,"redIMul works only with red numbers"),this.red.verify2(this,e),this.red.imul(this,e)}redSqr(){return this.assert(this.red,"redSqr works only with red numbers"),this.red.verify1(this),this.red.sqr(this)}redISqr(){return this.assert(this.red,"redISqr works only with red numbers"),this.red.verify1(this),this.red.isqr(this)}redSqrt(){return this.assert(this.red,"redSqrt works only with red numbers"),this.red.verify1(this),this.red.sqrt(this)}redInvm(){return this.assert(this.red,"redInvm works only with red numbers"),this.red.verify1(this),this.red.invm(this)}redNeg(){return this.assert(this.red,"redNeg works only with red numbers"),this.red.verify1(this),this.red.neg(this)}redPow(e){return this.assert(null!=this.red&&null==e.red,"redPow(normalNum)"),this.red.verify1(this),this.red.pow(this,e)}static fromHex(e,t){let n="be";return"little"!==t&&"le"!==t||(n="le"),new Be(e,16,n)}toHex(e=0){if(this.isZero()&&0===e)return"";let t=this._getMinimalHex();"0"!==t&&t.length%2!=0&&(t="0"+t);const n=2*e;for(;t.length<n;)t="0"+t;return(this.isNeg()?"-":"")+t}static fromJSON(e){return new Be(e,16)}static fromNumber(e){return new Be(e)}static fromString(e,t){return new Be(e,t)}static fromSm(e,t="big"){if(0===e.length)return new Be(0n);const n=e.slice();"little"===t&&n.reverse();let r,i=0;if(n.length>0&&128&n[0]&&(i=1,n[0]&=127),Ne)r=ke.from(n).toString("hex");else{r="";for(const e of n)r+=e<16?"0"+e.toString(16):e.toString(16)}const s=0===r.length?0n:BigInt("0x"+r),a=new Be(0n);return a._initializeState(s,i),a}toSm(e="big"){if(0n===this._magnitude)return 1===this._sign?[128]:[];let t=this._getMinimalHex();t.length%2!=0&&(t="0"+t);const n=t.length/2,r=Array.from({length:n});for(let e=0,n=0;e<t.length;e+=2){const i=Re[t.codePointAt(e)],s=Re[t.codePointAt(e+1)];r[n++]=(15&i)<<4|15&s}let i;return 1===this._sign?128&r[0]?i=[128,...r]:(i=r.slice(),i[0]|=128):i=128&r[0]?[0,...r]:r.slice(),"little"===e?i.reverse():i}static fromBits(e,t=!1){const n=e>>>24,r=8388607&e,i=!!(8388608&e);if(t&&i)throw new Error("negative bit set");if(0===n&&0===r){if(i&&t)throw new Error("negative bit set for zero value");return new Be(0n)}const s=new Be(r);return n<=3?s.iushrn(8*(3-n)):s.iushln(8*(n-3)),i&&s.ineg(),s}toBits(){if(this.strip(),this.isZero()&&!this.isNeg())return 0;const e=this.isNeg();let t=this.abs().toArray("be"),n=0;for(;n<t.length-1&&0===t[n];)n++;t=t.slice(n);let r,i=t.length;if(0===i)r=0;else if(i<=3){r=0;for(let e=0;e<i;e++)r=r<<8|t[e]}else r=t[0]<<16|t[1]<<8|t[2];8388608&r&&i<=255&&(r>>>=8,i++);let s=i<<24|r;return e&&(s|=8388608),s>>>0}static fromScriptNum(e,t=!1,n){if(void 0!==n&&e.length>n)throw new Error("script number overflow");if(0===e.length)return new Be(0n);if(t&&!(127&e.at(-1)||!(e.length<=1)&&128&e.at(-2)))throw new Error("non-minimally encoded script number");return Be.fromSm(e,"little")}toScriptNum(){return this.toSm("little")}_invmp(e){this.assert(0===e._sign,"p must not be negative for _invmp"),this.assert(!e.isZero(),"p must not be zero for _invmp");const t=this.umod(e),n=e.subn(2);if(null!==t.red)return t.redPow(n);let r=new Be(1n),i=t.clone();const s=n.clone();for(;!s.isZero();)s.isOdd()&&(r=r.mul(i).umod(e)),i=i.sqr().umod(e),s.iushrn(1);return r}mulTo(e,t){return t._magnitude=this._magnitude*e._magnitude,t._sign=0n===t._magnitude?0:this._sign^e._sign,t._nominalWordLength=this.length+e.length,t.red=null,t.normSign(),t}}const Ce=/^[0-9a-fA-F]*$/;function Te(e){if("string"!=typeof e)throw new TypeError("Invalid hex string");if(0!==e.length&&!Ce.test(e))throw new Error("Invalid hex string")}const Le=(e,t="Hash assertion failed")=>{if(!e)throw new Error(t)};class Me{pending=null;pendingTotal=0;blockSize;outSize;endian;_delta8;_delta32;padLength;hmacStrength;constructor(e,t,n,r){this.blockSize=e,this.outSize=t,this.hmacStrength=n,this.padLength=r/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}_update(e,t){throw new Error("Not implemented")}_digest(){throw new Error("Not implemented")}_digestHex(){throw new Error("Not implemented")}update(e,t){if(e=De(e,t),null==this.pending?this.pending=e:this.pending=this.pending.concat(e),this.pendingTotal+=e.length,this.pending.length>=this._delta8){const t=(e=this.pending).length%this._delta8;this.pending=e.slice(e.length-t,e.length),0===this.pending.length&&(this.pending=null),e=function(e,t,n,r){const i=n-0;Le(i%4==0);const s=Array.from({length:i/4});for(let t=0,n=0;t<s.length;t++,n+=4){let i;i="big"===r?e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3]:e[n+3]<<24|e[n+2]<<16|e[n+1]<<8|e[n],s[t]=i>>>0}return s}(e,0,e.length-t,this.endian);for(let t=0;t<e.length;t+=this._delta32)this._update(e,t)}return this}digest(){return this.update(this._pad()),Le(null===this.pending),this._digest()}digestHex(){return this.update(this._pad()),Le(null===this.pending),this._digestHex()}_pad(){const e=this.pendingTotal;if(!Number.isSafeInteger(e)||e<0)throw new Error("Message too long for this hash function");const t=this._delta8,n=t-(e+this.padLength)%t,r=Array.from({length:n+this.padLength});let i;for(r[0]=128,i=1;i<n;i++)r[i]=0;const s=this.padLength,a=1n<<BigInt(8*s);let o=8n*BigInt(e);if(o>=a)throw new Error("Message too long for this hash function");if("big"===this.endian){const e=Array.from({length:s});for(let t=s-1;t>=0;t--)e[t]=Number(0xffn&o),o>>=8n;for(let t=0;t<s;t++)r[i++]=e[t]}else for(let e=0;e<s;e++)r[i++]=Number(0xffn&o),o>>=8n;return r}}function Ke(e,t,n){const r=e.codePointAt(t);return r<128?(n.push(r),t):r<2048?(n.push(r>>6|192,63&r|128),t):r>65535?(n.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128),t+1):(n.push(r>>12|224,r>>6&63|128,63&r|128),t)}function De(e,t){return Array.isArray(e)?e.slice():e?"string"==typeof e?"hex"===t?function(e){Te(e);const t=function(e){if(Te(e),0===e.length)return"";let t=e.toLowerCase();return t.length%2!=0&&(t="0"+t),t}(e),n=[];for(let e=0;e<t.length;e+=2)n.push(Number.parseInt(t[e]+t[e+1],16));return n}(e):function(e){const t=[];let n=0;for(;n<e.length;)n=Ke(e,n,t)+1;return t}(e):function(e){const t=[];for(let n=0;n<e.length;n++)t[n]=Math.trunc(e[n]);return t}(e):[]}function Pe(e){return function(e){return(e>>>24|e>>>8&65280|e<<8&16711680|(255&e)<<24)>>>0}(e)}function Ue(e){return 7===e.length?"0"+e:6===e.length?"00"+e:5===e.length?"000"+e:4===e.length?"0000"+e:3===e.length?"00000"+e:2===e.length?"000000"+e:1===e.length?"0000000"+e:e}const Oe="undefined"==typeof globalThis?void 0:globalThis.Buffer,qe=null!=Oe&&"function"==typeof Oe.from,Fe="0123456789abcdef",ze=Array.from({length:256});for(let e=0;e<ze.length;e++)ze[e]=Fe[e>>4&15]+Fe[15&e];const Ve=(()=>{const e="undefined"==typeof globalThis?void 0:globalThis.process,t=e?.getBuiltinModule;if("function"==typeof t)try{const n=t.call(e,"node:crypto");if(null!=n)return n}catch{}})();function He(e,t){return e instanceof Uint8Array?e:Array.isArray(e)?new Uint8Array(e):Uint8Array.from(De(e,t))}function je(e){return"string"==typeof e?He(e,"hex"):He(e)}function We(e,t,n){null!=e?e.update(n):null!=t&&t.update(n)}function $e(e,t){return null!=e?Array.from(e.digest()):null!=t?Array.from(t.digest()):[]}function Ge(e,t){return null!=e?e.digest("hex"):null!=t?function(e){if(qe)return Oe.from(e).toString("hex");const t=Array.from({length:e.length});for(let n=0;n<e.length;n++)t[n]=ze[e[n]];return t.join("")}(t.digest()):""}function Ze(e,t){const n=Ve?.createHmac;if("function"==typeof n)try{return n(e,t)}catch{return}}function Xe(e,t,n){const r=function(e){const t=Ve?.createHash;if("function"==typeof t)try{return t(e)}catch{return}}(e);if(null!=r)return r.update(He(t,n)),r.digest()}function Ye(e,t,n,r){const i=Ze(e,je(t));if(null!=i)return i.update(He(n,r)),i.digest()}function Je(e,t){return e>>>t|e<<32-t}function Qe(e,t){return e<<t|e>>>32-t}function et(e,t){return e+t>>>0}function tt(e,t,n){return e+t+n>>>0}function nt(e,t,n,r){return e+t+n+r>>>0}function rt(e,t,n,r,i){return e+t+n+r+i>>>0}function it(e,t,n){return e&t^~e&n}function st(e,t,n){return e&t^e&n^t&n}function at(e){return Je(e,2)^Je(e,13)^Je(e,22)}function ot(e){return Je(e,6)^Je(e,11)^Je(e,25)}function ct(e){return Je(e,7)^Je(e,18)^e>>>3}function dt(e){return Je(e,17)^Je(e,19)^e>>>10}const ft=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],ht=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],ut=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],lt=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11];function bt(e,t,n,r){return e<=15?t^n^r:e<=31?t&n|~t&r:e<=47?(t|~n)^r:e<=63?t&r|n&~r:t^(n|~r)}function pt(e){return e<=15?0:e<=31?1518500249:e<=47?1859775393:e<=63?2400959708:2840853838}function gt(e){return e<=15?1352829926:e<=31?1548603684:e<=47?1836072691:e<=63?2053994217:0}class yt extends Me{h;constructor(){super(512,160,192,64),this.endian="little",this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"}_update(e,t){let n,r=this.h[0],i=this.h[1],s=this.h[2],a=this.h[3],o=this.h[4],c=r,d=i,f=s,h=a,u=o;for(let l=0;l<80;l++)n=et(Qe(nt(r,bt(l,i,s,a),e[ft[l]+t],pt(l)),ut[l]),o),r=o,o=a,a=Qe(s,10),s=i,i=n,n=et(Qe(nt(c,bt(79-l,d,f,h),e[ht[l]+t],gt(l)),lt[l]),u),c=u,u=h,h=Qe(f,10),f=d,d=n;n=tt(this.h[1],s,h),this.h[1]=tt(this.h[2],a,u),this.h[2]=tt(this.h[3],o,c),this.h[3]=tt(this.h[4],r,d),this.h[4]=tt(this.h[0],i,f),this.h[0]=n}_digest(){return function(e,t){const n=Array.from({length:4*e.length});for(let r=0,i=0;r<e.length;r++,i+=4){const s=e[r];"big"===t?(n[i]=s>>>24,n[i+1]=s>>>16&255,n[i+2]=s>>>8&255,n[i+3]=255&s):(n[i+3]=s>>>24,n[i+2]=s>>>16&255,n[i+1]=s>>>8&255,n[i]=255&s)}return n}(this.h,"little")}_digestHex(){return function(e,t){let n="";for(let r of e)"little"===t&&(r=Pe(r)),n+=Ue(r.toString(16));return n}(this.h,"little")}}class mt{h;native;blockSize=64;outSize=32;constructor(e){const t=je(e);this.native=Ze("sha256",t),null==this.native&&(this.h=new fn(en,t))}update(e,t){return We(this.native,this.h,He(e,t)),this}digest(){return $e(this.native,this.h)}digestHex(){return Ge(this.native,this.h)}}class wt{h;native;blockSize=128;outSize=32;constructor(e){const t=je(e);this.native=Ze("sha512",t),null==this.native&&(this.h=new fn(dn,t))}update(e,t){return We(this.native,this.h,He(e,t)),this}digest(){return $e(this.native,this.h)}digestHex(){return Ge(this.native,this.h)}}function vt(e,t){const n=Xe("sha256",e,t);return null!=n?n:(new Qt).update(He(e,t)).digest()}const _t=(e,t)=>Array.from(vt(e,t)),St=(e,t)=>Array.from(vt(vt(e,t))),It=(e,t,n)=>{const r=Ye("sha256",e,t,n);return null!=r?Array.from(r):new mt(e).update(t,n).digest()},At=(e,t,n)=>{const r=Ye("sha512",e,t,n);return null!=r?Array.from(r):new wt(e).update(t,n).digest()};function Et(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, got ${e}`)}function xt(e,...t){if(!((n=e)instanceof Uint8Array||ArrayBuffer.isView(n)&&"Uint8Array"===n.constructor.name))throw new Error("Uint8Array expected");var n;if(t.length>0&&!t.includes(e.length)){const n=t.join(",");throw new Error(`Uint8Array expected of length ${n}, got length=${e.length}`)}}function kt(e,t=!0){if(!0===e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&!0===e.finished)throw new Error("Hash#digest() has already been called")}function Nt(...e){for(const t of e)t.fill(0)}function Rt(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Bt(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e)),xt(e),e}class Ct{}function Tt(e){const t=t=>e().update(Bt(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}const Lt=BigInt(2**32-1),Mt=BigInt(32);function Kt(e,t=!1){return t?{h:Number(e&Lt),l:Number(e>>Mt&Lt)}:{h:0|Number(e>>Mt&Lt),l:0|Number(e&Lt)}}const Dt=(e,t,n)=>e>>>n,Pt=(e,t,n)=>e<<32-n|t>>>n,Ut=(e,t,n)=>e>>>n|t<<32-n,Ot=(e,t,n)=>e<<32-n|t>>>n,qt=(e,t,n)=>e<<64-n|t>>>n-32,Ft=(e,t,n)=>e>>>n-32|t<<64-n;function zt(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:0|i}}const Vt=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Ht=(e,t,n,r)=>Math.trunc(t+n+r+Math.trunc(e/2**32)),jt=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Wt=(e,t,n,r,i)=>Math.trunc(t+n+r+i+Math.trunc(e/2**32)),$t=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),Gt=(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0;class Zt extends Ct{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){super(),this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=Rt(this.buffer)}update(e){kt(this),xt(e=Bt(e));const{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let s=0;s<i;){const a=Math.min(r-this.pos,i-s);if(a===r){const t=Rt(e);for(;r<=i-s;s+=r)this.process(t,s);continue}n.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){kt(this),function(e,t){xt(e);const n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:i}=this;let{pos:s}=this;t[s++]=128,Nt(this.buffer.subarray(s)),this.padOffset>r-s&&(this.process(n,0),s=0);for(let e=s;e<r;e++)t[e]=0;!function(e,t,n,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,r);const i=BigInt(32),s=BigInt(4294967295),a=Number(n>>i&s),o=Number(n&s),c=r?4:0,d=r?0:4;e.setUint32(t+c,a,r),e.setUint32(t+d,o,r)}(n,r-8,BigInt(8*this.length),i),this.process(n,0);const a=Rt(e),o=this.outputLen;if(o%4!=0)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=o/4,d=this.get();if(c>d.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)a.setUint32(4*e,d[e],i)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e??=new this.constructor,e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:i,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=i,e.length=r,e.pos=a,r%t!==0&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const Xt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Yt=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]),Jt=new Uint32Array(64);class Qt extends Zt{A=0|Xt[0];B=0|Xt[1];C=0|Xt[2];D=0|Xt[3];E=0|Xt[4];F=0|Xt[5];G=0|Xt[6];H=0|Xt[7];constructor(e=32){super(64,e,8,!1)}get(){const{A:e,B:t,C:n,D:r,E:i,F:s,G:a,H:o}=this;return[e,t,n,r,i,s,a,o]}set(...[e,t,n,r,i,s,a,o]){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|i,this.F=0|s,this.G=0|a,this.H=0|o}process(e,t){for(let n=0;n<16;n++,t+=4)Jt[n]=e.getUint32(t);for(let e=16;e<64;e++){const t=Jt[e-15],n=Jt[e-2],r=ct(t),i=dt(n);Jt[e]=et(et(r,Jt[e-7]),et(i,Jt[e-16]))}let{A:n,B:r,C:i,D:s,E:a,F:o,G:c,H:d}=this;for(let e=0;e<64;e++){const t=rt(d,ot(a),it(a,o,c),Yt[e],Jt[e]),f=et(at(n),st(n,r,i));d=c,c=o,o=a,a=et(s,t),s=i,i=r,r=n,n=et(t,f)}this.A=et(this.A,n),this.B=et(this.B,r),this.C=et(this.C,i),this.D=et(this.D,s),this.E=et(this.E,a),this.F=et(this.F,o),this.G=et(this.G,c),this.H=et(this.H,d)}roundClean(){Nt(Jt)}destroy(){Nt(this.buffer),this.set(0,0,0,0,0,0,0,0)}}const en=Tt(()=>new Qt),tn=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),nn=function(e,t=!1){const n=e.length,r=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){const{h:n,l:a}=Kt(e[s],t);r[s]=n,i[s]=a}return[r,i]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(BigInt)),rn=nn[0],sn=nn[1],an=new Uint32Array(80),on=new Uint32Array(80);class cn extends Zt{Ah=0|tn[0];Al=0|tn[1];Bh=0|tn[2];Bl=0|tn[3];Ch=0|tn[4];Cl=0|tn[5];Dh=0|tn[6];Dl=0|tn[7];Eh=0|tn[8];El=0|tn[9];Fh=0|tn[10];Fl=0|tn[11];Gh=0|tn[12];Gl=0|tn[13];Hh=0|tn[14];Hl=0|tn[15];constructor(e=64){super(128,e,16,!1)}get(){const{Ah:e,Al:t,Bh:n,Bl:r,Ch:i,Cl:s,Dh:a,Dl:o,Eh:c,El:d,Fh:f,Fl:h,Gh:u,Gl:l,Hh:b,Hl:p}=this;return[e,t,n,r,i,s,a,o,c,d,f,h,u,l,b,p]}set(...[e,t,n,r,i,s,a,o,c,d,f,h,u,l,b,p]){this.Ah=0|e,this.Al=0|t,this.Bh=0|n,this.Bl=0|r,this.Ch=0|i,this.Cl=0|s,this.Dh=0|a,this.Dl=0|o,this.Eh=0|c,this.El=0|d,this.Fh=0|f,this.Fl=0|h,this.Gh=0|u,this.Gl=0|l,this.Hh=0|b,this.Hl=0|p}process(e,t){for(let n=0;n<16;n++,t+=8)an[n]=e.getUint32(t),on[n]=e.getUint32(t+4);for(let e=16;e<80;e++){const t=0|an[e-15],n=0|on[e-15],r=Ut(t,n,1)^Ut(t,n,8)^Dt(t,0,7),i=Ot(t,n,1)^Ot(t,n,8)^Pt(t,n,7),s=0|an[e-2],a=0|on[e-2],o=Ut(s,a,19)^qt(s,a,61)^Dt(s,0,6),c=Ot(s,a,19)^Ft(s,a,61)^Pt(s,a,6),d=jt(i,c,on[e-7],on[e-16]),f=Wt(d,r,o,an[e-7],an[e-16]);an[e]=0|f,on[e]=0|d}let{Ah:n,Al:r,Bh:i,Bl:s,Ch:a,Cl:o,Dh:c,Dl:d,Eh:f,El:h,Fh:u,Fl:l,Gh:b,Gl:p,Hh:g,Hl:y}=this;for(let e=0;e<80;e++){const t=Ut(f,h,14)^Ut(f,h,18)^qt(f,h,41),m=Ot(f,h,14)^Ot(f,h,18)^Ft(f,h,41),w=f&u^~f&b,v=$t(y,m,h&l^~h&p,sn[e],on[e]),_=Gt(v,g,t,w,rn[e],an[e]),S=0|v,I=Ut(n,r,28)^qt(n,r,34)^qt(n,r,39),A=Ot(n,r,28)^Ft(n,r,34)^Ft(n,r,39),E=n&i^n&a^i&a,x=r&s^r&o^s&o;g=0|b,y=0|p,b=0|u,p=0|l,u=0|f,l=0|h,({h:f,l:h}=zt(0|c,0|d,0|_,0|S)),c=0|a,d=0|o,a=0|i,o=0|s,i=0|n,s=0|r;const k=Vt(A,x,S);n=Ht(k,I,E,_),r=0|k}({h:n,l:r}=zt(n,r,this.Ah,this.Al)),({h:i,l:s}=zt(i,s,this.Bh,this.Bl)),({h:a,l:o}=zt(a,o,this.Ch,this.Cl)),({h:c,l:d}=zt(c,d,this.Dh,this.Dl)),({h:f,l:h}=zt(f,h,this.Eh,this.El)),({h:u,l}=zt(u,l,this.Fh,this.Fl)),({h:b,l:p}=zt(b,p,this.Gh,this.Gl)),({h:g,l:y}=zt(g,y,this.Hh,this.Hl)),this.set(n,r,i,s,a,o,c,d,f,h,u,l,b,p,g,y)}roundClean(){Nt(an,on)}destroy(){Nt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const dn=Tt(()=>new cn);class fn extends Ct{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){super(),function(e){if("function"!=typeof e||"function"!=typeof e.create)throw new TypeError("Hash should be wrapped by utils.createHasher");Et(e.outputLen),Et(e.blockLen)}(e);const n=Bt(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new TypeError("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?e.create().update(n).digest():n);for(let e=0;e<i.length;e++)i[e]^=54;this.iHash.update(i),this.oHash=e.create();for(let e=0;e<i.length;e++)i[e]^=106;this.oHash.update(i),Nt(i)}update(e){return kt(this),this.iHash.update(e),this}digestInto(e){kt(this),xt(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e??=Object.create(Object.getPrototypeOf(this),{});const{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:s,outputLen:a}=this;return e.finished=r,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash??void 0),e.iHash=n._cloneInto(e.iHash??void 0),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}(()=>{const e=new ArrayBuffer(4),t=new Uint32Array(e),n=new Uint8Array(e);t[0]=16909060,n[0]})();const hn=globalThis.Buffer,un=null!=hn&&"function"==typeof hn.from,ln="0123456789abcdef",bn=Array.from({length:256},()=>"");for(let e=0;e<256;e++)bn[e]=ln[e>>4&15]+ln[15&e];const pn=e=>un?hn.from(e).toString("hex"):0===e.length?"":Array.from(e,e=>bn[255&e]).join(""),gn=(e,t)=>{if(Array.isArray(e))return e.slice();if(void 0===e)return[];if("string"!=typeof e)return Array.from(e,e=>Math.trunc(e));switch(t){case"hex":return mn(e);case"base64":return function(e){const t=vn(e),n=[];let r=0,i=0;for(let e=0;e<t.length;e++){const s=t.codePointAt(e);for(r=r<<6|_n(s,e),i+=6;i>=8;)i-=8,n.push(r>>i&255),r&=(1<<i)-1}return n}(e);default:return n=e,Array.from((new TextEncoder).encode(n))}var n},yn=new Int8Array(256).fill(-1);for(let e=0;e<10;e++)yn[48+e]=e;for(let e=0;e<6;e++)yn[65+e]=10+e,yn[97+e]=10+e;const mn=e=>Array.from(wn(e)),wn=e=>{Te(e);const t=e.length%2==0?e:"0"+e;if(un){const e=hn.from(t,"hex");return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}const n=new Uint8Array(t.length/2);let r=0;for(let e=0;e<t.length;e+=2){const i=yn[t.codePointAt(e)],s=yn[t.codePointAt(e+1)];n[r++]=i<<4|s}return n},vn=e=>{if("string"!=typeof e)throw new TypeError("msg must be a string");const t=e.trim().replaceAll(/[\r\n\t\f\v ]+/g,"").replaceAll("-","+").replaceAll("_","/"),n=t.indexOf("=");if(-1===n)return t;const r=t.slice(n);if(!/^={1,2}$/.test(r)||t.slice(0,n).includes("="))throw new Error("Invalid base64 padding");return t.slice(0,n)},_n=(e,t)=>{if(e>=65&&e<=90)return e-65;if(e>=97&&e<=122)return e-97+26;if(e>=48&&e<=57)return e-48+52;if(43===e)return 62;if(47===e)return 63;throw new Error(`Invalid base64 character at index ${t}`)},Sn=e=>(new TextDecoder).decode(e instanceof Uint8Array?e:new Uint8Array(e)),In=(e,t)=>{switch(t){case"hex":return pn(e);case"utf8":return Sn(e);default:return e}};function An(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let n,r="";for(n=0;n<e.length;n+=3){const i=e[n],s=n+1<e.length?e[n+1]:0,a=n+2<e.length?e[n+2]:0,o=(3&i)<<4|s>>4,c=(15&s)<<2|a>>6,d=63&a;r+=t.charAt(i>>2)+t.charAt(o),r+=n+1<e.length?t.charAt(c):"=",r+=n+2<e.length?t.charAt(d):"="}return r}const En="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",xn=e=>{if(""===e||"string"!=typeof e)throw new Error(`Expected base58 string but got “${e}”`);const t=e.match(/[^1-9A-HJ-NP-Za-km-z]/gmu);if(null!==t)throw new Error(`Invalid base58 character “${t.join("")}”`);const n=e.match(/^1+/gmu),r=null===n?0:n[0].length,i=(e.length-r)*(Math.log(58)/Math.log(256))+1>>>0,s=new Uint8Array([...new Uint8Array(r),...Array.from(e).map(e=>En.indexOf(e)).reduce((e,t)=>e.map(e=>{const n=58*e+t;return t=n>>8,n}),new Uint8Array(i)).reverse().filter((a=!1,e=>a=a||e))]);var a;return[...s]},kn=e=>{const t=Array.from({length:256},()=>-1);for(let e=0;e<58;++e)t[En.codePointAt(e)]=e;const n=[];for(const r of e){let e=r;for(let r=0;r<n.length;++r){const i=(t[n[r]]<<8)+e,s=Math.trunc(i/58),a=i-58*s;n[r]=En.codePointAt(a),e=s}for(;0!==e;){const t=Math.trunc(e/58),r=e-58*t;n.push(En.codePointAt(r)),e=t}}for(const t of e){if(0!==t)break;n.push("1".codePointAt(0))}return n.reverse(),String.fromCodePoint(...n)},Nn=(e,t=[0])=>{let n=St([...t,...e]);return n=[...t,...e,...n.slice(0,4)],kn(n)};class Rn{bufs;length;constructor(e){this.bufs=e??[],this.length=0;for(const e of this.bufs)this.length+=e.length}getLength(){return this.length}toUint8Array(){const e=new Uint8Array(this.length);let t=0;for(const n of this.bufs)e.set(n,t),t+=n.length;return e}toArray(){const e=this.length,t=Array.from({length:e},()=>0);let n=0;for(const e of this.bufs)if(e instanceof Uint8Array)for(const r of e)t[n++]=r;else{const r=e;for(const e of r)t[n++]=e}return t}toHex(){return this.toArray().map(e=>e.toString(16).padStart(2,"0")).join("")}write(e){return this.bufs.push(e),this.length+=e.length,this}writeReverse(e){const t=Array.from({length:e.length},()=>0);for(let n=0;n<t.length;n++)t[n]=e[e.length-1-n];return this.write(t)}writeUInt8(e){const t=Array.from({length:1},()=>0);return t[0]=255&e,this.write(t),this}writeInt8(e){return this.writeUInt8(e)}writeUInt16BE(e){const t=[e>>8&255,255&e];return this.write(t)}writeInt16BE(e){return this.writeUInt16BE(65535&e)}writeUInt16LE(e){const t=[255&e,e>>8&255];return this.write(t)}writeInt16LE(e){return this.writeUInt16LE(65535&e)}writeUInt32BE(e){const t=[e>>24&255,e>>16&255,e>>8&255,255&e];return this.write(t)}writeInt32BE(e){return this.writeUInt32BE(e>>>0)}writeUInt32LE(e){const t=[255&e,e>>8&255,e>>16&255,e>>24&255];return this.write(t)}writeInt32LE(e){return this.writeUInt32LE(e>>>0)}writeUInt64BEBn(e){const t=e.toArray("be",8);return this.write(t),this}writeUInt64LEBn(e){const t=e.toArray("be",8);return this.writeReverse(t),this}writeUInt64LE(e){if(-1===e)this.write(Array.from({length:8},()=>255));else{const t=new Be(e).toArray("be",8);this.writeReverse(t)}return this}writeVarIntNum(e){const t=Rn.varIntNum(e);return this.write(t),this}writeVarIntBn(e){const t=Rn.varIntBn(e);return this.write(t),this}static varIntNum(e){let t;if(e<0)return this.varIntBn(new Be(e));if(e<253)t=[e];else if(e<65536)t=[253,255&e,e>>8&255];else if(e<4294967296)t=[254,255&e,e>>8&255,e>>16&255,e>>24&255];else{const n=4294967295&e,r=4294967295&Math.floor(e/4294967296);t=[255,255&n,n>>8&255,n>>16&255,n>>24&255,255&r,r>>8&255,r>>16&255,r>>24&255]}return t}static varIntBn(e){let t;if(e.isNeg()&&(e=e.add(Tn)),e.ltn(253))t=[e.toNumber()];else if(e.ltn(65536)){const n=e.toNumber();t=[253,255&n,n>>8&255]}else if(e.lt(new Be(4294967296))){const n=e.toNumber();t=[254,255&n,n>>8&255,n>>16&255,n>>24&255]}else{const n=new Rn;n.writeUInt8(255),n.writeUInt64LEBn(e),t=n.toArray()}return t}}class Bn{bin;pos;length;constructor(e=[],t=0){this.bin=e,this.pos=t,this.length=e.length}eof(){return this.pos>=this.length}read(e=this.length){const t=this.pos,n=this.pos+e;return this.pos=n,this.bin.slice(t,n)}readReverse(e=this.length){const t=Array.from({length:e},()=>0);for(let n=0;n<e;n++)t[n]=this.bin[this.pos+e-1-n];return this.pos+=e,t}readUInt8(){const e=this.bin[this.pos];return this.pos+=1,e}readInt8(){const e=this.bin[this.pos];return this.pos+=1,128&e?e-256:e}readUInt16BE(){const e=this.bin[this.pos]<<8|this.bin[this.pos+1];return this.pos+=2,e}readInt16BE(){const e=this.readUInt16BE();return 32768&e?e-65536:e}readUInt16LE(){const e=this.bin[this.pos]|this.bin[this.pos+1]<<8;return this.pos+=2,e}readInt16LE(){const e=this.readUInt16LE();return 32768&e?e-65536:e}readUInt32BE(){const e=16777216*this.bin[this.pos]+(this.bin[this.pos+1]<<16|this.bin[this.pos+2]<<8|this.bin[this.pos+3]);return this.pos+=4,e}readInt32BE(){const e=this.readUInt32BE();return 2147483648&e?e-4294967296:e}readUInt32LE(){const e=(this.bin[this.pos]|this.bin[this.pos+1]<<8|this.bin[this.pos+2]<<16|this.bin[this.pos+3]<<24)>>>0;return this.pos+=4,e}readInt32LE(){const e=this.readUInt32LE();return 2147483648&e?e-4294967296:e}readUInt64BEBn(){const e=this.bin.slice(this.pos,this.pos+8),t=new Be(e);return this.pos=this.pos+8,t}readUInt64LEBn(){const e=this.readReverse(8);return new Be(e)}readInt64LEBn(){const e=this.readReverse(8);let t=new Be(e);return t.gte(Cn)&&(t=t.sub(Tn)),t}readVarIntNum(e=!0){const t=this.readUInt8();let n;switch(t){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:if(n=e?this.readInt64LEBn():this.readUInt64LEBn(),n.lte(new Be(2).pow(new Be(53))))return n.toNumber();throw new Error("number too large to retain precision - use readVarIntBn");default:return t}}readVarInt(){switch(this.bin[this.pos]){case 253:return this.read(3);case 254:return this.read(5);case 255:return this.read(9);default:return this.read(1)}}readVarIntBn(){const e=this.readUInt8();switch(e){case 253:return new Be(this.readUInt16LE());case 254:return new Be(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new Be(e)}}}const Cn=new Be(2).pow(new Be(63)),Tn=new Be(2).pow(new Be(64));function Ln(e){return null!=e&&"object"==typeof e&&"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView(e)&&"[object Uint8Array]"===Object.prototype.toString.call(e)}function Mn(e,t){const n=null==this?void 0:this[e];return Ln(n)?Array.from(n):Ln(t)?Array.from(t):t}Object.prototype.hasOwnProperty,new Set(["BEEF","atomicBEEF","beef","ciphertext","competingBeef","data","encryptedLinkage","encryptedLinkageProof","hashToDirectlySign","hashToDirectlyVerify","hmac","inputBEEF","payload","plaintext","signature","transaction","tx"]);class Kn{sessionNonceToSession;identityKeyToNonces;constructor(){this.sessionNonceToSession=new Map,this.identityKeyToNonces=new Map}addSession(e){if("string"!=typeof e.sessionNonce)throw new TypeError("Invalid session: sessionNonce is required to add a session.");if(this.sessionNonceToSession.set(e.sessionNonce,e),"string"==typeof e.peerIdentityKey){let t=this.identityKeyToNonces.get(e.peerIdentityKey);null==t&&(t=new Set,this.identityKeyToNonces.set(e.peerIdentityKey,t)),t.add(e.sessionNonce)}}updateSession(e){this.removeSession(e),this.addSession(e)}getSession(e){const t=this.sessionNonceToSession.get(e);if(null!=t)return t;const n=this.identityKeyToNonces.get(e);if(null==n||0===n.size)return;let r;for(const e of n){const t=this.sessionNonceToSession.get(e);null!=t&&(null==r||(t.lastUpdate??0)>(r.lastUpdate??0))&&(r=t)}return r}removeSession(e){if("string"==typeof e.sessionNonce&&this.sessionNonceToSession.delete(e.sessionNonce),"string"==typeof e.peerIdentityKey){const t=this.identityKeyToNonces.get(e.peerIdentityKey);null!=t&&(t.delete(e.sessionNonce??""),0===t.size&&this.identityKeyToNonces.delete(e.peerIdentityKey))}}hasSession(e){if(this.sessionNonceToSession.has(e))return!0;const t=this.identityKeyToNonces.get(e);return null!=t&&t.size>0}}class Dn{_rand;getRandomValues(e,t){const n=new Uint8Array(t);return e.crypto.getRandomValues(n),Array.from(n)}constructor(){const e=()=>{throw new Error("No secure random number generator is available in this environment.")};if(this._rand=e,"undefined"==typeof globalThis||"function"!=typeof globalThis.crypto?.getRandomValues)if(void 0===globalThis.self||"function"!=typeof globalThis.self.crypto?.getRandomValues)if(void 0===globalThis.window||"function"!=typeof globalThis.window.crypto?.getRandomValues){if("undefined"!=typeof process&&"function"==typeof process.getBuiltinModule){const e=process.getBuiltinModule("node:crypto");if("function"==typeof e?.randomBytes)return void(this._rand=t=>Array.from(e.randomBytes(t)))}this._rand=e}else this._rand=e=>this.getRandomValues(globalThis.window,e);else this._rand=e=>this.getRandomValues(globalThis.self,e);else this._rand=e=>this.getRandomValues(globalThis,e)}generate(e){return this._rand(e)}}let Pn=null;const Un=e=>(Pn??=new Dn,Pn.generate(e));async function On(e,t="self",n){const r=Un(16),{hmac:i}=await e.createHmac({protocolID:[2,"server hmac"],keyID:Sn(r),data:r,counterparty:t},n);return An([...r,...i])}const qn=new Uint8Array([99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22]),Fn=[[0,0,0,0],[1,0,0,0],[2,0,0,0],[4,0,0,0],[8,0,0,0],[16,0,0,0],[32,0,0,0],[64,0,0,0],[128,0,0,0],[27,0,0,0],[54,0,0,0]].map(e=>new Uint8Array(e)),zn=new Uint8Array(256),Vn=new Uint8Array(256);for(let e=0;e<256;e++){const t=255&(e<<1^(128&e?27:0));zn[e]=t,Vn[e]=t^e}function Hn(e){for(let t=0;t<4;t++){const n=e[0][t],r=e[1][t],i=e[2][t],s=e[3][t];e[0][t]=zn[n]^Vn[r]^i^s,e[1][t]=n^zn[r]^Vn[i]^s,e[2][t]=n^r^zn[i]^Vn[s],e[3][t]=Vn[n]^r^i^zn[s]}}function jn(e,t,n){for(let r=0;r<4;r++){const i=t[n+r];for(let t=0;t<4;t++)e[t][r]^=i[t]}}function Wn(e){for(let t=0;t<4;t++)for(let n=0;n<4;n++)e[t][n]=qn[e[t][n]]}function $n(e){for(let t=0;t<4;t++)e[t]=qn[e[t]]}function Gn(e){const t=e[0];e[0]=e[1],e[1]=e[2],e[2]=e[3],e[3]=t}function Zn(e){let t=e[1][0];e[1][0]=e[1][1],e[1][1]=e[1][2],e[1][2]=e[1][3],e[1][3]=t,t=e[2][0];const n=e[2][1];e[2][0]=e[2][2],e[2][1]=e[2][3],e[2][2]=t,e[2][3]=n,t=e[3][3],e[3][3]=e[3][2],e[3][2]=e[3][1],e[3][1]=e[3][0],e[3][0]=t}function Xn(e,t){let n,r,i,s;const a=[[],[],[],[]],o=[],c=Array.from(t);if(16===c.length)s=11;else if(24===c.length)s=13;else{if(32!==c.length)throw new Error("Illegal key length: "+String(c.length));s=15}const d=function(e,t){const n=t.length/4,r=[];for(let e=0;e<t.length;e++)e%4==0&&r.push([]),r[e>>2].push(t[e]);for(let t=n;t<4*e;t++){r[t]=[];const e=r[t-1].slice();if(t%n===0){Gn(e),$n(e);const r=Fn[t/n];for(let t=0;t<4;t++)e[t]^=r[t]}else n>6&&t%n===4&&$n(e);for(let i=0;i<4;i++)r[t][i]=r[t-n][i]^e[i]}return r}(s,c);for(let t=0;t<4;t++)a[0][t]=e[4*t],a[1][t]=e[4*t+1],a[2][t]=e[4*t+2],a[3][t]=e[4*t+3];for(jn(a,d,0),i=1;i<s;i++)Wn(a),Zn(a),i+1<s&&Hn(a),jn(a,d,4*i);for(n=0;n<4;n++)for(r=0;r<4;r++)o.push(a[r][n]);return o}const Yn=function(e){if(e<0||e>Number.MAX_SAFE_INTEGER)throw new Error("getBytes64: value out of range");const t=Math.floor(e/4294967296),n=e>>>0;return[t>>>24&255,t>>>16&255,t>>>8&255,255&t,n>>>24&255,n>>>16&255,n>>>8&255,255&n]},Jn=function(e){return new Uint8Array(e)},Qn=(()=>{const e=new Uint8Array(16);return e[0]=225,e})(),er=(...e)=>{let t=0;for(const n of e)t+=n.length;const n=new Uint8Array(t);let r=0;for(const t of e)n.set(t,r),r+=t.length;return n},tr=function(e){let t=0,n=0;for(let r=0;r<e.length;r++)n=t,t=1&e[r],e[r]=e[r]>>1,0!==n&&(e[r]=128|e[r]);return e},nr=function(e,t){const n=t.slice(),r=Jn(16);for(let t=0;t<16;t++){const i=e[t];for(let e=7;e>=0;e--){const t=255&-(i>>e&1);for(let e=0;e<16;e++)r[e]^=n[e]&t;const s=255&-(1&n[15]);tr(n);for(let e=0;e<16;e++)n[e]^=Qn[e]&s}}return r},rr=function(e){const t=e.slice();for(let e=15;e>11&&(t[e]=t[e]+1&255,0===t[e]);e--);return t};function ir(e,t){let n=Jn(16);const r=new Uint8Array(16);for(let i=0;i<e.length;i+=16){r.set(n);for(let t=0;t<16;t++)r[t]^=e[i+t]??0;n=nr(r,t)}return n}function sr(e,t,n){if(0===e.length)return new Uint8Array(0);const r=new Uint8Array(e.length);let i=t.slice(),s=0;const a=Math.ceil(e.length/16);for(let t=0;t<a;t++){const o=Xn(i,n),c=Math.min(16,e.length-s);for(let t=0;t<c;t++)r[s]=e[s]^o[t],s++;t+1<a&&(i=rr(i))}return r}function ar(e){const t=8*e.length;let n;n=0===e.length?16:e.length%16==0?0:16-e.length%16;const r=16+e.length+n+16,i=new Uint8Array(r);let s=0;s+=16,i.set(e,s),s+=e.length,s+=n;const a=Yn(0);i.set(a,s),s+=8;const o=Yn(t);return i.set(o,s),i}const or=(()=>{const e="undefined"==typeof globalThis?void 0:globalThis.process,t=e?.getBuiltinModule;if("function"==typeof t)try{const n=t.call(e,"node:crypto");if(null!=n)return n}catch{}})(),cr=null!=or&&"function"==typeof or.createCipheriv&&"function"==typeof or.createDecipheriv;class dr extends Be{static fromRandom(){return new dr(Un(32))}encrypt(e,t){const n=new Uint8Array(Un(32)),r=new Uint8Array(gn(e,t)),i=new Uint8Array(this.toArray("be",32));if(cr){const e=function(e,t,n){try{const r=or.createCipheriv("aes-256-gcm",Buffer.from(n.buffer,n.byteOffset,n.byteLength),Buffer.from(t.buffer,t.byteOffset,t.byteLength)),i=Buffer.concat([r.update(Buffer.from(e.buffer,e.byteOffset,e.byteLength)),r.final()]),s=r.getAuthTag(),a=new Uint8Array(t.length+i.length+s.length);let o=0;return a.set(t,o),o+=t.length,a.set(i,o),o+=i.length,a.set(s,o),a}catch{return null}}(r,n,i);if(null!==e)return In(Array.from(e),t)}const{result:s,authenticationTag:a}=function(e,t,n){if(0===t.length)throw new Error("Initialization vector must not be empty");if(0===n.length)throw new Error("Key must not be empty");const r=new Uint8Array(Xn(Jn(16),n));let i;if(12===t.length)i=er(t,Jn(3),new Uint8Array([1]));else{let e=t;e.length%16!=0&&(e=er(e,Jn(16-e.length%16)));const n=Yn(8*t.length);i=ir(er(e,Jn(8),new Uint8Array(n)),r)}const s=sr(e,rr(i),n);return{result:s,authenticationTag:sr(ir(ar(s),r),i,n)}}(r,n,i),o=n.length+s.length+a.length,c=new Uint8Array(o);let d=0;return c.set(n,d),d+=n.length,c.set(s,d),d+=s.length,c.set(a,d),In(Array.from(c),t)}decrypt(e,t){const n=new Uint8Array(gn(e,t));if(n.length<48)throw new Error("Ciphertext too short");const r=new Uint8Array(this.toArray("be",32));if(cr){const e=function(e,t,n,r){try{const t=e.slice(0,32),n=e.length-16,i=e.slice(32,n),s=e.slice(n),a=or.createDecipheriv("aes-256-gcm",Buffer.from(r.buffer,r.byteOffset,r.byteLength),Buffer.from(t.buffer,t.byteOffset,t.byteLength));a.setAuthTag(Buffer.from(s.buffer,s.byteOffset,s.byteLength));const o=Buffer.concat([a.update(Buffer.from(i.buffer,i.byteOffset,i.byteLength)),a.final()]);return new Uint8Array(o.buffer,o.byteOffset,o.byteLength)}catch{return null}}(n,0,0,r);if(void 0!==e){if(null===e)throw new Error("Decryption failed!");return In(Array.from(e),t)}}const i=n.slice(0,32),s=n.length-16,a=function(e,t,n,r){if(0===e.length)throw new Error("Cipher text must not be empty");if(0===t.length)throw new Error("Initialization vector must not be empty");if(0===r.length)throw new Error("Key must not be empty");const i=new Uint8Array(Xn(Jn(16),r));let s;if(12===t.length)s=er(t,Jn(3),new Uint8Array([1]));else{let e=t;e.length%16!=0&&(e=er(e,Jn(16-e.length%16)));const n=Yn(8*t.length);s=ir(er(e,Jn(8),new Uint8Array(n)),i)}const a=sr(e,rr(s),r),o=sr(ir(ar(e),i),s,r);if(o.length!==n.length)return null;let c=0;for(let e=0;e<o.length;e++)c|=o[e]^n[e];return 0!==c?null:a}(n.slice(32,s),i,n.slice(s),r);if(null===a)throw new Error("Decryption failed!");return In(Array.from(a),t)}}class fr{bin;pos;length;static makeReader(e,t=0){if(e instanceof Uint8Array)return new fr(e,t);if(Array.isArray(e))return new Bn(e,t);throw new Error("ReaderUint8Array.makeReader: bin must be Uint8Array or number[]")}constructor(e=new Uint8Array(0),t=0){if(e instanceof Uint8Array)this.bin=e;else{if(!Array.isArray(e))throw new TypeError("ReaderUint8Array constructor: bin must be Uint8Array or number[]");this.bin=new Uint8Array(e)}this.pos=t,this.length=this.bin.length}eof(){return this.pos>=this.length}read(e=this.length){const t=this.pos,n=this.pos+e;return this.pos=n,this.bin.slice(t,n)}readView(e=this.length-this.pos){if(!Number.isSafeInteger(e)||e<0||this.pos+e>this.length)throw new RangeError("ReaderUint8Array read exceeds available data");const t=this.pos;return this.pos+=e,this.bin.subarray(t,this.pos)}skip(e){if(!Number.isSafeInteger(e)||e<0||this.pos+e>this.length)throw new RangeError("ReaderUint8Array skip exceeds available data");this.pos+=e}remaining(){return this.length-this.pos}readReverse(e=this.length){const t=new Uint8Array(e);for(let n=0;n<e;n++)t[n]=this.bin[this.pos+e-1-n];return this.pos+=e,t}readUInt8(){const e=this.bin[this.pos];return this.pos+=1,e}readInt8(){const e=this.bin[this.pos];return this.pos+=1,128&e?e-256:e}readUInt16BE(){const e=this.bin[this.pos]<<8|this.bin[this.pos+1];return this.pos+=2,e}readInt16BE(){const e=this.readUInt16BE();return 32768&e?e-65536:e}readUInt16LE(){const e=this.bin[this.pos]|this.bin[this.pos+1]<<8;return this.pos+=2,e}readInt16LE(){const e=this.readUInt16LE();return 32768&e?e-65536:e}readUInt32BE(){const e=16777216*this.bin[this.pos]+(this.bin[this.pos+1]<<16|this.bin[this.pos+2]<<8|this.bin[this.pos+3]);return this.pos+=4,e}readInt32BE(){const e=this.readUInt32BE();return 2147483648&e?e-4294967296:e}readUInt32LE(){const e=(this.bin[this.pos]|this.bin[this.pos+1]<<8|this.bin[this.pos+2]<<16|this.bin[this.pos+3]<<24)>>>0;return this.pos+=4,e}readInt32LE(){const e=this.readUInt32LE();return 2147483648&e?e-4294967296:e}readUInt64BEBn(){const e=Array.from(this.bin.slice(this.pos,this.pos+8)),t=new Be(e);return this.pos=this.pos+8,t}readUInt64LEBn(){const e=Array.from(this.readReverse(8));return new Be(e)}readInt64LEBn(){const e=new Be(2).pow(new Be(63)),t=new Be(2).pow(new Be(64)),n=Array.from(this.readReverse(8));let r=new Be(n);return r.gte(e)&&(r=r.sub(t)),r}readVarIntNum(e=!0){const t=this.readUInt8();let n;switch(t){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:if(n=e?this.readInt64LEBn():this.readUInt64LEBn(),n.lte(new Be(2).pow(new Be(53))))return n.toNumber();throw new Error("number too large to retain precision - use readVarIntBn");default:return t}}readVarInt(){switch(this.bin[this.pos]){case 253:return this.read(3);case 254:return this.read(5);case 255:return this.read(9);default:return this.read(1)}}readVarIntBn(){const e=this.readUInt8();switch(e){case 253:return new Be(this.readUInt16LE());case 254:return new Be(this.readUInt32LE());case 255:return this.readUInt64LEBn();default:return new Be(e)}}}class hr{name;p;k;n;tmp;constructor(e,t){this.name=e,this.p=new Be(t,16),this.n=this.p.bitLength(),this.k=new Be(BigInt(1)).iushln(this.n).isub(this.p),this.tmp=this._tmp()}_tmp(){const e=new Be(BigInt(0)),t=Math.ceil(this.n/Be.wordSize);return e.expand(Math.max(1,t)),e}ireduce(e){const t=e;let n;do{this.split(t,this.tmp),this.imulK(t),t.iadd(this.tmp),n=t.bitLength()}while(n>this.n);const r=n<this.n?-1:t.ucmp(this.p);return 0===r?t.words=[0]:r>0&&t.isub(this.p),t.strip(),t}split(e,t){e.iushrn(this.n,0,t)}imulK(e){return e.imul(this.k)}}class ur extends hr{constructor(){super("k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}split(e,t){const n=4194303,r=e.words,i=e.length,s=Math.min(i,9),a=Array.from({length:s+(i>9?1:0)},()=>0);for(let e=0;e<s;e++)a[e]=r[e];let o=s;if(i<=9){const n=Array.from({length:o},()=>0);for(let e=0;e<o;++e)n[e]=a[e];return t.words=n,void(e.words=[0])}let c=r[9];a[o++]=c&n;const d=Array.from({length:o},()=>0);for(let e=0;e<o;++e)d[e]=a[e];t.words=d;const f=Array.from({length:Math.max(1,i-9)},()=>0);let h=0;for(let e=10;e<i;e++){const t=Math.trunc(r[e]);h<f.length&&(f[h++]=(t&n)<<4|c>>>22),c=t}c>>>=22,h<f.length?f[h++]=c:0!==c&&f.length;const u=Array.from({length:h},()=>0);for(let e=0;e<h;++e)u[e]=f[e];e.words=u}imulK(e){const t=e.words,n=e.length,r=n+2,i=Array.from({length:r},()=>0);for(let e=0;e<n;e++)i[e]=t[e];let s=0;for(let e=0;e<r;e++){const t=Math.trunc(i[e]);s+=977*t,i[e]=67108863&s,s=64*t+Math.trunc(s/67108864)}return e.words=i,e}}class lr{prime;m;constructor(e){if("k256"===e){const e=new ur;this.m=e.p,this.prime=e}else this.assert(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}assert(e,t="Assertion failed"){if(!e)throw new Error(t)}verify1(e){this.assert(0===e.negative,"red works only with positives"),this.assert(e.red,"red works only with red numbers")}verify2(e,t){this.assert(0===(e.negative|t.negative),"red works only with positives"),this.assert(null!=e.red&&e.red===t.red,"red works only with red numbers")}imod(e){return null!=this.prime?this.prime.ireduce(e).forceRed(this):(Be.move(e,e.umod(this.m).forceRed(this)),e)}neg(e){return e.isZero()?e.clone():this.m.sub(e).forceRed(this)}add(e,t){this.verify2(e,t);const n=e.clone();return n.iadd(t),n.isub(this.m),n.isNeg()&&n.iadd(this.m),n}iadd(e,t){return this.verify2(e,t),e.iadd(t),e.isub(this.m),e.isNeg()&&e.iadd(this.m),e}sub(e,t){this.verify2(e,t);const n=e.sub(t);return n.cmpn(0)<0&&n.iadd(this.m),n.forceRed(this)}isub(e,t){this.verify2(e,t);const n=e.isub(t);return n.cmpn(0)<0&&n.iadd(this.m),n}shl(e,t){return this.verify1(e),this.imod(e.ushln(t))}imul(e,t){return this.verify2(e,t),this.imod(e.imul(t))}mul(e,t){return this.verify2(e,t),this.imod(e.mul(t))}isqr(e){return this.imul(e,e.clone())}sqr(e){return this.mul(e,e)}sqrt(e){if(e.isZero())return e.clone();const t=this.m.andln(3);if(this.assert(t%2==1),3===t){const t=this.m.add(new Be(1)).iushrn(2);return this.pow(e,t)}const n=this.m.subn(1);let r=0;for(;!n.isZero()&&0===n.andln(1);)r++,n.iushrn(1);this.assert(!n.isZero());const i=new Be(1).toRed(this),s=i.redNeg(),a=this.m.subn(1).iushrn(1),o=this.m.bitLength(),c=new Be(2*o*o).toRed(this);for(;0!==this.pow(c,a).cmp(s);)c.redIAdd(s);let d=this.pow(c,n),f=this.pow(e,n.addn(1).iushrn(1)),h=this.pow(e,n),u=r;for(;0!==h.cmp(i);){let e=h,t=0;for(;0!==e.cmp(i);)e=e.redSqr(),t++;this.assert(t<u);const n=this.pow(d,new Be(1).iushln(u-t-1));f=f.redMul(n),d=n.redSqr(),h=h.redMul(d),u=t}return f}invm(e){const t=e._invmp(this.m);return 0!==t.negative?(t.negative=0,this.imod(t).redNeg()):this.imod(t)}pow(e,t){if(this.verify1(e),t.isZero())return new Be(1).toRed(this);let n=new Be(1).toRed(this);const r=e.clone();for(let e=t.bitLength()-1;e>=0;e--)n=this.sqr(n),t.testn(e)&&(n=this.mul(n,r));return n}convertTo(e){const t=e.umod(this.m);return t===e?t.clone():t}convertFrom(e){const t=e.clone();return t.red=null,t}}class br extends lr{shift;r;r2;rinv;minv;constructor(e){super(e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new Be(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}convertTo(e){return this.imod(e.ushln(this.shift))}convertFrom(e){const t=this.imod(e.mul(this.rinv));return t.red=null,t}imul(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;const n=e.imul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=n.isub(r).iushrn(this.shift);let s=i;return i.cmp(this.m)>=0?s=i.isub(this.m):i.cmpn(0)<0&&(s=i.iadd(this.m)),s.forceRed(this)}mul(e,t){if(e.isZero()||t.isZero())return new Be(0).forceRed(this);const n=e.mul(t),r=n.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=n.isub(r).iushrn(this.shift);let s=i;return i.cmp(this.m)>=0?s=i.isub(this.m):i.cmpn(0)<0&&(s=i.iadd(this.m)),s.forceRed(this)}invm(e){return this.imod(e._invmp(this.m).mul(this.r2)).forceRed(this)}}let pr;function gr(e,t){const n=e.andln(3)+t&3;return 3===n?-1:n}function yr(e,t,n,r){if(!(1&n))return 0;const i=e.andln(7)+t&7;return 3!==i&&5!==i||2!==r?n:-n}function mr(e,t){return 2*e===t+1?1-e:e}class wr{p;red;redN;zero;one;two;g;n;a;b;tinv;zeroA;threeA;endo;_endoWnafT1;_endoWnafT2;_wnafT1;_wnafT2;_wnafT3;_wnafT4;_bitLength;static assert(e,t="Elliptic curve assertion failed"){if(!e)throw new Error(t)}getNAF(e,t,n){const r=Array.from({length:Math.max(e.bitLength(),n)+1},()=>0);r.fill(0);const i=1<<t+1,s=e.clone();for(let e=0;e<r.length;e++){let t;const n=s.andln(i-1);s.isOdd()?(t=n>(i>>1)-1?(i>>1)-n:n,s.isubn(t)):t=0,r[e]=t,s.iushrn(1)}return r}getJSF(e,t){const n=[[],[]];e=e.clone(),t=t.clone();let r=0,i=0;for(;e.cmpn(-r)>0||t.cmpn(-i)>0;){const s=gr(e,r),a=gr(t,i),o=yr(e,r,s,a);n[0].push(o);const c=yr(t,i,a,s);n[1].push(c),r=mr(r,o),i=mr(i,c),e.iushrn(1),t.iushrn(1)}return n}static cachedProperty(e,t,n){const r="_"+t;e.prototype[t]=function(){return void 0===this[r]&&(this[r]=n.call(this)),this[r]}}static parseBytes(e){return"string"==typeof e?gn(e,"hex"):e}static intFromLE(e){return new Be(e,"hex","le")}constructor(){if(void 0!==pr)return pr;pr=this;const e={prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",{doubles:{step:4,points:[["e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a","f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821"],["8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508","11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf"],["175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739","d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695"],["363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640","4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9"],["8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c","4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36"],["723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda","96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f"],["eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa","5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999"],["100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0","cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09"],["e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d","9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d"],["feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d","e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088"],["da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1","9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d"],["53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0","5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8"],["8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047","10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a"],["385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862","283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453"],["6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7","7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160"],["3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd","56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0"],["85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83","7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6"],["948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a","53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589"],["6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8","bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17"],["e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d","4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda"],["e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725","7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd"],["213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754","4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2"],["4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c","17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6"],["fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6","6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f"],["76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39","c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01"],["c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891","893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3"],["d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b","febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f"],["b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03","2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7"],["e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d","eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78"],["a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070","7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1"],["90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4","e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150"],["8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da","662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82"],["e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11","1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc"],["8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e","efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b"],["e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41","2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51"],["b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef","67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45"],["d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8","db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120"],["324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d","648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84"],["4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96","35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d"],["9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd","ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d"],["6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5","9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8"],["a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266","40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8"],["7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71","34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac"],["928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac","c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f"],["85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751","1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962"],["ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e","493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907"],["827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241","c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec"],["eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3","be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d"],["e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f","4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414"],["1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19","aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd"],["146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be","b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0"],["fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9","6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811"],["da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2","8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1"],["a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13","7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c"],["174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c","ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73"],["959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba","2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd"],["d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151","e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405"],["64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073","d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589"],["8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458","38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e"],["13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b","69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27"],["bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366","d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1"],["8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa","40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482"],["8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0","620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945"],["dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787","7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573"],["f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e","ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82"]]},naf:{wnd:7,points:[["f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672"],["2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4","d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6"],["5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc","6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da"],["acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe","cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37"],["774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b"],["f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8","ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81"],["d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e","581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58"],["defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34","4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77"],["2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c","85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a"],["352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5","321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c"],["2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f","2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67"],["9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714","73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402"],["daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729","a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55"],["c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db","2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482"],["6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4","e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82"],["1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5","b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396"],["605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479","2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49"],["62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d","80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf"],["80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f","1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a"],["7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb","d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7"],["d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9","eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933"],["49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963","758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a"],["77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74","958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6"],["f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530","e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37"],["463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b","5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e"],["f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247","cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6"],["caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1","cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476"],["2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120","4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40"],["7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435","91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61"],["754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18","673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683"],["e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8","59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5"],["186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb","3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b"],["df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f","55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417"],["5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143","efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868"],["290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba","e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a"],["af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45","f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6"],["766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a","744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996"],["59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e","c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e"],["f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8","e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d"],["7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c","30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2"],["948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519","e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e"],["7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab","100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437"],["3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca","ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311"],["d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf","8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4"],["1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610","68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575"],["733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4","f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d"],["15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c","d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d"],["a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940","edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629"],["e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980","a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06"],["311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3","66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374"],["34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf","9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee"],["f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63","4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1"],["d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448","fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b"],["32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf","5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661"],["7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5","8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6"],["ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6","8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e"],["16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5","5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d"],["eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99","f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc"],["78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51","f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4"],["494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5","42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c"],["a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5","204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b"],["c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997","4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913"],["841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881","73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154"],["5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5","39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865"],["36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66","d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc"],["336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726","ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224"],["8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede","6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e"],["1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94","60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6"],["85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31","3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511"],["29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51","b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b"],["a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252","ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2"],["4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5","cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c"],["d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b","6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3"],["ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4","322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d"],["af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f","6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700"],["e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889","2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4"],["591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246","b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196"],["11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984","998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4"],["3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a","b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257"],["cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030","bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13"],["c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197","6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096"],["c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593","c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38"],["a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef","21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f"],["347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38","60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448"],["da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a","49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a"],["c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111","5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4"],["4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502","7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437"],["3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea","be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7"],["cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26","8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d"],["b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986","39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a"],["d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e","62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54"],["48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4","25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77"],["dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda","ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517"],["6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859","cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10"],["e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f","f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125"],["eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c","6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e"],["13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942","fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1"],["ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a","1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2"],["b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80","5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423"],["ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d","438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8"],["8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1","cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758"],["52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63","c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375"],["e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352","6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d"],["7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193","ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec"],["5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00","9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0"],["32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58","ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c"],["e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7","d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4"],["8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8","c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f"],["4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e","67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649"],["3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d","cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826"],["674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b","299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5"],["d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f","f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87"],["30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6","462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b"],["be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297","62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc"],["93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a","7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c"],["b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c","ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f"],["d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52","4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a"],["d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb","bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46"],["463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065","bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f"],["7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917","603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03"],["74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9","cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08"],["30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3","553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8"],["9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57","712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373"],["176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66","ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3"],["75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8","9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8"],["809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721","9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1"],["1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180","4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9"]]}}]};this.p=new Be(e.p,16),this.red=new lr(e.prime),this.zero=new Be(0).toRed(this.red),this.one=new Be(1).toRed(this.red),this.two=new Be(2).toRed(this.red),this.n=new Be(e.n,16),this.g=Vr.fromJSON(e.g,e.gRed),this._wnafT1=Array.from({length:4},()=>{}),this._wnafT2=Array.from({length:4},()=>{}),this._wnafT3=Array.from({length:4},()=>{}),this._wnafT4=Array.from({length:4},()=>{}),this._bitLength=this.n.bitLength(),this.redN=this.n.toRed(this.red),this.a=new Be(e.a,16).toRed(this.red),this.b=new Be(e.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=0===this.a.fromRed().cmpn(0),this.threeA=0===this.a.fromRed().sub(this.p).cmpn(-3),this.endo=this._getEndomorphism(e),this._endoWnafT1=Array.from({length:4},()=>{}),this._endoWnafT2=Array.from({length:4},()=>{})}_getEndomorphism(e){if(!this.zeroA||1!==this.p.modrn(3))return;const t=this._resolveEndomorphismBeta(e),n=this._resolveEndomorphismLambda(e,t);return{beta:t,lambda:n,basis:this._resolveEndomorphismBasis(e,n)}}_resolveEndomorphismBeta(e){if(void 0!==e.beta)return new Be(e.beta,16).toRed(this.red);const t=this._getEndoRoots(this.p);if(null==t)throw new Error("Failed to get endomorphism roots for beta.");return(t[0].cmp(t[1])<0?t[0]:t[1]).toRed(this.red)}_endomorphismLambdaMatches(e,t,n=!1){if(null==this.g)throw new Error("Curve generator point (g) is not defined.");const r=this.g.mul(e)?.x,i=null==this.g.x?void 0:this.g.x.redMul(t);if(null==r||null==i){if(n)throw new Error("Lambda computation failed: g.mul(lambda).x or g.x.redMul(beta) is undefined.");return!1}return 0===r.cmp(i)}_resolveEndomorphismLambda(e,t){if(void 0!==e.lambda)return new Be(e.lambda,16);const n=this._getEndoRoots(this.n);if(null==n)throw new Error("Failed to get endomorphism roots for lambda.");return this._endomorphismLambdaMatches(n[0],t)?n[0]:(wr.assert(this._endomorphismLambdaMatches(n[1],t,!0),"Lambda selection does not match computed beta."),n[1])}_resolveEndomorphismBasis(e,t){return"object"!=typeof e.basis||null===e.basis?this._getEndoBasis(t):e.basis.map(e=>({a:new Be(e.a,16),b:new Be(e.b,16)}))}_getEndoRoots(e){const t=e===this.p?this.red:new br(e),n=new Be(2).toRed(t).redInvm(),r=n.redNeg(),i=new Be(3).toRed(t).redNeg().redSqrt().redMul(n);return[r.redAdd(i).fromRed(),r.redSub(i).fromRed()]}_getEndoBasis(e){const t=this.n.ushrn(Math.floor(this.n.bitLength()/2));let n,r,i,s,a,o,c=e,d=this.n.clone(),f=new Be(1),h=new Be(0),u=new Be(0),l=new Be(1),b=new Be(0),p=0,g=new Be(0),y=new Be(0);for(;0!==c.cmpn(0);){const e=d.div(c);g=d.sub(e.mul(c)),y=u.sub(e.mul(f));const a=l.sub(e.mul(h));if(void 0===i&&g.cmp(t)<0)n=b.neg(),r=f,i=g.neg(),s=y;else if(void 0!==i&&2===++p)break;b=g,d=c,c=g,u=f,f=y,l=h,h=a}if(void 0===n||void 0===r||void 0===i||void 0===s)throw new Error("Failed to compute Endo Basis values");a=g.neg(),o=y;const m=i.sqr().add(s.sqr());return a.sqr().add(o.sqr()).cmp(m)>=0&&(a=n,o=r),0!==i.negative&&(i=i.neg(),s=s.neg()),0!==a.negative&&(a=a.neg(),o=o.neg()),[{a:i,b:s},{a,b:o}]}_endoSplit(e){if(null==this.endo)throw new Error("Endomorphism is not defined.");const t=this.endo.basis,n=t[0],r=t[1],i=r.b.mul(e).divRound(this.n),s=n.b.neg().mul(e).divRound(this.n),a=i.mul(n.a),o=s.mul(r.a),c=i.mul(n.b),d=s.mul(r.b);return{k1:e.sub(a).sub(o),k2:c.add(d).neg()}}validate(e){if(e.inf)return!0;const t=e.x,n=e.y;if(null===t||null===n)throw new Error("Point coordinates cannot be null");const r=this.a.redMul(t),i=t.redSqr().redMul(t).redIAdd(r).redIAdd(this.b);return 0===n.redSqr().redISub(i).cmpn(0)}}class vr{curve;type;precomputed;constructor(e){this.curve=new wr,this.type=e,this.precomputed=null}}class _r extends vr{x;y;z;zOne;constructor(e,t,n){super("jacobian"),null===e&&null===t&&null===n?(this.x=this.curve.one,this.y=this.curve.one,this.z=new Be(0)):(Be.isBN(e)||(e=new Be(e,16)),this.x=e,Be.isBN(t)||(t=new Be(t,16)),this.y=t,Be.isBN(n)||(n=new Be(n,16)),this.z=n),null==this.x.red&&(this.x=this.x.toRed(this.curve.red)),null==this.y.red&&(this.y=this.y.toRed(this.curve.red)),null==this.z.red&&(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.isInfinity()&&(this.x=this.curve.one,this.y=this.curve.one,this.z=new Be(0).toRed(this.curve.red),this.zOne=!1)}toP(){if(this.isInfinity())return new Vr(null,null);const e=this.z.redInvm(),t=e.redSqr(),n=this.x.redMul(t),r=this.y.redMul(t).redMul(e);return new Vr(n,r)}neg(){return new _r(this.x,this.y.redNeg(),this.z)}add(e){if(this.isInfinity())return e;if(e.isInfinity())return this;const t=e.z.redSqr(),n=this.z.redSqr(),r=this.x.redMul(t),i=e.x.redMul(n),s=this.y.redMul(t.redMul(e.z)),a=e.y.redMul(n.redMul(this.z)),o=r.redSub(i),c=s.redSub(a);if(0===o.cmpn(0))return 0===c.cmpn(0)?this.dbl():new _r(null,null,null);const d=o.redSqr(),f=d.redMul(o),h=r.redMul(d),u=c.redSqr().redIAdd(f).redISub(h).redISub(h),l=c.redMul(h.redISub(u)).redISub(s.redMul(f)),b=this.z.redMul(e.z).redMul(o);return new _r(u,l,b)}mixedAdd(e){if(this.isInfinity())return e.toJ();if(e.isInfinity())return this;if(null===e.x||null===e.y)throw new Error("Point coordinates cannot be null");const t=this.z.redSqr(),n=this.x,r=e.x.redMul(t),i=this.y,s=e.y.redMul(t).redMul(this.z),a=n.redSub(r),o=i.redSub(s);if(0===a.cmpn(0))return 0===o.cmpn(0)?this.dbl():new _r(null,null,null);const c=a.redSqr(),d=c.redMul(a),f=n.redMul(c),h=o.redSqr().redIAdd(d).redISub(f).redISub(f),u=o.redMul(f.redISub(h)).redISub(i.redMul(d)),l=this.z.redMul(a);return new _r(h,u,l)}dblp(e){if(0===e)return this;if(this.isInfinity())return this;if(void 0===e)return this.dbl();let t=this;for(let n=0;n<e;n++)t=t.dbl();return t}dbl(){if(this.isInfinity())return this;let e,t,n;if(this.zOne){const r=this.x.redSqr(),i=this.y.redSqr(),s=i.redSqr();let a=this.x.redAdd(i).redSqr().redISub(r).redISub(s);a=a.redIAdd(a);const o=r.redAdd(r).redIAdd(r),c=o.redSqr().redISub(a).redISub(a);let d=s.redIAdd(s);d=d.redIAdd(d),d=d.redIAdd(d),e=c,t=o.redMul(a.redISub(c)).redISub(d),n=this.y.redAdd(this.y)}else{const r=this.x.redSqr(),i=this.y.redSqr(),s=i.redSqr();let a=this.x.redAdd(i).redSqr().redISub(r).redISub(s);a=a.redIAdd(a);const o=r.redAdd(r).redIAdd(r),c=o.redSqr();let d=s.redIAdd(s);d=d.redIAdd(d),d=d.redIAdd(d),e=c.redISub(a).redISub(a),t=o.redMul(a.redISub(e)).redISub(d),n=this.y.redMul(this.z),n=n.redIAdd(n)}return new _r(e,t,n)}eq(e){if("affine"===e.type)return this.eq(e.toJ());if(this===e)return!0;if(this.isInfinity()&&e.isInfinity())return!0;if(this.isInfinity()!==e.isInfinity())return!1;const t=this.z.redSqr(),n=e.z.redSqr();if(0!==this.x.redMul(n).redISub(e.x.redMul(t)).cmpn(0))return!1;const r=t.redMul(this.z),i=n.redMul(e.z);return 0===this.y.redMul(i).redISub(e.y.redMul(r)).cmpn(0)}eqXToP(e){const t=this.z.redSqr(),n=e.toRed(this.curve?.red).redMul(t);if(0===this.x.cmp(n))return!0;const r=e.clone();if(null==this.curve?.redN)throw new Error("Curve or redN is not initialized.");const i=this.curve.redN.redMul(t);for(;r.cmp(this.curve.p)<0;){if(r.iadd(this.curve.n),r.cmp(this.curve.p)>=0)return!1;if(n.redIAdd(i),0===this.x.cmp(n))return!0}return!1}inspect(){return this.isInfinity()?"<EC JPoint Infinity>":"<EC JPoint x: "+this.x.toString(16,2)+" y: "+this.y.toString(16,2)+" z: "+this.z.toString(16,2)+">"}isInfinity(){return 0===this.z.cmpn(0)}}function Sr(e,t,n){const r=-e,i=(t.X^n.X)&r,s=(t.Y^n.Y)&r,a=(t.Z^n.Z)&r;t.X^=i,n.X^=i,t.Y^=s,n.Y^=s,t.Z^=a,n.Z^=a}const Ir=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,Ar=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,Er=(1n<<256n)-1n;function xr(e){let t=e>>256n;return t=(e=(e&Er)+(t<<32n)+977n*t)>>256n,(e=(e&Er)+(t<<32n)+977n*t)>=Ir&&(e-=Ir),e}const kr=e=>xr((e%Ir+Ir)%Ir),Nr=(e,t)=>e>=t?e-t:Ir-(t-e),Rr=(e,t)=>xr(e*t),Br=(e,t)=>xr(e+t),Cr=e=>{let t=1n,n=0n,r=kr(e),i=Ir;for(;r>1n;){const e=i/r;[t,n]=[n-t*e,t],[r,i]=[i-r*e,r]}return kr(t)},Tr=Ir+1n>>2n,Lr=BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Mr=BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"),Kr=new Map,Dr=e=>{const{X:t,Y:n,Z:r}=e;if(0n===n)return{X:0n,Y:1n,Z:0n};const i=Rr(n,n),s=Rr(4n,Rr(t,i)),a=Rr(3n,Rr(t,t)),o=Nr(Rr(a,a),Rr(2n,s));return{X:o,Y:Nr(Rr(a,Nr(s,o)),Rr(8n,Rr(i,i))),Z:Rr(2n,Rr(n,r))}},Pr=(e,t)=>{if(0n===e.Z)return t;if(0n===t.Z)return e;const n=Rr(e.Z,e.Z),r=Rr(t.Z,t.Z),i=Rr(e.X,r),s=Rr(t.X,n),a=Rr(e.Y,Rr(r,t.Z)),o=Rr(t.Y,Rr(n,e.Z)),c=Nr(s,i),d=Nr(o,a);if(0n===c)return 0n===d?Dr(e):{X:0n,Y:1n,Z:0n};const f=Rr(c,c),h=Rr(c,f),u=Rr(i,f),l=Nr(Nr(Rr(d,d),h),Rr(2n,u));return{X:l,Y:Nr(Rr(d,Nr(u,l)),Rr(a,h)),Z:Rr(c,Rr(e.Z,t.Z))}},Ur=e=>0n===e.Z?e:{X:e.X,Y:Ir-e.Y,Z:e.Z},Or=(e,t,n=5)=>{const r=((e,t)=>{const n=`${e}:${t.x.toString(16)}:${t.y.toString(16)}`,r=Kr.get(n);if(void 0!==r)return r;const i=Array.from({length:1<<e-1},()=>({X:0n,Y:1n,Z:0n})),s={X:t.x,Y:t.y,Z:1n};i[0]=s;const a=Dr(s);for(let e=1;e<i.length;e++)i[e]=Pr(i[e-1],a);return Kr.set(n,i),i})(n,t),i=((e,t)=>{const n=[],r=1n<<BigInt(t),i=r>>1n;let s=e;for(;s>0n;){if(0n==(1n&s))n.push(0);else{let e=s&r-1n;e>i&&(e-=r),n.push(Number(e)),s-=e}s>>=1n}return n})(e,n);let s={X:0n,Y:1n,Z:0n};for(let e=i.length-1;e>=0;e--){s=Dr(s);const t=i[e];if(0!==t){const e=Math.abs(t)>>1,n=t>0?r[e]:Ur(r[e]);s=Pr(s,n)}}return s},qr=e=>{let t=e%Ar;return t<0n&&(t+=Ar),t},Fr=(e,t)=>qr(e*t),zr=e=>{let t=1n,n=0n,r=qr(e),i=Ar;for(;r>1n;){const e=i/r;[t,n]=[n-t*e,t],[r,i]=[i-r*e,r]}return qr(t)};class Vr extends vr{x;y;inf;static _assertOnCurve(e){if(!e.validate())throw new Error("Invalid point");return e}static fromDER(e){if((4===e[0]||6===e[0]||7===e[0])&&e.length-1==64){if(6===e[0]){if(e.at(-1)%2!=0)throw new Error("Point string value is wrong length")}else if(7===e[0]&&e.at(-1)%2!=1)throw new Error("Point string value is wrong length");const t=new Vr(e.slice(1,33),e.slice(33,65));return Vr._assertOnCurve(t)}if((2===e[0]||3===e[0])&&e.length-1==32)return Vr._assertOnCurve(Vr.fromX(e.slice(1,33),3===e[0]));throw new Error("Unknown point format")}static fromString(e){const t=gn(e,"hex");return Vr._assertOnCurve(Vr.fromDER(t))}static fromX(e,t){let n=(e=>Be.isBN(e)?BigInt("0x"+e.toString(16)):"string"==typeof e?BigInt("0x"+e):Array.isArray(e)?BigInt("0x"+pn(e)):BigInt(e))(e);n=kr(n);var r;const i=(e=>{const t=((e,t)=>{let n=1n;for(e=kr(e);t>0n;)0n!=(1n&t)&&(n=Rr(n,e)),e=Rr(e,e),t>>=1n;return n})(e,Tr);return Rr(t,t)!==kr(e)?null:t})(Br(Rr(Rr(r=n,r),n),7n));if(null===i)throw new Error("Invalid point");let s=i;(1n&s)!=(t?1n:0n)&&(s=Nr(Ir,s));const a=new Be(n.toString(16),16),o=new Be(s.toString(16),16);return Vr._assertOnCurve(new Vr(a,o))}static fromJSON(e,t){"string"==typeof e&&(e=JSON.parse(e));let n=new Vr(e[0],e[1],t);if(n=Vr._assertOnCurve(n),"object"!=typeof e[2]||null===e[2])return n;const r=e[2],i=e=>{const n=new Vr(e[0],e[1],t);return Vr._assertOnCurve(n)};return n.precomputed={beta:null,doubles:"object"==typeof r.doubles&&null!==r.doubles?{step:r.doubles.step,points:[n].concat(r.doubles.points.map(i))}:void 0,naf:"object"==typeof r.naf&&null!==r.naf?{wnd:r.naf.wnd,points:[n].concat(r.naf.points.map(i))}:void 0},n}constructor(e,t,n=!0){super("affine"),this.precomputed=null,null===e&&null===t?(this.x=null,this.y=null,this.inf=!0):(Be.isBN(e)||(e=new Be(e,16)),this.x=e,Be.isBN(t)||(t=new Be(t,16)),this.y=t,n&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),null===this.x.red&&(this.x=this.x.toRed(this.curve.red)),null===this.y.red&&(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}validate(){if(this.inf||null==this.x||null==this.y)return!1;try{const e=BigInt("0x"+this.x.fromRed().toString(16)),t=BigInt("0x"+this.y.fromRed().toString(16));return Rr(t,t)===Br(Rr(Rr(e,e),e),7n)}catch{return!1}}encode(e=!0,t){if(this.inf)return"hex"===t?"00":[0];const n=this.curve.p.byteLength(),r=this.getX().toArray("be",n);let i;return i=e?[this.getY().isEven()?2:3].concat(r):[4].concat(r,this.getY().toArray("be",n)),"hex"===t?pn(i):i}toString(){return this.encode(!0,"hex")}toJSON(){return null==this.precomputed?[this.x,this.y]:[this.x,this.y,"object"==typeof this.precomputed&&null!==this.precomputed?{doubles:null==this.precomputed.doubles?void 0:{step:this.precomputed.doubles.step,points:this.precomputed.doubles.points.slice(1)},naf:null==this.precomputed.naf?void 0:{wnd:this.precomputed.naf.wnd,points:this.precomputed.naf.points.slice(1)}}:void 0]}inspect(){return this.isInfinity()?"<EC Point Infinity>":"<EC Point x: "+(this.x?.fromRed()?.toString(16,2)??"undefined")+" y: "+(this.y?.fromRed()?.toString(16,2)??"undefined")+">"}isInfinity(){return this.inf}add(e){if(this.inf)return e;if(e.inf)return this;if(this.eq(e))return this.dbl();if(this.neg().eq(e))return new Vr(null,null);if(0===this.x?.cmp(e.x??new Be(0)))return new Vr(null,null);const t={X:BigInt("0x"+this.x.fromRed().toString(16)),Y:BigInt("0x"+this.y.fromRed().toString(16)),Z:1n},n={X:BigInt("0x"+e.x.fromRed().toString(16)),Y:BigInt("0x"+e.y.fromRed().toString(16)),Z:1n},r=Pr(t,n);if(0n===r.Z)return new Vr(null,null);const i=Cr(r.Z),s=Rr(i,i),a=Rr(r.X,s),o=Rr(r.Y,Rr(s,i));return new Vr(a.toString(16),o.toString(16))}dbl(){if(this.inf)return this;if(null===this.x||null===this.y)throw new Error("Point coordinates cannot be null");const e=BigInt("0x"+this.x.fromRed().toString(16)),t=BigInt("0x"+this.y.fromRed().toString(16));if(0n===t)return new Vr(null,null);const n=Dr({X:e,Y:t,Z:1n}),r=Cr(n.Z),i=Rr(r,r),s=Rr(n.X,i),a=Rr(n.Y,Rr(i,r));return new Vr(s.toString(16),a.toString(16))}getX(){return(this.x??new Be(0)).fromRed()}getY(){return(this.y??new Be(0)).fromRed()}mul(e){if(Be.isBN(e)||(e=new Be(e,16)),this.inf)return this;const t=e.isNeg(),n=t?e.neg():e;let r,i,s=BigInt("0x"+n.toString(16));if(s=kr(s),0n===s)return new Vr(null,null);if(0n===s)return new Vr(null,null);if(null===this.x||null===this.y)throw new Error("Point coordinates cannot be null");this===this.curve.g?(r=Lr,i=Mr):(r=BigInt("0x"+this.x.fromRed().toString(16)),i=BigInt("0x"+this.y.fromRed().toString(16)));const a=Or(s,{x:r,y:i});if(0n===a.Z)return new Vr(null,null);const o=Cr(a.Z),c=Rr(o,o),d=Rr(a.X,c),f=Rr(a.Y,Rr(c,o)),h=new Be(d.toString(16),16),u=new Be(f.toString(16),16),l=new Vr(h,u);return t?l.neg():l}mulCT(e){if(Be.isBN(e)||(e=new Be(e,16)),this.inf)return new Vr(null,null);const t=e.isNeg(),n=t?e.neg():e;let r=BigInt("0x"+n.toString(16));if(r=kr(r),0n===r)return new Vr(null,null);let i={X:0n,Y:1n,Z:0n},s={X:this===this.curve.g?Lr:BigInt("0x"+this.getX().toString(16)),Y:this===this.curve.g?Mr:BigInt("0x"+this.getY().toString(16)),Z:1n};const a=r.toString(2);for(const e of a){const t="1"===e?1n:0n;Sr(t,i,s),s=Pr(i,s),i=Dr(i),Sr(t,i,s)}if(0n===i.Z)return new Vr(null,null);const o=Cr(i.Z),c=Rr(o,o),d=Rr(i.X,c),f=Rr(i.Y,Rr(c,o)),h=new Vr(d.toString(16),f.toString(16));return t?h.neg():h}mulAdd(e,t,n){const r=[this,t],i=[e,n];return this._endoWnafMulAdd(r,i)}jmulAdd(e,t,n){const r=[this,t],i=[e,n];return this._endoWnafMulAdd(r,i,!0)}eq(e){return this===e||this.inf===e.inf&&(this.inf||0===(this.x??new Be(0)).cmp(e.x??new Be(0))&&0===(this.y??new Be(0)).cmp(e.y??new Be(0)))}neg(e){if(this.inf)return this;const t=new Vr(this.x,(this.y??new Be(0)).redNeg());if(!0===e&&null!=this.precomputed){const e=this.precomputed,n=e=>e.neg();t.precomputed={naf:null==e.naf?void 0:{wnd:e.naf.wnd,points:e.naf.points.map(n)},doubles:null==e.doubles?void 0:{step:e.doubles.step,points:e.doubles.points.map(e=>e.neg())},beta:void 0}}return t}dblp(e){let t;for(let n=0;n<e;n++)t=(t??this).dbl();return t??this}toJ(){return this.inf?new _r(null,null,null):new _r(this.x,this.y,this.curve.one)}_getBeta(){if("object"!=typeof this.curve.endo)return;const e=this.precomputed;if("object"==typeof e&&null!==e&&"object"==typeof e.beta&&null!==e.beta)return e.beta;const t=new Vr((this.x??new Be(0)).redMul(this.curve.endo.beta),this.y);if(null!=e){const n=this.curve,r=e=>{const t=e;if(null===t.x)throw new Error("p.x is null");if(void 0===n.endo||null===n.endo)throw new Error("curve.endo is undefined");return new Vr(t.x.redMul(n.endo.beta),t.y)};e.beta=t,t.precomputed={beta:null,naf:null==e.naf?void 0:{wnd:e.naf.wnd,points:e.naf.points.map(r)},doubles:null==e.doubles?void 0:{step:e.doubles.step,points:e.doubles.points.map(r)}}}return t}_fixedNafMul(e){if("object"!=typeof this.precomputed||null===this.precomputed)throw new Error("_fixedNafMul requires precomputed values for the point");const t=this._getDoubles(),n=this.curve.getNAF(e,1,this.curve._bitLength);let r=(1<<t.step+1)-(t.step%2==0?2:1);r/=3;const i=[];for(let e=0;e<n.length;e+=t.step){let r=0;for(let i=e+t.step-1;i>=e;i--)r=(r<<1)+n[i];i.push(r)}let s=new _r(null,null,null),a=new _r(null,null,null);for(let e=r;e>0;e--){for(let n=0;n<i.length;n++){const r=i[n];r===e?a=a.mixedAdd(t.points[n]):r===-e&&(a=a.mixedAdd(t.points[n].neg()))}s=s.add(a)}return s.toP()}_prepareWnafWindows(e,t,n,r,i){for(let s=0;s<n;s++){const n=t[s]._getNAFPoints(e);r[s]=n.wnd,i[s]=n.points}}_combineWnafPair(e,t,n){const{points:r,coeffs:i,wndWidth:s,wnd:a,naf:o,currentMax:c}=n;if(1!==s[e]||1!==s[t])return o[e]=this.curve.getNAF(i[e],s[e],this.curve._bitLength),o[t]=this.curve.getNAF(i[t],s[t],this.curve._bitLength),Math.max(c,o[e].length,o[t].length);const d=[r[e],null,null,r[t]],f=r[e].y??new Be(0),h=r[t].y??new Be(0);0===f.cmp(h)?(d[1]=r[e].add(r[t]),d[2]=r[e].toJ().mixedAdd(r[t].neg())):0===f.cmp(h.redNeg())?(d[1]=r[e].toJ().mixedAdd(r[t]),d[2]=r[e].add(r[t].neg())):(d[1]=r[e].toJ().mixedAdd(r[t]),d[2]=r[e].toJ().mixedAdd(r[t].neg()));const u=[-3,-1,-5,-7,0,7,5,1,3],l=this.curve.getJSF(i[e],i[t]),b=Math.max(c,l[0].length);o[e]=Array.from({length:b}),o[t]=Array.from({length:b});for(let n=0;n<b;n++){const r=Math.trunc(l[0][n]),i=Math.trunc(l[1][n]);o[e][n]=u[3*(r+1)+(i+1)],o[t][n]=0,a[e]=d}return b}_prepareWnafRepresentations(e,t,n,r,i,s){let a=0;for(let o=n-1;o>=1;o-=2)a=this._combineWnafPair(o-1,o,{points:e,coeffs:t,wndWidth:r,wnd:i,naf:s,currentMax:a});return a}_collectWnafStep(e,t,n,r){let i=e,s=0;for(;i>=0;){let e=!0;for(let s=0;s<t;s++)r[s]=new Be("number"==typeof n[s][i]?n[s][i]:0),r[s].isZero()||(e=!1);if(!e)break;s++,i--}return i>=0&&s++,{index:i,doubles:s}}_addWnafStep(e,t,n,r){const i=new Be(1),s=new Be(2);let a=e;for(let e=0;e<t;e++){const t=n[e];if(0===t.cmpn(0))continue;const o=t.isNeg()?r[e][t.neg().sub(i).div(s).toNumber()].neg():r[e][t.sub(i).div(s).toNumber()];a="affine"===o.type?a.mixedAdd(o):a.add(o)}return a}_wnafMulAdd(e,t,n,r,i){const s=this.curve._wnafT1.length,a=Array.from({length:s}),o=Array.from({length:s},()=>[]),c=Array.from({length:s},()=>[]);this._prepareWnafWindows(e,t,r,a,o);const d=this._prepareWnafRepresentations(t,n,r,a,o,c);let f=new _r(null,null,null);const h=this.curve._wnafT4;let u=d;for(;u>=0;){const e=this._collectWnafStep(u,r,c,h);if(u=e.index,f=f.dblp(e.doubles),u<0)break;f=this._addWnafStep(f,r,h,o),u--}for(let e=0;e<r;e++)o[e]=[];return!0===i?f:f.toP()}_endoWnafMulAdd(e,t,n){const r=Array.from({length:2*e.length}),i=Array.from({length:2*e.length});let s;for(s=0;s<e.length;s++){const n=this.curve._endoSplit(t[s]);let a=e[s],o=a._getBeta()??new Vr(null,null);0!==n.k1.negative&&(n.k1.ineg(),a=a.neg(!0)),0!==n.k2.negative&&(n.k2.ineg(),o=o.neg(!0)),r[2*s]=a,r[2*s+1]=o,i[2*s]=n.k1,i[2*s+1]=n.k2}const a=this._wnafMulAdd(1,r,i,2*s,n);for(let e=0;e<2*s;e++)r[e]=null,i[e]=null;return a}_hasDoubles(e){if(null==this.precomputed)return!1;const t=this.precomputed.doubles;return"object"==typeof t&&t.points.length>=Math.ceil((e.bitLength()+1)/t.step)}_getDoubles(e,t){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.doubles&&null!==this.precomputed.doubles)return this.precomputed.doubles;const n=[this];let r;for(let i=0;i<(t??0);i+=e??1){for(let t=0;t<(e??1);t++)r=(r??this).dbl();n.push(r)}return{step:e??1,points:n}}_getNAFPoints(e){if("object"==typeof this.precomputed&&null!==this.precomputed&&"object"==typeof this.precomputed.naf&&null!==this.precomputed.naf)return this.precomputed.naf;const t=[this],n=(1<<e)-1,r=1===n?null:this.dbl();for(let e=1;e<n;e++)null!==r&&(t[e]=t[e-1].add(r));return{wnd:e,points:t}}}class Hr{r;s;static fromDER(e,t){const n=(e,t)=>{const n=e[t.place++];if(128&n)throw new Error("Invalid DER entity length");return n};e=gn(e,t);const r=new class{place=0};if(48!==e[r.place++])throw new Error("Signature DER must start with 0x30");if(n(e,r)+r.place!==e.length)throw new Error("Signature DER invalid");if(2!==e[r.place++])throw new Error("Signature DER invalid");const i=n(e,r);let s=e.slice(r.place,i+r.place);if(r.place+=i,2!==e[r.place++])throw new Error("Signature DER invalid");const a=n(e,r);if(e.length!==a+r.place)throw new Error("Invalid R-length in signature DER");let o=e.slice(r.place,a+r.place);if(0===s[0]){if(!(128&s[1]))throw new Error("Invalid R-value in signature DER");s=s.slice(1)}if(0===o[0]){if(!(128&o[1]))throw new Error("Invalid S-value in signature DER");o=o.slice(1)}return new Hr(new Be(s),new Be(o))}static fromCompact(e,t){if(65!==(e=gn(e,t)).length)throw new Error("Invalid Compact Signature");const n=e[0];if(n<27||n>=35)throw new Error("Invalid Compact Byte");return new Hr(new Be(e.slice(1,33)),new Be(e.slice(33,65)))}constructor(e,t){this.r=e,this.s=t}verify(e,t,n){const r=new Be(_t(e,n),16);return ni(r,this,t)}toString(e){return this.toDER(e)}toDER(e){const t=(e,t)=>{if(!(t<128))throw new Error("len must be < 0x80");e.push(t)},n=e=>{let t=0;const n=e.length-1;for(;0===e[t]&&!(128&e[t+1])&&t<n;)t++;return 0===t?e:e.slice(t)};let r=this.r.toArray(),i=this.s.toArray();for(128&r[0]&&(r=[0].concat(r)),128&i[0]&&(i=[0].concat(i)),r=n(r),i=n(i);0===i[0]&&!(128&i[1]);)i=i.slice(1);let s=[2];t(s,r.length),s=s.concat(r),s.push(2),t(s,i.length);const a=s.concat(i);let o=[48];return t(o,a.length),o=o.concat(a),"hex"===e?pn(o):"base64"===e?An(o):o}toCompact(e,t,n){if(e<0||e>3)throw new Error("Invalid recovery param");if("boolean"!=typeof t)throw new TypeError("Invalid compressed param");let r=27+e;t&&(r+=4);let i=[r];return i=i.concat(this.r.toArray("be",32)),i=i.concat(this.s.toArray("be",32)),"hex"===n?pn(i):"base64"===n?An(i):i}RecoverPublicKey(e,t){const n=this.r,r=this.s,i=!!(1&e),s=e>>1,a=new wr,o=a.n,c=a.g,d=0===s?n:n.add(o),f=Vr.fromX(d,i);if(!f.mul(o).isInfinity())throw new Error("nR is not at infinity");const h=t.neg().umod(o),u=n.invm(o),l=u.mul(r).umod(o),b=u.mul(h).umod(o),p=c.mul(b).add(f.mul(l)),g=new ri(p);return g.validate(),g}CalculateRecoveryFactor(e,t){for(let n=0;n<4;n++){let r;try{r=this.RecoverPublicKey(n,t)}catch{continue}if(e.eq(r))return n}throw new Error("Unable to find valid recovery factor")}}class jr{K;V;constructor(e,t){const n=gn(e,"hex"),r=gn(t,"hex");if(32!==n.length)throw new Error("Entropy must be exactly 32 bytes (256 bits)");if(32!==r.length)throw new Error("Nonce must be exactly 32 bytes (256 bits)");const i=n.concat(r);this.K=Array.from({length:32}),this.V=Array.from({length:32});for(let e=0;e<32;e++)this.K[e]=0,this.V[e]=1;this.update(i)}hmac(){return new mt(this.K)}update(e){let t=this.hmac().update(this.V).update([0]);void 0!==e&&(t=t.update(e)),this.K=t.digest(),this.V=this.hmac().update(this.V).digest(),void 0!==e&&(this.K=this.hmac().update(this.V).update([1]).update(e).digest(),this.V=this.hmac().update(this.V).digest())}generate(e){let t=[];for(;t.length<e;)this.V=this.hmac().update(this.V).digest(),t=t.concat(this.V);const n=t.slice(0,e);return this.update(),pn(n)}}function Wr(e,t,n=new wr){const r=8*e.byteLength()-n.n.bitLength();return r>0&&e.iushrn(r),!0!==t&&e.cmp(n.n)>=0?e.sub(n.n):e}function $r(e){const t=e.toArray("be");let n=0n;for(const e of t)n=n<<8n|BigInt(e);return n}const Gr=new wr,Zr=Gr.n.byteLength(),Xr=Gr.n.subn(1),Yr=Ar>>1n;function Jr(e,t,n){let r;if(r="function"==typeof e?e(t):void 0!==e&&Be.isBN(e)?e:new Be(n.generate(Zr),16),null==r)throw new Error("k is undefined");return Wr(r,!0)}function Qr(e,t){if(e)throw new Error(t)}function ei(e,t,n,r,i){if(e.cmpn(1)<0||e.cmp(Xr)>0)return Qr(i,"Invalid fixed custom K value (must be >1 and <N-1)");const s=Gr.g.mulCT(e);if(s.isInfinity())return Qr(i,"Invalid fixed custom K value (k·G at infinity)");const a=qr(BigInt("0x"+s.getX().toString(16)));if(0n===a)return Qr(i,"Invalid fixed custom K value (r == 0)");const o=zr(BigInt("0x"+e.toString(16))),c=qr(t+Fr(a,n));let d=Fr(o,c);return 0n===d?Qr(i,"Invalid fixed custom K value (s == 0)"):(r&&d>Yr&&(d=Ar-d),new Hr(new Be(a.toString(16),16),new Be(d.toString(16),16)))}const ti=(e,t,n=!1,r)=>{const i=Gr.n.bitLength();if(e.bitLength()>i)throw new Error(`ECDSA message is too large: expected <= ${i} bits. Callers must hash messages before signing.`);const s=$r(e=Wr(e)),a=$r(t),o=t.toArray("be",Zr),c=e.toArray("be",Zr),d=new jr(o,c),f=Be.isBN(r);for(let e=0;;e++){const t=ei(Jr(r,e,d),s,a,n,f);if(null!=t)return t}},ni=(e,t,n)=>{const r=Gr.n.bitLength();if(e.bitLength()>r)return!1;const i=$r(e);if(null==n.x||null==n.y)throw new Error("Invalid public key: missing coordinates.");const s={x:$r(n.x),y:$r(n.y)},a={r:$r(t.r),s:$r(t.s)},{r:o,s:c}=a,d=i;if(o<=0n||o>=Ar||c<=0n||c>=Ar)return!1;const f=zr(c);if(0n===f)return!1;const h=Fr(d,f),u=Fr(o,f),l=Or(h,{x:Lr,y:Mr}),b=Or(u,s),p=Pr(l,b);if(0n===p.Z)return!1;const g=Cr(p.Z),y=Rr(g,g),m=Rr(p.X,y);return qr(m)===o};class ri extends Vr{static fromPrivateKey(e){const t=(new wr).g.mul(e);return new ri(t.x,t.y)}static fromString(e){const t=Vr.fromString(e);return new ri(t.x,t.y)}static fromDER(e){const t=Vr.fromDER(e);return new ri(t.x,t.y)}constructor(e,t=null,n=!0){if(e instanceof Vr)super(e.getX(),e.getY());else{if(null===t&&n&&"string"==typeof e&&(66===e.length||130===e.length))throw new Error('You are using the "new PublicKey()" constructor with a DER hex string. You need to use "PublicKey.fromString()" instead.');super(e,t,n)}}deriveSharedSecret(e){if(!this.validate())throw new Error("Public key not valid for ECDH secret derivation");return this.mulCT(e)}verify(e,t,n){const r=new Be(_t(e,n),16);return ni(r,t,this)}toDER(e){return"hex"===e?this.encode(!0,e):this.encode(!0)}toHash(e){const t=(()=>{const e=vt(this.encode(!0),void 0),t=function(e,t){return Xe("ripemd160",e,t)}(e);return null!=t?Array.from(t):(new yt).update(e).digest()})();return"hex"===e?pn(t):t}toAddress(e=[0]){if("string"==typeof e)if("testnet"===e||"test"===e)e=[111];else{if("mainnet"!==e&&"main"!==e)throw new Error(`Invalid prefix ${e}`);e=[0]}return Nn(this.toHash(),e)}deriveChild(e,t,n,r){let i;if("function"==typeof r){const t=r(e,this);void 0===t?(i=this.deriveSharedSecret(e),"function"==typeof n&&n(e,this,i)):i=t}else i=this.deriveSharedSecret(e);const s=gn(t,"utf8"),a=It(i.encode(!0),s),o=(new wr).g.mul(new Be(a)),c=this.add(o);return new ri(c.x,c.y)}static fromMsgHashAndCompactSignature(e,t,n){const r=gn(t,n);if(65!==r.length)throw new Error("Invalid Compact Signature");const i=r[0];if(i<27||i>=35)throw new Error("Invalid Compact Byte");let s=r[0]-27;return s>3&&(s-=4),new Hr(new Be(r.slice(1,33)),new Be(r.slice(33,65))).RecoverPublicKey(s,e)}}class ii{x;y;constructor(e,t){const n=(new wr).p;this.x=e.umod(n),this.y=t.umod(n)}toString(){return kn(this.x.toArray())+"."+kn(this.y.toArray())}static fromString(e){const[t,n]=e.split(".");return new ii(new Be(xn(t)),new Be(xn(n)))}}class si{points;threshold;constructor(e,t){this.points=e,this.threshold=t??e.length}static fromPrivateKey(e,t){const n=(new wr).p,r=[new ii(new Be(0),new Be(e.toArray()))];for(let e=1;e<t;e++){const e=new Be(Un(32)).umod(n),t=new Be(Un(32)).umod(n);r.push(new ii(e,t))}return new si(r)}valueAt(e){const t=(new wr).p;let n=new Be(0);for(let r=0;r<this.threshold;r++){let i=this.points[r].y;for(let n=0;n<this.threshold;n++)if(r!==n){const s=this.points[n].x,a=this.points[r].x,o=e.sub(s).umod(t),c=a.sub(s).umod(t).invm(t),d=o.mul(c).umod(t);i=i.mul(d).umod(t)}n=n.add(i).umod(t)}return n}}class ai{points;threshold;integrity;constructor(e,t,n){this.points=e,this.threshold=t,this.integrity=n}static fromBackupFormat(e){let t=0,n="";const r=e.map((e,r)=>{const i=e.split(".");if(4!==i.length)throw new Error("Invalid share format in share "+r.toString()+'. Expected format: "x.y.t.i" - received '+e);const[s,a,o,c]=i;if(void 0===o)throw new Error("Threshold not found in share "+r.toString());if(void 0===c)throw new Error("Integrity not found in share "+r.toString());const d=Number.parseInt(o,10);if(0!==r&&t!==d)throw new Error("Threshold mismatch in share "+r.toString());if(0!==r&&n!==c)throw new Error("Integrity mismatch in share "+r.toString());return t=d,n=c,ii.fromString([s,a].join("."))});return new ai(r,t,n)}toBackupFormat(){return this.points.map(e=>e.toString()+"."+this.threshold.toString()+"."+this.integrity)}}class oi extends Be{static fromRandom(){return new oi(Un(32))}static fromString(e,t="hex"){return new oi(super.fromString(e,t).toArray())}static fromHex(e){return new oi(super.fromHex(e,"big"))}static fromWif(e,t=1){const n=((e,t,n=1)=>{const r=xn(e);let i=r.slice(0,n),s=r.slice(n,-4),a=[...i,...s];return a=St(a),r.slice(-4).forEach((e,t)=>{if(e!==a[t])throw new Error("Invalid checksum")}),"hex"===t&&(i=pn(i),s=pn(s)),{prefix:i,data:s}})(e,void 0,t);if(33!==n.data.length)throw new Error("Invalid WIF length");if(1!==n.data[32])throw new Error("Invalid WIF padding");return new oi(n.data.slice(0,32))}constructor(e=0,t=10,n="be",r="apply"){if(e instanceof Be?(super(),e.copy(this)):super(e,t,n),"nocheck"!==r){const e=this.checkInField();if(!e.inField){if("error"===r)throw new Error("Input is out of field");Be.move(this,e.modN)}}}checkInField(){const e=new wr,t=this.mod(e.n);return{inField:0===this.cmp(t),modN:t}}isValid(){return this.checkInField().inField}sign(e,t,n=!0,r){const i=new Be(_t(e,t),16);return ti(i,this,n,r)}verify(e,t,n){const r=new Be(_t(e,n),16);return ni(r,t,this.toPublicKey())}toPublicKey(){const e=(new wr).g.mulCT(this);return new ri(e.x,e.y)}toWif(e=[128]){if(!this.isValid())throw new Error("Value is out of field");return Nn([...this.toArray("be",32),1],e)}toAddress(e=[0]){return this.toPublicKey().toAddress(e)}toHex(){return super.toHex(32)}toString(e="hex",t=64){return super.toString(e,t)}deriveSharedSecret(e){if(!e.validate())throw new Error("Public key not valid for ECDH secret derivation");return e.mulCT(this)}deriveChild(e,t,n,r){let i;if("function"==typeof r){const t=r(this,e);void 0===t?(i=this.deriveSharedSecret(e),"function"==typeof n&&n(this,e,i)):i=t}else i=this.deriveSharedSecret(e);const s=gn(t,"utf8"),a=It(i.encode(!0),s),o=new wr;return new oi(this.add(new Be(a)).mod(o.n).toArray())}toKeyShares(e,t){if("number"!=typeof e||"number"!=typeof t)throw new TypeError("threshold and totalShares must be numbers");if(e<2)throw new Error("threshold must be at least 2");if(t<2)throw new Error("totalShares must be at least 2");if(e>t)throw new Error("threshold should be less than or equal to totalShares");const n=si.fromPrivateKey(this,e),r=[],i=new Set,s=new wr,a=Un(64);for(let e=0;e<t;e++){let t,o=0;do{const n=[e,o,...Un(32)],r=At(a,n);if(t=new Be(r).umod(s.p),o++,o>5)throw new Error("Failed to generate unique x coordinate after 5 attempts")}while(t.isZero()||i.has(t.toString()));i.add(t.toString());const c=n.valueAt(t);r.push(new ii(t,c))}const o=this.toPublicKey().toHash("hex").slice(0,8);return new ai(r,e,o)}toBackupShares(e,t){return this.toKeyShares(e,t).toBackupFormat()}static fromBackupShares(e){return oi.fromKeyShares(ai.fromBackupFormat(e))}static fromKeyShares(e){const{points:t,threshold:n,integrity:r}=e;if(n<2)throw new Error("threshold must be at least 2");if(t.length<n)throw new Error(`At least ${n} shares are required to reconstruct the private key`);for(let e=0;e<n;e++)for(let r=e+1;r<n;r++)if(t[e].x.eq(t[r].x))throw new Error("Duplicate share detected, each must be unique.");const i=new si(t,n),s=new oi(i.valueAt(new Be(0)).toArray());if(s.toPublicKey().toHash("hex").slice(0,8)!==r)throw new Error("Integrity hash mismatch");return s}}function ci(e){return 32===e.length&&e.every(e=>Number.isInteger(e)&&e>=0&&e<=255)}function di(e,t,n){if(!(t instanceof Uint8Array))throw new TypeError(`${e} returned a non-byte result`);if(void 0!==n&&t.length!==n)throw new Error(`${e} returned ${t.length} bytes; expected ${n}`);return t}function fi(e){const t=globalThis.__bsvSdkAsyncCryptoBackendV1;if(void 0!==t){if(t.isReady())return t.supportsCrypto(e)?t:void 0;t.preload().catch(()=>{})}}class hi{cacheSharedSecret;retrieveCachedSharedSecret;rootKey;identityKey;anyone;constructor(e,t,n){this.cacheSharedSecret=t,this.retrieveCachedSharedSecret=n,this.anyone=new oi(1).toPublicKey(),this.rootKey="anyone"===e?new oi(1):e,this.identityKey=this.rootKey.toPublicKey().toString()}derivePublicKey(e,t,n,r=!1){return n=this.normalizeCounterparty(n),r?this.rootKey.deriveChild(n,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret).toPublicKey():n.deriveChild(this.rootKey,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}derivePrivateKey(e,t,n){return n=this.normalizeCounterparty(n),this.rootKey.deriveChild(n,this.computeInvoiceNumber(e,t),this.cacheSharedSecret,this.retrieveCachedSharedSecret)}derivePrivateKeys(e){const t=e.map((e,t)=>({index:t,counterparty:this.normalizeCounterparty(e.counterparty),invoiceNumber:this.computeInvoiceNumber(e.protocolID,e.keyID)})),n=new Map;for(const e of t){const t=e.counterparty.toString(),r=n.get(t)??[];r.push(e),n.set(t,r)}const r=[];for(const e of n.values()){let t;for(let n=0;n<e.length;n++){const i=e[n];r[i.index]=this.rootKey.deriveChild(i.counterparty,i.invoiceNumber,0===n?(e,n,r)=>{t=r,this.cacheSharedSecret?.(e,n,r)}:void 0,0===n?(e,n)=>(t=this.retrieveCachedSharedSecret?.(e,n),t):()=>t)}}return r}deriveSymmetricKey(e,t,n){n="anyone"===n?this.anyone:this.normalizeCounterparty(n);const r=this.derivePublicKey(e,t,n),i=this.derivePrivateKey(e,t,n);return new dr(i.deriveSharedSecret(r)?.x?.toArray()??[])}accelerationBackend(e){const t=fi("multiplyPublicKey");if(void 0!==t&&t.supportsCrypto(e)&&t.supportsCrypto("publicKeyFromPrivate"))return t}async sharedSecretBytes(e,t){const n=this.retrieveCachedSharedSecret?.(this.rootKey,t);if(void 0!==n)return Uint8Array.from(n.encode(!0));const r=di("multiplyPublicKey",await e.multiplyPublicKey(Uint8Array.from(t.encode(!0)),Uint8Array.from(this.rootKey.toArray("be",32))),33),i=Vr.fromDER(Array.from(r));return this.cacheSharedSecret?.(this.rootKey,t,i),Uint8Array.from(i.encode(!0))}async childTweak(e,t,n,r){const i=await this.sharedSecretBytes(e,r),s=gn(this.computeInvoiceNumber(t,n),"utf8"),a=new wr;return Uint8Array.from(new Be(It(i,s)).mod(a.n).toArray("be",32))}async derivePublicKeyAsync(e,t,n,r=!1){const i=this.accelerationBackend(r?"tweakPrivateKeyAdd":"tweakPublicKeyAdd");if(void 0===i)return this.derivePublicKey(e,t,n,r);const s=this.normalizeCounterparty(n),a=await this.childTweak(i,e,t,s);let o;if(r){const e=di("tweakPrivateKeyAdd",await i.tweakPrivateKeyAdd(Uint8Array.from(this.rootKey.toArray("be",32)),a),32);o=await i.publicKeyFromPrivate(e)}else o=await i.tweakPublicKeyAdd(Uint8Array.from(s.encode(!0)),a);return ri.fromDER(Array.from(di(r?"publicKeyFromPrivate":"tweakPublicKeyAdd",o,33)))}async deriveSymmetricKeyAsync(e,t,n){const r=this.accelerationBackend("tweakPrivateKeyAdd");if(!r?.supportsCrypto("tweakPublicKeyAdd"))return this.deriveSymmetricKey(e,t,n);const i="anyone"===n?this.anyone:this.normalizeCounterparty(n),s=await this.childTweak(r,e,t,i),[a,o]=await Promise.all([r.tweakPrivateKeyAdd(Uint8Array.from(this.rootKey.toArray("be",32)),s),r.tweakPublicKeyAdd(Uint8Array.from(i.encode(!0)),s)]),c=di("tweakPrivateKeyAdd",a,32),d=di("tweakPublicKeyAdd",o,33);ri.fromDER(Array.from(d));const f=di("multiplyPublicKey",await r.multiplyPublicKey(d,c),33);return Vr.fromDER(Array.from(f)),new dr(Array.from(f.slice(1)))}revealCounterpartySecret(e){if("self"===e)throw new Error("Counterparty secrets cannot be revealed for counterparty=self.");e=this.normalizeCounterparty(e);const t=this.rootKey.toPublicKey();if(this.rootKey.deriveChild(t,"test").toHex()===this.rootKey.deriveChild(e,"test").toHex())throw new Error("Counterparty secrets cannot be revealed for counterparty=self.");return this.rootKey.deriveSharedSecret(e).encode(!0)}revealSpecificSecret(e,t,n){e=this.normalizeCounterparty(e);const r=this.rootKey.deriveSharedSecret(e),i=gn(this.computeInvoiceNumber(t,n),"utf8");return It(r.encode(!0),i)}normalizeCounterparty(e){if(null==e)throw new Error("counterparty must be self, anyone or a public key!");return"self"===e?this.rootKey.toPublicKey():"anyone"===e?new oi(1).toPublicKey():"string"==typeof e?ri.fromString(e):e}computeInvoiceNumber(e,t){const n=e[0];if(!Number.isInteger(n)||n<0||n>2)throw new Error("Protocol security level must be 0, 1, or 2");const r=e[1].toLowerCase().trim();if(t.length>800)throw new Error("Key IDs must be 800 characters or less");if(t.length<1)throw new Error("Key IDs must be 1 character or more");if(r.length>400){if(!r.startsWith("specific linkage revelation "))throw new Error("Protocol names must be 400 characters or less");if(r.length>430)throw new Error("Specific linkage revelation protocol names must be 430 characters or less")}if(r.length<5)throw new Error("Protocol names must be 5 characters or more");if(r.includes(" "))throw new Error('Protocol names cannot contain multiple consecutive spaces (" ")');if(!/^[a-z0-9 ]+$/g.test(r))throw new Error("Protocol names can only contain letters, numbers and spaces");if(r.endsWith(" protocol"))throw new Error('No need to end your protocol name with " protocol"');return`${n}-${r}-${t}`}}class ui{keyDeriver;cache;maxCacheSize;rootKey;identityKey;constructor(e,t){this.rootKey="anyone"===e?new oi(1):e,this.keyDeriver=new hi(this.rootKey,(e,t,n)=>{this.cacheSet(`${e.toString()}-${t.toString()}`,n)},(e,t)=>this.cacheGet(`${e.toString()}-${t.toString()}`)),this.identityKey=this.rootKey.toPublicKey().toString(),this.cache=new Map;const n=t?.maxCacheSize;this.maxCacheSize=null!=n&&!Number.isNaN(n)&&n>0?n:1e3}derivePublicKey(e,t,n,r=!1){const i=this.generateCacheKey("derivePublicKey",e,t,n,r);if(this.cache.has(i)){const e=this.cacheGet(i);if(void 0===e)throw new Error("Cached value is undefined");return e}{const s=this.keyDeriver.derivePublicKey(e,t,n,r);return this.cacheSet(i,s),s}}async derivePublicKeyAsync(e,t,n,r=!1){const i=this.generateCacheKey("derivePublicKey",e,t,n,r),s=this.cacheGet(i);if(void 0!==s)return s;const a=await this.keyDeriver.derivePublicKeyAsync(e,t,n,r);return this.cacheSet(i,a),a}derivePrivateKey(e,t,n){const r=this.generateCacheKey("derivePrivateKey",e,t,n);if(this.cache.has(r)){const e=this.cacheGet(r);if(void 0===e)throw new Error("Cached value is undefined");return e}{const i=this.keyDeriver.derivePrivateKey(e,t,n);return this.cacheSet(r,i),i}}derivePrivateKeys(e){const t=[],n=[],r=[],i=[];for(let s=0;s<e.length;s++){const a=e[s],o=this.generateCacheKey("derivePrivateKey",a.protocolID,a.keyID,a.counterparty),c=this.cacheGet(o);c instanceof oi?t[s]=c:(n.push(a),r.push(s),i.push(o))}if(n.length>0){const e=this.keyDeriver.derivePrivateKeys(n);for(let n=0;n<e.length;n++)t[r[n]]=e[n],this.cacheSet(i[n],e[n])}return t}deriveSymmetricKey(e,t,n){const r=this.generateCacheKey("deriveSymmetricKey",e,t,n);if(this.cache.has(r)){const e=this.cacheGet(r);if(void 0===e)throw new Error("Cached value is undefined");return e}{const i=this.keyDeriver.deriveSymmetricKey(e,t,n);return this.cacheSet(r,i),i}}async deriveSymmetricKeyAsync(e,t,n){const r=this.generateCacheKey("deriveSymmetricKey",e,t,n),i=this.cacheGet(r);if(void 0!==i)return i;const s=await this.keyDeriver.deriveSymmetricKeyAsync(e,t,n);return this.cacheSet(r,s),s}revealCounterpartySecret(e){const t=this.generateCacheKey("revealCounterpartySecret",e);if(this.cache.has(t)){const e=this.cacheGet(t);if(void 0===e)throw new Error("Cached value is undefined");return e}{const n=this.keyDeriver.revealCounterpartySecret(e);return this.cacheSet(t,n),n}}revealSpecificSecret(e,t,n){const r=this.generateCacheKey("revealSpecificSecret",e,t,n);if(this.cache.has(r)){const e=this.cacheGet(r);if(void 0===e)throw new Error("Cached value is undefined");return e}{const i=this.keyDeriver.revealSpecificSecret(e,t,n);return this.cacheSet(r,i),i}}generateCacheKey(e,...t){return`${e}|${t.map(e=>this.serializeArgument(e)).join("|")}`}serializeArgument(e){return e instanceof ri||e instanceof oi?e.toString():Array.isArray(e)?e.map(e=>this.serializeArgument(e)).join(","):"object"==typeof e&&null!==e?JSON.stringify(e):String(e)}cacheGet(e){const t=this.cache.get(e);return this.cache.delete(e),void 0!==t&&this.cache.set(e,t),t}cacheSet(e,t){if(this.cache.size>=this.maxCacheSize){const e=this.cache.keys().next().value;void 0!==e&&this.cache.delete(e)}this.cache.set(e,t)}}class li{curve;constructor(){this.curve=new wr}generateProof(e,t,n,r){const i=oi.fromRandom(),s=i.toPublicKey(),a=n.mul(i),o=this.computeChallenge(t,n,r,a,s);return{R:s,SPrime:a,z:i.add(o.mul(e)).umod(this.curve.n)}}verifyProof(e,t,n,r){const{R:i,SPrime:s,z:a}=r,o=this.computeChallenge(e,t,n,s,i),c=this.curve.g.mul(a),d=i.add(e.mul(o));if(!c.eq(d))return!1;const f=t.mul(a),h=s.add(n.mul(o));return!!f.eq(h)}computeChallenge(e,t,n,r,i){const s=[...e.encode(!0),...t.encode(!0),...n.encode(!0),...r.encode(!0),...i.encode(!0)],a=_t(s);return new Be(a).umod(this.curve.n)}}function bi(e){return e??(()=>{throw new Error("keyDeriver is undefined")})()}async function pi(e,t){const n=t.protocolID,r=t.keyID;if(null==n||null==r)throw new Error("protocolID and keyID are required");return void 0!==e.derivePublicKeyAsync?await e.derivePublicKeyAsync(n,r,t.counterparty??"self",t.forSelf):e.derivePublicKey(n,r,t.counterparty??"self",t.forSelf)}async function gi(e,t,n,r){return void 0!==e.deriveSymmetricKeyAsync?await e.deriveSymmetricKeyAsync(t,n,r):e.deriveSymmetricKey(t,n,r)}const yi=class{keyDeriver;constructor(e){"string"!=typeof e.identityKey&&(e=new ui(e)),this.keyDeriver=e}async getPublicKey(e){if(e.identityKey){const e=bi(this.keyDeriver).rootKey,t=fi("publicKeyFromPrivate");if(void 0!==t){const n=di("publicKeyFromPrivate",await t.publicKeyFromPrivate(Uint8Array.from(e.toArray("be",32))),33);return{publicKey:ri.fromDER(Array.from(n)).toString()}}return{publicKey:e.toPublicKey().toString()}}if(null==e.protocolID||null==e.keyID||""===e.keyID)throw new Error("protocolID and keyID are required if identityKey is false or undefined.");return{publicKey:(await pi(bi(this.keyDeriver),e)).toString()}}async revealCounterpartyKeyLinkage(e){const{publicKey:t}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const n=this.keyDeriver.revealCounterpartySecret(e.counterparty),r=(new li).generateProof(this.keyDeriver.rootKey,this.keyDeriver.rootKey.toPublicKey(),ri.fromString(e.counterparty),Vr.fromDER(n)),i=[...r.R.encode(!0),...r.SPrime.encode(!0),...r.z.toArray("be",32)],s=(new Date).toISOString(),{ciphertext:a}=await this.encrypt({plaintext:n,protocolID:[2,"counterparty linkage revelation"],keyID:s,counterparty:e.verifier}),{ciphertext:o}=await this.encrypt({plaintext:i,protocolID:[2,"counterparty linkage revelation"],keyID:s,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,revelationTime:s,encryptedLinkage:a,encryptedLinkageProof:o}}async revealSpecificKeyLinkage(e){const{publicKey:t}=await this.getPublicKey({identityKey:!0});if(null==this.keyDeriver)throw new Error("keyDeriver is undefined");const n=this.keyDeriver.revealSpecificSecret(e.counterparty,e.protocolID,e.keyID),{ciphertext:r}=await this.encrypt({plaintext:n,protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier}),{ciphertext:i}=await this.encrypt({plaintext:[0],protocolID:[2,`specific linkage revelation ${e.protocolID[0]} ${e.protocolID[1]}`],keyID:e.keyID,counterparty:e.verifier});return{prover:t,verifier:e.verifier,counterparty:e.counterparty,protocolID:e.protocolID,keyID:e.keyID,encryptedLinkage:r,encryptedLinkageProof:i,proofType:0}}async encrypt(e){return{ciphertext:(await gi(bi(this.keyDeriver),e.protocolID,e.keyID,e.counterparty??"self")).encrypt(e.plaintext)}}async decrypt(e,t){return{plaintext:(await gi(bi(this.keyDeriver),e.protocolID,e.keyID,e.counterparty??"self")).decrypt(e.ciphertext)}}async createHmac(e){const t=await gi(bi(this.keyDeriver),e.protocolID,e.keyID,e.counterparty??"self");return{hmac:It(t.toArray(),e.data)}}async verifyHmac(e){const t=await gi(bi(this.keyDeriver),e.protocolID,e.keyID,e.counterparty??"self"),n=It(t.toArray(),e.data),r=e.hmac,i=function(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return 0===n}(gn(n),gn(r));if(!i){const e=new Error("HMAC is not valid");throw e.code="ERR_INVALID_HMAC",e}return{valid:i}}async createSignature(e){if(null==e.hashToDirectlySign&&null==e.data)throw new Error("args.data or args.hashToDirectlySign must be valid");const t=e.hashToDirectlySign??_t(e.data??[]),n=(r=bi(this.keyDeriver),i=e.protocolID,s=e.keyID,a=e.counterparty??"anyone",r.derivePrivateKey(i,s,a));var r,i,s,a;const o=ci(t)?fi("signDigest"):void 0;return{signature:(void 0===o?ti(new Be(t),n,!0):Hr.fromDER(Array.from(di("signDigest",await o.signDigest(Uint8Array.from(n.toArray("be",32)),Uint8Array.from(t)))))).toDER()}}async verifySignature(e){if(null==e.hashToDirectlyVerify&&null==e.data)throw new Error("args.data or args.hashToDirectlyVerify must be valid");const t=e.hashToDirectlyVerify??_t(e.data??[]),n=await pi(bi(this.keyDeriver),e),r=Hr.fromDER(e.signature),i=ci(t)?fi("verifyDigest"):void 0,s=void 0===i?ni(new Be(t),r,n):await i.verifyDigest(Uint8Array.from(n.encode(!0)),Uint8Array.from(t),Uint8Array.from(r.toDER()));if(!s){const e=new Error("Signature is not valid");throw e.code="ERR_INVALID_SIGNATURE",e}return{valid:s}}};class mi{type;serialNumber;subject;certifier;revocationOutpoint;fields;signature;constructor(e,t,n,r,i,s,a){this.type=e,this.serialNumber=t,this.subject=n,this.certifier=r,this.revocationOutpoint=i,this.fields=s,this.signature=a}toBinary(e=!0){const t=new Rn,n=gn(this.type,"base64");t.write(n);const r=gn(this.serialNumber,"base64");t.write(r);const i=gn(this.subject,"hex");t.write(i);const s=gn(this.certifier,"hex");t.write(s);const[a,o]=this.revocationOutpoint.split("."),c=gn(a,"hex");t.write(c),t.writeVarIntNum(Number(o));const d=Object.keys(this.fields).sort((e,t)=>e.localeCompare(t));t.writeVarIntNum(d.length);for(const e of d){const n=this.fields[e],r=gn(e,"utf8");t.writeVarIntNum(r.length),t.write(r);const i=gn(n,"utf8");t.writeVarIntNum(i.length),t.write(i)}if(e&&(this.signature??"").length>0){const e=gn(this.signature,"hex");t.write(e)}return t.toArray()}static fromBinary(e){const t=new fr(e),n=An(t.read(32)),r=An(t.read(32)),i=t.read(33),s=pn(i),a=t.read(33),o=pn(a),c=t.read(32),d=`${pn(c)}.${t.readVarIntNum()}`,f=t.readVarIntNum(),h={};for(let e=0;e<f;e++){const e=t.readVarIntNum(),n=t.read(e),r=Sn(n),i=t.readVarIntNum(),s=t.read(i),a=Sn(s);h[r]=a}let u;if(!t.eof()){const e=t.read();u=Hr.fromDER(Array.from(e)).toString("hex")}return new mi(n,r,s,o,d,h,u)}async verify(){const e=new yi("anyone"),t=this.toBinary(!1),n=this.signature??"",{valid:r}=await e.verifySignature({signature:gn(n,"hex"),data:t,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`,counterparty:this.certifier});return r}async sign(e){if(null!=this.signature&&this.signature.length>0)throw new Error(`Certificate has already been signed! Signature present: ${this.signature}`);this.certifier=(await e.getPublicKey({identityKey:!0})).publicKey;const t=this.toBinary(!1),{signature:n}=await e.createSignature({data:t,protocolID:[2,"certificate signature"],keyID:`${this.type} ${this.serialNumber}`});this.signature=pn(n)}static getCertificateFieldEncryptionDetails(e,t){return{protocolID:[2,"certificate field encryption"],keyID:t?`${t} ${e}`:e}}static fromObject(e){return new mi(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,e.signature)}}class wi extends mi{keyring;decryptedFields;constructor(...[e,t,n,r,i,s,a,o,c]){super(e,t,n,r,i,s,o),this.keyring=a,this.decryptedFields=c}static fromCertificate(e,t){return new wi(e.type,e.serialNumber,e.subject,e.certifier,e.revocationOutpoint,e.fields,t,e.signature)}async decryptFields(e,t,n,r){if(null==this.keyring||0===Object.keys(this.keyring).length)throw new Error("A keyring is required to decrypt certificate fields for the verifier.");try{const i={};for(const s in this.keyring){const{plaintext:a}=await e.decrypt({ciphertext:gn(this.keyring[s],"base64"),...mi.getCertificateFieldEncryptionDetails(s,this.serialNumber),counterparty:this.subject,privileged:t,privilegedReason:n},r),o=new dr(a).decrypt(gn(this.fields[s],"base64"));i[s]=Sn(o)}return i}catch(e){throw new Error(`Failed to decrypt selectively revealed certificate fields using keyring: ${String(e instanceof Error?e.message:e)}`)}}}const vi=async(e,t,n,r)=>{const i=await e.listCertificates({certifiers:t.certifiers,types:Object.keys(t.types)},r);return await Promise.all(i.certificates.map(async i=>{const{keyringForVerifier:s}=await e.proveCertificate({certificate:i,fieldsToReveal:t.types[i.type],verifier:n},r);return new wi(i.type,i.serialNumber,i.subject,i.certifier,i.revocationOutpoint,i.fields,s,i.signature)}))};async function _i(e,t,n="self",r){const i=gn(e,"base64"),s=i.slice(0,16),a=i.slice(16),{valid:o}=await t.verifyHmac({data:s,hmac:a,protocolID:[2,"server hmac"],keyID:Sn(s),counterparty:n},r);return o}const Si=async(e,t,n,r)=>{if(null==t.certificates||0===t.certificates.length)throw new Error("No certificates were provided in the AuthMessage.");await Promise.all(t.certificates.map(async i=>{if(i.subject!==t.identityKey)throw new Error(`The subject of one of your certificates ("${i.subject}") is not the same as the request sender ("${t.identityKey}").`);const s=new wi(i.type,i.serialNumber,i.subject,i.certifier,i.revocationOutpoint,i.fields,i.keyring,i.signature);if(!await s.verify())throw new Error(`The signature for the certificate with serial number ${s.serialNumber} is invalid!`);if(null!=n){const{certifiers:e,types:t}=n;if(!e.includes(s.certifier))throw new Error(`Certificate with serial number ${s.serialNumber} has an unrequested certifier: ${s.certifier}`);if(null==t[s.type])throw new Error(`Certificate with type ${s.type} was not requested`)}await s.decryptFields(e,void 0,void 0,r)}))},Ii="0.1",Ai="undefined"==typeof globalThis?void 0:globalThis.Buffer;class Ei{sessionManager;transport;wallet;certificatesToRequest;onGeneralMessageReceivedCallbacks=new Map;onCertificatesReceivedCallbacks=new Map;onCertificateRequestReceivedCallbacks=new Map;onInitialResponseReceivedCallbacks=new Map;certificateValidationPromises=new Map;callbackIdCounter=0;autoPersistLastSession=!0;lastInteractedWithPeer;originator;identityPublicKey;ready;constructor(e,t,n,r,i,s){this.wallet=e,this.originator=s,this.transport=t,this.certificatesToRequest=n??{certifiers:[],types:{}},this.ready=this.transport.onData(this.handleIncomingMessage.bind(this)),this.sessionManager=r??new Kn,this.autoPersistLastSession=!1!==i}async toPeer(e,t){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof t&&(t=this.lastInteractedWithPeer);const n=await this.getAuthenticatedSession(t);if(null==n.peerIdentityKey)throw new Error("Peer identity is not established");if(!0===n.certificatesRequired&&!0!==n.certificatesValidated)throw new Error("Cannot send general message before certificate validation is complete");const r=An(Un(32)),{signature:i}=await this.wallet.createSignature({data:e,protocolID:[2,"auth message signature"],keyID:`${r} ${n.peerNonce??""}`,counterparty:n.peerIdentityKey},this.originator),s={version:Ii,messageType:"general",identityKey:await this.getIdentityPublicKey(),nonce:r,yourNonce:n.peerNonce,payload:e,signature:i};n.lastUpdate=Date.now(),await this.sessionManager.updateSession(n);try{await this.transport.send(s)}catch(e){this.propagateTransportError(n.peerIdentityKey,e)}}async requestCertificates(e,t){this.autoPersistLastSession&&"string"==typeof this.lastInteractedWithPeer&&"string"!=typeof t&&(t=this.lastInteractedWithPeer);const n=await this.getAuthenticatedSession(t),r=An(Un(32)),{signature:i}=await this.wallet.createSignature({data:Ei.utf8ToBytes(JSON.stringify(e)),protocolID:[2,"auth message signature"],keyID:`${r} ${n.peerNonce??""}`,counterparty:n.peerIdentityKey},this.originator),s={version:Ii,messageType:"certificateRequest",identityKey:await this.getIdentityPublicKey(),nonce:r,initialNonce:n.sessionNonce,yourNonce:n.peerNonce,requestedCertificates:e,signature:i};n.lastUpdate=Date.now(),await this.sessionManager.updateSession(n);try{await this.transport.send(s)}catch(e){this.propagateTransportError(n.peerIdentityKey,e)}}async getAuthenticatedSession(e){if(void 0===this.transport)throw new Error("Peer transport is not connected!");let t;if("string"==typeof e&&(t=await this.sessionManager.getSession(e)),!0!==t?.isAuthenticated){const n=await this.initiateHandshake(e);if(t=await this.sessionManager.getSession(n),!0!==t?.isAuthenticated)throw new Error("Unable to establish mutual authentication with peer!")}return t}listenForGeneralMessages(e){const t=this.callbackIdCounter++;return this.onGeneralMessageReceivedCallbacks.set(t,e),t}stopListeningForGeneralMessages(e){this.onGeneralMessageReceivedCallbacks.delete(e)}listenForCertificatesReceived(e){const t=this.callbackIdCounter++;return this.onCertificatesReceivedCallbacks.set(t,e),t}stopListeningForCertificatesReceived(e){this.onCertificatesReceivedCallbacks.delete(e)}listenForCertificatesRequested(e){const t=this.callbackIdCounter++;return this.onCertificateRequestReceivedCallbacks.set(t,e),t}stopListeningForCertificatesRequested(e){this.onCertificateRequestReceivedCallbacks.delete(e)}async initiateHandshake(e){const t=await On(this.wallet,void 0,this.originator),n=Date.now(),r=this.certificatesToRequest.certifiers.length>0;await this.sessionManager.addSession({isAuthenticated:!1,sessionNonce:t,peerIdentityKey:e,lastUpdate:n,certificatesRequired:r,certificatesValidated:!r});const i={version:Ii,messageType:"initialRequest",identityKey:await this.getIdentityPublicKey(),initialNonce:t,requestedCertificates:this.certificatesToRequest},s=this.waitForInitialResponse(t);try{return await this.transport.send(i),await s}catch(e){throw this.stopListeningForInitialResponsesByNonce(t),e}}async waitForInitialResponse(e){return await new Promise(t=>{const n=this.listenForInitialResponse(e,e=>{this.stopListeningForInitialResponses(n),t(e)})})}listenForInitialResponse(e,t){const n=this.callbackIdCounter++;return this.onInitialResponseReceivedCallbacks.set(n,{callback:t,sessionNonce:e}),n}stopListeningForInitialResponses(e){this.onInitialResponseReceivedCallbacks.delete(e)}stopListeningForInitialResponsesByNonce(e){for(const[t,n]of this.onInitialResponseReceivedCallbacks)n.sessionNonce===e&&this.stopListeningForInitialResponses(t)}propagateTransportError(e,t){if(t instanceof Error){if(null!=e){const n=t.details;null!=n&&"object"==typeof n?n.peerIdentityKey??=e:t.details={peerIdentityKey:e}}throw t}const n=`Failed to send message to peer ${e??"unknown"}: ${((e,t="Unknown value")=>{if(null===e)return"null";if(void 0===e)return"undefined";if("string"==typeof e)return e;if("number"==typeof e||"bigint"==typeof e)return e.toString();if("boolean"==typeof e)return e?"true":"false";if("symbol"==typeof e)return e.description??e.toString();if(e instanceof Error&&e.message.length>0)return e.message;const n=e.message;if("string"==typeof n&&n.length>0)return n;try{return JSON.stringify(e)??t}catch{return t}})(t)}`;throw new Error(n)}async handleIncomingMessage(e){if(null==e||"object"!=typeof e||Array.isArray(e))throw new Error("Invalid authentication message.");if("string"!=typeof e.version||e.version!==Ii)throw new Error(`Invalid or unsupported message auth version! Received: ${e.version}, expected: ${Ii}`);switch(e.messageType){case"initialRequest":await this.processInitialRequest(e);break;case"initialResponse":await this.processInitialResponse(e);break;case"certificateRequest":await this.processCertificateRequest(e);break;case"certificateResponse":await this.processCertificateResponse(e);break;case"general":await this.processGeneralMessage(e);break;default:throw new Error(`Unknown message type of ${String(e.messageType)} from ${String(e.identityKey)}`)}}async processInitialRequest(e){if("string"!=typeof e.identityKey||"string"!=typeof e.initialNonce||""===e.initialNonce)throw new Error("Missing required fields in initialRequest message.");const t=await On(this.wallet,void 0,this.originator),n=Date.now(),r=Array.isArray(this.certificatesToRequest?.certifiers)&&this.certificatesToRequest.certifiers.length>0;let i;if(await this.sessionManager.addSession({isAuthenticated:!0,sessionNonce:t,peerNonce:e.initialNonce,peerIdentityKey:e.identityKey,lastUpdate:n,certificatesRequired:r,certificatesValidated:!r}),Array.isArray(e.requestedCertificates?.certifiers)&&e.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)for(const t of this.onCertificateRequestReceivedCallbacks.values())await t(e.identityKey,e.requestedCertificates);else i=await vi(this.wallet,e.requestedCertificates,e.identityKey,this.originator);const{signature:s}=await this.wallet.createSignature({data:[...Ei.base64ToBytes(e.initialNonce),...Ei.base64ToBytes(t)],protocolID:[2,"auth message signature"],keyID:`${e.initialNonce} ${t}`,counterparty:e.identityKey},this.originator),a={version:Ii,messageType:"initialResponse",identityKey:await this.getIdentityPublicKey(),initialNonce:t,yourNonce:e.initialNonce,certificates:i,requestedCertificates:this.certificatesToRequest,signature:s};this.lastInteractedWithPeer??=e.identityKey,await this.transport.send(a)}async authenticateInitialResponse(e){if(!await _i(e.yourNonce,this.wallet,void 0,this.originator))throw new Error(`Initial response nonce verification failed from peer: ${e.identityKey}`);const t=await this.sessionManager.getSession(e.yourNonce);if(null==t)throw new Error(`Peer session not found for peer: ${e.identityKey}`);const n=Ei.base64ToBytes((t.sessionNonce??"")+(e.initialNonce??"")),{valid:r}=await this.wallet.verifySignature({data:n,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${t.sessionNonce??""} ${e.initialNonce??""}`,counterparty:e.identityKey},this.originator);if(!r)throw new Error(`Unable to verify initial response signature for peer: ${e.identityKey}`);return t.peerNonce=e.initialNonce,t.peerIdentityKey=e.identityKey,t.isAuthenticated=!0,t.certificatesRequired=Array.isArray(this.certificatesToRequest?.certifiers)&&this.certificatesToRequest.certifiers.length>0,t.certificatesValidated=!t.certificatesRequired,t.lastUpdate=Date.now(),await this.sessionManager.updateSession(t),t}async validateInitialResponseCertificates(e,t){if(t.certificatesRequired&&Array.isArray(e.certificates)&&0!==e.certificates.length){await Si(this.wallet,e,this.certificatesToRequest,this.originator),t.certificatesValidated=!0,t.lastUpdate=Date.now(),await this.sessionManager.updateSession(t),null!=t.sessionNonce&&this.resolveCertificateValidation(t.sessionNonce);for(const t of this.onCertificatesReceivedCallbacks.values())await t(e.identityKey,e.certificates)}}releaseInitialResponseWaiters(e){this.onInitialResponseReceivedCallbacks.forEach(t=>{t.sessionNonce===e.sessionNonce&&t.callback(e.sessionNonce)})}async answerInitialCertificateRequest(e){if(null==e.requestedCertificates||!Array.isArray(e.requestedCertificates.certifiers)||0===e.requestedCertificates.certifiers.length)return;if(this.onCertificateRequestReceivedCallbacks.size>0){for(const t of this.onCertificateRequestReceivedCallbacks.values())await t(e.identityKey,e.requestedCertificates);return}const t=await vi(this.wallet,e.requestedCertificates,e.identityKey,this.originator);t.length>0&&await this.sendCertificateResponse(e.identityKey,t)}async processInitialResponse(e){const t=await this.authenticateInitialResponse(e);await this.validateInitialResponseCertificates(e,t),this.lastInteractedWithPeer=e.identityKey,this.releaseInitialResponseWaiters(t),await this.answerInitialCertificateRequest(e)}async processCertificateRequest(e){if(!await _i(e.yourNonce,this.wallet,void 0,this.originator))throw new Error(`Unable to verify nonce for certificate request message from: ${e.identityKey}`);const t=await this.sessionManager.getSession(e.yourNonce);if(null==t)throw new Error(`Session not found for nonce: ${e.yourNonce}`);const{valid:n}=await this.wallet.verifySignature({data:Ei.utf8ToBytes(JSON.stringify(e.requestedCertificates)),signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey},this.originator);if(!n)throw new Error(`Invalid signature in certificate request message from ${t.peerIdentityKey}`);if(t.lastUpdate=Date.now(),await this.sessionManager.updateSession(t),null!=e.requestedCertificates&&Array.isArray(e.requestedCertificates.certifiers)&&e.requestedCertificates.certifiers.length>0)if(this.onCertificateRequestReceivedCallbacks.size>0)for(const t of this.onCertificateRequestReceivedCallbacks.values())await t(e.identityKey,e.requestedCertificates);else{const t=await vi(this.wallet,e.requestedCertificates,e.identityKey,this.originator);await this.sendCertificateResponse(e.identityKey,t)}}async sendCertificateResponse(e,t){const n=await this.getAuthenticatedSession(e),r=An(Un(32)),{signature:i}=await this.wallet.createSignature({data:Ei.utf8ToBytes(JSON.stringify(t)),protocolID:[2,"auth message signature"],keyID:`${r} ${n.peerNonce??""}`,counterparty:n.peerIdentityKey},this.originator),s={version:Ii,messageType:"certificateResponse",identityKey:await this.getIdentityPublicKey(),nonce:r,initialNonce:n.sessionNonce,yourNonce:n.peerNonce,certificates:t,signature:i};n.lastUpdate=Date.now(),await this.sessionManager.updateSession(n);try{await this.transport.send(s)}catch(e){this.propagateTransportError(n.peerIdentityKey,e)}}async processCertificateResponse(e){if(!await _i(e.yourNonce,this.wallet,void 0,this.originator))throw new Error(`Unable to verify nonce for certificate response from: ${e.identityKey}`);const t=await this.sessionManager.getSession(e.yourNonce);if(null==t)throw new Error(`Session not found for nonce: ${e.yourNonce}`);const{valid:n}=await this.wallet.verifySignature({data:Ei.utf8ToBytes(JSON.stringify(e.certificates)),signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:e.identityKey},this.originator);if(!n)throw new Error(`Unable to verify certificate response signature for peer: ${e.identityKey}`);Array.isArray(e.certificates)&&e.certificates.length>0&&(await Si(this.wallet,e,e.requestedCertificates,this.originator),t.certificatesValidated=!0,t.lastUpdate=Date.now(),await this.sessionManager.updateSession(t),null!=t.sessionNonce&&this.resolveCertificateValidation(t.sessionNonce));for(const t of this.onCertificatesReceivedCallbacks.values())await t(e.identityKey,e.certificates??[])}async processGeneralMessage(e){if(!await _i(e.yourNonce,this.wallet,void 0,this.originator))throw new Error(`Unable to verify nonce for general message from: ${e.identityKey}`);const t=await this.sessionManager.getSession(e.yourNonce);if(null==t)throw new Error(`Session not found for nonce: ${e.yourNonce}`);const n=!0===t.certificatesRequired,r=!0===t.certificatesValidated;if(n&&!r){const e=3e4,n=t.sessionNonce;if(null==n)throw new Error("Session nonce is required for certificate validation");await new Promise((r,i)=>{const s=setTimeout(()=>{null!=this.certificateValidationPromises.get(n)&&(this.certificateValidationPromises.delete(n),i(new Error(`Timeout waiting for certificate validation from peer ${t.peerIdentityKey??"unknown"}`)))},e);"object"==typeof s&&"unref"in s&&s.unref(),this.certificateValidationPromises.set(n,{resolve:()=>{clearTimeout(s),r()},reject:e=>{clearTimeout(s),i(e)}})})}const{valid:i}=await this.wallet.verifySignature({data:e.payload,signature:e.signature,protocolID:[2,"auth message signature"],keyID:`${e.nonce??""} ${t.sessionNonce??""}`,counterparty:t.peerIdentityKey},this.originator);if(!i)throw new Error(`Invalid signature in generalMessage from ${t.peerIdentityKey}`);t.lastUpdate=Date.now(),await this.sessionManager.updateSession(t),this.lastInteractedWithPeer=e.identityKey;for(const t of this.onGeneralMessageReceivedCallbacks.values())await t(e.identityKey,e.payload??[])}resolveCertificateValidation(e){const t=this.certificateValidationPromises.get(e);null!=t&&(t.resolve(),this.certificateValidationPromises.delete(e))}async getIdentityPublicKey(){if(null!=this.identityPublicKey)return this.identityPublicKey;const{publicKey:e}=await this.wallet.getPublicKey({identityKey:!0},this.originator);return this.identityPublicKey=e,e}static utf8ToBytes(e){return null!=Ai?Array.from(Ai.from(e,"utf8")):"undefined"!=typeof TextEncoder?Array.from((new TextEncoder).encode(e)):gn(e,"utf8")}static base64ToBytes(e){return null!=Ai?Array.from(Ai.from(e,"base64")):gn(e,"base64")}}function xi(e){try{const t=Sn(e),n=JSON.parse(t);return null===n||"object"!=typeof n||Array.isArray(n)||"string"!=typeof n.eventName?{eventName:"_unknown",data:void 0}:{eventName:n.eventName,data:n.data}}catch{return{eventName:"_unknown",data:void 0}}}var ki=class{ioSocket;peer;onError;connected=!1;id="";serverIdentityKey;eventCallbacks=new Map;constructor(e,t,n=()=>{}){this.ioSocket=e,this.peer=t,this.onError=n,this.ioSocket.on("connect",()=>{this.connected=!0,this.id=this.ioSocket.id??"",this.fireEventCallbacks("connect")}),this.ioSocket.on("disconnect",e=>{this.connected=!1,this.fireEventCallbacks("disconnect",e)}),this.peer.listenForGeneralMessages(async(e,t)=>{this.serverIdentityKey=e;const{eventName:n,data:r}=this.decodeEventPayload(t);await this.fireEventCallbacks(n,r)})}on(e,t){let n=this.eventCallbacks.get(e);return void 0===n&&(n=[],this.eventCallbacks.set(e,n)),n.push(t),this}emit(e,t){let n;try{n=this.encodeEventPayload(e,t)}catch(t){return this.reportError(t,{phase:"send",socketId:this.ioSocket.id??this.id,eventName:e}),this}return this.peer.toPeer(n,this.serverIdentityKey).catch(t=>{this.reportError(t,{phase:"send",socketId:this.ioSocket.id??this.id,eventName:e})}),this}disconnect(){this.serverIdentityKey=void 0,this.ioSocket.disconnect()}async fireEventCallbacks(e,t){const n=this.eventCallbacks.get(e);if(void 0!==n)try{for(const e of n){const n=e(t);null!=n&&"function"==typeof n.then&&await n}}catch(t){this.reportError(t,{phase:"application",socketId:this.ioSocket.id??this.id,eventName:e}),"disconnect"!==e&&this.disconnectSafely()}}encodeEventPayload(e,t){return gn(function(e){const t=JSON.stringify(e,Mn,void 0);if(void 0===t)throw new TypeError("BRC-100 JSON payload is not serializable");return t}({eventName:e,data:t}),"utf8")}decodeEventPayload(e){return xi(e)}reportError(e,t){Promise.resolve().then(async()=>await this.onError(e,t)).catch(()=>{})}disconnectSafely(){try{this.ioSocket.disconnect()}catch{}}};function Ni(e,t){const n=xe(e,t.managerOptions),i=new r(n,{maxPendingMessages:t.maxPendingAuthMessages,onError:e=>{Ri(t.onError,e,{phase:"authentication",socketId:n.id})}});return new ki(n,new Ei(t.wallet,i,t.requestedCertificates,t.sessionManager,void 0,t.originator),(e,n)=>{Ri(t.onError,e,n)})}function Ri(e,t,n){Promise.resolve().then(async()=>await(e?.(t,n))).catch(()=>{})}return t})());
//# sourceMappingURL=bundle.js.map