@helia/ipns 10.0.8 → 10.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -13
- package/dist/index.min.js +1 -1
- package/dist/index.min.js.map +2 -2
- package/dist/src/index.d.ts +11 -13
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +11 -13
- package/dist/src/index.js.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +11 -13
package/README.md
CHANGED
|
@@ -133,25 +133,23 @@ may fail to be published with "Insufficient peers" errors.
|
|
|
133
133
|
|
|
134
134
|
```TypeScript
|
|
135
135
|
import { ipns, pubSubIPNSRouting } from '@helia/ipns'
|
|
136
|
-
import { withLibp2p
|
|
136
|
+
import { withLibp2p } from '@helia/libp2p'
|
|
137
137
|
import { unixfs } from '@helia/unixfs'
|
|
138
|
+
import { fetch } from '@libp2p/fetch'
|
|
138
139
|
import { floodsub } from '@libp2p/floodsub'
|
|
139
140
|
import { createHelia } from 'helia'
|
|
140
|
-
import type { Helia } from '@helia/interface'
|
|
141
|
-
import type { PubSub } from '@helia/ipns'
|
|
142
|
-
import type { DefaultLibp2pServices } from '@helia/libp2p'
|
|
143
|
-
import type { FloodSub } from '@libp2p/floodsub'
|
|
144
|
-
import type { Libp2p } from '@libp2p/interface'
|
|
145
141
|
|
|
146
|
-
const
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
142
|
+
const helia = await withLibp2p(createHelia(), {
|
|
143
|
+
services: {
|
|
144
|
+
fetch: fetch(),
|
|
145
|
+
pubsub: floodsub()
|
|
146
|
+
}
|
|
147
|
+
}).start()
|
|
150
148
|
|
|
151
149
|
const name = ipns(helia, {
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
150
|
+
routers: [
|
|
151
|
+
pubSubIPNSRouting(helia)
|
|
152
|
+
]
|
|
155
153
|
})
|
|
156
154
|
|
|
157
155
|
// store some data to publish
|
package/dist/index.min.js
CHANGED
|
@@ -10,7 +10,7 @@ ${e}`)}`:n!=null?`${n.split(`
|
|
|
10
10
|
${e}`)}`:r!=null?`${r}`:`${t.toString()}`}function Nh(t){return t instanceof AggregateError||t?.name==="AggregateError"&&Array.isArray(t.errors)}function uu(t,e=""){if(Nh(t)){let r=au(t,e);return t.errors.length>0?(e=`${e} `,r+=`
|
|
11
11
|
${e}${t.errors.map(n=>`${uu(n,`${e}`)}`).join(`
|
|
12
12
|
${e}`)}`):r+=`
|
|
13
|
-
${e}[Error list was empty]`,r.trim()}return au(t,e)}Ee.formatters.e=t=>t==null?"undefined":uu(t);function Uh(t){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=t,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function Zr(t,e){let r=Uh(`${t}:trace`);return Ee.enabled(`${t}:trace`)&&Ee.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(r=Ee(`${t}:trace`,e)),Object.assign(Ee(t,e),{error:Ee(`${t}:error`,e),trace:r,newScope:n=>Zr(`${t}:${n}`,e)})}function cu(t){if(t!=null&&(t=t.trim(),t.length!==0))return t}var fu=oi(_n(),1);var kh=Zr("ipns"),Fh=300000000000n;async function ur(t,e,r,n,o){r=BigInt(r),e=so(e);let i=se(e),s=o?.ttlNs??Fh,a=new fu.default((o?.now??Date.now())+Number(n)),c=Q.ValidityType.EOL,f=se(a.toString()),u=ru({...o?.data??{},Value:i,Validity:f,ValidityType:0,Sequence:r,TTL:s}),l=oo(u),h=await t.sign(l,o),m;return o?.v1Compatible===!1?m={signatureV2:h,data:u}:m={value:i,signatureV1:await Oh(t,i,c,f),validityType:c,validity:f,sequence:r,ttl:s,signatureV2:h,data:u},Ph(t.publicKey)&&(m.publicKey=t.publicKey.toProtobuf()),m}var Oh=async(t,e,r,n,o)=>{try{let i=tu(e,r,n);return await t.sign(i,o)}catch(i){throw kh.error("record signature creation failed",i),new wn("Record signature creation failed")}};function Ph(t){return t.toMultihash().code!==Wc}var uo=class{routers;localStore;keychain;constructor(e,r){this.keychain=e.keychain,this.localStore=r.localStore,this.routers=r.routers}async publish(e,r,n={}){try{let o=await this.#e(e,n),i=o.publicKey.toMultihash(),s=it(i),a=1n;if(await this.localStore.has(s,n)){let{record:l}=await this.localStore.get(s,n),h=Q.decode(l);a=(ke(h.data).Sequence??0n)+1n}let c=n.lifetime??1728e5,f=await ur(o,r,a,c,{...n,ttlNs:n.ttl!=null?BigInt(n.ttl)*1000000n:void 0}),u=Q.encode(f);return n.offline===!0?await this.localStore.put(s,u,{...n,metadata:{keyName:e,lifetime:c}}):await Promise.all(this.routers.map(async l=>{await l.put(s,u,{...n,metadata:{keyName:e,lifetime:c}})})),{record:f,name:`/ipns/${o.publicKey.toCID().toString(we)}`,publicKey:o.publicKey}}catch(o){throw n.onProgress?.(new fe("ipns:publish:error",o)),o}}async#e(e,r){try{return await this.keychain.exportKey(e,r)}catch(n){if(n.name==="NotFoundError")return this.keychain.generateKey(e,r);throw n}}async unpublish(e,r){let o=(await this.keychain.exportKey(e,r)).publicKey.toMultihash(),i=it(o);await this.localStore.delete(i,r)}};function fr(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var fo=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},lr=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new fo(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let r=this.head;this.head=r.next=new fo(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var os=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function lu(t={}){return Mh(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function Mh(t,e){e=e??{};let r=e.onEnd,n=new lr,o,i,s,a=fr(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((b,E)=>{i=B=>{i=null,n.push(B);try{b(t(n))}catch(y){E(y)}return o}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=fr()})}},f=b=>i!=null?i(b):(n.push(b),o),u=b=>(n=new lr,i!=null?i({error:b}):(n.push({error:b}),o)),l=b=>{if(s)return o;if(e?.objectMode!==!0&&b?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:b})},h=b=>s?o:(s=!0,b!=null?u(b):f({done:!0})),m=()=>(n=new lr,h(),{done:!0}),L=b=>(h(b),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:m,throw:L,push:l,end:h,get readableLength(){return n.size},onEmpty:async b=>{let E=b?.signal;if(E?.throwIfAborted(),n.isEmpty())return;let B,y;E!=null&&(B=new Promise((N,U)=>{y=()=>{U(new os)},E.addEventListener("abort",y)}));try{await Promise.race([a.promise,B])}finally{y!=null&&E!=null&&E?.removeEventListener("abort",y)}}},r==null)return o;let v=o;return o={[Symbol.asyncIterator](){return this},next(){return v.next()},throw(b){return v.throw(b),r!=null&&(r(b),r=void 0),{done:!0}},return(){return v.return(),r!=null&&(r(),r=void 0),{done:!0}},push:l,end(b){return v.end(b),r!=null&&(r(b),r=void 0),o},get readableLength(){return v.readableLength},onEmpty:b=>v.onEmpty(b)},o}var is=class t extends Error{name="TimeoutError";constructor(e,r){super(e,r),Error.captureStackTrace?.(this,t)}},du=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function ss(t,e){let{milliseconds:r,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout},signal:s}=e,a,c,u=new Promise((l,h)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(s?.aborted){h(du(s));return}if(s&&(c=()=>{h(du(s))},s.addEventListener("abort",c,{once:!0})),t.then(l,h),r===Number.POSITIVE_INFINITY)return;let m=new is;a=i.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(L){h(L)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?l():o instanceof Error?h(o):(m.message=o??`Promise timed out after ${r} milliseconds`,h(m))},r)}).finally(()=>{u.clear(),c&&s&&s.removeEventListener("abort",c)});return u.clear=()=>{i.clearTimeout.call(void 0,a),a=void 0},u}var Kh=t=>{let e=t.addEventListener||t.on||t.addListener,r=t.removeEventListener||t.off||t.removeListener;if(!e||!r)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:r.bind(t)}};function Vh(t,e,r){let n,o=new Promise((i,s)=>{if(r={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...r},!(r.count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:f,removeListener:u}=Kh(t),l=async(...m)=>{let L=r.multiArgs?m:m[0];if(r.filter)try{if(!await r.filter(L))return}catch(v){n(),s(v);return}c.push(L),r.count===c.length&&(n(),i(c))},h=(...m)=>{n(),s(r.rejectionMultiArgs?m:m[0])};n=()=>{for(let m of a)u(m,l);for(let m of r.rejectionEvents)a.includes(m)||u(m,h)};for(let m of a)f(m,l);for(let m of r.rejectionEvents)a.includes(m)||f(m,h);r.signal&&r.signal.addEventListener("abort",()=>{h(r.signal.reason)},{once:!0}),r.resolveImmediately&&i(c)});if(o.cancel=n,typeof r.timeout=="number"){let i=ss(o,{milliseconds:r.timeout});return i.cancel=()=>{n(),i.clear()},i}return o}function lo(t,e,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=Vh(t,e,r),o=n.then(i=>i[0]);return o.cancel=n.cancel,o}function Gr(t,e){let r,n=function(){let o=function(){r=void 0,t()};clearTimeout(r),r=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(r)},n}var ho=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function $h(t){return t.reason}async function po(t,e,r){if(e==null)return t;let n=r?.translateError??$h;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([t,new Promise((i,s)=>{o=()=>{s(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var mo=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=fr(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new rt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function qh(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var yo=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,r){this.id=qh(),this.status="queued",this.fn=e,this.options=r,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((r,n)=>r&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new rt),this.cleanup())}async join(e){let r=new mo(e);return this.recipients.push(r),e?.signal?.addEventListener("abort",this.onAbort),r.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await po(this.fn({...this.options??{},signal:this.controller.signal,onProgress:r=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(r)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(r=>{r.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(r=>{r.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var dr=class extends Jn{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Gr(this.emitEmpty.bind(this),1),this.emitIdle=Gr(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let r of this.queue)if(r.status==="queued"){e=r;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let r=0;r<this.queue.length;r++)if(this.queue[r]===e){this.queue.splice(r,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,r){if(r?.signal?.throwIfAborted(),this.size===this.maxSize)throw new ho;let n=new yo(e,r);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(r).then(i=>(this.safeDispatchEvent("completed",{detail:i}),this.safeDispatchEvent("success",{detail:{job:n,result:i}}),i)).catch(i=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:i}}),i});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new rt)}),this.clear()}async onEmpty(e){this.size!==0&&await lo(this,"empty",e)}async onSizeLessThan(e,r){this.size<e||await lo(this,"next",{...r,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await lo(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let r=lu({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),r.end(c)},o=c=>{c.detail!=null&&r.push(c.detail)},i=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new rt("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*r}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};function Xr(t){let e=new globalThis.AbortController;function r(){let i=t.filter(s=>s?.aborted===!0).map(s=>s?.reason).pop();e.abort(i);for(let s of t)s?.removeEventListener!=null&&s.removeEventListener("abort",r)}for(let i of t){if(i?.aborted===!0){r();break}i?.addEventListener!=null&&i.addEventListener("abort",r)}function n(){for(let i of t)i?.removeEventListener!=null&&i.removeEventListener("abort",r)}let o=e.signal;return o.clear=n,o}var hu=Symbol.for("sindresorhus/unlimited-timeout#brand");function pu(t,e,...r){if(typeof t!="function")throw new TypeError("Expected callback to be a function");e??=0,e=Number(e);let n=!1,o={[hu]:!0,id:void 0,cleared:!1,ref(){return n=!1,o.id?.ref?.(),o},unref(){return n=!0,o.id?.unref?.(),o}};if(e===Number.POSITIVE_INFINITY||e>Number.MAX_SAFE_INTEGER)return o;(!Number.isFinite(e)||e<0)&&(e=0);let i=performance.now()+e,s=a=>{o.cleared||(a<=2147483647?(o.id=globalThis.setTimeout(()=>{o.cleared||t(...r)},a),n&&o.id?.unref?.()):(o.id=globalThis.setTimeout(()=>{let c=performance.now(),f=Math.max(0,i-c);s(f)},2147483647),n&&o.id?.unref?.()))};return s(e),o}function mu(t){!t||typeof t!="object"||!t[hu]||(t.cleared=!0,t.id!==void 0&&(globalThis.clearTimeout(t.id),t.id=void 0))}var zh=new WeakMap;function Hh({clearTimeout:t,setTimeout:e}={}){return(r,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(o.reason);let i,s,a,c=t??clearTimeout,f=()=>{c(i),a(o.reason)},u=()=>{o&&o.removeEventListener("abort",f)},l=new Promise((h,m)=>{s=()=>{u(),h(n)},a=m,i=(e??setTimeout)(s,r)});return o&&o.addEventListener("abort",f,{once:!0}),zh.set(l,()=>{c(i),i=null,s()}),l}}var jh=Hh({setTimeout:pu,clearTimeout:mu}),yu=jh;function gu(t,e,r){let n,o,i=!1;function s(){let f={signal:o.signal},u;r?.timeout!=null&&(u=Xr([o.signal,AbortSignal.timeout(r.timeout)]),f.signal=u),i=!0,Promise.resolve().then(async()=>{await t(f)}).catch(()=>{}).finally(()=>{u!=null&&(u.aborted?u.clear():u.addEventListener("abort",()=>{u.clear()},{once:!0})),i=!1,!o.signal.aborted&&(n=setTimeout(s,e))})}let a=Gr(s,r?.debounce??100),c=!1;return{setInterval:f=>{e!==f&&(e=f,n!=null&&(clearTimeout(n),n=setTimeout(s,e)))},setTimeout:f=>{r??={},r.timeout=f},run:()=>{i||(clearTimeout(n),a())},start:()=>{c||(c=!0,o=new AbortController,o.signal,r?.runImmediately===!0?queueMicrotask(()=>{s()}):n=setTimeout(s,e))},stop:()=>{clearTimeout(n),o?.abort(),c=!1}}}var go=class{routers;localStore;republishTask;log;keychain;started=!1;republishConcurrency;constructor(e,r){this.log=e.logger.forComponent("helia:ipns"),this.localStore=r.localStore,this.keychain=e.keychain,this.republishConcurrency=r.republishConcurrency||ma,this.started=!1,this.routers=r.routers??[],this.republishTask=gu(this.#e.bind(this),r.republishInterval??36e5,{runImmediately:!0}),this.started&&this.republishTask.start()}start(){this.started||(this.started=!0,this.republishTask.start())}stop(){this.started&&(this.started=!1,this.republishTask.stop())}async#e(e={}){if(!this.started)return;this.log("starting ipns republish records loop");let r=new dr({concurrency:this.republishConcurrency});try{let n=[],o=0;for await(let{routingKey:i,record:s,metadata:a,created:c}of this.localStore.list(e)){if(o++,a==null){this.log("no metadata found for record %b, skipping",i);continue}let f;try{f=Q.decode(s)}catch{this.log.trace("skipping invalid record %b because could not decode",i);continue}if(f.data==null){this.log.trace("skipping record %b because data was missing",i);continue}let u;try{u=ke(f.data)}catch{this.log.trace("skipping record %b because could not decode data",i);continue}if(!eu(c,new Date(W(u.Validity)))){this.log.trace("skipping record %b within republish threshold",i);continue}let l=u.Sequence+1n,h=u.TTL??yn,m;try{m=await this.keychain.exportKey(a.keyName)}catch(L){this.log.error("missing key %s, skipping republishing record - %e",a.keyName,L);continue}try{let L=await ur(m,W(u.Value),l,a.lifetime,{...e,ttlNs:h});n.push({routingKey:i,record:L})}catch(L){this.log.error("error creating updated IPNS record for %s - %e",i,L);continue}}this.log(`found ${n.length}/${o} records to republish`);for(let{routingKey:i,record:s}of n)r.add(async()=>{try{let a=Q.encode(s);await Promise.all(this.routers.map(c=>c.put(i,a,e)))}catch(a){this.log.error("error republishing record - %e",a)}},e)}catch(n){this.log.error("error during republish - %e",n)}await r.onIdle(e)}};var Wr;(function(t){let e;t.codec=()=>(e==null&&(e=Ze((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.key!=null&&i.key.byteLength>0&&(s.uint32(10),s.bytes(i.key)),i.value!=null&&i.value.byteLength>0&&(s.uint32(18),s.bytes(i.value)),i.timeReceived!=null&&i.timeReceived!==""&&(s.uint32(42),s.string(i.timeReceived)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={key:Ne(0),value:Ne(0),timeReceived:""},f=s==null?i.len:i.pos+s;for(;i.pos<f;){let u=i.uint32();switch(u>>>3){case 1:{c.key=i.bytes();break}case 2:{c.value=i.bytes();break}case 5:{c.timeReceived=i.string();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let f=s==null?i.len:i.pos+s;for(;i.pos<f;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.key`,value:i.bytes()};break}case 2:{yield{field:`${a}.value`,value:i.bytes()};break}case 5:{yield{field:`${a}.timeReceived`,value:i.string()};break}default:{i.skipType(u&7);break}}}})),e);function r(i){return je(i,t.codec())}t.encode=r;function n(i,s){return He(i,t.codec(),s)}t.decode=n;function o(i,s){return Ye(i,t.codec(),s)}t.stream=o})(Wr||(Wr={}));function bu(t){let e=t.getUTCFullYear(),r=String(t.getUTCMonth()+1).padStart(2,"0"),n=String(t.getUTCDate()).padStart(2,"0"),o=String(t.getUTCHours()).padStart(2,"0"),i=String(t.getUTCMinutes()).padStart(2,"0"),s=String(t.getUTCSeconds()).padStart(2,"0"),a=t.getUTCMilliseconds(),c=String(a*1e3*1e3).padStart(9,"0");return`${e}-${r}-${n}T${o}:${i}:${s}.${c}Z`}function wu(t){let e=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),r=String(t).trim().match(e);if(r==null)throw new Error("Invalid format");let n=parseInt(r[1],10),o=parseInt(r[2],10)-1,i=parseInt(r[3],10),s=parseInt(r[4],10),a=parseInt(r[5],10),c=parseInt(r[6],10),f=parseInt(r[7].slice(0,-6),10);return new Date(Date.UTC(n,o,i,s,a,c,f))}var vt=class t{key;value;timeReceived;constructor(e,r,n){if(!(e instanceof Uint8Array))throw new Error("key must be a Uint8Array");if(!(r instanceof Uint8Array))throw new Error("value must be a Uint8Array");this.key=e,this.value=r,this.timeReceived=n}serialize(){return Wr.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:bu(this.timeReceived)}}static deserialize(e){let r=Wr.decode(e);return new t(r.key,r.value,new Date(r.timeReceived))}static fromDeserialized(e){let r=wu(e.timeReceived);if(e.key==null)throw new Error("key missing from deserialized object");if(e.value==null)throw new Error("value missing from deserialized object");return new t(e.key,e.value,r)}};async function xu(t,e,r,n){let o=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,xe(e),xe(r.subarray()));return n?.signal?.throwIfAborted(),i}var Gh=parseInt("11111",2),as=parseInt("10000000",2),Xh=parseInt("01111111",2),Eu={0:Qr,1:Qr,2:Wh,3:ep,4:tp,5:Jh,6:Qh,16:Qr,22:Qr,48:Qr};function cs(t,e={offset:0}){let r=t[e.offset]&Gh;if(e.offset++,Eu[r]!=null)return Eu[r](t,e);throw new Error("No decoder for tag "+r)}function Jr(t,e){let r=0;if((t[e.offset]&as)===as){let n=t[e.offset]&Xh,o="0x";e.offset++;for(let i=0;i<n;i++,e.offset++){if(e.offset>=t.byteLength)throw new Error("invalid DER element length");o+=t[e.offset].toString(16).padStart(2,"0")}r=parseInt(o,16)}else r=t[e.offset],e.offset++;if(!Number.isInteger(r)||r<0||r>t.byteLength-e.offset)throw new Error("invalid DER element length");return r}function Qr(t,e){Jr(t,e);let r=[];for(;!(e.offset>=t.byteLength);){let n=cs(t,e);if(n===null)break;r.push(n)}return r}function Wh(t,e){let r=Jr(t,e),n=e.offset,o=e.offset+r,i=[];for(let s=n;s<o;s++)s===n&&t[s]===0||i.push(t[s]);return e.offset+=r,Uint8Array.from(i)}function Qh(t,e){let r=Jr(t,e),n=e.offset+r,o=t[e.offset];e.offset++;let i=0,s=0;o<40?(i=0,s=o):o<80?(i=1,s=o-40):(i=2,s=o-80);let a=`${i}.${s}`,c=[];for(;e.offset<n;){let f=t[e.offset];if(e.offset++,c.push(f&127),f<128){c.reverse();let u=0;for(let l=0;l<c.length;l++)u+=c[l]<<l*7;a+=`.${u}`,c=[]}}return a}function Jh(t,e){return e.offset++,null}function ep(t,e){let r=Jr(t,e),n=t[e.offset];e.offset++;let o=t.subarray(e.offset,e.offset+r-1);if(e.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function tp(t,e){let r=Jr(t,e),n=t.subarray(e.offset,e.offset+r);return e.offset+=r,n}function rp(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);let r=new Ie;for(let n=0;n<e.length;n+=2)r.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return r}function us(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);let e=rp(t.byteLength);return new Ie(Uint8Array.from([e.byteLength|as]),e)}function Su(t){let e=new Ie,r=128;return(t.subarray()[0]&r)===r&&e.append(Uint8Array.from([0])),e.append(t),new Ie(Uint8Array.from([2]),us(e),e)}function vu(t){let e=Uint8Array.from([0]),r=new Ie(e,t);return new Ie(Uint8Array.from([3]),us(r),r)}function bo(t,e=48){let r=new Ie;for(let n of t)r.append(n);return new Ie(Uint8Array.from([e]),us(r),r)}var np=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),op=Uint8Array.from([6,5,43,129,4,0,34]),ip=Uint8Array.from([6,5,43,129,4,0,35]),sp={ext:!0,kty:"EC",crv:"P-256"},ap={ext:!0,kty:"EC",crv:"P-384"},cp={ext:!0,kty:"EC",crv:"P-521"},fs=32,ls=48,ds=66;function Au(t){let e=cs(t);return Tu(e)}function Tu(t){let e=t[1][1][0],r=1,n,o;if(e.byteLength===fs*2+1)return n=W(e.subarray(r,r+fs),"base64url"),o=W(e.subarray(r+fs),"base64url"),new hr({...sp,key_ops:["verify"],x:n,y:o});if(e.byteLength===ls*2+1)return n=W(e.subarray(r,r+ls),"base64url"),o=W(e.subarray(r+ls),"base64url"),new hr({...ap,key_ops:["verify"],x:n,y:o});if(e.byteLength===ds*2+1)return n=W(e.subarray(r,r+ds),"base64url"),o=W(e.subarray(r+ds),"base64url"),new hr({...cp,key_ops:["verify"],x:n,y:o});throw new nt(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Bu(t){return bo([Su(Uint8Array.from([1])),bo([up(t.crv)],160),bo([vu(new Ie(Uint8Array.from([4]),se(t.x??"","base64url"),se(t.y??"","base64url")))],161)]).subarray()}function up(t){if(t==="P-256")return np;if(t==="P-384")return op;if(t==="P-521")return ip;throw new nt(`Invalid curve ${t}`)}var hr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Bu(this.jwk)),this._raw}toMultihash(){return Ke.digest(pr(this))}toCID(){return te.createV1(114,this.toMultihash())}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:de(this.raw,e.raw)}async verify(e,r,n){return xu(this.jwk,r,e,n)}};var wo=BigInt(4294967295),Iu=BigInt(32);function fp(t,e=!1){return e?{h:Number(t&wo),l:Number(t>>Iu&wo)}:{h:Number(t>>Iu&wo)|0,l:Number(t&wo)|0}}function Cu(t,e=!1){let r=t.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=fp(t[i],e);[n[i],o[i]]=[s,a]}return[n,o]}var lp=t=>t/2**32|0,dp=t=>t>>>0;function _u(t,e,r,n){let o=lp(r),i=dp(r);t.setUint32(e,n?i:o,n),t.setUint32(e+4,n?o:i,n)}var hs=(t,e,r)=>t>>>r,ps=(t,e,r)=>t<<32-r|e>>>r,Kt=(t,e,r)=>t>>>r|e<<32-r,Vt=(t,e,r)=>t<<32-r|e>>>r,en=(t,e,r)=>t<<64-r|e>>>r-32,tn=(t,e,r)=>t>>>r-32|e<<64-r;function Je(t,e,r,n){let o=(e>>>0)+(n>>>0);return{h:t+r+(o/2**32|0)|0,l:o|0}}var Du=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Ru=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,Lu=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),Nu=(t,e,r,n,o)=>e+r+n+o+(t/2**32|0)|0,Uu=(t,e,r,n,o)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(o>>>0),ku=(t,e,r,n,o,i)=>e+r+n+o+i+(t/2**32|0)|0;function xo(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}var ms=t=>t?`"${t}" `:"";function st(t,e=""){if(typeof t!="number")throw new TypeError(ms(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(ms(e)+"expected integer >= 0, got "+t);return t}function Fe(t,e,r=""){if(xo(t)&&(e===void 0||t.length===e))return t;e!==void 0&&st(e,"length");let n=xo(t),o=e!==void 0?` of length ${e}`:"",i=n?`length=${t.length}`:`type=${typeof t}`,s=ms(r)+"expected Uint8Array"+o+", got "+i;throw n?new RangeError(s):new TypeError(s)}function Eo(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(st(t.outputLen),st(t.blockLen),t.outputLen<1||t.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var Fu=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof t)};function mr(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function So(t,e){Fe(t,void 0,"output");let r=e.outputLen;if(!(t.length>=r))throw new RangeError('"output" expected length >= '+r)}function $t(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function vo(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function $e(t,e){return t<<32-e|t>>>e}var Pu=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",pp=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ao(t){if(Fe(t),Pu)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=pp[t[r]];return e}function Ou(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function To(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Pu)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=t.length,r=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let o=0,i=0;o<r;o++,i+=2){let s=Ou(t.charCodeAt(i)),a=Ou(t.charCodeAt(i+1));if(s===void 0||a===void 0){let c=t[i]+t[i+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function ys(...t){let e=0;for(let n=0;n<t.length;n++){let o=t[n];Fe(o),e+=o.length}let r=new Uint8Array(e);for(let n=0,o=0;n<t.length;n++){let i=t[n];r.set(i,o),o+=i.length}return r}function mp(t,e,r="opts"){return Fu(t,"defaults"),e!==void 0&&Fu(e,r),Object.assign(t,e)}function gs(t,e={}){if(typeof t!="function")throw new TypeError('"hashCons" expected function, got type='+typeof t);e=mp({},e,"info");let r=(o,i)=>t(i).update(o).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=o=>t(o),Object.assign(r,e),Object.freeze(r)}function Mu(t=32){st(t,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(t>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var bs=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function Ku(t,e,r){return t&e^~t&r}function Vu(t,e,r){return t&e^t&r^e&r}var rn=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,o){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=vo(this.buffer)}update(e){mr(this),Fe(e);let{view:r,buffer:n,blockLen:o}=this,i=e.length,s=!1;for(let a=0;a<i;){let c=Math.min(o-this.pos,i-a);if(c===o){let f=vo(e);for(;o<=i-a;a+=o)this.process(f,a);s=!0;continue}n.set(a===0&&c===i?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(r,0),this.pos=0,s=!0)}return this.length+=e.length,s&&this.roundClean(),this}digestInto(e){mr(this),So(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;r[s++]=128,r.fill(0,s),this.padOffset>o-s&&(this.process(n,0),r.fill(0)),_u(n,o-8,this.length*8,i),this.process(n,0),this.roundClean();let a=e===r?n:vo(e),c=this.outputLen,f=c/4,u=this.get();if(c%4||f>u.length)throw new Error("invalid outputLen");for(let l=0;l<f;l++)a.setUint32(4*l,u[l],i)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:r,length:n,finished:o,destroyed:i,pos:s}=this;return e.destroyed=i,e.finished=o,e.length=n,e.pos=s,s&&e.buffer.set(r),e}clone(){return this._cloneInto()}},$u=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var qu=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var yp=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]),At=new Uint32Array(64),ws=class extends rn{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,r){super(64,e,8,!1),this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){let{A:e,B:r,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[e,r,n,o,i,s,a,c]}set(e,r,n,o,i,s,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,r){for(let l=0;l<16;l++,r+=4)At[l]=e.getUint32(r,!1);for(let l=16;l<64;l++){let h=At[l-15],m=At[l-2],L=$e(h,7)^$e(h,18)^h>>>3,v=$e(m,17)^$e(m,19)^m>>>10;At[l]=v+At[l-7]+L+At[l-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:f,H:u}=this;for(let l=0;l<64;l++){let h=$e(a,6)^$e(a,11)^$e(a,25),m=u+h+Ku(a,c,f)+yp[l]+At[l]|0,v=($e(n,2)^$e(n,13)^$e(n,22))+Vu(n,o,i)|0;u=f,f=c,c=a,a=s+m|0,s=i,i=o,o=n,n=m+v|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,u=u+this.H|0,this.set(n,o,i,s,a,c,f,u)}roundClean(){$t(At)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),$t(this.buffer)}},xs=class extends ws{constructor(){super(32,$u)}};var zu=Cu(["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(t=>BigInt(t))),gp=zu[0],bp=zu[1],Tt=new Uint32Array(80),Bt=new Uint32Array(80),Es=class extends rn{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,r){super(128,e,16,!1),this.Ah=r[0]|0,this.Al=r[1]|0,this.Bh=r[2]|0,this.Bl=r[3]|0,this.Ch=r[4]|0,this.Cl=r[5]|0,this.Dh=r[6]|0,this.Dl=r[7]|0,this.Eh=r[8]|0,this.El=r[9]|0,this.Fh=r[10]|0,this.Fl=r[11]|0,this.Gh=r[12]|0,this.Gl=r[13]|0,this.Hh=r[14]|0,this.Hl=r[15]|0}get(){let{Ah:e,Al:r,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:f,El:u,Fh:l,Fl:h,Gh:m,Gl:L,Hh:v,Hl:b}=this;return[e,r,n,o,i,s,a,c,f,u,l,h,m,L,v,b]}set(e,r,n,o,i,s,a,c,f,u,l,h,m,L,v,b){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=f|0,this.El=u|0,this.Fh=l|0,this.Fl=h|0,this.Gh=m|0,this.Gl=L|0,this.Hh=v|0,this.Hl=b|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,r){for(let y=0;y<16;y++,r+=4)Tt[y]=e.getUint32(r),Bt[y]=e.getUint32(r+=4);for(let y=16;y<80;y++){let N=Tt[y-15]|0,U=Bt[y-15]|0,V=Kt(N,U,1)^Kt(N,U,8)^hs(N,U,7),$=Vt(N,U,1)^Vt(N,U,8)^ps(N,U,7),w=Tt[y-2]|0,S=Bt[y-2]|0,I=Kt(w,S,19)^en(w,S,61)^hs(w,S,6),F=Vt(w,S,19)^tn(w,S,61)^ps(w,S,6),x=Lu($,F,Bt[y-7],Bt[y-16]),q=Nu(x,V,I,Tt[y-7],Tt[y-16]);Tt[y]=q|0,Bt[y]=x|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:f,Dl:u,Eh:l,El:h,Fh:m,Fl:L,Gh:v,Gl:b,Hh:E,Hl:B}=this;for(let y=0;y<80;y++){let N=Kt(l,h,14)^Kt(l,h,18)^en(l,h,41),U=Vt(l,h,14)^Vt(l,h,18)^tn(l,h,41),V=l&m^~l&v,$=h&L^~h&b,w=Uu(B,U,$,bp[y],Bt[y]),S=ku(w,E,N,V,gp[y],Tt[y]),I=w|0,F=Kt(n,o,28)^en(n,o,34)^en(n,o,39),x=Vt(n,o,28)^tn(n,o,34)^tn(n,o,39),q=n&i^n&a^i&a,C=o&s^o&c^s&c;E=v|0,B=b|0,v=m|0,b=L|0,m=l|0,L=h|0,{h:l,l:h}=Je(f|0,u|0,S|0,I|0),f=a|0,u=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let A=Du(I,x,C);n=Ru(A,S,F,q),o=A|0}({h:n,l:o}=Je(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=Je(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Je(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l:u}=Je(this.Dh|0,this.Dl|0,f|0,u|0),{h:l,l:h}=Je(this.Eh|0,this.El|0,l|0,h|0),{h:m,l:L}=Je(this.Fh|0,this.Fl|0,m|0,L|0),{h:v,l:b}=Je(this.Gh|0,this.Gl|0,v|0,b|0),{h:E,l:B}=Je(this.Hh|0,this.Hl|0,E|0,B|0),this.set(n,o,i,s,a,c,f,u,l,h,m,L,v,b,E,B)}roundClean(){$t(Tt,Bt)}destroy(){this.destroyed=!0,$t(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Ss=class extends Es{constructor(){super(64,qu)}};var Hu=gs(()=>new xs,bs(1));var vs=gs(()=>new Ss,bs(3));function Io(t,e,r=()=>{}){if(!Array.isArray(t))throw new TypeError(`"${e}" expected array, got type=${typeof t}`);for(let n=0;n<t.length;n++)r(t[n],`${e}[${n}]`);return t}var G=(t,e,r)=>Fe(t,e,r),As=st;function Yu(t,e=""){if(typeof t!="string"){let r=e&&`"${e}" `;throw new TypeError(r+"expected string, got type="+typeof t)}return t}function It(t,e="object"){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof t}`);return t}function qt(t,e){if(typeof t!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof t}`);return t}var nn=Ao,Oe=(...t)=>ys(...t),yr=t=>To(t),_t=xo,zt=t=>Mu(t),Bo=BigInt(0),ju=BigInt(1),wp=t=>t?`"${t}" `:"";function Se(t,e=""){if(typeof t!="boolean")throw new TypeError(wp(e)+"expected boolean, got type="+typeof t);return t}function Co(t){if(typeof t=="bigint"){if(!Ct(t))throw new RangeError("positive bigint expected, got "+t)}else As(t);return t}function Dt(t,e=""){if(typeof t!="number"){let r=e&&`"${e}" `;throw new TypeError(r+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){let r=e&&`"${e}" `;throw new RangeError(r+"expected safe integer, got "+t)}}function on(t){let e=Co(t).toString(16);return e.length&1?"0"+e:e}function Zu(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?Bo:BigInt("0x"+t)}function et(t){return Zu(Ao(t))}function Ht(t){return Zu(Ao(Do(Fe(t)).reverse()))}function _o(t,e){if(st(e),e===0)throw new Error("zero output length is invalid");t=Co(t);let r=e*2,n=t.toString(16);if(n.length>r)throw new RangeError("number is too large");return To(n.padStart(r,"0"))}function Ts(t,e){return _o(t,e).reverse()}function Do(t){return Uint8Array.from(G(t))}function Ct(t){return typeof t=="bigint"&&Bo<=t}function Bs(t,e,r){return Ct(t)&&Ct(e)&&Ct(r)&&e<=t&&t<r}function gr(t,e,r,n){if(!Bs(e,r,n))throw new RangeError("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function br(t){if(t<Bo)throw new Error("expected non-negative bigint, got "+t);return t===Bo?0:t.toString(2).length}var sn=t=>(Dt(t,"n"),(ju<<BigInt(t))-ju);function Gu(t,e,r){if(st(t,"hashLen"),st(e,"qByteLen"),typeof r!="function")throw new TypeError("hmacFn must be a function");let n=b=>new Uint8Array(b),o=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1e3,c=n(t),f=n(t),u=0,l=()=>{c.fill(1),f.fill(0),u=0},h=(...b)=>r(f,Oe(c,...b)),m=(b=o)=>{f=h(i,b),c=h(),b.length!==0&&(f=h(s,b),c=h())},L=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let b=0,E=[];for(;b<e;){c=h();let B=c.slice();E.push(B),b+=c.length}return Oe(...E)};return(b,E)=>{l(),m(b);let B;for(;(B=E(L()))===void 0;)m();return l(),B}}function ve(t,e={},r={},n="object"){It(t,n),It(e,"fields"),It(r,"optFields");function o(s,a,c){let f=n==="object"?`param "${String(s)}"`:`"${n}.${String(s)}"`,u=t[s];if(!Object.hasOwn(t,s)&&(c?u!==void 0:a!=="function"))throw new TypeError(`${f} is invalid: expected own property`);if(c&&u===void 0)return;let l=typeof u;if(l!==a||u===null)throw new TypeError(`${f} is invalid: expected ${a}, got ${l}`)}let i=(s,a)=>Object.entries(s).forEach(([c,f])=>o(c,f,a));i(e,!1),i(r,!0)}var le=BigInt(0),X=BigInt(1),Rt=BigInt(2),Qu=BigInt(3),Is=BigInt(4),Ju=BigInt(5),xp=BigInt(7),ef=BigInt(8),Ep=BigInt(9),Sp=BigInt(15),tf=BigInt(16),vp=BigInt("0x10000000000000000");function re(t,e){if(e<=le)throw new Error("mod: expected positive modulus, got "+e);let r=t%e;return r>=le?r:e+r}function rf(t,e,r){if(r<=X)throw new Error("pow: expected modulus > 1, got "+r);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<le)throw new Error("invalid exponent, negatives unsupported");if(e===le)return X;if(e===X)return t;let n=t%r;if(n<le&&(n+=r),e<vp){let a=X;for(;e>le;)e&X&&(a=a*n%r),n=n*n%r,e>>=X;return a}let o=[];for(;e>le;)o.push(Number(e&Sp)),e>>=Is;let i=new Array(16);i[0]=X,i[1]=n;for(let a=2;a<16;a++)i[a]=i[a-1]*n%r;let s=i[o[o.length-1]];for(let a=o.length-2;a>=0;a--){s=s*s%r,s=s*s%r,s=s*s%r,s=s*s%r;let c=o[a];c!==0&&(s=s*i[c]%r)}return s}function ee(t,e,r){if(r<=X)throw new Error("pow2: expected modulus > 1, got "+r);if(e<le)throw new Error("pow2: expected non-negative exponent, got "+e);let n=t;for(;e-- >le;)n*=n,n%=r;return n}function Xu(t,e){if(t===le)throw new Error("invert: expected non-zero number");if(e<=X)throw new Error("invert: expected modulus > 1, got "+e);let r=re(t,e),n=e,o=le,i=X;for(;r!==le;){let a=n/r,c=n-r*a,f=o-i*a;n=r,r=c,o=i,i=f}if(n!==X)throw new Error("invert: does not exist");return re(o,e)}function nf(t,e){if(e<=X)throw new Error("invertCt: expected prime modulus > 1, got "+e);let r=re(t,e);if(r===le)throw new Error("invertCt: expected non-zero number");let n=rf(r,e-Rt,e);if(re(r*n,e)!==X)throw new Error("invertCt: does not exist");return n}function Cs(t,e,r){let n=t;if(!n.eql(n.sqr(e),r))throw new Error("Cannot find square root")}function _s(t,e){if((t&X)===le)throw new Error(e+": expected odd modulus, got "+t)}function of(t,e){let r=t,n=(r.ORDER+X)/Is,o=r.pow(e,n);return Cs(r,o,e),o}function Ap(t,e){let r=t,n=(r.ORDER-Ju)/ef,o=r.mul(e,Rt),i=r.pow(o,n),s=r.mul(e,i),a=r.mul(r.mul(s,Rt),i),c=r.mul(s,r.sub(a,r.ONE));return Cs(r,c,e),c}function Tp(t){let e=xr(t),r=sf(t),n=r(e,e.neg(e.ONE)),o=r(e,n),i=r(e,e.neg(n)),s=(t+xp)/tf;return((a,c)=>{let f=a,u=f.pow(c,s),l=f.mul(u,n),h=f.mul(u,o),m=f.mul(u,i),L=f.eql(f.sqr(l),c),v=f.eql(f.sqr(h),c);u=f.cmov(u,l,L),l=f.cmov(m,h,v);let b=f.eql(f.sqr(l),c),E=f.cmov(u,l,b);return Cs(f,E,c),E})}function sf(t){if(t<Qu)throw new Error("sqrt is not defined for small field");_s(t,"tonelliShanks");let e=t-X,r=0;for(;e%Rt===le;)e/=Rt,r++;let n=Rt,o=xr(t);for(;an(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return of;let i=o.pow(n,e),s=(e+X)/Rt;return function(c,f){let u=c;if(u.is0(f))return f;if(an(u,f)!==1)throw new Error("Cannot find square root");let l=r,h=u.mul(u.ONE,i),m=u.pow(f,e),L=u.pow(f,s);for(;!u.eql(m,u.ONE);){if(u.is0(m))throw new Error("Cannot find square root: probably non-prime P");let v=1,b=u.sqr(m);for(;!u.eql(b,u.ONE);)if(v++,b=u.sqr(b),v===l)throw new Error("Cannot find square root");let E=X<<BigInt(l-v-1),B=u.pow(h,E);l=v,h=u.sqr(B),m=u.mul(m,h),L=u.mul(L,B)}return L}}function Bp(t){return _s(t,"Fp.sqrt"),t%Is===Qu?of:t%ef===Ju?Ap:t%tf===Ep?Tp(t):sf(t)}var af=(t,e)=>(re(t,e)&X)===X,Ip=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function wr(t){if(It(t,"field"),typeof t.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof t.ORDER);Dt(t.BYTES,"BYTES"),Dt(t.BITS,"BITS");for(let e of Ip)qt(t[e],"field."+e);if(t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=X)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function Lo(t,e,r=!1){wr(t),Io(e,"nums"),Se(r,"passZero");let n=t,o=new Array(e.length).fill(r?n.ZERO:void 0),i=e.reduce((a,c,f)=>n.is0(c)?a:(o[f]=a,n.mul(a,c)),n.ONE),s=n.inv(i);return e.reduceRight((a,c,f)=>n.is0(c)?a:(o[f]=n.mul(a,o[f]),n.mul(a,c)),s),o}function an(t,e){wr(t);let r=t;_s(r.ORDER,"FpLegendre");let n=(r.ORDER-X)/Rt,o=r.pow(e,n),i=r.eql(o,r.ONE),s=r.eql(o,r.ZERO),a=r.eql(o,r.neg(r.ONE));if(!i&&!s&&!a)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function Cp(t,e){if(e!==void 0&&As(e),t<=le)throw new Error("invalid n length: expected positive n, got "+t);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let r=br(t);if(e!==void 0&&e<r)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${r})`);let n=e!==void 0?e:r,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var Wu=new WeakMap,Ro=class{ORDER;BITS;BYTES;isLE;ZERO=le;ONE=X;_lengths;_mod;constructor(e,r={}){if(e<=X)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:r.sqrt,enumerable:!0}),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=Object.freeze(r.allowedLengths.slice())),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:o,nByteLength:i}=Cp(e,n);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=i,Object.freeze(this)}create(e){return re(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return le<=e&&e<this.ORDER}is0(e){return e===le}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&X)===X}neg(e){return re(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return re(e*e,this.ORDER)}add(e,r){return re(e+r,this.ORDER)}sub(e,r){return re(e-r,this.ORDER)}mul(e,r){return re(e*r,this.ORDER)}pow(e,r){return rf(e,r,this.ORDER)}div(e,r){return re(e*Xu(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return Xu(e,this.ORDER)}sqrt(e){let r=Wu.get(this);return r||Wu.set(this,r=Bp(this.ORDER)),r(this,e)}toBytes(e){return this.isLE?Ts(e,this.BYTES):_o(e,this.BYTES)}fromBytes(e,r=!1){G(e);let{_lengths:n,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let f=new Uint8Array(o);f.set(e,i?0:f.length-e.length),e=f}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=i?Ht(e):et(e);if(a&&(c=re(c,s)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Lo(this,e,!0)}cmov(e,r,n){return Se(n,"condition"),n?r:e}};function xr(t,e={}){return Object.freeze(Ro.prototype),new Ro(t,e)}function cf(t){if(typeof t!="bigint")throw new Error("field order must be bigint");if(t<=X)throw new Error("field order must be greater than 1");let e=br(t-X);return Math.ceil(e/8)}function No(t){let e=cf(t);return e+Math.ceil(e/2)}function Uo(t,e,r=!1){G(t);let n=t.length,o=cf(e),i=Math.max(No(e),16);if(n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=r?Ht(t):et(t),a=re(s,e-X)+X;return r?Ts(a,o):_o(a,o)}var Ls=BigInt(0),cn=BigInt(1),_p=BigInt(4),Ds=16,uf=128,Dp=5,ff=2**31;function Lt(t){let e=t;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof t);qt(e.fromAffine,"Point.fromAffine"),qt(e.fromBytes,"Point.fromBytes"),qt(e.fromHex,"Point.fromHex"),It(e.BASE,"Point.BASE"),It(e.ZERO,"Point.ZERO"),wr(e.Fp),wr(e.Fn)}function ko(t,e){Lt(t),df(e,t);let r=Lo(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function Rp(t,e,r=1){if(!Number.isSafeInteger(t)||t<r||t>e)throw new Error("invalid window size, expected ["+r+".."+e+"], got W="+t)}function Lp(t,e){let r=t*(4*e+128);if(r>ff)throw new Error("invalid window size: table would need ~"+Math.ceil(r/2**20)+" MiB, max "+ff/2**20+" MiB")}function Ns(t,e){if(t!==void 0){qt(t,"randomBytes");try{let r=t(e);if(!_t(r)||r.length!==e)return}catch{return}return t}}function df(t,e){Io(t,"points"),t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function Np(t,e,r){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,o)=>{if(!(r===void 0?e.isValid(n):Ct(n)&&n<r))throw new Error("invalid scalar at index "+o)})}var hf=new WeakMap;function Rs(t){return hf.get(t)||1}function Up(t,e){let r=t.double(),n=[t];for(let o=1;o<e;o++)n.push(n[o-1].add(r));return n}function kp(t,e){let r=2**e,n=r/2,o=BigInt(r-1),i=[];for(;t>Ls;){let s=0;t&cn&&(s=Number(t&o),s>=n&&(s-=r),t-=BigInt(s)),i.push(s),t>>=cn}return i}function Fp(t,e,r){let n=2**e,o=n/2,i=BigInt(n-1),s=BigInt(e),a=[];for(let c=0;c<r;c++){let f=Number(t&i);t>>=s,f>o&&(f-=n,t+=cn),a.push(f)}if(t!==Ls)throw new Error("invalid wnaf");return a}function Op(t,e,r){let n=0;for(let i of r)n=Math.max(n,i.length);let o=t;for(let i=n-1;i>=0;i--){i!==n-1&&(o=o.double());for(let s=0;s<r.length;s++){let a=r[s][i];if(a){let c=e[s][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}var Er=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,r){Lt(e),this.randomBytes=Ns(r,Ds),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,r,n){let o=Math.ceil(n/r)+1,i=2**(r-1),s=[],a=e;for(let c=0;c<o;c++){let f=a;for(let u=0;u<i;u++)s.push(f),f=f.add(a);a=s[s.length-1].double()}return{W:r,bits:n,windows:o,comp:s}}wnafCachedCT(e,r){let{W:n,windows:o,comp:i}=e,s=2**(n-1),a=Fp(r,n,o),c=this.ZERO,f=this.BASE;for(let u=0;u<o;u++){let l=a[u],h=u*s,m=Math.abs(l)-1,L=i[h];for(let b=1;b<s;b++)L=b===m?i[h+b]:L;let v=L.negate();l===0?f=f.add(i[h]):c=c.add(l<0?v:L)}return{p:c,f}}getWnafPrecomputes(e,r,n,o){let i=this.wnafPrecomputes.get(r),s=i?.find(a=>a.W===e&&a.bits===n);return s||(s=this.buildWnafTable(r,e,n),typeof o=="function"&&(s={...s,comp:o(s.comp)}),i||(i=[],this.wnafPrecomputes.set(r,i)),i.push(s)),s}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,r){if(this.assertPoint(e),!Bs(r,cn,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,r,n,o){let i=Rs(e);return i===1?this.fixedWindowCT(e,r,n):this.wnafCachedCT(this.getWnafPrecomputes(i,e,n,o),r)}mulCT(e,r,n){return this.validateMulInput(e,r),this.runCT(e,r,this.bits,n)}mulCTBlinded(e,r,n){if(this.validateMulInput(e,r),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let o=this.Point.Fn.BITS+uf,i=this.randomBytes(Ds);if(!_t(i)||i.length!==Ds)throw new Error("randomBytes returned invalid byte array");i[0]=i[0]&63|128;let s=r+et(i)*this.Point.Fn.ORDER;return this.runCT(e,s,o,n)}fixedWindowCT(e,r,n){let o=Dp,i=1<<o,s=sn(o),a=new Array(i);a[0]=this.ZERO;for(let u=1;u<i;u++)a[u]=a[u-1].add(e);let c=Math.ceil(n/o),f=this.ZERO;for(let u=c-1;u>=0;u--){if(u!==c-1)for(let m=0;m<o;m++)f=f.double();let l=Number(r>>BigInt(u*o)&s),h=a[0];for(let m=1;m<i;m++)h=m===l?a[m]:h;f=f.add(h)}return{p:f,f}}shouldBlind(e,r){return this.randomBytes===void 0?!1:r===cn?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,r,n,o){return this.shouldBlind(e,n)?this.mulCTBlinded(e,r,o):this.mulCT(e,r,o)}mulUnsafe(e,r,n){if(this.assertPoint(e),!Ct(r))throw new Error("invalid scalar");let o=Rs(e);if(o===1||r>=this.Point.Fn.ORDER)return Fo(this.Point,[e],[r],!0);let i=this.getWnafPrecomputes(o,e,this.bits,n);return this.wnafCachedCT(i,r).p}setWindowSize(e,r){this.assertPoint(e),Rp(r,this.bits);let n=Math.ceil((this.bits+uf)/r)+1;Lp(n*2**(r-1),this.Point.Fp.BYTES),hf.set(e,r),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Rs(e)!==1}};function Fo(t,e,r,n=!1){if(Lt(t),df(e,t),Se(n,"allowOversized"),Np(r,t.Fn,n?t.Fn.ORDER**_p:void 0),e.length!==r.length)throw new Error("arrays of points and scalars must have equal length");let o=e.map(s=>Up(s,4)),i=r.map(s=>kp(s,4));return Op(t.ZERO,o,i)}function lf(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return wr(e),e}else return xr(t,{isLE:r})}function Oo(t,e,r={},n){if(t!=="weierstrass"&&t!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);ve(r);for(let c of["p","n","h"]){let f=e[c];if(!(Ct(f)&&f!==Ls))throw new Error(`CURVE.${c} must be positive bigint`)}let o=lf(e.p,r.Fp,n),i=lf(e.n,r.Fn,n),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:i}}function Po(t,e){return function(n){let o=t(n);return{secretKey:o,publicKey:e(o)}}}var Mo=BigInt(0),Ko=BigInt(1),Vo=BigInt(2),Pp=BigInt(4),pf=BigInt(8);function Mp(t,e,r,n){let o=t.sqr(r),i=t.sqr(n),s=t.add(t.mul(e.a,o),i),a=t.add(t.ONE,t.mul(e.d,t.mul(o,i)));return t.eql(s,a)}function mf(t,e={}){ve(e,{},{},"extraOpts");let r=e,n=Oo("edwards",t,r,r.FpFnLE),{Fp:o,Fn:i}=n,s=n.CURVE,{h:a}=s;if(an(o,s.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(an(o,s.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");ve(r,{},{uvRatio:"function",randomBytes:"function"});let c=r.randomBytes===void 0?zt:r.randomBytes,f=Vo<<BigInt(o.BYTES*8)-Ko;function u(B){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(B)}let l=r.uvRatio===void 0?(B,y)=>{try{return{isValid:!0,value:o.sqrt(o.div(B,y))}}catch{return{isValid:!1,value:Mo}}}:r.uvRatio;if(!Mp(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");let h=o.eql(s.a,o.neg(o.ONE))?B=>o.neg(B):o.eql(s.a,o.ONE)?B=>B:B=>o.mul(s.a,B);function m(B,y,N=!1){let U=N?Ko:Mo;return gr("coordinate "+B,y,U,f),y}function L(B){if(!(B instanceof v))throw new Error("EdwardsPoint expected")}class v{static BASE=new v(s.Gx,s.Gy,o.ONE,o.mul(s.Gx,s.Gy));static ZERO=new v(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=i;X;Y;Z;T;constructor(y,N,U,V){this.X=m("x",y),this.Y=m("y",N),this.Z=m("z",U,!0),this.T=m("t",V),Object.freeze(this)}static CURVE(){return s}static fromAffine(y){if(y instanceof v)throw new Error("extended point not allowed");let{x:N,y:U}=y||{};return m("x",N),m("y",U),new v(N,U,o.ONE,o.mul(N,U))}static fromBytes(y,N=!1){let U=o.BYTES,{a:V,d:$}=s;y=Do(G(y,U,"point")),Se(N,"zip215");let w=Do(y),S=y[U-1];w[U-1]=S&-129;let I=Ht(w),F=N?f:o.ORDER;gr("point.y",I,Mo,F);let x=o.sqr(I),q=o.sub(x,o.ONE),C=o.sub(o.mulN($,x),V),{isValid:A,value:p}=l(q,C);if(!A)throw new Error("bad point: invalid y coordinate");let T=u(p),_=(S&128)!==0;if(!N&&o.is0(p)&&_)throw new Error("bad point: x=0 and x_0=1");return _!==T&&(p=o.neg(p)),v.fromAffine({x:p,y:I})}static fromHex(y,N=!1){return v.fromBytes(yr(y),N)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=6,N=!0){return E.setWindowSize(this,y),N||this.multiply(Vo),this}assertValidity(){let y=this,{a:N,d:U}=s;if(y.is0())throw new Error("bad point: ZERO");let{X:V,Y:$,Z:w,T:S}=y,I=o.sqr(V),F=o.sqr($),x=o.sqr(w),q=o.sqr(x),C=o.mul(I,N),A=o.mul(o.add(C,F),x),p=o.add(q,o.mul(U,o.mul(I,F)));if(!o.eql(A,p))throw new Error("bad point: equation left != right (1)");let T=o.mul(V,$),_=o.mul(w,S);if(!o.eql(T,_))throw new Error("bad point: equation left != right (2)")}equals(y){L(y);let{X:N,Y:U,Z:V}=this,{X:$,Y:w,Z:S}=y,I=o.mul(N,S),F=o.mul($,V),x=o.mul(U,S),q=o.mul(w,V);return o.eql(I,F)&&o.eql(x,q)}is0(){return this.equals(v.ZERO)}negate(){return new v(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){let{X:y,Y:N,Z:U}=this,V=o.sqr(y),$=o.sqr(N),w=o.mul(o.sqr(U),Vo),S=h(V),I=o.addN(y,N),F=o.sub(o.subN(o.sqr(I),V),$),x=o.addN(S,$),q=o.subN(x,w),C=o.subN(S,$),A=o.mul(F,q),p=o.mul(x,C),T=o.mul(F,C),_=o.mul(q,x);return new v(A,p,_,T)}add(y){L(y);let{d:N}=s,{X:U,Y:V,Z:$,T:w}=this,{X:S,Y:I,Z:F,T:x}=y,q=o.mul(U,S),C=o.mul(V,I),A=o.mul(o.mulN(w,N),x),p=o.mul($,F),T=o.sub(o.subN(o.mulN(o.addN(U,V),o.addN(S,I)),q),C),_=o.subN(p,A),M=o.addN(p,A),D=o.sub(C,h(q)),g=o.mul(T,_),O=o.mul(M,D),P=o.mul(T,D),z=o.mul(_,M);return new v(g,O,z,P)}subtract(y){return L(y),this.add(y.negate())}multiply(y){if(!i.isValidNot0(y))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:N,f:U}=E.mulSecret(this,y,a,b);return b([N,U])[0]}multiplyUnsafe(y){if(!i.isValid(y))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return y===Mo?v.ZERO:this.is0()||y===Ko?this:E.mulUnsafe(this,y,b)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return E.mulUnsafe(this,s.n).is0()}toAffine(y){let N=this,U=y;if(U!=null&&typeof U!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof U);let{X:V,Y:$,Z:w}=N,S=N.is0();U==null&&(U=S?o.create(pf):o.inv(w));let I=o.mul(V,U),F=o.mul($,U),x=o.mul(w,U);if(S)return{x:o.ZERO,y:o.ONE};if(!o.eql(x,o.ONE))throw new Error("invZ was invalid");return{x:I,y:F}}clearCofactor(){return a===Ko?this:a===Vo?this.double():a===Pp?this.double().double():a===pf?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:y,y:N}=this.toAffine(),U=o.toBytes(N);return U[U.length-1]|=u(y)?128:0,U}toHex(){return nn(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let b=B=>ko(v,B),E=new Er(v,c);return E.bits>=6&&v.BASE.precompute(6),Object.freeze(v.prototype),Object.freeze(v),v}function yf(t,e,r={}){if(Lt(t),typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=r;ve(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:i}=o,{BASE:s,Fp:a,Fn:c}=t,f=n.outputLen,u=2*a.BYTES;if(f!==void 0&&(Dt(f,"hash.outputLen"),f!==u))throw new Error(`hash.outputLen must be ${u}, got ${f}`);let l=o.randomBytes===void 0?zt:o.randomBytes,h=o.toMontgomery,m=o.toMontgomerySecret,L=o.adjustScalarBytes===void 0?C=>C:o.adjustScalarBytes,v=o.domain===void 0?(C,A,p)=>{if(Se(p,"phflag"),A.length||p)throw new Error("Contexts/pre-hash are not supported");return C}:o.domain;function b(C){return c.create(Ht(C))}function E(C){let A=S.secretKey;G(C,S.secretKey,"secretKey");let p=G(n(C),2*A,"hashedSecretKey"),T=L(p.slice(0,A)),_=p.slice(A,2*A),M=b(T);return{head:T,prefix:_,scalar:M}}function B(C){let{head:A,prefix:p,scalar:T}=E(C),_=s.multiply(T),M=_.toBytes();return{head:A,prefix:p,scalar:T,point:_,pointBytes:M}}function y(C){return B(C).pointBytes}function N(C=Uint8Array.of(),...A){let p=Oe(...A);return b(n(v(p,G(C,void 0,"context"),!!i)))}function U(C,A,p={}){ve(p,{},{},"options"),C=G(C,void 0,"message"),i&&(C=i(C));let{prefix:T,scalar:_,pointBytes:M}=B(A),D=N(p.context,T,C),g=s.multiply(D).toBytes(),O=N(p.context,g,M,C),P=c.create(D+O*_);if(!c.isValid(P))throw new Error("sign failed: invalid s");let z=Oe(g,c.toBytes(P));return G(z,S.signature,"result")}let V={zip215:o.zip215};function $(C,A,p,T=V){ve(T);let{context:_}=T,M=T.zip215===void 0?!!V.zip215:T.zip215,D=S.signature;C=G(C,D,"signature"),A=G(A,void 0,"message"),p=G(p,S.publicKey,"publicKey"),M!==void 0&&Se(M,"zip215"),i&&(A=i(A));let g=D/2,O=C.subarray(0,g),P=Ht(C.subarray(g,D)),z,H,Z;try{z=t.fromBytes(p,M),H=t.fromBytes(O,M),Z=s.multiplyUnsafe(P)}catch{return!1}if(!M&&z.isSmallOrder())return!1;let Y=N(_,O,p,A);return H.add(z.multiplyUnsafe(Y)).subtract(Z).clearCofactor().is0()}let w=a.BYTES,S={secretKey:w,publicKey:w,signature:2*w,seed:w};function I(C){return C=C===void 0?l(S.seed):C,G(C,S.seed,"seed")}function F(C){return _t(C)&&C.length===S.secretKey}function x(C,A){try{return!!t.fromBytes(C,A===void 0?V.zip215:A)}catch{return!1}}let q={getExtendedPublicKey:B,randomSecretKey:I,isValidSecretKey:F,isValidPublicKey:x,toMontgomery(C){if(h===void 0)throw new Error("Montgomery conversion is not supported for this curve");return h(t.fromBytes(C))},toMontgomerySecret(C){if(m===void 0)throw new Error("Montgomery conversion is not supported for this curve");return m(C)}};return Object.freeze(S),Object.freeze(q),Object.freeze({keygen:Po(I,y),getPublicKey:y,sign:U,verify:$,utils:q,Point:t,lengths:S})}var Us=BigInt(1),gf=BigInt(2);var Kp=BigInt(5),Vp=BigInt(8),ks=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),$p={p:ks,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Vp,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function qp(t){let e=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),i=ks,a=t*t%i*t%i,c=ee(a,gf,i)*a%i,f=ee(c,Us,i)*t%i,u=ee(f,Kp,i)*f%i,l=ee(u,e,i)*u%i,h=ee(l,r,i)*l%i,m=ee(h,n,i)*h%i,L=ee(m,o,i)*m%i,v=ee(L,o,i)*m%i,b=ee(v,e,i)*u%i;return{pow_p_5_8:ee(b,gf,i)*t%i,b2:a}}function xf(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}var bf=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function zp(t,e){let r=ks,n=re(e*e*e,r),o=re(n*n*e,r),i=qp(t*o).pow_p_5_8,s=re(t*n*i,r),a=re(e*s*s,r),c=s,f=re(s*bf,r),u=a===t,l=a===re(-t,r),h=a===re(-t*bf,r);return u&&(s=c),(l||h)&&(s=f),af(s,r)&&(s=re(-s,r)),{isValid:u||l,value:s}}var Fs=mf($p,{uvRatio:zp}),wf=Fs.Fp;function Hp(t){let{y:e}=t;return wf.toBytes(wf.div(Us+e,Us-e))}function jp(t){let e=Fs.Fp.BYTES;return Fe(t,e),xf(vs(t.subarray(0,e))).subarray(0,e)}function Yp(t){return yf(Fs,vs,Object.assign({adjustScalarBytes:xf,toMontgomery:Hp,toMontgomerySecret:jp,zip215:!0},t))}var Ef=Yp({});var un=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},$o=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var qo={get(t=globalThis){let e=t.crypto;if(e?.subtle==null)throw new $o("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var zo=32;var Os,Zp=(async()=>{try{return await qo.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Gp(t,e,r){if(t.buffer instanceof ArrayBuffer){let n=await qo.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await qo.get().subtle.verify({name:"Ed25519"},n,xe(e),xe(r instanceof Uint8Array?r:r.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Xp(t,e,r){return Ef.verify(e,r instanceof Uint8Array?r:r.subarray(),t)}async function Sf(t,e,r){return Os==null&&(Os=await Zp),Os?Gp(t,e,r):Xp(t,e,r)}function Ho(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var jo=class{type="Ed25519";raw;constructor(e){this.raw=Ps(e,zo)}toMultihash(){return Ke.digest(pr(this))}toCID(){return te.createV1(114,this.toMultihash())}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:de(this.raw,e.raw)}verify(e,r,n){n?.signal?.throwIfAborted();let o=Sf(this.raw,r,e);return Ho(o)?o.then(i=>(n?.signal?.throwIfAborted(),i)):o}};function Af(t){return t=Ps(t,zo),new jo(t)}function Ps(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new nt(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}var be;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(be||(be={}));var Ms;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(Ms||(Ms={}));(function(t){t.codec=()=>Fr(Ms)})(be||(be={}));var fn;(function(t){let e;t.codec=()=>(e==null&&(e=Ze((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.Type!=null&&(s.uint32(8),be.codec().encode(i.Type,s)),i.Data!=null&&(s.uint32(18),s.bytes(i.Data)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={},f=s==null?i.len:i.pos+s;for(;i.pos<f;){let u=i.uint32();switch(u>>>3){case 1:{c.Type=be.codec().decode(i);break}case 2:{c.Data=i.bytes();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let f=s==null?i.len:i.pos+s;for(;i.pos<f;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:be.codec().decode(i)};break}case 2:{yield{field:`${a}.Data`,value:i.bytes()};break}default:{i.skipType(u&7);break}}}})),e);function r(i){return je(i,t.codec())}t.encode=r;function n(i,s){return He(i,t.codec(),s)}t.decode=n;function o(i,s){return Ye(i,t.codec(),s)}t.stream=o})(fn||(fn={}));var Ks;(function(t){let e;t.codec=()=>(e==null&&(e=Ze((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.Type!=null&&(s.uint32(8),be.codec().encode(i.Type,s)),i.Data!=null&&(s.uint32(18),s.bytes(i.Data)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={},f=s==null?i.len:i.pos+s;for(;i.pos<f;){let u=i.uint32();switch(u>>>3){case 1:{c.Type=be.codec().decode(i);break}case 2:{c.Data=i.bytes();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let f=s==null?i.len:i.pos+s;for(;i.pos<f;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:be.codec().decode(i)};break}case 2:{yield{field:`${a}.Data`,value:i.bytes()};break}default:{i.skipType(u&7);break}}}})),e);function r(i){return je(i,t.codec())}t.encode=r;function n(i,s){return He(i,t.codec(),s)}t.decode=n;function o(i,s){return Ye(i,t.codec(),s)}t.stream=o})(Ks||(Ks={}));var Yo=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,r){if(Eo(e),Fe(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),$t(o)}update(e){return mr(this),this.iHash.update(e),this}digestInto(e){mr(this),So(e,this),this.finished=!0;let r=e.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a,canXOF:c}=this;return e=e,e.finished=o,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.canXOF=c,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Tf=(()=>{let t=((e,r,n)=>new Yo(e,r).update(n).digest());return t.create=(e,r)=>new Yo(e,r),t})();var Jp=BigInt(0),Vs=class extends Error{constructor(e=""){super(e)}},at={Err:Vs,_tlv:{encode:(t,e)=>{let{Err:r}=at;if(Dt(t,"tag"),t<0||t>255)throw new r("tlv.encode: wrong tag");if(Yu(e,"data"),e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,o=on(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let i=n>127?on(o.length/2|128):"";return on(t)+i+o+e},decode(t,e){let{Err:r}=at;e=G(e,void 0,"DER data");let n=0;if(t<0||t>255)throw new r("tlv.decode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let o=e[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let f=e.subarray(n,n+c);if(f.length!==c)throw new r("tlv.decode: length bytes not complete");if(f[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let u of f)s=s<<8|u;if(n+=c,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+s)}}},_int:{encode(t){let{Err:e}=at;if(Co(t),t<Jp)throw new e("integer: negative integers are not allowed");let r=on(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=at;if(t.length<1)throw new e("invalid signature integer: empty");if(t[0]&128)throw new e("invalid signature integer: negative");if(t.length>1&&t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return et(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=at,o=G(t,void 0,"signature"),{v:i,l:s}=n.decode(48,o);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:f,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(f)}},hexFromSig(t){let{_tlv:e,_int:r}=at;ve(t,{r:"bigint",s:"bigint"},{},"sig");let n=e.encode(2,r.encode(t.r)),o=e.encode(2,r.encode(t.s)),i=n+o;return e.encode(48,i)}},$s=(Object.freeze(at._tlv),Object.freeze(at._int),Object.freeze(at));var Bf=(t,e)=>(t+(t>=0?e:-e)/If)/e;function em(t,e,r){gr("scalar",t,ct,r);let[[n,o],[i,s]]=e,a=Bf(s*t,r),c=Bf(-o*t,r),f=t-a*n-c*i,u=-a*o-c*s,l=f<ct,h=u<ct;l&&(f=-f),h&&(u=-u);let m=sn(Math.ceil(br(r)/2))+jt;if(f<ct||f>=m||u<ct||u>=m)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:l,k1:f,k2neg:h,k2:u}}function Hs(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function qs(t,e){ve(t);let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Se(r.lowS,"lowS"),Se(r.prehash,"prehash"),r.format!==void 0&&Hs(r.format),r}var ct=BigInt(0),jt=BigInt(1),If=BigInt(2),zs=BigInt(3),tm=BigInt(4);function Cf(t,e={}){let r=Oo("weierstrass",t,e),n=r.Fp,o=r.Fn,i=r.CURVE,{h:s,n:a}=i;ve(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:f}=e,u=e.randomBytes===void 0?zt:e.randomBytes;if(c&&(!n.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=Df(n,o);function h(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function m(A,p,T){if(f&&p.is0())return Uint8Array.of(0);let{x:_,y:M}=p.toAffine(),D=n.toBytes(_);if(Se(T,"isCompressed"),T){h();let g=!n.isOdd(M);return Oe(_f(g),D)}else return Oe(Uint8Array.of(4),D,n.toBytes(M))}function L(A){G(A,void 0,"Point");let{publicKey:p,publicKeyUncompressed:T}=l,_=A.length,M=A[0],D=A.subarray(1);if(f&&_===1&&M===0)return{x:n.ZERO,y:n.ZERO};if(_===p&&(M===2||M===3)){let g=n.fromBytes(D);if(!n.isValid(g))throw new Error("bad point: is not on curve, wrong x");let O=y(g),P;try{P=n.sqrt(O)}catch(Z){let Y=Z instanceof Error?": "+Z.message:"";throw new Error("bad point: is not on curve, sqrt error"+Y)}h();let z=n.isOdd(P);return(M&1)===1!==z&&(P=n.neg(P)),{x:g,y:P}}else if(_===T&&M===4){let g=n.BYTES,O=n.fromBytes(D.subarray(0,g)),P=n.fromBytes(D.subarray(g,g*2));if(!N(O,P))throw new Error("bad point: is not on curve");return{x:O,y:P}}else throw new Error(`bad point: got length ${_}, expected compressed=${p} or uncompressed=${T}`)}let v=e.toBytes===void 0?m:e.toBytes,b=e.fromBytes===void 0?L:e.fromBytes,E=n.mul(i.b,zs),B=n.is0(i.a)?A=>n.ZERO:A=>n.mul(i.a,A);function y(A){let p=n.sqr(A),T=n.mul(p,A);return n.add(n.add(T,n.mul(A,i.a)),i.b)}function N(A,p){let T=n.sqr(p),_=y(A);return n.eql(T,_)}if(!N(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let U=n.mul(n.pow(i.a,zs),tm),V=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(U,V)))throw new Error("bad curve params: a or b");function $(A,p,T=!1){if(!n.isValid(p)||T&&n.is0(p))throw new Error(`bad point coordinate ${A}`);return p}function w(A){if(!(A instanceof x))throw new Error("Weierstrass Point expected")}function S(A){if(!c||!c.basises)throw new Error("no endo");return em(A,c.basises,o.ORDER)}function I(A,p,T,_){if(!o.isValid(_))throw new RangeError("invalid scalar: out of range");if(c){let{k1neg:M,k1:D,k2neg:g,k2:O}=S(_),P=new x(n.mul(T.X,c.beta),T.Y,T.Z);A.push(M?T.negate():T,g?P.negate():P),p.push(D,O)}else A.push(T),p.push(_)}let F=new WeakSet;class x{static BASE=new x(i.Gx,i.Gy,n.ONE);static ZERO=new x(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(p,T,_){this.X=$("x",p),this.Y=$("y",T,!0),this.Z=$("z",_),Object.freeze(this)}static CURVE(){return i}static fromAffine(p){let{x:T,y:_}=p||{};if(!p||!n.isValid(T)||!n.isValid(_))throw new Error("invalid affine point");if(p instanceof x)throw new Error("projective point not allowed");return n.is0(T)&&n.is0(_)?x.ZERO:new x(T,_,n.ONE)}static fromBytes(p){let T=x.fromAffine(b(G(p,void 0,"point")));return T.assertValidity(),T}static fromHex(p){return x.fromBytes(yr(p))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=6,T=!0){return C.setWindowSize(this,p),T||this.multiply(zs),this}assertValidity(){let p=this;if(p.is0()){if(e.allowInfinityPoint&&n.is0(p.X)&&n.eql(p.Y,n.ONE)&&n.is0(p.Z))return;throw new Error("bad point: ZERO")}if(F.has(p))return;let{x:T,y:_}=p.toAffine();if(!n.isValid(T)||!n.isValid(_))throw new Error("bad point: x or y not field elements");if(!N(T,_))throw new Error("bad point: equation left != right");if(!p.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");F.add(p)}hasEvenY(){let{y:p}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(p)}equals(p){w(p);let{X:T,Y:_,Z:M}=this,{X:D,Y:g,Z:O}=p,P=n.eql(n.mul(T,O),n.mul(D,M)),z=n.eql(n.mul(_,O),n.mul(g,M));return P&&z}negate(){return new x(this.X,n.neg(this.Y),this.Z)}double(){let{X:p,Y:T,Z:_}=this,M=n.ZERO,D=n.ZERO,g=n.ZERO,O=n.mul(p,p),P=n.mul(T,T),z=n.mul(_,_),H=n.mul(p,T);return H=n.add(H,H),g=n.mul(p,_),g=n.add(g,g),M=B(g),D=n.mul(E,z),D=n.add(M,D),M=n.sub(P,D),D=n.add(P,D),D=n.mul(M,D),M=n.mul(H,M),g=n.mul(E,g),z=B(z),H=n.sub(O,z),H=B(H),H=n.add(H,g),g=n.add(O,O),O=n.add(g,O),O=n.add(O,z),O=n.mul(O,H),D=n.add(D,O),z=n.mul(T,_),z=n.add(z,z),O=n.mul(z,H),M=n.sub(M,O),g=n.mul(z,P),g=n.add(g,g),g=n.add(g,g),new x(M,D,g)}add(p){w(p);let{X:T,Y:_,Z:M}=this,{X:D,Y:g,Z:O}=p,P=n.ZERO,z=n.ZERO,H=n.ZERO,Z=n.mul(T,D),Y=n.mul(_,g),ne=n.mul(M,O),ye=n.add(T,_),oe=n.add(D,g);ye=n.mul(ye,oe),oe=n.add(Z,Y),ye=n.sub(ye,oe),oe=n.add(T,M);let pe=n.add(D,O);return oe=n.mul(oe,pe),pe=n.add(Z,ne),oe=n.sub(oe,pe),pe=n.add(_,M),P=n.add(g,O),pe=n.mul(pe,P),P=n.add(Y,ne),pe=n.sub(pe,P),H=B(oe),P=n.mul(E,ne),H=n.add(P,H),P=n.sub(Y,H),H=n.add(Y,H),z=n.mul(P,H),Y=n.add(Z,Z),Y=n.add(Y,Z),ne=B(ne),oe=n.mul(E,oe),Y=n.add(Y,ne),ne=n.sub(Z,ne),ne=B(ne),oe=n.add(oe,ne),Z=n.mul(Y,oe),z=n.add(z,Z),Z=n.mul(pe,oe),P=n.mul(ye,P),P=n.sub(P,Z),Z=n.mul(ye,Y),H=n.mul(pe,H),H=n.add(H,Z),new x(P,z,H)}subtract(p){return w(p),this.add(p.negate())}is0(){return this.equals(x.ZERO)}multiply(p){if(!o.isValidNot0(p))throw new RangeError("invalid scalar: out of range");let{p:T,f:_}=C.mulSecret(this,p,s,q);return q([T,_])[0]}multiplyUnsafe(p){let T=this,_=p;if(!o.isValid(_))throw new RangeError("invalid scalar: out of range");if(_===ct||T.is0())return x.ZERO;if(_===jt)return T;if(C.hasWindowSize(this))return C.mulUnsafe(T,_,q);let M=[],D=[];return I(M,D,T,_),Fo(x,M,D)}mulAddUnsafe(p,T,_){w(T);let M=[],D=[];return I(M,D,this,p),I(M,D,T,_),Fo(x,M,D)}toAffine(p){let T=this,_=p;if(_!=null&&!n.isValid(_))throw new RangeError('"invertedZ" expected valid field element');let{X:M,Y:D,Z:g}=T;if(n.eql(g,n.ONE))return{x:M,y:D};let O=T.is0();_==null&&(_=O?n.ONE:n.inv(g));let P=n.mul(M,_),z=n.mul(D,_),H=n.mul(g,_);if(O)return{x:n.ZERO,y:n.ZERO};if(!n.eql(H,n.ONE))throw new Error("invZ was invalid");return{x:P,y:z}}isTorsionFree(){let{isTorsionFree:p}=e;return s===jt?!0:p?p(x,this):C.mulUnsafe(this,a).is0()}clearCofactor(){let{clearCofactor:p}=e;return s===jt?this:p?p(x,this):this.multiplyUnsafe(s)}isSmallOrder(){return s===jt?this.is0():this.clearCofactor().is0()}toBytes(p=!0){return Se(p,"isCompressed"),this.assertValidity(),v(x,this,p)}toHex(p=!0){return nn(this.toBytes(p))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let q=A=>ko(x,A),C=new Er(x,u);return C.bits>=6&&x.BASE.precompute(6),Object.freeze(x.prototype),Object.freeze(x),x}function _f(t){return Uint8Array.of(t?2:3)}function Df(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function rm(t,e={}){Lt(t);let{Fn:r}=t,n=e.randomBytes===void 0?zt:e.randomBytes,o=Object.assign(Df(t.Fp,r),{seed:Math.max(No(r.ORDER),16)});function i(m){try{let L=r.fromBytes(m);return r.isValidNot0(L)}catch{return!1}}function s(m,L){let{publicKey:v,publicKeyUncompressed:b}=o;try{let E=m.length;return L===!0&&E!==v||L===!1&&E!==b?!1:!!t.fromBytes(m)}catch{return!1}}function a(m){return m=m===void 0?n(o.seed):m,Uo(G(m,o.seed,"seed"),r.ORDER)}function c(m,L=!0){return t.BASE.multiply(r.fromBytes(m)).toBytes(L)}function f(m){let{secretKey:L,publicKey:v,publicKeyUncompressed:b}=o,E=r._lengths;if(!_t(m))return;let B=G(m,void 0,"key").length,y=B===v||B===b,N=B===L||!!E?.includes(B);if(!(y&&N))return y}function u(m,L,v=!0){if(f(m)===!0)throw new Error("first arg must be private key");if(f(L)===!1)throw new Error("second arg must be public key");let b=r.fromBytes(m);return t.fromBytes(L).multiply(b).toBytes(v)}let l={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},h=Po(a,c);return Object.freeze(l),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:h,Point:t,utils:l,lengths:o})}function Rf(t,e,r={}){Lt(t);let n=e;Eo(n),ve(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let o=Object.assign({},r),i=o.randomBytes===void 0?zt:o.randomBytes,s=o.hmac===void 0?(D,g)=>Tf(n,D,g):o.hmac,{Fp:a,Fn:c}=t,{ORDER:f,BITS:u}=c,l=No(f),h=Ns(i,l),{keygen:m,getPublicKey:L,getSharedSecret:v,utils:b,lengths:E}=rm(t,o),B={prehash:!0,lowS:typeof o.lowS=="boolean"?o.lowS:!0,format:"compact",extraEntropy:!1},y=f*If+jt<a.ORDER;function N(D){let g=f>>jt;return D>g}function U(D,g){if(!c.isValidNot0(g))throw new Error(`invalid signature ${D}: out of range 1..Point.Fn.ORDER`);return g}function V(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function $(D,g,O){return V(),(D===O?0:2)|Number(a.isOdd(g))}function w(){if(y)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function S(D,g){Hs(g);let O=E.signature,P=g==="compact"?O:g==="recovered"?O+1:void 0;return G(D,P)}class I{r;s;recovery;constructor(g,O,P){if(this.r=U("r",g),this.s=U("s",O),P!=null){if(w(),![0,1,2,3].includes(P))throw new Error("invalid recovery id");this.recovery=P}Object.freeze(this)}static fromBytes(g,O=B.format){S(g,O);let P;if(O==="der"){let{r:Y,s:ne}=$s.toSig(G(g));return new I(Y,ne)}O==="recovered"&&(P=g[0],O="compact",g=g.subarray(1));let z=E.signature/2,H=g.subarray(0,z),Z=g.subarray(z,z*2);return new I(c.fromBytes(H),c.fromBytes(Z),P)}static fromHex(g,O){return this.fromBytes(yr(g),O)}assertRecovery(){let{recovery:g}=this;if(g==null)throw new Error("invalid recovery id: must be present");return g}addRecoveryBit(g){return new I(this.r,this.s,g)}recoverPublicKey(g){let{r:O,s:P}=this,z=this.assertRecovery(),H=z===2||z===3?O+f:O;if(!a.isValid(H))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let Z=a.toBytes(H),Y=t.fromBytes(Oe(_f((z&1)===0),Z)),ne=c.inv(H),ye=x(G(g,void 0,"msgHash")),oe=c.create(-ye*ne),pe=c.create(P*ne),qe=t.BASE.mulAddUnsafe(oe,Y,pe);if(qe.is0())throw new Error("invalid recovery: point at infinify");return qe.assertValidity(),qe}hasHighS(){return N(this.s)}toBytes(g=B.format){if(Hs(g),g==="der")return yr($s.hexFromSig(this));let{r:O,s:P}=this,z=c.toBytes(O),H=c.toBytes(P);return g==="recovered"?(w(),Oe(Uint8Array.of(this.assertRecovery()),z,H)):Oe(z,H)}toHex(g){return nn(this.toBytes(g))}}Object.freeze(I.prototype),Object.freeze(I);let F=o.bits2int===void 0?function(g){if(g.length>8192)throw new Error("input is too large");let O=et(g),P=g.length*8-u;return P>0?O>>BigInt(P):O}:o.bits2int,x=o.bits2int_modN===void 0?function(g){return c.create(F(g))}:o.bits2int_modN,q=sn(u);function C(D){return gr("num < 2^"+u,D,ct,q),c.toBytes(D)}function A(D,g){return G(D,void 0,"message"),g?G(n(D),void 0,"prehashed message"):D}function p(D,g,O){let{lowS:P,prehash:z,extraEntropy:H}=qs(O,B);D=A(D,z);let Z=x(D),Y=c.fromBytes(g);if(!c.isValidNot0(Y))throw new Error("invalid private key");let ne=[C(Y),C(Z)];if(H!=null&&H!==!1){let qe=H===!0?i(E.secretKey):H;ne.push(G(qe,void 0,"extraEntropy"))}let ye=Oe(...ne),oe=Z;function pe(qe){let Yt=F(qe);if(!c.isValidNot0(Yt))return;let Tr=t.BASE.multiply(Yt).toAffine(),ut=c.create(Tr.x);if(ut===ct)return;let ze;if(h!==void 0){let Br=et(Uo(h(l),f)),qf=c.inv(c.mul(Br,Yt)),zf=c.mul(Br,oe),Hf=c.mul(Br,Y);ze=c.create(qf*c.create(zf+Hf*ut))}else{let Br=nf(Yt,f);ze=c.create(Br*c.create(oe+ut*Y))}if(ze===ct)return;let ni=$(Tr.x,Tr.y,ut),Js=ze;return P&&N(ze)&&(Js=c.neg(ze),ni^=1),new I(ut,Js,y?void 0:ni)}return{seed:ye,k2sig:pe}}function T(D,g,O={}){let{seed:P,k2sig:z}=p(D,g,O);return Gu(n.outputLen,c.BYTES,s)(P,z).toBytes(O.format)}function _(D,g,O,P={}){let{lowS:z,prehash:H,format:Z}=qs(P,B);if(O=G(O,void 0,"publicKey"),g=A(g,H),!_t(D)){let Y=D instanceof I?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+Y)}S(D,Z);try{let Y=I.fromBytes(D,Z),ne=t.fromBytes(O);if(z&&Y.hasHighS())return!1;let{r:ye,s:oe}=Y,pe=x(g),qe=c.inv(oe),Yt=c.create(pe*qe),Tr=c.create(ye*qe),ut=t.BASE.mulAddUnsafe(Yt,ne,Tr);if(ut.is0())return!1;let ze=ut.toAffine();return!(c.create(ze.x)!==ye||Z==="recovered"&&Y.recovery!==$(ze.x,ze.y,ye))}catch{return!1}}function M(D,g,O={}){let{prehash:P}=qs(O,B);return g=A(g,P),I.fromBytes(D,"recovered").recoverPublicKey(g).toBytes()}return Object.freeze({keygen:m,getPublicKey:L,getSharedSecret:v,utils:b,lengths:E,Point:t,sign:T,verify:_,recoverPublicKey:M,Signature:I,hash:n})}var Ys={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},nm={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Lf=BigInt(2);function om(t){let e=Ys.p,r=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),f=t*t*t%e,u=f*f*t%e,l=ee(u,r,e)*u%e,h=ee(l,r,e)*u%e,m=ee(h,Lf,e)*f%e,L=ee(m,o,e)*m%e,v=ee(L,i,e)*L%e,b=ee(v,a,e)*v%e,E=ee(b,c,e)*b%e,B=ee(E,a,e)*v%e,y=ee(B,r,e)*u%e,N=ee(y,s,e)*L%e,U=ee(N,n,e)*f%e,V=ee(U,Lf,e);if(!js.eql(js.sqr(V),t))throw new Error("Cannot find square root");return V}var js=xr(Ys.p,{sqrt:om}),im=Cf(Ys,{Fp:js,endo:nm}),Sr=Rf(im,Hu);function Nf(t,e,r,n){let o=Nr.digest(r instanceof Uint8Array?r:r.subarray());if(Ho(o))return o.then(({digest:i})=>(n?.signal?.throwIfAborted(),Sr.verify(e,i,t,{prehash:!1,format:"der"}))).catch(i=>{throw i.name==="AbortError"?i:new un(String(i))});try{return n?.signal?.throwIfAborted(),Sr.verify(e,o.digest,t,{prehash:!1,format:"der"})}catch(i){throw new un(String(i))}}var Zo=class{type="secp256k1";raw;_key;constructor(e){this._key=kf(e),this.raw=Uf(this._key)}toMultihash(){return Ke.digest(pr(this))}toCID(){return te.createV1(114,this.toMultihash())}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:de(this.raw,e.raw)}verify(e,r,n){return Nf(this._key,r,e,n)}};function Ff(t){return new Zo(t)}function Uf(t){return Sr.Point.fromBytes(t).toBytes()}function kf(t){try{return Sr.Point.fromBytes(t),t}catch(e){throw new Wn(String(e))}}function Of(t){let{Type:e,Data:r}=fn.decode(t.digest),n=r??new Uint8Array;switch(e){case be.Ed25519:return Af(n);case be.secp256k1:return Ff(n);case be.ECDSA:return Au(n);default:throw new Hr}}function pr(t){return fn.encode({Type:be[t.type],Data:t.raw})}var Pf=Symbol.for("nodejs.util.inspect.custom"),sm=114,ln=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Ji]=!0;toString(){return this.string==null&&(this.string=J.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return te.createV1(sm,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return de(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return de(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Pf](){return`PeerId(${this.toString()})`}},Go=class extends ln{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Xo=class extends ln{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Wo=class extends ln{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},am=2336,Qo=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ke.digest(se(this.url))}[Pf](){return`PeerId(${this.url})`}[Ji]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return te.createV1(am,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=W(e)),e.toString()===this.toString())}};function Mf(t){if(um(t))return new Go({multihash:t});if(cm(t))try{let e=Of(t);if(e.type==="Ed25519")return new Xo({multihash:t,publicKey:e});if(e.type==="secp256k1")return new Wo({multihash:t,publicKey:e})}catch{let r=W(t.digest);return new Qo(new URL(r))}throw new Qn("Supplied PeerID Multihash is invalid")}function cm(t){return t.code===Ke.code}function um(t){return t.code===Nr.code}function Zs(t,e){let r={[Symbol.iterator]:()=>r,next:()=>{let n=t.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return r}function Jo(t){let e=dt(J.decode(`z${t}`));return Mf(e)}var dn=class t{set;constructor(e){if(this.set=new Set,e!=null)for(let r of e)this.set.add(r.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return Zs(this.set.entries(),e=>{let r=Jo(e[0]);return[r,r]})}forEach(e){this.set.forEach(r=>{let n=Jo(r);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Zs(this.set.values(),e=>Jo(e))}intersection(e){let r=new t;for(let n of e)this.has(n)&&r.add(n);return r}difference(e){let r=new t;for(let n of this)e.has(n)||r.add(n);return r}union(e){let r=new t;for(let n of e)r.add(n);for(let n of this)r.add(n);return r}};var Kf;(function(t){t[t.SEND_QUERY=0]="SEND_QUERY",t[t.PEER_RESPONSE=1]="PEER_RESPONSE",t[t.FINAL_PEER=2]="FINAL_PEER",t[t.QUERY_ERROR=3]="QUERY_ERROR",t[t.PROVIDER=4]="PROVIDER",t[t.VALUE=5]="VALUE",t[t.ADD_PEER=6]="ADD_PEER",t[t.DIAL_PEER=7]="DIAL_PEER",t[t.PATH_ENDED=8]="PATH_ENDED"})(Kf||(Kf={}));var hn;(function(t){let e;t.codec=()=>(e==null&&(e=Ze((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.keyName!=null&&i.keyName!==""&&(s.uint32(10),s.string(i.keyName)),i.lifetime!=null&&i.lifetime!==0&&(s.uint32(16),s.uint32(i.lifetime)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={keyName:"",lifetime:0},f=s==null?i.len:i.pos+s;for(;i.pos<f;){let u=i.uint32();switch(u>>>3){case 1:{c.keyName=i.string();break}case 2:{c.lifetime=i.uint32();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let f=s==null?i.len:i.pos+s;for(;i.pos<f;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.keyName`,value:i.string()};break}case 2:{yield{field:`${a}.lifetime`,value:i.uint32()};break}default:{i.skipType(u&7);break}}}})),e);function r(i){return je(i,t.codec())}t.encode=r;function n(i,s){return He(i,t.codec(),s)}t.decode=n;function o(i,s){return Ye(i,t.codec(),s)}t.stream=o})(hn||(hn={}));function vr(t,e){return{async put(r,n,o={}){try{let i=jr(r);try{let c=await t.get(i),f=vt.deserialize(c);if(de(f.value,n))return}catch(c){if(c.name!=="NotFoundError")throw c}let s=new vt(r,n,new Date);o.onProgress?.(new fe("ipns:routing:datastore:put"));let a=t.batch();a.put(i,s.serialize()),o.metadata!=null&&a.put(no(r),hn.encode(o.metadata)),await a.commit(o)}catch(i){throw o.onProgress?.(new fe("ipns:routing:datastore:error",i)),i}},async get(r,n={}){try{let o=jr(r);n.onProgress?.(new fe("ipns:routing:datastore:get"));let i=await t.get(o,n),s=vt.deserialize(i);return{record:xe(s.value),created:s.timeReceived}}catch(o){throw n.onProgress?.(new fe("ipns:routing:datastore:error",o)),o}},async has(r,n={}){let o=jr(r);return t.has(o,n)},async delete(r,n){let o=jr(r),i=t.batch();i.delete(o),i.delete(no(r)),await i.commit(n)},async*list(r={}){try{r.onProgress?.(new fe("ipns:routing:datastore:list"));for await(let{key:n,value:o}of t.query({prefix:ro},r))try{let i=vt.deserialize(o),a=n.toString().substring(ro.length),c=se(a,"base32"),f=no(c),u;try{let l=await t.get(f,r);u=hn.decode(l)}catch(l){e.error("Error deserializing metadata for %s - %e",a,l)}yield{routingKey:c,metadata:u,record:i.value,created:i.timeReceived}}catch(i){e.error("Error deserializing record - %e",i)}}catch(n){throw r.onProgress?.(new fe("ipns:routing:datastore:error",n)),n}}}}var Gs=class{routing;constructor(e){this.routing=e}async put(e,r,n={}){try{await this.routing.put(e,r,n)}catch(o){throw n.onProgress?.(new fe("ipns:routing:helia:error",o)),o}}async get(e,r={}){try{return await this.routing.get(e,r)}catch(n){throw r.onProgress?.(new fe("ipns:routing:helia:error",n)),n}}toString(){return"HeliaRouting()"}};function Ar(t){return new Gs(t)}var Xs=class{localStore;constructor(e){this.localStore=e}async put(e,r,n){await this.localStore.put(e,r,n)}async get(e,r){let{record:n}=await this.localStore.get(e,r);return n}toString(){return"LocalStoreRouting()"}};function ei(t){return new Xs(t)}var ti=class{routers;publisher;republisher;resolver;localStore;components;started;constructor(e,r={}){this.localStore=vr(e.datastore,e.logger.forComponent("helia:ipns:local-store")),this.components=e,this.started=!1,this.routers=[ei(this.localStore),Ar(e.routing),...r.routers??[]],this.publisher=new uo(e,{...r,routers:this.routers,localStore:this.localStore}),this.republisher=new go(e,{...r,routers:this.routers,localStore:this.localStore}),this.resolver=new cr(e,{...r,routers:this.routers,localStore:this.localStore}),e.events.addEventListener("start",this.start.bind(this)),e.events.addEventListener("stop",this.stop.bind(this)),this.started&&this.republisher.start();for(let n of Object.values(this.components))if(fm(n))for(let o of Object.values(n.services))lm(o)&&(o.selectors.ipns=async(i,s)=>{let a=s.map(c=>Q.decode(c));return St(i,a)},o.validators.ipns=async(i,s)=>{await Qe(i,s,this.components.keychain)})}start(){this.started||(this.started=!0,this.republisher.start())}stop(){this.started&&(this.started=!1,this.republisher.stop())}async publish(e,r,n={}){return this.publisher.publish(e,so(r),n)}async*resolve(e,r={}){let{digest:n}=Yr(e);yield*this.resolver.resolve(n,r)}async unpublish(e,r){return this.publisher.unpublish(e,r)}};function fm(t){return t?.services!=null}function lm(t){return t?.validators!=null&&t?.selectors!=null}var ae=Zr("helia:ipns:routing:pubsub"),Qs=class{subscriptions;localStore;libp2p;fetchConcurrency;fetchTimeout;fetchDelay;fetchQueue;fetchPeers;shutdownController;fetchTopologyId;keychain;constructor(e,r={}){if(this.subscriptions=new Set,this.shutdownController=new AbortController,this.shutdownController.signal,this.fetchPeers=new dn,this.localStore=vr(e.datastore,e.logger.forComponent("helia:ipns:local-store")),this.libp2p=e.libp2p,this.fetchConcurrency=r.fetchConcurrency??8,this.fetchDelay=r.fetchDelay??0,this.keychain=e.keychain,this.fetchTimeout=r.fetchTimeout??2500,this.fetchQueue=new dr({concurrency:this.fetchConcurrency,metrics:e.metrics,metricName:"helia_ipns_pubsub_fetch_queue"}),this.libp2p.services.pubsub.addEventListener("message",n=>{let o=n.detail;this.subscriptions.has(o.topic)&&this.#e(o,{signal:this.shutdownController.signal}).catch(i=>{ae.error("Error processing message - %e",i)})}),this.libp2p.services.fetch!=null)try{this.libp2p.services.pubsub.addEventListener("subscription-change",n=>{let{peerId:o,subscriptions:i}=n.detail;if(this.fetchPeers.has(o))for(let s of i){if(!this.subscriptions.has(s.topic)||s.subscribe===!1)continue;ae("peer %s joined topic %s",o,s.topic);let a=Vf(s.topic);this.#t(s.topic,a,o,{signal:this.shutdownController.signal}).catch(c=>{ae.error("failed to fetch IPNS record for %m from peer %s - %e",a,o,c)})}}),this.libp2p.services.fetch.registerLookupFunction(to,async n=>{try{let{record:o}=await this.localStore.get(n,{signal:this.shutdownController.signal});return o}catch(o){if(o.name!=="NotFoundError")throw o}}),ae("registered lookup function for IPNS with libp2p/fetch service")}catch(n){ae("unable to register lookup function for IPNS with libp2p/fetch service - %e",n)}else ae("no libp2p/fetch service found. Skipping registration of lookup function for IPNS.")}async#e(e,r){if(ae("message received for topic",e.topic),e.type!=="signed"){ae.error("unsigned message received, this module can only work with signed messages");return}if(e.from.equals(this.libp2p.peerId)){ae("not storing record from self");return}await this.#r(e.topic,Vf(e.topic),e.data,!1,r)}async#t(e,r,n,o){let i=await this.fetchQueue.add(async({signal:s})=>{ae("fetching ipns record for %m from peer %s",r,n);let a=Xr([s,AbortSignal.timeout(this.fetchTimeout)]);try{return await this.libp2p.services.fetch?.fetch(n,r,{signal:a})}finally{a.clear()}},o);if(i==null)throw new zr(`Peer ${n} did not have record for routing key ${W(r,"base64")}`);return ae("fetched ipns record for %m from peer %s",r,n),this.#r(e,r,i,!0,o)}async#r(e,r,n,o,i){let s=await Qe(r,n,this.keychain,i);if(this.shutdownController.signal.throwIfAborted(),await this.localStore.has(r)){let{record:a}=await this.localStore.get(r,i),c=await Qe(r,a,this.keychain,i);if(de(a,n))return ae.trace("found identical record for %m",r),a;if(St(r,[c,s])===0)return ae.trace("found old record for %m",r),a}if(ae("found new record for %m",r),await this.localStore.put(r,n,i),o){ae("publish value for topic %s",e);try{let a=await this.libp2p.services.pubsub.publish(e,n);ae("published record on topic %s to %d recipients",e,a.recipients)}catch(a){ae.error("could not publish record on topic %s - %e",a)}}return xe(n)}async put(e,r,n={}){try{let o=Ws(e);ae("publish value for topic %s",o);let i=await this.libp2p.services.pubsub.publish(o,r);n?.signal?.throwIfAborted(),ae("published record on topic %s to %d recipients",o,i.recipients),n.onProgress?.(new fe("ipns:pubsub:publish",{topic:o,result:i}))}catch(o){throw n.onProgress?.(new fe("ipns:pubsub:error",o)),o}}async get(e,r={}){let n=Ws(e);try{this.libp2p.services.pubsub.getTopics().includes(n)||(ae("add subscription for topic",n),this.libp2p.services.pubsub.subscribe(n),this.subscriptions.add(n),r.onProgress?.(new fe("ipns:pubsub:subscribe",{topic:n})))}catch(s){throw r.onProgress?.(new fe("ipns:pubsub:error",s)),s}await po(yu(this.fetchDelay),this.shutdownController.signal);let o=new AbortController,i=[];for(let s of this.libp2p.services.pubsub.getSubscribers(n)){let a=Xr([r?.signal,o.signal]);i.push(this.#t(n,e,s,{...r,signal:a}).finally(()=>{a.clear()}))}if(i.length>0){let s=await Promise.any(i);if(o.abort(),s!=null)return s}throw new zr("Pubsub routing does not actively query peers")}getSubscriptions(){return[...this.subscriptions]}cancel(e){let r=Yc(e)?e.toMultihash():e,n=it(r),o=Ws(n);this.subscriptions.has(o)&&(this.libp2p.services.pubsub.unsubscribe(o),this.subscriptions.delete(o))}toString(){return"PubSubRouting()"}async start(){this.shutdownController=new AbortController,this.shutdownController.signal,this.libp2p.services.fetch!=null&&(this.fetchTopologyId=await this.libp2p.register(this.libp2p.services.fetch.protocol,{onConnect:e=>{this.fetchPeers.add(e)},onDisconnect:e=>{this.fetchPeers.delete(e)}},{signal:this.shutdownController.signal}))}stop(){this.fetchQueue.abort(),this.shutdownController.abort(),this.fetchTopologyId!=null&&this.libp2p.unregister(this.fetchTopologyId)}},ri="/record/";function Ws(t){let e=W(t,"base64url");return`${ri}${e}`}function Vf(t){if(t.substring(0,ri.length)!==ri)throw new bn("Topic received is not from a record");let e=t.substring(ri.length);return se(e,"base64url")}function $f(t,e={}){return new Qs(t,e)}function dm(t,e={}){return new ti(t,e)}function hm(t,e={}){let r=vr(t.datastore,t.logger.forComponent("helia:ipns:local-store")),n=[ei(r),Ar(t.routing),...e.routers??[]];return new cr(t,{routers:n,localStore:r})}return Qf(pm);})();
|
|
13
|
+
${e}[Error list was empty]`,r.trim()}return au(t,e)}Ee.formatters.e=t=>t==null?"undefined":uu(t);function Uh(t){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=t,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function Zr(t,e){let r=Uh(`${t}:trace`);return Ee.enabled(`${t}:trace`)&&Ee.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(r=Ee(`${t}:trace`,e)),Object.assign(Ee(t,e),{error:Ee(`${t}:error`,e),trace:r,newScope:n=>Zr(`${t}:${n}`,e)})}function cu(t){if(t!=null&&(t=t.trim(),t.length!==0))return t}var fu=oi(_n(),1);var kh=Zr("ipns"),Fh=300000000000n;async function ur(t,e,r,n,o){r=BigInt(r),e=so(e);let i=se(e),s=o?.ttlNs??Fh,a=new fu.default((o?.now??Date.now())+Number(n)),c=Q.ValidityType.EOL,f=se(a.toString()),u=ru({...o?.data??{},Value:i,Validity:f,ValidityType:0,Sequence:r,TTL:s}),l=oo(u),h=await t.sign(l,o),m;return o?.v1Compatible===!1?m={signatureV2:h,data:u}:m={value:i,signatureV1:await Oh(t,i,c,f),validityType:c,validity:f,sequence:r,ttl:s,signatureV2:h,data:u},Ph(t.publicKey)&&(m.publicKey=t.publicKey.toProtobuf()),m}var Oh=async(t,e,r,n,o)=>{try{let i=tu(e,r,n);return await t.sign(i,o)}catch(i){throw kh.error("record signature creation failed",i),new wn("Record signature creation failed")}};function Ph(t){return t.toMultihash().code!==Wc}var uo=class{routers;localStore;keychain;constructor(e,r){this.keychain=e.keychain,this.localStore=r.localStore,this.routers=r.routers}async publish(e,r,n={}){try{let o=await this.#e(e,n),i=o.publicKey.toMultihash(),s=it(i),a=1n;if(await this.localStore.has(s,n)){let{record:l}=await this.localStore.get(s,n),h=Q.decode(l);a=(ke(h.data).Sequence??0n)+1n}let c=n.lifetime??1728e5,f=await ur(o,r,a,c,{...n,ttlNs:n.ttl!=null?BigInt(n.ttl)*1000000n:void 0}),u=Q.encode(f);return n.offline===!0?await this.localStore.put(s,u,{...n,metadata:{keyName:e,lifetime:c}}):await Promise.all(this.routers.map(async l=>{await l.put(s,u,{...n,metadata:{keyName:e,lifetime:c}})})),{record:f,name:`/ipns/${o.publicKey.toCID().toString(we)}`,publicKey:o.publicKey}}catch(o){throw n.onProgress?.(new fe("ipns:publish:error",o)),o}}async#e(e,r){try{return await this.keychain.exportKey(e,r)}catch(n){if(n.name==="NotFoundError")return this.keychain.generateKey(e,r);throw n}}async unpublish(e,r){let o=(await this.keychain.exportKey(e,r)).publicKey.toMultihash(),i=it(o);await this.localStore.delete(i,r)}};function fr(){let t={};return t.promise=new Promise((e,r)=>{t.resolve=e,t.reject=r}),t}var fo=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},lr=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new fo(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let r=this.head;this.head=r.next=new fo(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let r=this.tail.next;this.tail.next=null,this.tail=r,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var os=class extends Error{type;code;constructor(e,r){super(e??"The operation was aborted"),this.type="aborted",this.code=r??"ABORT_ERR"}};function lu(t={}){return Mh(r=>{let n=r.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},t)}function Mh(t,e){e=e??{};let r=e.onEnd,n=new lr,o,i,s,a=fr(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((b,E)=>{i=B=>{i=null,n.push(B);try{b(t(n))}catch(y){E(y)}return o}}):t(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=fr()})}},f=b=>i!=null?i(b):(n.push(b),o),u=b=>(n=new lr,i!=null?i({error:b}):(n.push({error:b}),o)),l=b=>{if(s)return o;if(e?.objectMode!==!0&&b?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return f({done:!1,value:b})},h=b=>s?o:(s=!0,b!=null?u(b):f({done:!0})),m=()=>(n=new lr,h(),{done:!0}),L=b=>(h(b),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:m,throw:L,push:l,end:h,get readableLength(){return n.size},onEmpty:async b=>{let E=b?.signal;if(E?.throwIfAborted(),n.isEmpty())return;let B,y;E!=null&&(B=new Promise((N,U)=>{y=()=>{U(new os)},E.addEventListener("abort",y)}));try{await Promise.race([a.promise,B])}finally{y!=null&&E!=null&&E?.removeEventListener("abort",y)}}},r==null)return o;let v=o;return o={[Symbol.asyncIterator](){return this},next(){return v.next()},throw(b){return v.throw(b),r!=null&&(r(b),r=void 0),{done:!0}},return(){return v.return(),r!=null&&(r(),r=void 0),{done:!0}},push:l,end(b){return v.end(b),r!=null&&(r(b),r=void 0),o},get readableLength(){return v.readableLength},onEmpty:b=>v.onEmpty(b)},o}var is=class t extends Error{name="TimeoutError";constructor(e,r){super(e,r),Error.captureStackTrace?.(this,t)}},du=t=>t.reason??new DOMException("This operation was aborted.","AbortError");function ss(t,e){let{milliseconds:r,fallback:n,message:o,customTimers:i={setTimeout,clearTimeout},signal:s}=e,a,c,u=new Promise((l,h)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(s?.aborted){h(du(s));return}if(s&&(c=()=>{h(du(s))},s.addEventListener("abort",c,{once:!0})),t.then(l,h),r===Number.POSITIVE_INFINITY)return;let m=new is;a=i.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(L){h(L)}return}typeof t.cancel=="function"&&t.cancel(),o===!1?l():o instanceof Error?h(o):(m.message=o??`Promise timed out after ${r} milliseconds`,h(m))},r)}).finally(()=>{u.clear(),c&&s&&s.removeEventListener("abort",c)});return u.clear=()=>{i.clearTimeout.call(void 0,a),a=void 0},u}var Kh=t=>{let e=t.addEventListener||t.on||t.addListener,r=t.removeEventListener||t.off||t.removeListener;if(!e||!r)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(t),removeListener:r.bind(t)}};function Vh(t,e,r){let n,o=new Promise((i,s)=>{if(r={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...r},!(r.count>=0&&(r.count===Number.POSITIVE_INFINITY||Number.isInteger(r.count))))throw new TypeError("The `count` option should be at least 0 or more");r.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:f,removeListener:u}=Kh(t),l=async(...m)=>{let L=r.multiArgs?m:m[0];if(r.filter)try{if(!await r.filter(L))return}catch(v){n(),s(v);return}c.push(L),r.count===c.length&&(n(),i(c))},h=(...m)=>{n(),s(r.rejectionMultiArgs?m:m[0])};n=()=>{for(let m of a)u(m,l);for(let m of r.rejectionEvents)a.includes(m)||u(m,h)};for(let m of a)f(m,l);for(let m of r.rejectionEvents)a.includes(m)||f(m,h);r.signal&&r.signal.addEventListener("abort",()=>{h(r.signal.reason)},{once:!0}),r.resolveImmediately&&i(c)});if(o.cancel=n,typeof r.timeout=="number"){let i=ss(o,{milliseconds:r.timeout});return i.cancel=()=>{n(),i.clear()},i}return o}function lo(t,e,r){typeof r=="function"&&(r={filter:r}),r={...r,count:1,resolveImmediately:!1};let n=Vh(t,e,r),o=n.then(i=>i[0]);return o.cancel=n.cancel,o}function Gr(t,e){let r,n=function(){let o=function(){r=void 0,t()};clearTimeout(r),r=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(r)},n}var ho=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};function $h(t){return t.reason}function po(t,e,r){if(e==null||t==null)return t;let n=r?.translateError??$h;if(e.aborted)return t.catch(()=>{}),Promise.reject(n(e));let o;return Promise.race([t,new Promise((i,s)=>{o=()=>{s(n(e))},e.addEventListener("abort",o)})]).finally(()=>{o!=null&&e.removeEventListener("abort",o)})}var mo=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=fr(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new rt)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function qh(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var yo=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,r){this.id=qh(),this.status="queued",this.fn=e,this.options=r,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((r,n)=>r&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new rt),this.cleanup())}async join(e){let r=new mo(e);return this.recipients.push(r),e?.signal?.addEventListener("abort",this.onAbort),r.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await po(this.fn({...this.options??{},signal:this.controller.signal,onProgress:r=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(r)})}finally{this.dispatchingProgress=!1}}}}),this.controller.signal);this.recipients.forEach(r=>{r.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(r=>{r.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var dr=class extends Jn{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Gr(this.emitEmpty.bind(this),1),this.emitIdle=Gr(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let r of this.queue)if(r.status==="queued"){e=r;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let r=0;r<this.queue.length;r++)if(this.queue[r]===e){this.queue.splice(r,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,r){if(r?.signal?.throwIfAborted(),this.size===this.maxSize)throw new ho;let n=new yo(e,r);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(r).then(i=>(this.safeDispatchEvent("completed",{detail:i}),this.safeDispatchEvent("success",{detail:{job:n,result:i}}),i)).catch(i=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:i}}),i});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new rt)}),this.clear()}async onEmpty(e){this.size!==0&&await lo(this,"empty",e)}async onSizeLessThan(e,r){this.size<e||await lo(this,"next",{...r,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await lo(this,"idle",e)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let r=lu({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),r.end(c)},o=c=>{c.detail!=null&&r.push(c.detail)},i=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new rt("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",i),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*r}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",i),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};function Xr(t){let e=new globalThis.AbortController;function r(){let i=t.filter(s=>s?.aborted===!0).map(s=>s?.reason).pop();e.abort(i);for(let s of t)s?.removeEventListener!=null&&s.removeEventListener("abort",r)}for(let i of t){if(i?.aborted===!0){r();break}i?.addEventListener!=null&&i.addEventListener("abort",r)}function n(){for(let i of t)i?.removeEventListener!=null&&i.removeEventListener("abort",r)}let o=e.signal;return o.clear=n,o}var hu=Symbol.for("sindresorhus/unlimited-timeout#brand");function pu(t,e,...r){if(typeof t!="function")throw new TypeError("Expected callback to be a function");e??=0,e=Number(e);let n=!1,o={[hu]:!0,id:void 0,cleared:!1,ref(){return n=!1,o.id?.ref?.(),o},unref(){return n=!0,o.id?.unref?.(),o}};if(e===Number.POSITIVE_INFINITY||e>Number.MAX_SAFE_INTEGER)return o;(!Number.isFinite(e)||e<0)&&(e=0);let i=performance.now()+e,s=a=>{o.cleared||(a<=2147483647?(o.id=globalThis.setTimeout(()=>{o.cleared||t(...r)},a),n&&o.id?.unref?.()):(o.id=globalThis.setTimeout(()=>{let c=performance.now(),f=Math.max(0,i-c);s(f)},2147483647),n&&o.id?.unref?.()))};return s(e),o}function mu(t){!t||typeof t!="object"||!t[hu]||(t.cleared=!0,t.id!==void 0&&(globalThis.clearTimeout(t.id),t.id=void 0))}var zh=new WeakMap;function Hh({clearTimeout:t,setTimeout:e}={}){return(r,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(o.reason);let i,s,a,c=t??clearTimeout,f=()=>{c(i),a(o.reason)},u=()=>{o&&o.removeEventListener("abort",f)},l=new Promise((h,m)=>{s=()=>{u(),h(n)},a=m,i=(e??setTimeout)(s,r)});return o&&o.addEventListener("abort",f,{once:!0}),zh.set(l,()=>{c(i),i=null,s()}),l}}var jh=Hh({setTimeout:pu,clearTimeout:mu}),yu=jh;function gu(t,e,r){let n,o,i=!1;function s(){let f={signal:o.signal},u;r?.timeout!=null&&(u=Xr([o.signal,AbortSignal.timeout(r.timeout)]),f.signal=u),i=!0,Promise.resolve().then(async()=>{await t(f)}).catch(()=>{}).finally(()=>{u!=null&&(u.aborted?u.clear():u.addEventListener("abort",()=>{u.clear()},{once:!0})),i=!1,!o.signal.aborted&&(n=setTimeout(s,e))})}let a=Gr(s,r?.debounce??100),c=!1;return{setInterval:f=>{e!==f&&(e=f,n!=null&&(clearTimeout(n),n=setTimeout(s,e)))},setTimeout:f=>{r??={},r.timeout=f},run:()=>{i||(clearTimeout(n),a())},start:()=>{c||(c=!0,o=new AbortController,o.signal,r?.runImmediately===!0?queueMicrotask(()=>{s()}):n=setTimeout(s,e))},stop:()=>{clearTimeout(n),o?.abort(),c=!1}}}var go=class{routers;localStore;republishTask;log;keychain;started=!1;republishConcurrency;constructor(e,r){this.log=e.logger.forComponent("helia:ipns"),this.localStore=r.localStore,this.keychain=e.keychain,this.republishConcurrency=r.republishConcurrency||ma,this.started=!1,this.routers=r.routers??[],this.republishTask=gu(this.#e.bind(this),r.republishInterval??36e5,{runImmediately:!0}),this.started&&this.republishTask.start()}start(){this.started||(this.started=!0,this.republishTask.start())}stop(){this.started&&(this.started=!1,this.republishTask.stop())}async#e(e={}){if(!this.started)return;this.log("starting ipns republish records loop");let r=new dr({concurrency:this.republishConcurrency});try{let n=[],o=0;for await(let{routingKey:i,record:s,metadata:a,created:c}of this.localStore.list(e)){if(o++,a==null){this.log("no metadata found for record %b, skipping",i);continue}let f;try{f=Q.decode(s)}catch{this.log.trace("skipping invalid record %b because could not decode",i);continue}if(f.data==null){this.log.trace("skipping record %b because data was missing",i);continue}let u;try{u=ke(f.data)}catch{this.log.trace("skipping record %b because could not decode data",i);continue}if(!eu(c,new Date(W(u.Validity)))){this.log.trace("skipping record %b within republish threshold",i);continue}let l=u.Sequence+1n,h=u.TTL??yn,m;try{m=await this.keychain.exportKey(a.keyName)}catch(L){this.log.error("missing key %s, skipping republishing record - %e",a.keyName,L);continue}try{let L=await ur(m,W(u.Value),l,a.lifetime,{...e,ttlNs:h});n.push({routingKey:i,record:L})}catch(L){this.log.error("error creating updated IPNS record for %s - %e",i,L);continue}}this.log(`found ${n.length}/${o} records to republish`);for(let{routingKey:i,record:s}of n)r.add(async()=>{try{let a=Q.encode(s);await Promise.all(this.routers.map(c=>c.put(i,a,e)))}catch(a){this.log.error("error republishing record - %e",a)}},e)}catch(n){this.log.error("error during republish - %e",n)}await r.onIdle(e)}};var Wr;(function(t){let e;t.codec=()=>(e==null&&(e=Ze((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.key!=null&&i.key.byteLength>0&&(s.uint32(10),s.bytes(i.key)),i.value!=null&&i.value.byteLength>0&&(s.uint32(18),s.bytes(i.value)),i.timeReceived!=null&&i.timeReceived!==""&&(s.uint32(42),s.string(i.timeReceived)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={key:Ne(0),value:Ne(0),timeReceived:""},f=s==null?i.len:i.pos+s;for(;i.pos<f;){let u=i.uint32();switch(u>>>3){case 1:{c.key=i.bytes();break}case 2:{c.value=i.bytes();break}case 5:{c.timeReceived=i.string();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let f=s==null?i.len:i.pos+s;for(;i.pos<f;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.key`,value:i.bytes()};break}case 2:{yield{field:`${a}.value`,value:i.bytes()};break}case 5:{yield{field:`${a}.timeReceived`,value:i.string()};break}default:{i.skipType(u&7);break}}}})),e);function r(i){return je(i,t.codec())}t.encode=r;function n(i,s){return He(i,t.codec(),s)}t.decode=n;function o(i,s){return Ye(i,t.codec(),s)}t.stream=o})(Wr||(Wr={}));function bu(t){let e=t.getUTCFullYear(),r=String(t.getUTCMonth()+1).padStart(2,"0"),n=String(t.getUTCDate()).padStart(2,"0"),o=String(t.getUTCHours()).padStart(2,"0"),i=String(t.getUTCMinutes()).padStart(2,"0"),s=String(t.getUTCSeconds()).padStart(2,"0"),a=t.getUTCMilliseconds(),c=String(a*1e3*1e3).padStart(9,"0");return`${e}-${r}-${n}T${o}:${i}:${s}.${c}Z`}function wu(t){let e=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),r=String(t).trim().match(e);if(r==null)throw new Error("Invalid format");let n=parseInt(r[1],10),o=parseInt(r[2],10)-1,i=parseInt(r[3],10),s=parseInt(r[4],10),a=parseInt(r[5],10),c=parseInt(r[6],10),f=parseInt(r[7].slice(0,-6),10);return new Date(Date.UTC(n,o,i,s,a,c,f))}var vt=class t{key;value;timeReceived;constructor(e,r,n){if(!(e instanceof Uint8Array))throw new Error("key must be a Uint8Array");if(!(r instanceof Uint8Array))throw new Error("value must be a Uint8Array");this.key=e,this.value=r,this.timeReceived=n}serialize(){return Wr.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:bu(this.timeReceived)}}static deserialize(e){let r=Wr.decode(e);return new t(r.key,r.value,new Date(r.timeReceived))}static fromDeserialized(e){let r=wu(e.timeReceived);if(e.key==null)throw new Error("key missing from deserialized object");if(e.value==null)throw new Error("value missing from deserialized object");return new t(e.key,e.value,r)}};async function xu(t,e,r,n){let o=await crypto.subtle.importKey("jwk",t,{name:"ECDSA",namedCurve:t.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let i=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,xe(e),xe(r.subarray()));return n?.signal?.throwIfAborted(),i}var Gh=parseInt("11111",2),as=parseInt("10000000",2),Xh=parseInt("01111111",2),Eu={0:Qr,1:Qr,2:Wh,3:ep,4:tp,5:Jh,6:Qh,16:Qr,22:Qr,48:Qr};function cs(t,e={offset:0}){let r=t[e.offset]&Gh;if(e.offset++,Eu[r]!=null)return Eu[r](t,e);throw new Error("No decoder for tag "+r)}function Jr(t,e){let r=0;if((t[e.offset]&as)===as){let n=t[e.offset]&Xh,o="0x";e.offset++;for(let i=0;i<n;i++,e.offset++){if(e.offset>=t.byteLength)throw new Error("invalid DER element length");o+=t[e.offset].toString(16).padStart(2,"0")}r=parseInt(o,16)}else r=t[e.offset],e.offset++;if(!Number.isInteger(r)||r<0||r>t.byteLength-e.offset)throw new Error("invalid DER element length");return r}function Qr(t,e){Jr(t,e);let r=[];for(;!(e.offset>=t.byteLength);){let n=cs(t,e);if(n===null)break;r.push(n)}return r}function Wh(t,e){let r=Jr(t,e),n=e.offset,o=e.offset+r,i=[];for(let s=n;s<o;s++)s===n&&t[s]===0||i.push(t[s]);return e.offset+=r,Uint8Array.from(i)}function Qh(t,e){let r=Jr(t,e),n=e.offset+r,o=t[e.offset];e.offset++;let i=0,s=0;o<40?(i=0,s=o):o<80?(i=1,s=o-40):(i=2,s=o-80);let a=`${i}.${s}`,c=[];for(;e.offset<n;){let f=t[e.offset];if(e.offset++,c.push(f&127),f<128){c.reverse();let u=0;for(let l=0;l<c.length;l++)u+=c[l]<<l*7;a+=`.${u}`,c=[]}}return a}function Jh(t,e){return e.offset++,null}function ep(t,e){let r=Jr(t,e),n=t[e.offset];e.offset++;let o=t.subarray(e.offset,e.offset+r-1);if(e.offset+=r,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function tp(t,e){let r=Jr(t,e),n=t.subarray(e.offset,e.offset+r);return e.offset+=r,n}function rp(t){let e=t.toString(16);e.length%2===1&&(e="0"+e);let r=new Ie;for(let n=0;n<e.length;n+=2)r.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return r}function us(t){if(t.byteLength<128)return Uint8Array.from([t.byteLength]);let e=rp(t.byteLength);return new Ie(Uint8Array.from([e.byteLength|as]),e)}function Su(t){let e=new Ie,r=128;return(t.subarray()[0]&r)===r&&e.append(Uint8Array.from([0])),e.append(t),new Ie(Uint8Array.from([2]),us(e),e)}function vu(t){let e=Uint8Array.from([0]),r=new Ie(e,t);return new Ie(Uint8Array.from([3]),us(r),r)}function bo(t,e=48){let r=new Ie;for(let n of t)r.append(n);return new Ie(Uint8Array.from([e]),us(r),r)}var np=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),op=Uint8Array.from([6,5,43,129,4,0,34]),ip=Uint8Array.from([6,5,43,129,4,0,35]),sp={ext:!0,kty:"EC",crv:"P-256"},ap={ext:!0,kty:"EC",crv:"P-384"},cp={ext:!0,kty:"EC",crv:"P-521"},fs=32,ls=48,ds=66;function Au(t){let e=cs(t);return Tu(e)}function Tu(t){let e=t[1][1][0],r=1,n,o;if(e.byteLength===fs*2+1)return n=W(e.subarray(r,r+fs),"base64url"),o=W(e.subarray(r+fs),"base64url"),new hr({...sp,key_ops:["verify"],x:n,y:o});if(e.byteLength===ls*2+1)return n=W(e.subarray(r,r+ls),"base64url"),o=W(e.subarray(r+ls),"base64url"),new hr({...ap,key_ops:["verify"],x:n,y:o});if(e.byteLength===ds*2+1)return n=W(e.subarray(r,r+ds),"base64url"),o=W(e.subarray(r+ds),"base64url"),new hr({...cp,key_ops:["verify"],x:n,y:o});throw new nt(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Bu(t){return bo([Su(Uint8Array.from([1])),bo([up(t.crv)],160),bo([vu(new Ie(Uint8Array.from([4]),se(t.x??"","base64url"),se(t.y??"","base64url")))],161)]).subarray()}function up(t){if(t==="P-256")return np;if(t==="P-384")return op;if(t==="P-521")return ip;throw new nt(`Invalid curve ${t}`)}var hr=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Bu(this.jwk)),this._raw}toMultihash(){return Ke.digest(pr(this))}toCID(){return te.createV1(114,this.toMultihash())}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:de(this.raw,e.raw)}async verify(e,r,n){return xu(this.jwk,r,e,n)}};var wo=BigInt(4294967295),Iu=BigInt(32);function fp(t,e=!1){return e?{h:Number(t&wo),l:Number(t>>Iu&wo)}:{h:Number(t>>Iu&wo)|0,l:Number(t&wo)|0}}function Cu(t,e=!1){let r=t.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=fp(t[i],e);[n[i],o[i]]=[s,a]}return[n,o]}var lp=t=>t/2**32|0,dp=t=>t>>>0;function _u(t,e,r,n){let o=lp(r),i=dp(r);t.setUint32(e,n?i:o,n),t.setUint32(e+4,n?o:i,n)}var hs=(t,e,r)=>t>>>r,ps=(t,e,r)=>t<<32-r|e>>>r,Kt=(t,e,r)=>t>>>r|e<<32-r,Vt=(t,e,r)=>t<<32-r|e>>>r,en=(t,e,r)=>t<<64-r|e>>>r-32,tn=(t,e,r)=>t>>>r-32|e<<64-r;function Je(t,e,r,n){let o=(e>>>0)+(n>>>0);return{h:t+r+(o/2**32|0)|0,l:o|0}}var Du=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Ru=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,Lu=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),Nu=(t,e,r,n,o)=>e+r+n+o+(t/2**32|0)|0,Uu=(t,e,r,n,o)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(o>>>0),ku=(t,e,r,n,o,i)=>e+r+n+o+i+(t/2**32|0)|0;function xo(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in t&&t.BYTES_PER_ELEMENT===1}var ms=t=>t?`"${t}" `:"";function st(t,e=""){if(typeof t!="number")throw new TypeError(ms(e)+"expected number, got "+typeof t);if(!Number.isSafeInteger(t)||t<0)throw new RangeError(ms(e)+"expected integer >= 0, got "+t);return t}function Fe(t,e,r=""){if(xo(t)&&(e===void 0||t.length===e))return t;e!==void 0&&st(e,"length");let n=xo(t),o=e!==void 0?` of length ${e}`:"",i=n?`length=${t.length}`:`type=${typeof t}`,s=ms(r)+"expected Uint8Array"+o+", got "+i;throw n?new RangeError(s):new TypeError(s)}function Eo(t){if(typeof t!="function"||typeof t.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(st(t.outputLen),st(t.blockLen),t.outputLen<1||t.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}var Fu=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof t)};function mr(t,e=!0){if(t.destroyed)throw new Error("hash was destroyed");if(e&&t.finished)throw new Error("digest() was already called")}function So(t,e){Fe(t,void 0,"output");let r=e.outputLen;if(!(t.length>=r))throw new RangeError('"output" expected length >= '+r)}function $t(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function vo(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function $e(t,e){return t<<32-e|t>>>e}var Pu=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",pp=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ao(t){if(Fe(t),Pu)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=pp[t[r]];return e}function Ou(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:void 0}function To(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);if(Pu)try{return Uint8Array.fromHex(t)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=t.length,r=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let o=0,i=0;o<r;o++,i+=2){let s=Ou(t.charCodeAt(i)),a=Ou(t.charCodeAt(i+1));if(s===void 0||a===void 0){let c=t[i]+t[i+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function ys(...t){let e=0;for(let n=0;n<t.length;n++){let o=t[n];Fe(o),e+=o.length}let r=new Uint8Array(e);for(let n=0,o=0;n<t.length;n++){let i=t[n];r.set(i,o),o+=i.length}return r}function mp(t,e,r="opts"){return Fu(t,"defaults"),e!==void 0&&Fu(e,r),Object.assign(t,e)}function gs(t,e={}){if(typeof t!="function")throw new TypeError('"hashCons" expected function, got type='+typeof t);e=mp({},e,"info");let r=(o,i)=>t(i).update(o).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=o=>t(o),Object.assign(r,e),Object.freeze(r)}function Mu(t=32){st(t,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(t>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${t}`);return e.getRandomValues(new Uint8Array(t))}var bs=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});function Ku(t,e,r){return t&e^~t&r}function Vu(t,e,r){return t&e^t&r^e&r}var rn=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,o){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=vo(this.buffer)}update(e){mr(this),Fe(e);let{view:r,buffer:n,blockLen:o}=this,i=e.length,s=!1;for(let a=0;a<i;){let c=Math.min(o-this.pos,i-a);if(c===o){let f=vo(e);for(;o<=i-a;a+=o)this.process(f,a);s=!0;continue}n.set(a===0&&c===i?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(r,0),this.pos=0,s=!0)}return this.length+=e.length,s&&this.roundClean(),this}digestInto(e){mr(this),So(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;r[s++]=128,r.fill(0,s),this.padOffset>o-s&&(this.process(n,0),r.fill(0)),_u(n,o-8,this.length*8,i),this.process(n,0),this.roundClean();let a=e===r?n:vo(e),c=this.outputLen,f=c/4,u=this.get();if(c%4||f>u.length)throw new Error("invalid outputLen");for(let l=0;l<f;l++)a.setUint32(4*l,u[l],i)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:r,length:n,finished:o,destroyed:i,pos:s}=this;return e.destroyed=i,e.finished=o,e.length=n,e.pos=s,s&&e.buffer.set(r),e}clone(){return this._cloneInto()}},$u=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var qu=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var yp=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]),At=new Uint32Array(64),ws=class extends rn{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,r){super(64,e,8,!1),this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){let{A:e,B:r,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[e,r,n,o,i,s,a,c]}set(e,r,n,o,i,s,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,r){for(let l=0;l<16;l++,r+=4)At[l]=e.getUint32(r,!1);for(let l=16;l<64;l++){let h=At[l-15],m=At[l-2],L=$e(h,7)^$e(h,18)^h>>>3,v=$e(m,17)^$e(m,19)^m>>>10;At[l]=v+At[l-7]+L+At[l-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:f,H:u}=this;for(let l=0;l<64;l++){let h=$e(a,6)^$e(a,11)^$e(a,25),m=u+h+Ku(a,c,f)+yp[l]+At[l]|0,v=($e(n,2)^$e(n,13)^$e(n,22))+Vu(n,o,i)|0;u=f,f=c,c=a,a=s+m|0,s=i,i=o,o=n,n=m+v|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,f=f+this.G|0,u=u+this.H|0,this.set(n,o,i,s,a,c,f,u)}roundClean(){$t(At)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),$t(this.buffer)}},xs=class extends ws{constructor(){super(32,$u)}};var zu=Cu(["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(t=>BigInt(t))),gp=zu[0],bp=zu[1],Tt=new Uint32Array(80),Bt=new Uint32Array(80),Es=class extends rn{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,r){super(128,e,16,!1),this.Ah=r[0]|0,this.Al=r[1]|0,this.Bh=r[2]|0,this.Bl=r[3]|0,this.Ch=r[4]|0,this.Cl=r[5]|0,this.Dh=r[6]|0,this.Dl=r[7]|0,this.Eh=r[8]|0,this.El=r[9]|0,this.Fh=r[10]|0,this.Fl=r[11]|0,this.Gh=r[12]|0,this.Gl=r[13]|0,this.Hh=r[14]|0,this.Hl=r[15]|0}get(){let{Ah:e,Al:r,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:f,El:u,Fh:l,Fl:h,Gh:m,Gl:L,Hh:v,Hl:b}=this;return[e,r,n,o,i,s,a,c,f,u,l,h,m,L,v,b]}set(e,r,n,o,i,s,a,c,f,u,l,h,m,L,v,b){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=f|0,this.El=u|0,this.Fh=l|0,this.Fl=h|0,this.Gh=m|0,this.Gl=L|0,this.Hh=v|0,this.Hl=b|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,r){for(let y=0;y<16;y++,r+=4)Tt[y]=e.getUint32(r),Bt[y]=e.getUint32(r+=4);for(let y=16;y<80;y++){let N=Tt[y-15]|0,U=Bt[y-15]|0,V=Kt(N,U,1)^Kt(N,U,8)^hs(N,U,7),$=Vt(N,U,1)^Vt(N,U,8)^ps(N,U,7),w=Tt[y-2]|0,S=Bt[y-2]|0,I=Kt(w,S,19)^en(w,S,61)^hs(w,S,6),F=Vt(w,S,19)^tn(w,S,61)^ps(w,S,6),x=Lu($,F,Bt[y-7],Bt[y-16]),q=Nu(x,V,I,Tt[y-7],Tt[y-16]);Tt[y]=q|0,Bt[y]=x|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:f,Dl:u,Eh:l,El:h,Fh:m,Fl:L,Gh:v,Gl:b,Hh:E,Hl:B}=this;for(let y=0;y<80;y++){let N=Kt(l,h,14)^Kt(l,h,18)^en(l,h,41),U=Vt(l,h,14)^Vt(l,h,18)^tn(l,h,41),V=l&m^~l&v,$=h&L^~h&b,w=Uu(B,U,$,bp[y],Bt[y]),S=ku(w,E,N,V,gp[y],Tt[y]),I=w|0,F=Kt(n,o,28)^en(n,o,34)^en(n,o,39),x=Vt(n,o,28)^tn(n,o,34)^tn(n,o,39),q=n&i^n&a^i&a,C=o&s^o&c^s&c;E=v|0,B=b|0,v=m|0,b=L|0,m=l|0,L=h|0,{h:l,l:h}=Je(f|0,u|0,S|0,I|0),f=a|0,u=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let A=Du(I,x,C);n=Ru(A,S,F,q),o=A|0}({h:n,l:o}=Je(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=Je(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Je(this.Ch|0,this.Cl|0,a|0,c|0),{h:f,l:u}=Je(this.Dh|0,this.Dl|0,f|0,u|0),{h:l,l:h}=Je(this.Eh|0,this.El|0,l|0,h|0),{h:m,l:L}=Je(this.Fh|0,this.Fl|0,m|0,L|0),{h:v,l:b}=Je(this.Gh|0,this.Gl|0,v|0,b|0),{h:E,l:B}=Je(this.Hh|0,this.Hl|0,E|0,B|0),this.set(n,o,i,s,a,c,f,u,l,h,m,L,v,b,E,B)}roundClean(){$t(Tt,Bt)}destroy(){this.destroyed=!0,$t(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Ss=class extends Es{constructor(){super(64,qu)}};var Hu=gs(()=>new xs,bs(1));var vs=gs(()=>new Ss,bs(3));function Io(t,e,r=()=>{}){if(!Array.isArray(t))throw new TypeError(`"${e}" expected array, got type=${typeof t}`);for(let n=0;n<t.length;n++)r(t[n],`${e}[${n}]`);return t}var G=(t,e,r)=>Fe(t,e,r),As=st;function Yu(t,e=""){if(typeof t!="string"){let r=e&&`"${e}" `;throw new TypeError(r+"expected string, got type="+typeof t)}return t}function It(t,e="object"){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof t}`);return t}function qt(t,e){if(typeof t!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof t}`);return t}var nn=Ao,Oe=(...t)=>ys(...t),yr=t=>To(t),_t=xo,zt=t=>Mu(t),Bo=BigInt(0),ju=BigInt(1),wp=t=>t?`"${t}" `:"";function Se(t,e=""){if(typeof t!="boolean")throw new TypeError(wp(e)+"expected boolean, got type="+typeof t);return t}function Co(t){if(typeof t=="bigint"){if(!Ct(t))throw new RangeError("positive bigint expected, got "+t)}else As(t);return t}function Dt(t,e=""){if(typeof t!="number"){let r=e&&`"${e}" `;throw new TypeError(r+"expected number, got type="+typeof t)}if(!Number.isSafeInteger(t)){let r=e&&`"${e}" `;throw new RangeError(r+"expected safe integer, got "+t)}}function on(t){let e=Co(t).toString(16);return e.length&1?"0"+e:e}function Zu(t){if(typeof t!="string")throw new TypeError("hex string expected, got "+typeof t);return t===""?Bo:BigInt("0x"+t)}function et(t){return Zu(Ao(t))}function Ht(t){return Zu(Ao(Do(Fe(t)).reverse()))}function _o(t,e){if(st(e),e===0)throw new Error("zero output length is invalid");t=Co(t);let r=e*2,n=t.toString(16);if(n.length>r)throw new RangeError("number is too large");return To(n.padStart(r,"0"))}function Ts(t,e){return _o(t,e).reverse()}function Do(t){return Uint8Array.from(G(t))}function Ct(t){return typeof t=="bigint"&&Bo<=t}function Bs(t,e,r){return Ct(t)&&Ct(e)&&Ct(r)&&e<=t&&t<r}function gr(t,e,r,n){if(!Bs(e,r,n))throw new RangeError("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function br(t){if(t<Bo)throw new Error("expected non-negative bigint, got "+t);return t===Bo?0:t.toString(2).length}var sn=t=>(Dt(t,"n"),(ju<<BigInt(t))-ju);function Gu(t,e,r){if(st(t,"hashLen"),st(e,"qByteLen"),typeof r!="function")throw new TypeError("hmacFn must be a function");let n=b=>new Uint8Array(b),o=Uint8Array.of(),i=Uint8Array.of(0),s=Uint8Array.of(1),a=1e3,c=n(t),f=n(t),u=0,l=()=>{c.fill(1),f.fill(0),u=0},h=(...b)=>r(f,Oe(c,...b)),m=(b=o)=>{f=h(i,b),c=h(),b.length!==0&&(f=h(s,b),c=h())},L=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let b=0,E=[];for(;b<e;){c=h();let B=c.slice();E.push(B),b+=c.length}return Oe(...E)};return(b,E)=>{l(),m(b);let B;for(;(B=E(L()))===void 0;)m();return l(),B}}function ve(t,e={},r={},n="object"){It(t,n),It(e,"fields"),It(r,"optFields");function o(s,a,c){let f=n==="object"?`param "${String(s)}"`:`"${n}.${String(s)}"`,u=t[s];if(!Object.hasOwn(t,s)&&(c?u!==void 0:a!=="function"))throw new TypeError(`${f} is invalid: expected own property`);if(c&&u===void 0)return;let l=typeof u;if(l!==a||u===null)throw new TypeError(`${f} is invalid: expected ${a}, got ${l}`)}let i=(s,a)=>Object.entries(s).forEach(([c,f])=>o(c,f,a));i(e,!1),i(r,!0)}var le=BigInt(0),X=BigInt(1),Rt=BigInt(2),Qu=BigInt(3),Is=BigInt(4),Ju=BigInt(5),xp=BigInt(7),ef=BigInt(8),Ep=BigInt(9),Sp=BigInt(15),tf=BigInt(16),vp=BigInt("0x10000000000000000");function re(t,e){if(e<=le)throw new Error("mod: expected positive modulus, got "+e);let r=t%e;return r>=le?r:e+r}function rf(t,e,r){if(r<=X)throw new Error("pow: expected modulus > 1, got "+r);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<le)throw new Error("invalid exponent, negatives unsupported");if(e===le)return X;if(e===X)return t;let n=t%r;if(n<le&&(n+=r),e<vp){let a=X;for(;e>le;)e&X&&(a=a*n%r),n=n*n%r,e>>=X;return a}let o=[];for(;e>le;)o.push(Number(e&Sp)),e>>=Is;let i=new Array(16);i[0]=X,i[1]=n;for(let a=2;a<16;a++)i[a]=i[a-1]*n%r;let s=i[o[o.length-1]];for(let a=o.length-2;a>=0;a--){s=s*s%r,s=s*s%r,s=s*s%r,s=s*s%r;let c=o[a];c!==0&&(s=s*i[c]%r)}return s}function ee(t,e,r){if(r<=X)throw new Error("pow2: expected modulus > 1, got "+r);if(e<le)throw new Error("pow2: expected non-negative exponent, got "+e);let n=t;for(;e-- >le;)n*=n,n%=r;return n}function Xu(t,e){if(t===le)throw new Error("invert: expected non-zero number");if(e<=X)throw new Error("invert: expected modulus > 1, got "+e);let r=re(t,e),n=e,o=le,i=X;for(;r!==le;){let a=n/r,c=n-r*a,f=o-i*a;n=r,r=c,o=i,i=f}if(n!==X)throw new Error("invert: does not exist");return re(o,e)}function nf(t,e){if(e<=X)throw new Error("invertCt: expected prime modulus > 1, got "+e);let r=re(t,e);if(r===le)throw new Error("invertCt: expected non-zero number");let n=rf(r,e-Rt,e);if(re(r*n,e)!==X)throw new Error("invertCt: does not exist");return n}function Cs(t,e,r){let n=t;if(!n.eql(n.sqr(e),r))throw new Error("Cannot find square root")}function _s(t,e){if((t&X)===le)throw new Error(e+": expected odd modulus, got "+t)}function of(t,e){let r=t,n=(r.ORDER+X)/Is,o=r.pow(e,n);return Cs(r,o,e),o}function Ap(t,e){let r=t,n=(r.ORDER-Ju)/ef,o=r.mul(e,Rt),i=r.pow(o,n),s=r.mul(e,i),a=r.mul(r.mul(s,Rt),i),c=r.mul(s,r.sub(a,r.ONE));return Cs(r,c,e),c}function Tp(t){let e=xr(t),r=sf(t),n=r(e,e.neg(e.ONE)),o=r(e,n),i=r(e,e.neg(n)),s=(t+xp)/tf;return((a,c)=>{let f=a,u=f.pow(c,s),l=f.mul(u,n),h=f.mul(u,o),m=f.mul(u,i),L=f.eql(f.sqr(l),c),v=f.eql(f.sqr(h),c);u=f.cmov(u,l,L),l=f.cmov(m,h,v);let b=f.eql(f.sqr(l),c),E=f.cmov(u,l,b);return Cs(f,E,c),E})}function sf(t){if(t<Qu)throw new Error("sqrt is not defined for small field");_s(t,"tonelliShanks");let e=t-X,r=0;for(;e%Rt===le;)e/=Rt,r++;let n=Rt,o=xr(t);for(;an(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return of;let i=o.pow(n,e),s=(e+X)/Rt;return function(c,f){let u=c;if(u.is0(f))return f;if(an(u,f)!==1)throw new Error("Cannot find square root");let l=r,h=u.mul(u.ONE,i),m=u.pow(f,e),L=u.pow(f,s);for(;!u.eql(m,u.ONE);){if(u.is0(m))throw new Error("Cannot find square root: probably non-prime P");let v=1,b=u.sqr(m);for(;!u.eql(b,u.ONE);)if(v++,b=u.sqr(b),v===l)throw new Error("Cannot find square root");let E=X<<BigInt(l-v-1),B=u.pow(h,E);l=v,h=u.sqr(B),m=u.mul(m,h),L=u.mul(L,B)}return L}}function Bp(t){return _s(t,"Fp.sqrt"),t%Is===Qu?of:t%ef===Ju?Ap:t%tf===Ep?Tp(t):sf(t)}var af=(t,e)=>(re(t,e)&X)===X,Ip=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function wr(t){if(It(t,"field"),typeof t.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof t.ORDER);Dt(t.BYTES,"BYTES"),Dt(t.BITS,"BITS");for(let e of Ip)qt(t[e],"field."+e);if(t.BYTES<1||t.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(t.ORDER<=X)throw new Error("invalid field: expected ORDER > 1, got "+t.ORDER);return t}function Lo(t,e,r=!1){wr(t),Io(e,"nums"),Se(r,"passZero");let n=t,o=new Array(e.length).fill(r?n.ZERO:void 0),i=e.reduce((a,c,f)=>n.is0(c)?a:(o[f]=a,n.mul(a,c)),n.ONE),s=n.inv(i);return e.reduceRight((a,c,f)=>n.is0(c)?a:(o[f]=n.mul(a,o[f]),n.mul(a,c)),s),o}function an(t,e){wr(t);let r=t;_s(r.ORDER,"FpLegendre");let n=(r.ORDER-X)/Rt,o=r.pow(e,n),i=r.eql(o,r.ONE),s=r.eql(o,r.ZERO),a=r.eql(o,r.neg(r.ONE));if(!i&&!s&&!a)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function Cp(t,e){if(e!==void 0&&As(e),t<=le)throw new Error("invalid n length: expected positive n, got "+t);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let r=br(t);if(e!==void 0&&e<r)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${r})`);let n=e!==void 0?e:r,o=Math.ceil(n/8);return{nBitLength:n,nByteLength:o}}var Wu=new WeakMap,Ro=class{ORDER;BITS;BYTES;isLE;ZERO=le;ONE=X;_lengths;_mod;constructor(e,r={}){if(e<=X)throw new Error("invalid field: expected ORDER > 1, got "+e);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:r.sqrt,enumerable:!0}),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=Object.freeze(r.allowedLengths.slice())),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:o,nByteLength:i}=Cp(e,n);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=i,Object.freeze(this)}create(e){return re(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return le<=e&&e<this.ORDER}is0(e){return e===le}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&X)===X}neg(e){return re(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return re(e*e,this.ORDER)}add(e,r){return re(e+r,this.ORDER)}sub(e,r){return re(e-r,this.ORDER)}mul(e,r){return re(e*r,this.ORDER)}pow(e,r){return rf(e,r,this.ORDER)}div(e,r){return re(e*Xu(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return Xu(e,this.ORDER)}sqrt(e){let r=Wu.get(this);return r||Wu.set(this,r=Bp(this.ORDER)),r(this,e)}toBytes(e){return this.isLE?Ts(e,this.BYTES):_o(e,this.BYTES)}fromBytes(e,r=!1){G(e);let{_lengths:n,BYTES:o,isLE:i,ORDER:s,_mod:a}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let f=new Uint8Array(o);f.set(e,i?0:f.length-e.length),e=f}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=i?Ht(e):et(e);if(a&&(c=re(c,s)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Lo(this,e,!0)}cmov(e,r,n){return Se(n,"condition"),n?r:e}};function xr(t,e={}){return Object.freeze(Ro.prototype),new Ro(t,e)}function cf(t){if(typeof t!="bigint")throw new Error("field order must be bigint");if(t<=X)throw new Error("field order must be greater than 1");let e=br(t-X);return Math.ceil(e/8)}function No(t){let e=cf(t);return e+Math.ceil(e/2)}function Uo(t,e,r=!1){G(t);let n=t.length,o=cf(e),i=Math.max(No(e),16);if(n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=r?Ht(t):et(t),a=re(s,e-X)+X;return r?Ts(a,o):_o(a,o)}var Ls=BigInt(0),cn=BigInt(1),_p=BigInt(4),Ds=16,uf=128,Dp=5,ff=2**31;function Lt(t){let e=t;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof t);qt(e.fromAffine,"Point.fromAffine"),qt(e.fromBytes,"Point.fromBytes"),qt(e.fromHex,"Point.fromHex"),It(e.BASE,"Point.BASE"),It(e.ZERO,"Point.ZERO"),wr(e.Fp),wr(e.Fn)}function ko(t,e){Lt(t),df(e,t);let r=Lo(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function Rp(t,e,r=1){if(!Number.isSafeInteger(t)||t<r||t>e)throw new Error("invalid window size, expected ["+r+".."+e+"], got W="+t)}function Lp(t,e){let r=t*(4*e+128);if(r>ff)throw new Error("invalid window size: table would need ~"+Math.ceil(r/2**20)+" MiB, max "+ff/2**20+" MiB")}function Ns(t,e){if(t!==void 0){qt(t,"randomBytes");try{let r=t(e);if(!_t(r)||r.length!==e)return}catch{return}return t}}function df(t,e){Io(t,"points"),t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function Np(t,e,r){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,o)=>{if(!(r===void 0?e.isValid(n):Ct(n)&&n<r))throw new Error("invalid scalar at index "+o)})}var hf=new WeakMap;function Rs(t){return hf.get(t)||1}function Up(t,e){let r=t.double(),n=[t];for(let o=1;o<e;o++)n.push(n[o-1].add(r));return n}function kp(t,e){let r=2**e,n=r/2,o=BigInt(r-1),i=[];for(;t>Ls;){let s=0;t&cn&&(s=Number(t&o),s>=n&&(s-=r),t-=BigInt(s)),i.push(s),t>>=cn}return i}function Fp(t,e,r){let n=2**e,o=n/2,i=BigInt(n-1),s=BigInt(e),a=[];for(let c=0;c<r;c++){let f=Number(t&i);t>>=s,f>o&&(f-=n,t+=cn),a.push(f)}if(t!==Ls)throw new Error("invalid wnaf");return a}function Op(t,e,r){let n=0;for(let i of r)n=Math.max(n,i.length);let o=t;for(let i=n-1;i>=0;i--){i!==n-1&&(o=o.double());for(let s=0;s<r.length;s++){let a=r[s][i];if(a){let c=e[s][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}var Er=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,r){Lt(e),this.randomBytes=Ns(r,Ds),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,r,n){let o=Math.ceil(n/r)+1,i=2**(r-1),s=[],a=e;for(let c=0;c<o;c++){let f=a;for(let u=0;u<i;u++)s.push(f),f=f.add(a);a=s[s.length-1].double()}return{W:r,bits:n,windows:o,comp:s}}wnafCachedCT(e,r){let{W:n,windows:o,comp:i}=e,s=2**(n-1),a=Fp(r,n,o),c=this.ZERO,f=this.BASE;for(let u=0;u<o;u++){let l=a[u],h=u*s,m=Math.abs(l)-1,L=i[h];for(let b=1;b<s;b++)L=b===m?i[h+b]:L;let v=L.negate();l===0?f=f.add(i[h]):c=c.add(l<0?v:L)}return{p:c,f}}getWnafPrecomputes(e,r,n,o){let i=this.wnafPrecomputes.get(r),s=i?.find(a=>a.W===e&&a.bits===n);return s||(s=this.buildWnafTable(r,e,n),typeof o=="function"&&(s={...s,comp:o(s.comp)}),i||(i=[],this.wnafPrecomputes.set(r,i)),i.push(s)),s}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,r){if(this.assertPoint(e),!Bs(r,cn,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,r,n,o){let i=Rs(e);return i===1?this.fixedWindowCT(e,r,n):this.wnafCachedCT(this.getWnafPrecomputes(i,e,n,o),r)}mulCT(e,r,n){return this.validateMulInput(e,r),this.runCT(e,r,this.bits,n)}mulCTBlinded(e,r,n){if(this.validateMulInput(e,r),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let o=this.Point.Fn.BITS+uf,i=this.randomBytes(Ds);if(!_t(i)||i.length!==Ds)throw new Error("randomBytes returned invalid byte array");i[0]=i[0]&63|128;let s=r+et(i)*this.Point.Fn.ORDER;return this.runCT(e,s,o,n)}fixedWindowCT(e,r,n){let o=Dp,i=1<<o,s=sn(o),a=new Array(i);a[0]=this.ZERO;for(let u=1;u<i;u++)a[u]=a[u-1].add(e);let c=Math.ceil(n/o),f=this.ZERO;for(let u=c-1;u>=0;u--){if(u!==c-1)for(let m=0;m<o;m++)f=f.double();let l=Number(r>>BigInt(u*o)&s),h=a[0];for(let m=1;m<i;m++)h=m===l?a[m]:h;f=f.add(h)}return{p:f,f}}shouldBlind(e,r){return this.randomBytes===void 0?!1:r===cn?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,r,n,o){return this.shouldBlind(e,n)?this.mulCTBlinded(e,r,o):this.mulCT(e,r,o)}mulUnsafe(e,r,n){if(this.assertPoint(e),!Ct(r))throw new Error("invalid scalar");let o=Rs(e);if(o===1||r>=this.Point.Fn.ORDER)return Fo(this.Point,[e],[r],!0);let i=this.getWnafPrecomputes(o,e,this.bits,n);return this.wnafCachedCT(i,r).p}setWindowSize(e,r){this.assertPoint(e),Rp(r,this.bits);let n=Math.ceil((this.bits+uf)/r)+1;Lp(n*2**(r-1),this.Point.Fp.BYTES),hf.set(e,r),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Rs(e)!==1}};function Fo(t,e,r,n=!1){if(Lt(t),df(e,t),Se(n,"allowOversized"),Np(r,t.Fn,n?t.Fn.ORDER**_p:void 0),e.length!==r.length)throw new Error("arrays of points and scalars must have equal length");let o=e.map(s=>Up(s,4)),i=r.map(s=>kp(s,4));return Op(t.ZERO,o,i)}function lf(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return wr(e),e}else return xr(t,{isLE:r})}function Oo(t,e,r={},n){if(t!=="weierstrass"&&t!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);ve(r);for(let c of["p","n","h"]){let f=e[c];if(!(Ct(f)&&f!==Ls))throw new Error(`CURVE.${c} must be positive bigint`)}let o=lf(e.p,r.Fp,n),i=lf(e.n,r.Fn,n),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:i}}function Po(t,e){return function(n){let o=t(n);return{secretKey:o,publicKey:e(o)}}}var Mo=BigInt(0),Ko=BigInt(1),Vo=BigInt(2),Pp=BigInt(4),pf=BigInt(8);function Mp(t,e,r,n){let o=t.sqr(r),i=t.sqr(n),s=t.add(t.mul(e.a,o),i),a=t.add(t.ONE,t.mul(e.d,t.mul(o,i)));return t.eql(s,a)}function mf(t,e={}){ve(e,{},{},"extraOpts");let r=e,n=Oo("edwards",t,r,r.FpFnLE),{Fp:o,Fn:i}=n,s=n.CURVE,{h:a}=s;if(an(o,s.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(an(o,s.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");ve(r,{},{uvRatio:"function",randomBytes:"function"});let c=r.randomBytes===void 0?zt:r.randomBytes,f=Vo<<BigInt(o.BYTES*8)-Ko;function u(B){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(B)}let l=r.uvRatio===void 0?(B,y)=>{try{return{isValid:!0,value:o.sqrt(o.div(B,y))}}catch{return{isValid:!1,value:Mo}}}:r.uvRatio;if(!Mp(o,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");let h=o.eql(s.a,o.neg(o.ONE))?B=>o.neg(B):o.eql(s.a,o.ONE)?B=>B:B=>o.mul(s.a,B);function m(B,y,N=!1){let U=N?Ko:Mo;return gr("coordinate "+B,y,U,f),y}function L(B){if(!(B instanceof v))throw new Error("EdwardsPoint expected")}class v{static BASE=new v(s.Gx,s.Gy,o.ONE,o.mul(s.Gx,s.Gy));static ZERO=new v(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=i;X;Y;Z;T;constructor(y,N,U,V){this.X=m("x",y),this.Y=m("y",N),this.Z=m("z",U,!0),this.T=m("t",V),Object.freeze(this)}static CURVE(){return s}static fromAffine(y){if(y instanceof v)throw new Error("extended point not allowed");let{x:N,y:U}=y||{};return m("x",N),m("y",U),new v(N,U,o.ONE,o.mul(N,U))}static fromBytes(y,N=!1){let U=o.BYTES,{a:V,d:$}=s;y=Do(G(y,U,"point")),Se(N,"zip215");let w=Do(y),S=y[U-1];w[U-1]=S&-129;let I=Ht(w),F=N?f:o.ORDER;gr("point.y",I,Mo,F);let x=o.sqr(I),q=o.sub(x,o.ONE),C=o.sub(o.mulN($,x),V),{isValid:A,value:p}=l(q,C);if(!A)throw new Error("bad point: invalid y coordinate");let T=u(p),_=(S&128)!==0;if(!N&&o.is0(p)&&_)throw new Error("bad point: x=0 and x_0=1");return _!==T&&(p=o.neg(p)),v.fromAffine({x:p,y:I})}static fromHex(y,N=!1){return v.fromBytes(yr(y),N)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=6,N=!0){return E.setWindowSize(this,y),N||this.multiply(Vo),this}assertValidity(){let y=this,{a:N,d:U}=s;if(y.is0())throw new Error("bad point: ZERO");let{X:V,Y:$,Z:w,T:S}=y,I=o.sqr(V),F=o.sqr($),x=o.sqr(w),q=o.sqr(x),C=o.mul(I,N),A=o.mul(o.add(C,F),x),p=o.add(q,o.mul(U,o.mul(I,F)));if(!o.eql(A,p))throw new Error("bad point: equation left != right (1)");let T=o.mul(V,$),_=o.mul(w,S);if(!o.eql(T,_))throw new Error("bad point: equation left != right (2)")}equals(y){L(y);let{X:N,Y:U,Z:V}=this,{X:$,Y:w,Z:S}=y,I=o.mul(N,S),F=o.mul($,V),x=o.mul(U,S),q=o.mul(w,V);return o.eql(I,F)&&o.eql(x,q)}is0(){return this.equals(v.ZERO)}negate(){return new v(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){let{X:y,Y:N,Z:U}=this,V=o.sqr(y),$=o.sqr(N),w=o.mul(o.sqr(U),Vo),S=h(V),I=o.addN(y,N),F=o.sub(o.subN(o.sqr(I),V),$),x=o.addN(S,$),q=o.subN(x,w),C=o.subN(S,$),A=o.mul(F,q),p=o.mul(x,C),T=o.mul(F,C),_=o.mul(q,x);return new v(A,p,_,T)}add(y){L(y);let{d:N}=s,{X:U,Y:V,Z:$,T:w}=this,{X:S,Y:I,Z:F,T:x}=y,q=o.mul(U,S),C=o.mul(V,I),A=o.mul(o.mulN(w,N),x),p=o.mul($,F),T=o.sub(o.subN(o.mulN(o.addN(U,V),o.addN(S,I)),q),C),_=o.subN(p,A),M=o.addN(p,A),D=o.sub(C,h(q)),g=o.mul(T,_),O=o.mul(M,D),P=o.mul(T,D),z=o.mul(_,M);return new v(g,O,z,P)}subtract(y){return L(y),this.add(y.negate())}multiply(y){if(!i.isValidNot0(y))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:N,f:U}=E.mulSecret(this,y,a,b);return b([N,U])[0]}multiplyUnsafe(y){if(!i.isValid(y))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return y===Mo?v.ZERO:this.is0()||y===Ko?this:E.mulUnsafe(this,y,b)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return E.mulUnsafe(this,s.n).is0()}toAffine(y){let N=this,U=y;if(U!=null&&typeof U!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof U);let{X:V,Y:$,Z:w}=N,S=N.is0();U==null&&(U=S?o.create(pf):o.inv(w));let I=o.mul(V,U),F=o.mul($,U),x=o.mul(w,U);if(S)return{x:o.ZERO,y:o.ONE};if(!o.eql(x,o.ONE))throw new Error("invZ was invalid");return{x:I,y:F}}clearCofactor(){return a===Ko?this:a===Vo?this.double():a===Pp?this.double().double():a===pf?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:y,y:N}=this.toAffine(),U=o.toBytes(N);return U[U.length-1]|=u(y)?128:0,U}toHex(){return nn(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let b=B=>ko(v,B),E=new Er(v,c);return E.bits>=6&&v.BASE.precompute(6),Object.freeze(v.prototype),Object.freeze(v),v}function yf(t,e,r={}){if(Lt(t),typeof e!="function")throw new Error('"hash" function param is required');let n=e,o=r;ve(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:i}=o,{BASE:s,Fp:a,Fn:c}=t,f=n.outputLen,u=2*a.BYTES;if(f!==void 0&&(Dt(f,"hash.outputLen"),f!==u))throw new Error(`hash.outputLen must be ${u}, got ${f}`);let l=o.randomBytes===void 0?zt:o.randomBytes,h=o.toMontgomery,m=o.toMontgomerySecret,L=o.adjustScalarBytes===void 0?C=>C:o.adjustScalarBytes,v=o.domain===void 0?(C,A,p)=>{if(Se(p,"phflag"),A.length||p)throw new Error("Contexts/pre-hash are not supported");return C}:o.domain;function b(C){return c.create(Ht(C))}function E(C){let A=S.secretKey;G(C,S.secretKey,"secretKey");let p=G(n(C),2*A,"hashedSecretKey"),T=L(p.slice(0,A)),_=p.slice(A,2*A),M=b(T);return{head:T,prefix:_,scalar:M}}function B(C){let{head:A,prefix:p,scalar:T}=E(C),_=s.multiply(T),M=_.toBytes();return{head:A,prefix:p,scalar:T,point:_,pointBytes:M}}function y(C){return B(C).pointBytes}function N(C=Uint8Array.of(),...A){let p=Oe(...A);return b(n(v(p,G(C,void 0,"context"),!!i)))}function U(C,A,p={}){ve(p,{},{},"options"),C=G(C,void 0,"message"),i&&(C=i(C));let{prefix:T,scalar:_,pointBytes:M}=B(A),D=N(p.context,T,C),g=s.multiply(D).toBytes(),O=N(p.context,g,M,C),P=c.create(D+O*_);if(!c.isValid(P))throw new Error("sign failed: invalid s");let z=Oe(g,c.toBytes(P));return G(z,S.signature,"result")}let V={zip215:o.zip215};function $(C,A,p,T=V){ve(T);let{context:_}=T,M=T.zip215===void 0?!!V.zip215:T.zip215,D=S.signature;C=G(C,D,"signature"),A=G(A,void 0,"message"),p=G(p,S.publicKey,"publicKey"),M!==void 0&&Se(M,"zip215"),i&&(A=i(A));let g=D/2,O=C.subarray(0,g),P=Ht(C.subarray(g,D)),z,H,Z;try{z=t.fromBytes(p,M),H=t.fromBytes(O,M),Z=s.multiplyUnsafe(P)}catch{return!1}if(!M&&z.isSmallOrder())return!1;let Y=N(_,O,p,A);return H.add(z.multiplyUnsafe(Y)).subtract(Z).clearCofactor().is0()}let w=a.BYTES,S={secretKey:w,publicKey:w,signature:2*w,seed:w};function I(C){return C=C===void 0?l(S.seed):C,G(C,S.seed,"seed")}function F(C){return _t(C)&&C.length===S.secretKey}function x(C,A){try{return!!t.fromBytes(C,A===void 0?V.zip215:A)}catch{return!1}}let q={getExtendedPublicKey:B,randomSecretKey:I,isValidSecretKey:F,isValidPublicKey:x,toMontgomery(C){if(h===void 0)throw new Error("Montgomery conversion is not supported for this curve");return h(t.fromBytes(C))},toMontgomerySecret(C){if(m===void 0)throw new Error("Montgomery conversion is not supported for this curve");return m(C)}};return Object.freeze(S),Object.freeze(q),Object.freeze({keygen:Po(I,y),getPublicKey:y,sign:U,verify:$,utils:q,Point:t,lengths:S})}var Us=BigInt(1),gf=BigInt(2);var Kp=BigInt(5),Vp=BigInt(8),ks=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),$p={p:ks,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Vp,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function qp(t){let e=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),i=ks,a=t*t%i*t%i,c=ee(a,gf,i)*a%i,f=ee(c,Us,i)*t%i,u=ee(f,Kp,i)*f%i,l=ee(u,e,i)*u%i,h=ee(l,r,i)*l%i,m=ee(h,n,i)*h%i,L=ee(m,o,i)*m%i,v=ee(L,o,i)*m%i,b=ee(v,e,i)*u%i;return{pow_p_5_8:ee(b,gf,i)*t%i,b2:a}}function xf(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}var bf=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function zp(t,e){let r=ks,n=re(e*e*e,r),o=re(n*n*e,r),i=qp(t*o).pow_p_5_8,s=re(t*n*i,r),a=re(e*s*s,r),c=s,f=re(s*bf,r),u=a===t,l=a===re(-t,r),h=a===re(-t*bf,r);return u&&(s=c),(l||h)&&(s=f),af(s,r)&&(s=re(-s,r)),{isValid:u||l,value:s}}var Fs=mf($p,{uvRatio:zp}),wf=Fs.Fp;function Hp(t){let{y:e}=t;return wf.toBytes(wf.div(Us+e,Us-e))}function jp(t){let e=Fs.Fp.BYTES;return Fe(t,e),xf(vs(t.subarray(0,e))).subarray(0,e)}function Yp(t){return yf(Fs,vs,Object.assign({adjustScalarBytes:xf,toMontgomery:Hp,toMontgomerySecret:jp,zip215:!0},t))}var Ef=Yp({});var un=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},$o=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var qo={get(t=globalThis){let e=t.crypto;if(e?.subtle==null)throw new $o("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var zo=32;var Os,Zp=(async()=>{try{return await qo.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Gp(t,e,r){if(t.buffer instanceof ArrayBuffer){let n=await qo.get().subtle.importKey("raw",t.buffer,{name:"Ed25519"},!1,["verify"]);return await qo.get().subtle.verify({name:"Ed25519"},n,xe(e),xe(r instanceof Uint8Array?r:r.subarray()))}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function Xp(t,e,r){return Ef.verify(e,r instanceof Uint8Array?r:r.subarray(),t)}async function Sf(t,e,r){return Os==null&&(Os=await Zp),Os?Gp(t,e,r):Xp(t,e,r)}function Ho(t){return t==null?!1:typeof t.then=="function"&&typeof t.catch=="function"&&typeof t.finally=="function"}var jo=class{type="Ed25519";raw;constructor(e){this.raw=Ps(e,zo)}toMultihash(){return Ke.digest(pr(this))}toCID(){return te.createV1(114,this.toMultihash())}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:de(this.raw,e.raw)}verify(e,r,n){n?.signal?.throwIfAborted();let o=Sf(this.raw,r,e);return Ho(o)?o.then(i=>(n?.signal?.throwIfAborted(),i)):o}};function Af(t){return t=Ps(t,zo),new jo(t)}function Ps(t,e){if(t=Uint8Array.from(t??[]),t.length!==e)throw new nt(`Key must be a Uint8Array of length ${e}, got ${t.length}`);return t}var be;(function(t){t.RSA="RSA",t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.ECDSA="ECDSA"})(be||(be={}));var Ms;(function(t){t[t.RSA=0]="RSA",t[t.Ed25519=1]="Ed25519",t[t.secp256k1=2]="secp256k1",t[t.ECDSA=3]="ECDSA"})(Ms||(Ms={}));(function(t){t.codec=()=>Fr(Ms)})(be||(be={}));var fn;(function(t){let e;t.codec=()=>(e==null&&(e=Ze((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.Type!=null&&(s.uint32(8),be.codec().encode(i.Type,s)),i.Data!=null&&(s.uint32(18),s.bytes(i.Data)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={},f=s==null?i.len:i.pos+s;for(;i.pos<f;){let u=i.uint32();switch(u>>>3){case 1:{c.Type=be.codec().decode(i);break}case 2:{c.Data=i.bytes();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let f=s==null?i.len:i.pos+s;for(;i.pos<f;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:be.codec().decode(i)};break}case 2:{yield{field:`${a}.Data`,value:i.bytes()};break}default:{i.skipType(u&7);break}}}})),e);function r(i){return je(i,t.codec())}t.encode=r;function n(i,s){return He(i,t.codec(),s)}t.decode=n;function o(i,s){return Ye(i,t.codec(),s)}t.stream=o})(fn||(fn={}));var Ks;(function(t){let e;t.codec=()=>(e==null&&(e=Ze((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.Type!=null&&(s.uint32(8),be.codec().encode(i.Type,s)),i.Data!=null&&(s.uint32(18),s.bytes(i.Data)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={},f=s==null?i.len:i.pos+s;for(;i.pos<f;){let u=i.uint32();switch(u>>>3){case 1:{c.Type=be.codec().decode(i);break}case 2:{c.Data=i.bytes();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let f=s==null?i.len:i.pos+s;for(;i.pos<f;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Type`,value:be.codec().decode(i)};break}case 2:{yield{field:`${a}.Data`,value:i.bytes()};break}default:{i.skipType(u&7);break}}}})),e);function r(i){return je(i,t.codec())}t.encode=r;function n(i,s){return He(i,t.codec(),s)}t.decode=n;function o(i,s){return Ye(i,t.codec(),s)}t.stream=o})(Ks||(Ks={}));var Yo=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,r){if(Eo(e),Fe(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let i=0;i<o.length;i++)o[i]^=54;this.iHash.update(o),this.oHash=e.create();for(let i=0;i<o.length;i++)o[i]^=106;this.oHash.update(o),$t(o)}update(e){return mr(this),this.iHash.update(e),this}digestInto(e){mr(this),So(e,this),this.finished=!0;let r=e.subarray(0,this.outputLen);this.iHash.digestInto(r),this.oHash.update(r),this.oHash.digestInto(r),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:o,destroyed:i,blockLen:s,outputLen:a,canXOF:c}=this;return e=e,e.finished=o,e.destroyed=i,e.blockLen=s,e.outputLen=a,e.canXOF=c,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Tf=(()=>{let t=((e,r,n)=>new Yo(e,r).update(n).digest());return t.create=(e,r)=>new Yo(e,r),t})();var Jp=BigInt(0),Vs=class extends Error{constructor(e=""){super(e)}},at={Err:Vs,_tlv:{encode:(t,e)=>{let{Err:r}=at;if(Dt(t,"tag"),t<0||t>255)throw new r("tlv.encode: wrong tag");if(Yu(e,"data"),e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,o=on(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let i=n>127?on(o.length/2|128):"";return on(t)+i+o+e},decode(t,e){let{Err:r}=at;e=G(e,void 0,"DER data");let n=0;if(t<0||t>255)throw new r("tlv.decode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let o=e[n++],i=!!(o&128),s=0;if(!i)s=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let f=e.subarray(n,n+c);if(f.length!==c)throw new r("tlv.decode: length bytes not complete");if(f[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let u of f)s=s<<8|u;if(n+=c,s<128)throw new r("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+s);if(a.length!==s)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+s)}}},_int:{encode(t){let{Err:e}=at;if(Co(t),t<Jp)throw new e("integer: negative integers are not allowed");let r=on(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=at;if(t.length<1)throw new e("invalid signature integer: empty");if(t[0]&128)throw new e("invalid signature integer: negative");if(t.length>1&&t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return et(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=at,o=G(t,void 0,"signature"),{v:i,l:s}=n.decode(48,o);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,i),{v:f,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(f)}},hexFromSig(t){let{_tlv:e,_int:r}=at;ve(t,{r:"bigint",s:"bigint"},{},"sig");let n=e.encode(2,r.encode(t.r)),o=e.encode(2,r.encode(t.s)),i=n+o;return e.encode(48,i)}},$s=(Object.freeze(at._tlv),Object.freeze(at._int),Object.freeze(at));var Bf=(t,e)=>(t+(t>=0?e:-e)/If)/e;function em(t,e,r){gr("scalar",t,ct,r);let[[n,o],[i,s]]=e,a=Bf(s*t,r),c=Bf(-o*t,r),f=t-a*n-c*i,u=-a*o-c*s,l=f<ct,h=u<ct;l&&(f=-f),h&&(u=-u);let m=sn(Math.ceil(br(r)/2))+jt;if(f<ct||f>=m||u<ct||u>=m)throw new Error("splitScalar (endomorphism): failed for k");return{k1neg:l,k1:f,k2neg:h,k2:u}}function Hs(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function qs(t,e){ve(t);let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Se(r.lowS,"lowS"),Se(r.prehash,"prehash"),r.format!==void 0&&Hs(r.format),r}var ct=BigInt(0),jt=BigInt(1),If=BigInt(2),zs=BigInt(3),tm=BigInt(4);function Cf(t,e={}){let r=Oo("weierstrass",t,e),n=r.Fp,o=r.Fn,i=r.CURVE,{h:s,n:a}=i;ve(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",randomBytes:"function"});let{endo:c,allowInfinityPoint:f}=e,u=e.randomBytes===void 0?zt:e.randomBytes;if(c&&(!n.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=Df(n,o);function h(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function m(A,p,T){if(f&&p.is0())return Uint8Array.of(0);let{x:_,y:M}=p.toAffine(),D=n.toBytes(_);if(Se(T,"isCompressed"),T){h();let g=!n.isOdd(M);return Oe(_f(g),D)}else return Oe(Uint8Array.of(4),D,n.toBytes(M))}function L(A){G(A,void 0,"Point");let{publicKey:p,publicKeyUncompressed:T}=l,_=A.length,M=A[0],D=A.subarray(1);if(f&&_===1&&M===0)return{x:n.ZERO,y:n.ZERO};if(_===p&&(M===2||M===3)){let g=n.fromBytes(D);if(!n.isValid(g))throw new Error("bad point: is not on curve, wrong x");let O=y(g),P;try{P=n.sqrt(O)}catch(Z){let Y=Z instanceof Error?": "+Z.message:"";throw new Error("bad point: is not on curve, sqrt error"+Y)}h();let z=n.isOdd(P);return(M&1)===1!==z&&(P=n.neg(P)),{x:g,y:P}}else if(_===T&&M===4){let g=n.BYTES,O=n.fromBytes(D.subarray(0,g)),P=n.fromBytes(D.subarray(g,g*2));if(!N(O,P))throw new Error("bad point: is not on curve");return{x:O,y:P}}else throw new Error(`bad point: got length ${_}, expected compressed=${p} or uncompressed=${T}`)}let v=e.toBytes===void 0?m:e.toBytes,b=e.fromBytes===void 0?L:e.fromBytes,E=n.mul(i.b,zs),B=n.is0(i.a)?A=>n.ZERO:A=>n.mul(i.a,A);function y(A){let p=n.sqr(A),T=n.mul(p,A);return n.add(n.add(T,n.mul(A,i.a)),i.b)}function N(A,p){let T=n.sqr(p),_=y(A);return n.eql(T,_)}if(!N(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let U=n.mul(n.pow(i.a,zs),tm),V=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(U,V)))throw new Error("bad curve params: a or b");function $(A,p,T=!1){if(!n.isValid(p)||T&&n.is0(p))throw new Error(`bad point coordinate ${A}`);return p}function w(A){if(!(A instanceof x))throw new Error("Weierstrass Point expected")}function S(A){if(!c||!c.basises)throw new Error("no endo");return em(A,c.basises,o.ORDER)}function I(A,p,T,_){if(!o.isValid(_))throw new RangeError("invalid scalar: out of range");if(c){let{k1neg:M,k1:D,k2neg:g,k2:O}=S(_),P=new x(n.mul(T.X,c.beta),T.Y,T.Z);A.push(M?T.negate():T,g?P.negate():P),p.push(D,O)}else A.push(T),p.push(_)}let F=new WeakSet;class x{static BASE=new x(i.Gx,i.Gy,n.ONE);static ZERO=new x(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(p,T,_){this.X=$("x",p),this.Y=$("y",T,!0),this.Z=$("z",_),Object.freeze(this)}static CURVE(){return i}static fromAffine(p){let{x:T,y:_}=p||{};if(!p||!n.isValid(T)||!n.isValid(_))throw new Error("invalid affine point");if(p instanceof x)throw new Error("projective point not allowed");return n.is0(T)&&n.is0(_)?x.ZERO:new x(T,_,n.ONE)}static fromBytes(p){let T=x.fromAffine(b(G(p,void 0,"point")));return T.assertValidity(),T}static fromHex(p){return x.fromBytes(yr(p))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=6,T=!0){return C.setWindowSize(this,p),T||this.multiply(zs),this}assertValidity(){let p=this;if(p.is0()){if(e.allowInfinityPoint&&n.is0(p.X)&&n.eql(p.Y,n.ONE)&&n.is0(p.Z))return;throw new Error("bad point: ZERO")}if(F.has(p))return;let{x:T,y:_}=p.toAffine();if(!n.isValid(T)||!n.isValid(_))throw new Error("bad point: x or y not field elements");if(!N(T,_))throw new Error("bad point: equation left != right");if(!p.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");F.add(p)}hasEvenY(){let{y:p}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(p)}equals(p){w(p);let{X:T,Y:_,Z:M}=this,{X:D,Y:g,Z:O}=p,P=n.eql(n.mul(T,O),n.mul(D,M)),z=n.eql(n.mul(_,O),n.mul(g,M));return P&&z}negate(){return new x(this.X,n.neg(this.Y),this.Z)}double(){let{X:p,Y:T,Z:_}=this,M=n.ZERO,D=n.ZERO,g=n.ZERO,O=n.mul(p,p),P=n.mul(T,T),z=n.mul(_,_),H=n.mul(p,T);return H=n.add(H,H),g=n.mul(p,_),g=n.add(g,g),M=B(g),D=n.mul(E,z),D=n.add(M,D),M=n.sub(P,D),D=n.add(P,D),D=n.mul(M,D),M=n.mul(H,M),g=n.mul(E,g),z=B(z),H=n.sub(O,z),H=B(H),H=n.add(H,g),g=n.add(O,O),O=n.add(g,O),O=n.add(O,z),O=n.mul(O,H),D=n.add(D,O),z=n.mul(T,_),z=n.add(z,z),O=n.mul(z,H),M=n.sub(M,O),g=n.mul(z,P),g=n.add(g,g),g=n.add(g,g),new x(M,D,g)}add(p){w(p);let{X:T,Y:_,Z:M}=this,{X:D,Y:g,Z:O}=p,P=n.ZERO,z=n.ZERO,H=n.ZERO,Z=n.mul(T,D),Y=n.mul(_,g),ne=n.mul(M,O),ye=n.add(T,_),oe=n.add(D,g);ye=n.mul(ye,oe),oe=n.add(Z,Y),ye=n.sub(ye,oe),oe=n.add(T,M);let pe=n.add(D,O);return oe=n.mul(oe,pe),pe=n.add(Z,ne),oe=n.sub(oe,pe),pe=n.add(_,M),P=n.add(g,O),pe=n.mul(pe,P),P=n.add(Y,ne),pe=n.sub(pe,P),H=B(oe),P=n.mul(E,ne),H=n.add(P,H),P=n.sub(Y,H),H=n.add(Y,H),z=n.mul(P,H),Y=n.add(Z,Z),Y=n.add(Y,Z),ne=B(ne),oe=n.mul(E,oe),Y=n.add(Y,ne),ne=n.sub(Z,ne),ne=B(ne),oe=n.add(oe,ne),Z=n.mul(Y,oe),z=n.add(z,Z),Z=n.mul(pe,oe),P=n.mul(ye,P),P=n.sub(P,Z),Z=n.mul(ye,Y),H=n.mul(pe,H),H=n.add(H,Z),new x(P,z,H)}subtract(p){return w(p),this.add(p.negate())}is0(){return this.equals(x.ZERO)}multiply(p){if(!o.isValidNot0(p))throw new RangeError("invalid scalar: out of range");let{p:T,f:_}=C.mulSecret(this,p,s,q);return q([T,_])[0]}multiplyUnsafe(p){let T=this,_=p;if(!o.isValid(_))throw new RangeError("invalid scalar: out of range");if(_===ct||T.is0())return x.ZERO;if(_===jt)return T;if(C.hasWindowSize(this))return C.mulUnsafe(T,_,q);let M=[],D=[];return I(M,D,T,_),Fo(x,M,D)}mulAddUnsafe(p,T,_){w(T);let M=[],D=[];return I(M,D,this,p),I(M,D,T,_),Fo(x,M,D)}toAffine(p){let T=this,_=p;if(_!=null&&!n.isValid(_))throw new RangeError('"invertedZ" expected valid field element');let{X:M,Y:D,Z:g}=T;if(n.eql(g,n.ONE))return{x:M,y:D};let O=T.is0();_==null&&(_=O?n.ONE:n.inv(g));let P=n.mul(M,_),z=n.mul(D,_),H=n.mul(g,_);if(O)return{x:n.ZERO,y:n.ZERO};if(!n.eql(H,n.ONE))throw new Error("invZ was invalid");return{x:P,y:z}}isTorsionFree(){let{isTorsionFree:p}=e;return s===jt?!0:p?p(x,this):C.mulUnsafe(this,a).is0()}clearCofactor(){let{clearCofactor:p}=e;return s===jt?this:p?p(x,this):this.multiplyUnsafe(s)}isSmallOrder(){return s===jt?this.is0():this.clearCofactor().is0()}toBytes(p=!0){return Se(p,"isCompressed"),this.assertValidity(),v(x,this,p)}toHex(p=!0){return nn(this.toBytes(p))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let q=A=>ko(x,A),C=new Er(x,u);return C.bits>=6&&x.BASE.precompute(6),Object.freeze(x.prototype),Object.freeze(x),x}function _f(t){return Uint8Array.of(t?2:3)}function Df(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function rm(t,e={}){Lt(t);let{Fn:r}=t,n=e.randomBytes===void 0?zt:e.randomBytes,o=Object.assign(Df(t.Fp,r),{seed:Math.max(No(r.ORDER),16)});function i(m){try{let L=r.fromBytes(m);return r.isValidNot0(L)}catch{return!1}}function s(m,L){let{publicKey:v,publicKeyUncompressed:b}=o;try{let E=m.length;return L===!0&&E!==v||L===!1&&E!==b?!1:!!t.fromBytes(m)}catch{return!1}}function a(m){return m=m===void 0?n(o.seed):m,Uo(G(m,o.seed,"seed"),r.ORDER)}function c(m,L=!0){return t.BASE.multiply(r.fromBytes(m)).toBytes(L)}function f(m){let{secretKey:L,publicKey:v,publicKeyUncompressed:b}=o,E=r._lengths;if(!_t(m))return;let B=G(m,void 0,"key").length,y=B===v||B===b,N=B===L||!!E?.includes(B);if(!(y&&N))return y}function u(m,L,v=!0){if(f(m)===!0)throw new Error("first arg must be private key");if(f(L)===!1)throw new Error("second arg must be public key");let b=r.fromBytes(m);return t.fromBytes(L).multiply(b).toBytes(v)}let l={isValidSecretKey:i,isValidPublicKey:s,randomSecretKey:a},h=Po(a,c);return Object.freeze(l),Object.freeze(o),Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:h,Point:t,utils:l,lengths:o})}function Rf(t,e,r={}){Lt(t);let n=e;Eo(n),ve(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let o=Object.assign({},r),i=o.randomBytes===void 0?zt:o.randomBytes,s=o.hmac===void 0?(D,g)=>Tf(n,D,g):o.hmac,{Fp:a,Fn:c}=t,{ORDER:f,BITS:u}=c,l=No(f),h=Ns(i,l),{keygen:m,getPublicKey:L,getSharedSecret:v,utils:b,lengths:E}=rm(t,o),B={prehash:!0,lowS:typeof o.lowS=="boolean"?o.lowS:!0,format:"compact",extraEntropy:!1},y=f*If+jt<a.ORDER;function N(D){let g=f>>jt;return D>g}function U(D,g){if(!c.isValidNot0(g))throw new Error(`invalid signature ${D}: out of range 1..Point.Fn.ORDER`);return g}function V(){if(!a.isOdd)throw new Error("Field doesn't support isOdd")}function $(D,g,O){return V(),(D===O?0:2)|Number(a.isOdd(g))}function w(){if(y)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function S(D,g){Hs(g);let O=E.signature,P=g==="compact"?O:g==="recovered"?O+1:void 0;return G(D,P)}class I{r;s;recovery;constructor(g,O,P){if(this.r=U("r",g),this.s=U("s",O),P!=null){if(w(),![0,1,2,3].includes(P))throw new Error("invalid recovery id");this.recovery=P}Object.freeze(this)}static fromBytes(g,O=B.format){S(g,O);let P;if(O==="der"){let{r:Y,s:ne}=$s.toSig(G(g));return new I(Y,ne)}O==="recovered"&&(P=g[0],O="compact",g=g.subarray(1));let z=E.signature/2,H=g.subarray(0,z),Z=g.subarray(z,z*2);return new I(c.fromBytes(H),c.fromBytes(Z),P)}static fromHex(g,O){return this.fromBytes(yr(g),O)}assertRecovery(){let{recovery:g}=this;if(g==null)throw new Error("invalid recovery id: must be present");return g}addRecoveryBit(g){return new I(this.r,this.s,g)}recoverPublicKey(g){let{r:O,s:P}=this,z=this.assertRecovery(),H=z===2||z===3?O+f:O;if(!a.isValid(H))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let Z=a.toBytes(H),Y=t.fromBytes(Oe(_f((z&1)===0),Z)),ne=c.inv(H),ye=x(G(g,void 0,"msgHash")),oe=c.create(-ye*ne),pe=c.create(P*ne),qe=t.BASE.mulAddUnsafe(oe,Y,pe);if(qe.is0())throw new Error("invalid recovery: point at infinify");return qe.assertValidity(),qe}hasHighS(){return N(this.s)}toBytes(g=B.format){if(Hs(g),g==="der")return yr($s.hexFromSig(this));let{r:O,s:P}=this,z=c.toBytes(O),H=c.toBytes(P);return g==="recovered"?(w(),Oe(Uint8Array.of(this.assertRecovery()),z,H)):Oe(z,H)}toHex(g){return nn(this.toBytes(g))}}Object.freeze(I.prototype),Object.freeze(I);let F=o.bits2int===void 0?function(g){if(g.length>8192)throw new Error("input is too large");let O=et(g),P=g.length*8-u;return P>0?O>>BigInt(P):O}:o.bits2int,x=o.bits2int_modN===void 0?function(g){return c.create(F(g))}:o.bits2int_modN,q=sn(u);function C(D){return gr("num < 2^"+u,D,ct,q),c.toBytes(D)}function A(D,g){return G(D,void 0,"message"),g?G(n(D),void 0,"prehashed message"):D}function p(D,g,O){let{lowS:P,prehash:z,extraEntropy:H}=qs(O,B);D=A(D,z);let Z=x(D),Y=c.fromBytes(g);if(!c.isValidNot0(Y))throw new Error("invalid private key");let ne=[C(Y),C(Z)];if(H!=null&&H!==!1){let qe=H===!0?i(E.secretKey):H;ne.push(G(qe,void 0,"extraEntropy"))}let ye=Oe(...ne),oe=Z;function pe(qe){let Yt=F(qe);if(!c.isValidNot0(Yt))return;let Tr=t.BASE.multiply(Yt).toAffine(),ut=c.create(Tr.x);if(ut===ct)return;let ze;if(h!==void 0){let Br=et(Uo(h(l),f)),qf=c.inv(c.mul(Br,Yt)),zf=c.mul(Br,oe),Hf=c.mul(Br,Y);ze=c.create(qf*c.create(zf+Hf*ut))}else{let Br=nf(Yt,f);ze=c.create(Br*c.create(oe+ut*Y))}if(ze===ct)return;let ni=$(Tr.x,Tr.y,ut),Js=ze;return P&&N(ze)&&(Js=c.neg(ze),ni^=1),new I(ut,Js,y?void 0:ni)}return{seed:ye,k2sig:pe}}function T(D,g,O={}){let{seed:P,k2sig:z}=p(D,g,O);return Gu(n.outputLen,c.BYTES,s)(P,z).toBytes(O.format)}function _(D,g,O,P={}){let{lowS:z,prehash:H,format:Z}=qs(P,B);if(O=G(O,void 0,"publicKey"),g=A(g,H),!_t(D)){let Y=D instanceof I?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+Y)}S(D,Z);try{let Y=I.fromBytes(D,Z),ne=t.fromBytes(O);if(z&&Y.hasHighS())return!1;let{r:ye,s:oe}=Y,pe=x(g),qe=c.inv(oe),Yt=c.create(pe*qe),Tr=c.create(ye*qe),ut=t.BASE.mulAddUnsafe(Yt,ne,Tr);if(ut.is0())return!1;let ze=ut.toAffine();return!(c.create(ze.x)!==ye||Z==="recovered"&&Y.recovery!==$(ze.x,ze.y,ye))}catch{return!1}}function M(D,g,O={}){let{prehash:P}=qs(O,B);return g=A(g,P),I.fromBytes(D,"recovered").recoverPublicKey(g).toBytes()}return Object.freeze({keygen:m,getPublicKey:L,getSharedSecret:v,utils:b,lengths:E,Point:t,sign:T,verify:_,recoverPublicKey:M,Signature:I,hash:n})}var Ys={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},nm={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var Lf=BigInt(2);function om(t){let e=Ys.p,r=BigInt(3),n=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),f=t*t*t%e,u=f*f*t%e,l=ee(u,r,e)*u%e,h=ee(l,r,e)*u%e,m=ee(h,Lf,e)*f%e,L=ee(m,o,e)*m%e,v=ee(L,i,e)*L%e,b=ee(v,a,e)*v%e,E=ee(b,c,e)*b%e,B=ee(E,a,e)*v%e,y=ee(B,r,e)*u%e,N=ee(y,s,e)*L%e,U=ee(N,n,e)*f%e,V=ee(U,Lf,e);if(!js.eql(js.sqr(V),t))throw new Error("Cannot find square root");return V}var js=xr(Ys.p,{sqrt:om}),im=Cf(Ys,{Fp:js,endo:nm}),Sr=Rf(im,Hu);function Nf(t,e,r,n){let o=Nr.digest(r instanceof Uint8Array?r:r.subarray());if(Ho(o))return o.then(({digest:i})=>(n?.signal?.throwIfAborted(),Sr.verify(e,i,t,{prehash:!1,format:"der"}))).catch(i=>{throw i.name==="AbortError"?i:new un(String(i))});try{return n?.signal?.throwIfAborted(),Sr.verify(e,o.digest,t,{prehash:!1,format:"der"})}catch(i){throw new un(String(i))}}var Zo=class{type="secp256k1";raw;_key;constructor(e){this._key=kf(e),this.raw=Uf(this._key)}toMultihash(){return Ke.digest(pr(this))}toCID(){return te.createV1(114,this.toMultihash())}toString(){return J.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:de(this.raw,e.raw)}verify(e,r,n){return Nf(this._key,r,e,n)}};function Ff(t){return new Zo(t)}function Uf(t){return Sr.Point.fromBytes(t).toBytes()}function kf(t){try{return Sr.Point.fromBytes(t),t}catch(e){throw new Wn(String(e))}}function Of(t){let{Type:e,Data:r}=fn.decode(t.digest),n=r??new Uint8Array;switch(e){case be.Ed25519:return Af(n);case be.secp256k1:return Ff(n);case be.ECDSA:return Au(n);default:throw new Hr}}function pr(t){return fn.encode({Type:be[t.type],Data:t.raw})}var Pf=Symbol.for("nodejs.util.inspect.custom"),sm=114,ln=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Ji]=!0;toString(){return this.string==null&&(this.string=J.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return te.createV1(sm,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return de(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return de(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Pf](){return`PeerId(${this.toString()})`}},Go=class extends ln{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Xo=class extends ln{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Wo=class extends ln{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},am=2336,Qo=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=Ke.digest(se(this.url))}[Pf](){return`PeerId(${this.url})`}[Ji]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return te.createV1(am,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=W(e)),e.toString()===this.toString())}};function Mf(t){if(um(t))return new Go({multihash:t});if(cm(t))try{let e=Of(t);if(e.type==="Ed25519")return new Xo({multihash:t,publicKey:e});if(e.type==="secp256k1")return new Wo({multihash:t,publicKey:e})}catch{let r=W(t.digest);return new Qo(new URL(r))}throw new Qn("Supplied PeerID Multihash is invalid")}function cm(t){return t.code===Ke.code}function um(t){return t.code===Nr.code}function Zs(t,e){let r={[Symbol.iterator]:()=>r,next:()=>{let n=t.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return r}function Jo(t){let e=dt(J.decode(`z${t}`));return Mf(e)}var dn=class t{set;constructor(e){if(this.set=new Set,e!=null)for(let r of e)this.set.add(r.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return Zs(this.set.entries(),e=>{let r=Jo(e[0]);return[r,r]})}forEach(e){this.set.forEach(r=>{let n=Jo(r);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Zs(this.set.values(),e=>Jo(e))}intersection(e){let r=new t;for(let n of e)this.has(n)&&r.add(n);return r}difference(e){let r=new t;for(let n of this)e.has(n)||r.add(n);return r}union(e){let r=new t;for(let n of e)r.add(n);for(let n of this)r.add(n);return r}};var Kf;(function(t){t[t.SEND_QUERY=0]="SEND_QUERY",t[t.PEER_RESPONSE=1]="PEER_RESPONSE",t[t.FINAL_PEER=2]="FINAL_PEER",t[t.QUERY_ERROR=3]="QUERY_ERROR",t[t.PROVIDER=4]="PROVIDER",t[t.VALUE=5]="VALUE",t[t.ADD_PEER=6]="ADD_PEER",t[t.DIAL_PEER=7]="DIAL_PEER",t[t.PATH_ENDED=8]="PATH_ENDED"})(Kf||(Kf={}));var hn;(function(t){let e;t.codec=()=>(e==null&&(e=Ze((i,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),i.keyName!=null&&i.keyName!==""&&(s.uint32(10),s.string(i.keyName)),i.lifetime!=null&&i.lifetime!==0&&(s.uint32(16),s.uint32(i.lifetime)),a.lengthDelimited!==!1&&s.ldelim()},(i,s,a={})=>{let c={keyName:"",lifetime:0},f=s==null?i.len:i.pos+s;for(;i.pos<f;){let u=i.uint32();switch(u>>>3){case 1:{c.keyName=i.string();break}case 2:{c.lifetime=i.uint32();break}default:{i.skipType(u&7);break}}}return c},function*(i,s,a,c={}){let f=s==null?i.len:i.pos+s;for(;i.pos<f;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.keyName`,value:i.string()};break}case 2:{yield{field:`${a}.lifetime`,value:i.uint32()};break}default:{i.skipType(u&7);break}}}})),e);function r(i){return je(i,t.codec())}t.encode=r;function n(i,s){return He(i,t.codec(),s)}t.decode=n;function o(i,s){return Ye(i,t.codec(),s)}t.stream=o})(hn||(hn={}));function vr(t,e){return{async put(r,n,o={}){try{let i=jr(r);try{let c=await t.get(i),f=vt.deserialize(c);if(de(f.value,n))return}catch(c){if(c.name!=="NotFoundError")throw c}let s=new vt(r,n,new Date);o.onProgress?.(new fe("ipns:routing:datastore:put"));let a=t.batch();a.put(i,s.serialize()),o.metadata!=null&&a.put(no(r),hn.encode(o.metadata)),await a.commit(o)}catch(i){throw o.onProgress?.(new fe("ipns:routing:datastore:error",i)),i}},async get(r,n={}){try{let o=jr(r);n.onProgress?.(new fe("ipns:routing:datastore:get"));let i=await t.get(o,n),s=vt.deserialize(i);return{record:xe(s.value),created:s.timeReceived}}catch(o){throw n.onProgress?.(new fe("ipns:routing:datastore:error",o)),o}},async has(r,n={}){let o=jr(r);return t.has(o,n)},async delete(r,n){let o=jr(r),i=t.batch();i.delete(o),i.delete(no(r)),await i.commit(n)},async*list(r={}){try{r.onProgress?.(new fe("ipns:routing:datastore:list"));for await(let{key:n,value:o}of t.query({prefix:ro},r))try{let i=vt.deserialize(o),a=n.toString().substring(ro.length),c=se(a,"base32"),f=no(c),u;try{let l=await t.get(f,r);u=hn.decode(l)}catch(l){e.error("Error deserializing metadata for %s - %e",a,l)}yield{routingKey:c,metadata:u,record:i.value,created:i.timeReceived}}catch(i){e.error("Error deserializing record - %e",i)}}catch(n){throw r.onProgress?.(new fe("ipns:routing:datastore:error",n)),n}}}}var Gs=class{routing;constructor(e){this.routing=e}async put(e,r,n={}){try{await this.routing.put(e,r,n)}catch(o){throw n.onProgress?.(new fe("ipns:routing:helia:error",o)),o}}async get(e,r={}){try{return await this.routing.get(e,r)}catch(n){throw r.onProgress?.(new fe("ipns:routing:helia:error",n)),n}}toString(){return"HeliaRouting()"}};function Ar(t){return new Gs(t)}var Xs=class{localStore;constructor(e){this.localStore=e}async put(e,r,n){await this.localStore.put(e,r,n)}async get(e,r){let{record:n}=await this.localStore.get(e,r);return n}toString(){return"LocalStoreRouting()"}};function ei(t){return new Xs(t)}var ti=class{routers;publisher;republisher;resolver;localStore;components;started;constructor(e,r={}){this.localStore=vr(e.datastore,e.logger.forComponent("helia:ipns:local-store")),this.components=e,this.started=!1,this.routers=[ei(this.localStore),Ar(e.routing),...r.routers??[]],this.publisher=new uo(e,{...r,routers:this.routers,localStore:this.localStore}),this.republisher=new go(e,{...r,routers:this.routers,localStore:this.localStore}),this.resolver=new cr(e,{...r,routers:this.routers,localStore:this.localStore}),e.events.addEventListener("start",this.start.bind(this)),e.events.addEventListener("stop",this.stop.bind(this)),this.started&&this.republisher.start();for(let n of Object.values(this.components))if(fm(n))for(let o of Object.values(n.services))lm(o)&&(o.selectors.ipns=async(i,s)=>{let a=s.map(c=>Q.decode(c));return St(i,a)},o.validators.ipns=async(i,s)=>{await Qe(i,s,this.components.keychain)})}start(){this.started||(this.started=!0,this.republisher.start())}stop(){this.started&&(this.started=!1,this.republisher.stop())}async publish(e,r,n={}){return this.publisher.publish(e,so(r),n)}async*resolve(e,r={}){let{digest:n}=Yr(e);yield*this.resolver.resolve(n,r)}async unpublish(e,r){return this.publisher.unpublish(e,r)}};function fm(t){return t?.services!=null}function lm(t){return t?.validators!=null&&t?.selectors!=null}var ae=Zr("helia:ipns:routing:pubsub"),Qs=class{subscriptions;localStore;libp2p;fetchConcurrency;fetchTimeout;fetchDelay;fetchQueue;fetchPeers;shutdownController;fetchTopologyId;keychain;constructor(e,r={}){if(this.subscriptions=new Set,this.shutdownController=new AbortController,this.shutdownController.signal,this.fetchPeers=new dn,this.localStore=vr(e.datastore,e.logger.forComponent("helia:ipns:local-store")),this.libp2p=e.libp2p,this.fetchConcurrency=r.fetchConcurrency??8,this.fetchDelay=r.fetchDelay??0,this.keychain=e.keychain,this.fetchTimeout=r.fetchTimeout??2500,this.fetchQueue=new dr({concurrency:this.fetchConcurrency,metrics:e.metrics,metricName:"helia_ipns_pubsub_fetch_queue"}),this.libp2p.services.pubsub.addEventListener("message",n=>{let o=n.detail;this.subscriptions.has(o.topic)&&this.#e(o,{signal:this.shutdownController.signal}).catch(i=>{ae.error("Error processing message - %e",i)})}),this.libp2p.services.fetch!=null)try{this.libp2p.services.pubsub.addEventListener("subscription-change",n=>{let{peerId:o,subscriptions:i}=n.detail;if(this.fetchPeers.has(o))for(let s of i){if(!this.subscriptions.has(s.topic)||s.subscribe===!1)continue;ae("peer %s joined topic %s",o,s.topic);let a=Vf(s.topic);this.#t(s.topic,a,o,{signal:this.shutdownController.signal}).catch(c=>{ae.error("failed to fetch IPNS record for %m from peer %s - %e",a,o,c)})}}),this.libp2p.services.fetch.registerLookupFunction(to,async n=>{try{let{record:o}=await this.localStore.get(n,{signal:this.shutdownController.signal});return o}catch(o){if(o.name!=="NotFoundError")throw o}}),ae("registered lookup function for IPNS with libp2p/fetch service")}catch(n){ae("unable to register lookup function for IPNS with libp2p/fetch service - %e",n)}else ae("no libp2p/fetch service found. Skipping registration of lookup function for IPNS.")}async#e(e,r){if(ae("message received for topic",e.topic),e.type!=="signed"){ae.error("unsigned message received, this module can only work with signed messages");return}if(e.from.equals(this.libp2p.peerId)){ae("not storing record from self");return}await this.#r(e.topic,Vf(e.topic),e.data,!1,r)}async#t(e,r,n,o){let i=await this.fetchQueue.add(async({signal:s})=>{ae("fetching ipns record for %m from peer %s",r,n);let a=Xr([s,AbortSignal.timeout(this.fetchTimeout)]);try{return await this.libp2p.services.fetch?.fetch(n,r,{signal:a})}finally{a.clear()}},o);if(i==null)throw new zr(`Peer ${n} did not have record for routing key ${W(r,"base64")}`);return ae("fetched ipns record for %m from peer %s",r,n),this.#r(e,r,i,!0,o)}async#r(e,r,n,o,i){let s=await Qe(r,n,this.keychain,i);if(this.shutdownController.signal.throwIfAborted(),await this.localStore.has(r)){let{record:a}=await this.localStore.get(r,i),c=await Qe(r,a,this.keychain,i);if(de(a,n))return ae.trace("found identical record for %m",r),a;if(St(r,[c,s])===0)return ae.trace("found old record for %m",r),a}if(ae("found new record for %m",r),await this.localStore.put(r,n,i),o){ae("publish value for topic %s",e);try{let a=await this.libp2p.services.pubsub.publish(e,n);ae("published record on topic %s to %d recipients",e,a.recipients)}catch(a){ae.error("could not publish record on topic %s - %e",a)}}return xe(n)}async put(e,r,n={}){try{let o=Ws(e);ae("publish value for topic %s",o);let i=await this.libp2p.services.pubsub.publish(o,r);n?.signal?.throwIfAborted(),ae("published record on topic %s to %d recipients",o,i.recipients),n.onProgress?.(new fe("ipns:pubsub:publish",{topic:o,result:i}))}catch(o){throw n.onProgress?.(new fe("ipns:pubsub:error",o)),o}}async get(e,r={}){let n=Ws(e);try{this.libp2p.services.pubsub.getTopics().includes(n)||(ae("add subscription for topic",n),this.libp2p.services.pubsub.subscribe(n),this.subscriptions.add(n),r.onProgress?.(new fe("ipns:pubsub:subscribe",{topic:n})))}catch(s){throw r.onProgress?.(new fe("ipns:pubsub:error",s)),s}await po(yu(this.fetchDelay),this.shutdownController.signal);let o=new AbortController,i=[];for(let s of this.libp2p.services.pubsub.getSubscribers(n)){let a=Xr([r?.signal,o.signal]);i.push(this.#t(n,e,s,{...r,signal:a}).finally(()=>{a.clear()}))}if(i.length>0){let s=await Promise.any(i);if(o.abort(),s!=null)return s}throw new zr("Pubsub routing does not actively query peers")}getSubscriptions(){return[...this.subscriptions]}cancel(e){let r=Yc(e)?e.toMultihash():e,n=it(r),o=Ws(n);this.subscriptions.has(o)&&(this.libp2p.services.pubsub.unsubscribe(o),this.subscriptions.delete(o))}toString(){return"PubSubRouting()"}async start(){this.shutdownController=new AbortController,this.shutdownController.signal,this.libp2p.services.fetch!=null&&(this.fetchTopologyId=await this.libp2p.register(this.libp2p.services.fetch.protocol,{onConnect:e=>{this.fetchPeers.add(e)},onDisconnect:e=>{this.fetchPeers.delete(e)}},{signal:this.shutdownController.signal}))}stop(){this.fetchQueue.abort(),this.shutdownController.abort(),this.fetchTopologyId!=null&&this.libp2p.unregister(this.fetchTopologyId)}},ri="/record/";function Ws(t){let e=W(t,"base64url");return`${ri}${e}`}function Vf(t){if(t.substring(0,ri.length)!==ri)throw new bn("Topic received is not from a record");let e=t.substring(ri.length);return se(e,"base64url")}function $f(t,e={}){return new Qs(t,e)}function dm(t,e={}){return new ti(t,e)}function hm(t,e={}){let r=vr(t.datastore,t.logger.forComponent("helia:ipns:local-store")),n=[ei(r),Ar(t.routing),...e.routers??[]];return new cr(t,{routers:n,localStore:r})}return Qf(pm);})();
|
|
14
14
|
/*! Bundled license information:
|
|
15
15
|
|
|
16
16
|
@noble/curves/utils.js:
|