p2p-fret 0.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.
Files changed (55) hide show
  1. package/README.md +105 -0
  2. package/dist/index.min.js +18 -0
  3. package/dist/index.min.js.map +7 -0
  4. package/dist/src/estimate/size-estimator.d.ts +6 -0
  5. package/dist/src/estimate/size-estimator.js +45 -0
  6. package/dist/src/index.d.ts +84 -0
  7. package/dist/src/index.js +8 -0
  8. package/dist/src/logger.d.ts +2 -0
  9. package/dist/src/logger.js +5 -0
  10. package/dist/src/ring/distance.d.ts +4 -0
  11. package/dist/src/ring/distance.js +47 -0
  12. package/dist/src/ring/hash.d.ts +10 -0
  13. package/dist/src/ring/hash.js +37 -0
  14. package/dist/src/rpc/leave.d.ts +9 -0
  15. package/dist/src/rpc/leave.js +64 -0
  16. package/dist/src/rpc/maybe-act.d.ts +8 -0
  17. package/dist/src/rpc/maybe-act.js +66 -0
  18. package/dist/src/rpc/neighbors.d.ts +8 -0
  19. package/dist/src/rpc/neighbors.js +125 -0
  20. package/dist/src/rpc/ping.d.ts +21 -0
  21. package/dist/src/rpc/ping.js +115 -0
  22. package/dist/src/rpc/protocols.d.ts +14 -0
  23. package/dist/src/rpc/protocols.js +36 -0
  24. package/dist/src/selector/next-hop.d.ts +4 -0
  25. package/dist/src/selector/next-hop.js +64 -0
  26. package/dist/src/service/discovery.d.ts +3 -0
  27. package/dist/src/service/discovery.js +15 -0
  28. package/dist/src/service/fret-service.d.ts +95 -0
  29. package/dist/src/service/fret-service.js +932 -0
  30. package/dist/src/service/libp2p-fret-service.d.ts +46 -0
  31. package/dist/src/service/libp2p-fret-service.js +90 -0
  32. package/dist/src/store/digitree-store.d.ts +33 -0
  33. package/dist/src/store/digitree-store.js +166 -0
  34. package/dist/src/store/relevance.d.ts +18 -0
  35. package/dist/src/store/relevance.js +110 -0
  36. package/dist/src/utils/token-bucket.d.ts +10 -0
  37. package/dist/src/utils/token-bucket.js +36 -0
  38. package/package.json +47 -0
  39. package/src/estimate/size-estimator.ts +48 -0
  40. package/src/index.ts +84 -0
  41. package/src/logger.ts +9 -0
  42. package/src/ring/distance.ts +47 -0
  43. package/src/ring/hash.ts +47 -0
  44. package/src/rpc/leave.ts +80 -0
  45. package/src/rpc/maybe-act.ts +76 -0
  46. package/src/rpc/neighbors.ts +134 -0
  47. package/src/rpc/ping.ts +116 -0
  48. package/src/rpc/protocols.ts +35 -0
  49. package/src/selector/next-hop.ts +69 -0
  50. package/src/service/discovery.ts +16 -0
  51. package/src/service/fret-service.ts +936 -0
  52. package/src/service/libp2p-fret-service.ts +115 -0
  53. package/src/store/digitree-store.ts +184 -0
  54. package/src/store/relevance.ts +141 -0
  55. package/src/utils/token-bucket.ts +39 -0
package/README.md ADDED
@@ -0,0 +1,105 @@
1
+ # @optimystic/fret
2
+
3
+ FRET: Finger Ring Ensemble Topology — a Chord-style ring overlay for libp2p with JSON RPCs and a Digitree-backed cache.
4
+
5
+ ## Features
6
+
7
+ - **Chord-style Ring**: Distributed hash table with finger table routing
8
+ - **Digitree Cache**: Efficient peer storage and lookup
9
+ - **Network Size Estimation**: Real-time tracking of network size with confidence metrics
10
+ - **Partition Detection**: Monitors for sudden network changes and potential partitions
11
+ - **Neighbor Discovery**: Automatic peer discovery and announcement
12
+ - **Route Optimization**: Intelligent next-hop selection for DHT operations
13
+
14
+ ## Development
15
+
16
+ - Build
17
+
18
+ ```
19
+ yarn workspace @optimystic/fret build
20
+ ```
21
+
22
+ - Test (node only for now)
23
+
24
+ ```
25
+ yarn workspace @optimystic/fret test
26
+ ```
27
+
28
+ ## Network Size Estimation
29
+
30
+ FRET provides real-time network size estimation by aggregating observations from multiple sources:
31
+
32
+ ### Observation Sources
33
+
34
+ 1. **FRET Digitree**: Primary estimation based on finger table and neighbor cache
35
+ 2. **Ping Responses**: Peers share their size estimates in ping messages
36
+ 3. **Neighbor Announcements**: Size hints included in neighbor snapshots
37
+ 4. **External Reports**: Upper layers (e.g., cluster messages) can report observations
38
+
39
+ ### API
40
+
41
+ ```typescript
42
+ interface FretService {
43
+ // Report an external network size observation
44
+ reportNetworkSize(estimate: number, confidence: number, source?: string): void;
45
+
46
+ // Get current size estimate with confidence
47
+ getNetworkSizeEstimate(): {
48
+ size_estimate: number;
49
+ confidence: number;
50
+ sources: number
51
+ };
52
+
53
+ // Calculate rate of network size change (peers/minute)
54
+ getNetworkChurn(): number;
55
+
56
+ // Detect potential network partition
57
+ detectPartition(): boolean;
58
+ }
59
+ ```
60
+
61
+ ### Size Estimation Algorithm
62
+
63
+ FRET uses **exponential decay weighting** to favor recent observations:
64
+
65
+ - Recent observations get higher weight
66
+ - Confidence multiplied into weight calculation
67
+ - Rolling 5-minute window (configurable)
68
+ - Maximum 100 observations stored
69
+
70
+ ### Partition Detection
71
+
72
+ FRET detects potential partitions using multiple signals:
73
+
74
+ - **Sudden size drop**: >50% reduction indicates potential partition
75
+ - **High churn rate**: >10% peers/minute is suspicious
76
+ - **Confidence tracking**: Low confidence suggests instability
77
+
78
+ ### Integration Example
79
+
80
+ ```typescript
81
+ // FRET automatically includes size estimates in ping responses
82
+ registerPing(node, PROTOCOL_PING, () => {
83
+ return fretService.getNetworkSizeEstimate();
84
+ });
85
+
86
+ // Upper layers can report observations back to FRET
87
+ fretService.reportNetworkSize(observedSize, 0.8, 'cluster-message');
88
+
89
+ // Check network health
90
+ if (fretService.detectPartition()) {
91
+ console.warn('Potential network partition detected!');
92
+ }
93
+ ```
94
+
95
+ ## Test harness (local meshes)
96
+
97
+ A minimal harness will spin up a small libp2p mesh in-process and exercise:
98
+ - Join/bootstrap seeding
99
+ - Neighbor snapshots and discovery emissions
100
+ - Routing (routeAct) hop counts and anchors
101
+ - Diagnostics counters (pings, snapshots, announcements)
102
+ - Network size estimation accuracy
103
+
104
+ The harness will live under `test/` and use profile-tuned configs for edge/core.
105
+
@@ -0,0 +1,18 @@
1
+ (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.P2PFret = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
+ "use strict";var P2PFret=(()=>{var nc=Object.create;var gr=Object.defineProperty;var oc=Object.getOwnPropertyDescriptor;var sc=Object.getOwnPropertyNames;var ic=Object.getPrototypeOf,ac=Object.prototype.hasOwnProperty;var xn=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),dt=(r,t)=>{for(var e in t)gr(r,e,{get:t[e],enumerable:!0})},Ss=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of sc(t))!ac.call(r,o)&&o!==e&&gr(r,o,{get:()=>t[o],enumerable:!(n=oc(t,o))||n.enumerable});return r};var cc=(r,t,e)=>(e=r!=null?nc(ic(r)):{},Ss(t||!r||!r.__esModule?gr(e,"default",{value:r,enumerable:!0}):e,r)),fc=r=>Ss(gr({},"__esModule",{value:!0}),r);var ga=xn((km,ya)=>{var Pe=1e3,Ne=Pe*60,Re=Ne*60,he=Re*24,Nu=he*7,Ru=he*365.25;ya.exports=function(r,t){t=t||{};var e=typeof r;if(e==="string"&&r.length>0)return ku(r);if(e==="number"&&isFinite(r))return t.long?Mu(r):Uu(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function ku(r){if(r=String(r),!(r.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(t){var e=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return e*Ru;case"weeks":case"week":case"w":return e*Nu;case"days":case"day":case"d":return e*he;case"hours":case"hour":case"hrs":case"hr":case"h":return e*Re;case"minutes":case"minute":case"mins":case"min":case"m":return e*Ne;case"seconds":case"second":case"secs":case"sec":case"s":return e*Pe;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return e;default:return}}}}function Uu(r){var t=Math.abs(r);return t>=he?Math.round(r/he)+"d":t>=Re?Math.round(r/Re)+"h":t>=Ne?Math.round(r/Ne)+"m":t>=Pe?Math.round(r/Pe)+"s":r+"ms"}function Mu(r){var t=Math.abs(r);return t>=he?rn(r,t,he,"day"):t>=Re?rn(r,t,Re,"hour"):t>=Ne?rn(r,t,Ne,"minute"):t>=Pe?rn(r,t,Pe,"second"):r+" ms"}function rn(r,t,e,n){var o=t>=e*1.5;return Math.round(r/e)+" "+n+(o?"s":"")}});var xa=xn((Um,ba)=>{function Ku(r){e.debug=e,e.default=e,e.coerce=c,e.disable=i,e.enable=o,e.enabled=a,e.humanize=ga(),e.destroy=u,Object.keys(r).forEach(f=>{e[f]=r[f]}),e.names=[],e.skips=[],e.formatters={};function t(f){let l=0;for(let d=0;d<f.length;d++)l=(l<<5)-l+f.charCodeAt(d),l|=0;return e.colors[Math.abs(l)%e.colors.length]}e.selectColor=t;function e(f){let l,d=null,x,h;function v(...b){if(!v.enabled)return;let m=v,I=Number(new Date),w=I-(l||I);m.diff=w,m.prev=l,m.curr=I,l=I,b[0]=e.coerce(b[0]),typeof b[0]!="string"&&b.unshift("%O");let C=0;b[0]=b[0].replace(/%([a-zA-Z%])/g,(R,M)=>{if(R==="%%")return"%";C++;let S=e.formatters[M];if(typeof S=="function"){let E=b[C];R=S.call(m,E),b.splice(C,1),C--}return R}),e.formatArgs.call(m,b),(m.log||e.log).apply(m,b)}return v.namespace=f,v.useColors=e.useColors(),v.color=e.selectColor(f),v.extend=n,v.destroy=e.destroy,Object.defineProperty(v,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(x!==e.namespaces&&(x=e.namespaces,h=e.enabled(f)),h),set:b=>{d=b}}),typeof e.init=="function"&&e.init(v),v}function n(f,l){let d=e(this.namespace+(typeof l>"u"?":":l)+f);return d.log=this.log,d}function o(f){e.save(f),e.namespaces=f,e.names=[],e.skips=[];let l=(typeof f=="string"?f:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let d of l)d[0]==="-"?e.skips.push(d.slice(1)):e.names.push(d)}function s(f,l){let d=0,x=0,h=-1,v=0;for(;d<f.length;)if(x<l.length&&(l[x]===f[d]||l[x]==="*"))l[x]==="*"?(h=x,v=d,x++):(d++,x++);else if(h!==-1)x=h+1,v++,d=v;else return!1;for(;x<l.length&&l[x]==="*";)x++;return x===l.length}function i(){let f=[...e.names,...e.skips.map(l=>"-"+l)].join(",");return e.enable(""),f}function a(f){for(let l of e.skips)if(s(f,l))return!1;for(let l of e.names)if(s(f,l))return!0;return!1}function c(f){return f instanceof Error?f.stack||f.message:f}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return e.enable(e.load()),e}ba.exports=Ku});var wa=xn((ht,nn)=>{ht.formatArgs=Vu;ht.save=Hu;ht.load=qu;ht.useColors=Fu;ht.storage=zu();ht.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();ht.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Fu(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let r;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function Vu(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+nn.exports.humanize(this.diff),!this.useColors)return;let t="color: "+this.color;r.splice(1,0,t,"color: inherit");let e=0,n=0;r[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(e++,o==="%c"&&(n=e))}),r.splice(n,0,t)}ht.log=console.debug||console.log||(()=>{});function Hu(r){try{r?ht.storage.setItem("debug",r):ht.storage.removeItem("debug")}catch{}}function qu(){let r;try{r=ht.storage.getItem("debug")||ht.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function zu(){try{return localStorage}catch{}}nn.exports=xa()(ht);var{formatters:Gu}=nn.exports;Gu.j=function(r){try{return JSON.stringify(r)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var Xl={};dt(Xl,{FretServiceImpl:()=>re,Libp2pFretService:()=>mr,createFret:()=>Wl,fretService:()=>rc,hashKey:()=>$e,hashPeerId:()=>J,seedDiscovery:()=>bn});var Bt=class{entries;constructor(t){this.entries=t}},Me=class{partitions;nodes;constructor(t,e){this.partitions=t,this.nodes=e}};var Lt=class r{node;index;constructor(t,e){this.node=t,this.index=e}clone(){return new r(this.node,this.index)}},pe=class r{branches;leafNode;leafIndex;on;version;constructor(t,e,n,o,s){this.branches=t,this.leafNode=e,this.leafIndex=n,this.on=o,this.version=s}isEqual(t){return this.leafNode===t.leafNode&&this.leafIndex===t.leafIndex&&this.on===t.on&&this.version===t.version}clone(){return new r(this.branches.map(t=>t.clone()),this.leafNode,this.leafIndex,this.on,this.version)}};var wt=64,br=class{keyFromEntry;compare;_root;_version=0;constructor(t=n=>n,e=(n,o)=>n<o?-1:n>o?1:0){this.keyFromEntry=t,this.compare=e,this._root=new Bt([])}first(){return this.getFirst(this._root)}last(){return this.getLast(this._root)}find(t){return this.getPath(this._root,t)}get(t){return this.at(this.find(t))}at(t){return this.validatePath(t),t.on?t.leafNode.entries[t.leafIndex]:void 0}*range(t){let e=t.first?this.findFirst(t):t.isAscending?this.first():this.last(),n=t.last?this.findLast(t):t.isAscending?this.last():this.first(),o=this.keyFromEntry(n.leafNode.entries[n.leafIndex]),s=t.isAscending?this.internalAscending(e):this.internalDescending(e),i=t.isAscending?1:-1;for(let a of s){if(!a.on||!n.on||this.compareKeys(this.keyFromEntry(a.leafNode.entries[a.leafIndex]),o)*i>0)break;yield a}}isValid(t){return t.version===this._version}insert(t){Object.freeze(t);let e=this.internalInsert(t);return e.on&&(e.version=++this._version),e}updateAt(t,e){this.validatePath(t),t.on&&Object.freeze(e);let n=this.internalUpdate(t,e);return n[0].on&&(n[0].version=++this._version),n}upsert(t){let e=this.find(this.keyFromEntry(t));return Object.freeze(t),e.on?e.leafNode.entries[e.leafIndex]=t:this.internalInsertAt(e,t),e.version=++this._version,e}merge(t,e){let n=this.keyFromEntry(t),o=this.find(n);if(o.on){let s=this.updateAt(o,e(o.leafNode.entries[o.leafIndex]));return s[0].on&&(s[0].version=++this._version),s}else return this.internalInsertAt(o,Object.freeze(t)),o.on=!0,o.version=++this._version,[o,!1]}deleteAt(t){this.validatePath(t);let e=this.internalDelete(t);return e&&++this._version,e}ascending(t){return this.validatePath(t),this.internalAscending(t.clone())}descending(t){return this.validatePath(t),this.internalDescending(t.clone())}getCount(t){let e=0,n=t?t.path.clone():this.first();if(t?.ascending??!0)for(;n.on;)e+=n.leafNode.entries.length-n.leafIndex,n.leafIndex=n.leafNode.entries.length-1,this.internalNext(n);else for(;n.on;)e+=n.leafIndex+1,n.leafIndex=0,this.internalPrior(n);return e}next(t){let e=t.clone();return this.moveNext(e),e}moveNext(t){this.validatePath(t),this.internalNext(t)}prior(t){let e=t.clone();return this.movePrior(e),e}movePrior(t){this.validatePath(t),this.internalPrior(t)}compareKeys(t,e){let n=this.compare(t,e);if(n!==0&&n===this.compare(e,t))throw new Error("Inconsistent comparison function for given values");return n}*internalAscending(t){for(this.validatePath(t);t.on;)yield t,this.moveNext(t)}*internalDescending(t){for(this.validatePath(t);t.on;)yield t,this.movePrior(t)}findFirst(t){let e=this.find(t.first.key);return(!e.on||t.first&&!t.first.inclusive)&&(t.isAscending?this.internalNext(e):this.internalPrior(e)),e}findLast(t){let e=this.find(t.last.key);return(!e.on||t.last&&!t.last.inclusive)&&(t.isAscending?this.internalPrior(e):this.internalNext(e)),e}getPath(t,e){if(t instanceof Bt){let n=t,[o,s]=this.indexOfEntry(n.entries,e);return new pe([],n,s,o,this._version)}else{let n=t,o=this.indexOfKey(n.partitions,e),s=this.getPath(n.nodes[o],e);return s.branches.unshift(new Lt(n,o)),s}}indexOfEntry(t,e){let n=0,o=t.length-1,s=0,i=-1;for(;n<=o;){if(s=n+o>>>1,i=this.compareKeys(e,this.keyFromEntry(t[s])),i===0)return[!0,s];i<0?o=s-1:n=s+1}return[!1,n]}indexOfKey(t,e){let n=0,o=t.length-1,s=0,i=-1;for(;n<=o;){if(s=n+o>>>1,i=this.compareKeys(e,t[s]),i===0)return s+1;i<0?o=s-1:n=s+1}return n}internalNext(t){if(t.on)if(t.leafIndex>=t.leafNode.entries.length-1){let e=0,n=!1,o=t.branches.length-1;for(;e<=o&&!n;){let s=t.branches[o-e];s.index===s.node.partitions.length?++e:n=!0}if(!n)t.leafIndex=t.leafNode.entries.length,t.on=!1;else{t.branches.splice(-e,e);let s=t.branches.at(-1);++s.index,this.moveToFirst(s.node.nodes[s.index],t)}}else++t.leafIndex,t.on=!0;else if(t.on=t.branches.every(e=>e.index>=0&&e.index<e.node.nodes.length)&&t.leafIndex>=0&&t.leafIndex<t.leafNode.entries.length,t.on)return}internalPrior(t){if(this.validatePath(t),t.leafIndex<=0){let e=0,n=!1,o=t.branches.length-1;for(;e<=o&&!n;)t.branches[o-e].index===0?++e:n=!0;if(!n)t.leafIndex=0,t.on=!1;else{t.branches.splice(-e,e);let s=t.branches.at(-1);--s.index,this.moveToLast(s.node.nodes[s.index],t)}}else--t.leafIndex,t.on=!0}internalUpdate(t,e){if(t.on){let n=this.keyFromEntry(t.leafNode.entries[t.leafIndex]),o=this.keyFromEntry(e);if(this.compareKeys(n,o)!==0){let s=this.internalInsert(e);return s.on&&(this.internalDelete(this.find(n)),s=this.find(o)),[s,!1]}else t.leafNode.entries[t.leafIndex]=e}return[t,!0]}internalDelete(t){if(t.on){if(t.leafNode.entries.splice(t.leafIndex,1),t.branches.length>0){if(t.leafIndex===0){let n=t.branches.at(-1);this.updatePartition(n.index,t,t.branches.length-1,this.keyFromEntry(t.leafNode.entries[t.leafIndex]))}let e=this.rebalanceLeaf(t);e&&(this._root=e)}return t.on=!1,!0}else return!1}internalInsert(t){let e=this.find(this.keyFromEntry(t));return e.on?(e.on=!1,e):(this.internalInsertAt(e,t),e.on=!0,e)}internalInsertAt(t,e){let n=this.leafInsert(t,e),o=t.branches.length-1;for(;n&&o>=0;)n=this.branchInsert(t,o,n),--o;if(n){let s=new Me([n.key],[this._root,n.right]);this._root=s,t.branches.unshift(new Lt(s,n.indexDelta))}}moveToFirst(t,e){if(t instanceof Bt){let n=t;e.leafNode=n,e.leafIndex=0,e.on=n.entries.length>0}else e.branches.push(new Lt(t,0)),this.moveToFirst(t.nodes[0],e)}moveToLast(t,e){if(t instanceof Bt){let n=t,o=n.entries.length;e.leafNode=n,e.on=o>0,e.leafIndex=o>0?o-1:0}else{let n=t,o=new Lt(n,n.partitions.length);e.branches.push(o),this.moveToLast(n.nodes[o.index],e)}}getFirst(t){if(t instanceof Bt){let e=t;return new pe([],e,0,e.entries.length>0,this._version)}else{let e=t,n=this.getFirst(e.nodes[0]);return n.branches.unshift(new Lt(e,0)),n}}getLast(t){if(t instanceof Bt){let e=t,n=e.entries.length;return new pe([],e,n>0?n-1:0,n>0,this._version)}else{let e=t,n=e.nodes.length-1,o=this.getLast(e.nodes[n]);return o.branches.unshift(new Lt(e,n)),o}}leafInsert(t,e){let{leafNode:n,leafIndex:o}=t;if(n.entries.length<wt){n.entries.splice(o,0,e);return}let s=n.entries.length+1>>>1,i=n.entries.splice(s),a=new Bt(i),c=o<s?0:1;return c?(t.leafNode=a,t.leafIndex-=n.entries.length,a.entries.splice(t.leafIndex,0,e)):n.entries.splice(o,0,e),new xr(this.keyFromEntry(i[0]),a,c)}branchInsert(t,e,n){let o=t.branches[e],{index:s,node:i}=o;if(o.index+=n.indexDelta,i.partitions.splice(s,0,n.key),i.nodes.splice(s+1,0,n.right),i.nodes.length<=wt)return;let a=i.nodes.length>>>1,c=i.partitions.splice(a),u=i.partitions.pop(),f=i.nodes.splice(a),l=new Me(c,f),d=o.index<a?0:1;return d&&(o.index-=a,o.node=l),new xr(u,l,d)}rebalanceLeaf(t){if(t.leafNode.entries.length>=wt>>>1)return;let e=t.leafNode,n=t.branches.at(-1),o=t.branches.length-1,s=n.index,i=n.node,a=i.nodes[s+1];if(a&&a.entries.length>wt>>>1){let u=a.entries.shift();e.entries.push(u),this.updatePartition(s+1,t,o,this.keyFromEntry(a.entries[0]));return}let c=i.nodes[s-1];if(c&&c.entries.length>wt>>>1){let u=c.entries.pop();e.entries.unshift(u),this.updatePartition(s,t,o,this.keyFromEntry(u)),t.leafIndex+=1;return}if(a&&a.entries.length+e.entries.length<=wt)return e.entries.push(...a.entries),i.partitions.splice(s,1),i.nodes.splice(s+1,1),s===0&&this.updatePartition(s,t,o,this.keyFromEntry(e.entries[0])),this.rebalanceBranch(t,o);if(c&&c.entries.length+e.entries.length<=wt)return t.leafNode=c,t.leafIndex+=c.entries.length,c.entries.push(...e.entries),i.partitions.splice(s-1,1),i.nodes.splice(s,1),this.rebalanceBranch(t,o)}rebalanceBranch(t,e){let n=t.branches[e],o=n.node;if(e===0&&o.partitions.length===0)return t.branches[e+1]?.node??t.leafNode;if(e===0||o.nodes.length>=wt<<1)return;let s=t.branches.at(e-1),i=s.index,a=s.node,c=a.nodes[i+1];if(c&&c.nodes.length>wt>>>1){o.partitions.push(a.partitions[i]);let f=c.nodes.shift();o.nodes.push(f);let l=c.partitions.shift();this.updatePartition(i+1,t,e-1,l);return}let u=a.nodes[i-1];if(u&&u.nodes.length>wt>>>1){o.partitions.unshift(a.partitions[i-1]);let f=u.nodes.pop();o.nodes.unshift(f);let l=u.partitions.pop();n.index+=1,this.updatePartition(i,t,e-1,l);return}if(c&&c.nodes.length+o.nodes.length<=wt){let f=a.partitions.splice(i,1)[0];return o.partitions.push(f),o.partitions.push(...c.partitions),o.nodes.push(...c.nodes),a.nodes.splice(i+1,1),i===0&&a.partitions.length>0&&this.updatePartition(i,t,e-1,a.partitions[0]),this.rebalanceBranch(t,e-1)}if(u&&u.nodes.length+o.nodes.length<=wt){n.node=u,n.index+=u.nodes.length;let f=a.partitions.splice(i-1,1)[0];return u.partitions.push(f),u.partitions.push(...o.partitions),u.nodes.push(...o.nodes),a.nodes.splice(i,1),this.rebalanceBranch(t,e-1)}}updatePartition(t,e,n,o){let s=e.branches[n];t>0?s.node.partitions[t-1]=o:n!==0&&this.updatePartition(e.branches[n-1].index,e,n-1,o)}validatePath(t){if(!this.isValid(t))throw new Error("Path is invalid due to mutation of the tree")}},xr=class{key;right;indexDelta;constructor(t,e,n){this.key=t,this.right=e,this.indexDelta=n}};function Ke(r){let t="";for(let e=0;e<r.length;e++)t+=r[e].toString(16).padStart(2,"0");return t}function wr(r){return`${Ke(r.coord)}|${r.id}`}var Er=class{byKey;byId;constructor(){this.byKey=new br(t=>wr(t)),this.byId=new Map}insert(t){let e=wr(t);this.byKey.insert(t),this.byId.set(t.id,e)}upsert(t,e){let n=Date.now(),o=this.byId.get(t);if(o){let i=this.byKey.find(o);i.on&&this.byKey.deleteAt(i),this.byId.delete(t)}let s={id:t,coord:e,relevance:0,lastAccess:n,state:"disconnected",accessCount:0,successCount:0,failureCount:0,avgLatencyMs:0};return this.insert(s),s}update(t,e){let n=this.byId.get(t);if(!n)return;let o=this.byKey.find(n),s=this.byKey.at(o);if(!s)return;let i={...s,...e};this.byKey.updateAt(o,i),wr(s)!==wr(i)&&(this.byKey.deleteAt(o),this.insert(i))}getById(t){let e=this.byId.get(t);if(!e)return;let n=this.byKey.find(e);return n.on?this.byKey.at(n):void 0}remove(t){let e=this.byId.get(t);if(!e)return;let n=this.byKey.find(e);n.on&&this.byKey.deleteAt(n),this.byId.delete(t)}list(){let t=[];for(let e of this.byKey.ascending(this.byKey.first()))t.push(this.byKey.at(e));return t}size(){return this.byId.size}setState(t,e){this.update(t,{state:e})}protectedIdsAround(t,e){let n=new Set;for(let o of this.neighborsRight(t,e))n.add(o);for(let o of this.neighborsLeft(t,e))n.add(o);return n}ceilPath(t){let e=`${t}|\0`,n=this.byKey.find(e);return n.on||(n=this.byKey.next(n)),n}floorPath(t){let e=`${t}|\uFFFF`,n=this.byKey.find(e);return n.on||(n=this.byKey.prior(n)),n}successorOfCoord(t){let e=Ke(t),n=this.ceilPath(e);if(n.on)return this.byKey.at(n);let o=this.byKey.first();return o.on?this.byKey.at(o):void 0}predecessorOfCoord(t){let e=Ke(t),n=this.floorPath(e);if(n.on)return this.byKey.at(n);let o=this.byKey.last();return o.on?this.byKey.at(o):void 0}neighborsRight(t,e){let n=[],o=Ke(t),s=this.ceilPath(o);s=s.on?s:this.byKey.first();let i=0;for(;i<e&&!(!s.on&&(s=this.byKey.first(),!s.on));)n.push(this.byKey.at(s).id),s=this.byKey.next(s),i++;return Array.from(new Set(n))}neighborsLeft(t,e){let n=[],o=Ke(t),s=this.floorPath(o);s=s.on?s:this.byKey.last();let i=0;for(;i<e&&!(!s.on&&(s=this.byKey.last(),!s.on));)n.push(this.byKey.at(s).id),s=this.byKey.prior(s),i++;return Array.from(new Set(n))}};var Sn={};dt(Sn,{sha256:()=>zt,sha512:()=>Dc});var lh=new Uint8Array(0);function As(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Pt(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function Is(r){return new TextEncoder().encode(r)}function Cs(r){return new TextDecoder().decode(r)}var uc=Ts,_s=128,lc=127,hc=~lc,dc=Math.pow(2,31);function Ts(r,t,e){t=t||[],e=e||0;for(var n=e;r>=dc;)t[e++]=r&255|_s,r/=128;for(;r&hc;)t[e++]=r&255|_s,r>>>=7;return t[e]=r|0,Ts.bytes=e-n+1,t}var pc=wn,mc=128,Ds=127;function wn(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw wn.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&Ds)<<o:(i&Ds)*Math.pow(2,o),o+=7}while(i>=mc);return wn.bytes=s-n,e}var yc=Math.pow(2,7),gc=Math.pow(2,14),bc=Math.pow(2,21),xc=Math.pow(2,28),wc=Math.pow(2,35),Ec=Math.pow(2,42),vc=Math.pow(2,49),Sc=Math.pow(2,56),Ac=Math.pow(2,63),Ic=function(r){return r<yc?1:r<gc?2:r<bc?3:r<xc?4:r<wc?5:r<Ec?6:r<vc?7:r<Sc?8:r<Ac?9:10},Cc={encode:uc,decode:pc,encodingLength:Ic},Bc=Cc,Fe=Bc;function Ve(r,t=0){return[Fe.decode(r,t),Fe.decode.bytes]}function me(r,t,e=0){return Fe.encode(r,t,e),t}function ye(r){return Fe.encodingLength(r)}function be(r,t){let e=t.byteLength,n=ye(r),o=n+ye(e),s=new Uint8Array(o+e);return me(r,s,0),me(e,s,n),s.set(t,o),new ge(r,e,t,s)}function He(r){let t=Pt(r),[e,n]=Ve(t),[o,s]=Ve(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new ge(e,o,i,t)}function Os(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&As(r.bytes,e.bytes)}}var ge=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};var _c=20;function vn({name:r,code:t,encode:e,minDigestLength:n,maxDigestLength:o}){return new En(r,t,e,n,o)}var En=class{name;code;encode;minDigestLength;maxDigestLength;constructor(t,e,n,o,s){this.name=t,this.code=e,this.encode=n,this.minDigestLength=o??_c,this.maxDigestLength=s}digest(t,e){if(e?.truncate!=null){if(e.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&e.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(t instanceof Uint8Array){let n=this.encode(t);return n instanceof Uint8Array?Ls(n,this.code,e?.truncate):n.then(o=>Ls(o,this.code,e?.truncate))}else throw Error("Unknown type, must be binary type")}};function Ls(r,t,e){if(e!=null&&e!==r.byteLength){if(e>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e)}return be(t,r)}function Ns(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var zt=vn({name:"sha2-256",code:18,encode:Ns("SHA-256")}),Dc=vn({name:"sha2-512",code:19,encode:Ns("SHA-512")});var _n={};dt(_n,{base10:()=>kc});function Tc(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),f=Math.log(256)/Math.log(a);function l(h){if(h instanceof Uint8Array||(ArrayBuffer.isView(h)?h=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):Array.isArray(h)&&(h=Uint8Array.from(h))),!(h instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(h.length===0)return"";for(var v=0,b=0,m=0,I=h.length;m!==I&&h[m]===0;)m++,v++;for(var w=(I-m)*f+1>>>0,C=new Uint8Array(w);m!==I;){for(var P=h[m],R=0,M=w-1;(P!==0||R<b)&&M!==-1;M--,R++)P+=256*C[M]>>>0,C[M]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");b=R,m++}for(var S=w-b;S!==w&&C[S]===0;)S++;for(var E=c.repeat(v);S<w;++S)E+=r.charAt(C[S]);return E}function d(h){if(typeof h!="string")throw new TypeError("Expected String");if(h.length===0)return new Uint8Array;var v=0;if(h[v]!==" "){for(var b=0,m=0;h[v]===c;)b++,v++;for(var I=(h.length-v)*u+1>>>0,w=new Uint8Array(I);h[v];){var C=e[h.charCodeAt(v)];if(C===255)return;for(var P=0,R=I-1;(C!==0||P<m)&&R!==-1;R--,P++)C+=a*w[R]>>>0,w[R]=C%256>>>0,C=C/256>>>0;if(C!==0)throw new Error("Non-zero carry");m=P,v++}if(h[v]!==" "){for(var M=I-m;M!==I&&w[M]===0;)M++;for(var S=new Uint8Array(b+(I-M)),E=b;M!==I;)S[E++]=w[M++];return S}}}function x(h){var v=d(h);if(v)return v;throw new Error(`Non-${t} character`)}return{encode:l,decodeUnsafe:d,decode:x}}var Oc=Tc,Lc=Oc,Rs=Lc;var An=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},In=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){this.name=t,this.prefix=e;let o=e.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=n}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return ks(this,t)}},Cn=class{decoders;constructor(t){this.decoders=t}or(t){return ks(this,t)}decode(t){let e=t[0],n=this.decoders[e];if(n!=null)return n.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function ks(r,t){return new Cn({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var Bn=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new An(t,e,n),this.decoder=new In(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function we({name:r,prefix:t,encode:e,decode:n}){return new Bn(r,t,e,n)}function Gt({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Rs(e,r);return we({prefix:t,name:r,encode:n,decode:s=>Pt(o(s))})}function Pc(r,t,e,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*e/8|0),i=0,a=0,c=0;for(let u=0;u<o;++u){let f=t[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<e|f,i+=e,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=e||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Nc(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;(s.length*e&7)!==0;)s+="=";return s}function Rc(r){let t={};for(let e=0;e<r.length;++e)t[r[e]]=e;return t}function Y({name:r,prefix:t,bitsPerChar:e,alphabet:n}){let o=Rc(n);return we({prefix:t,name:r,encode(s){return Nc(s,n,e)},decode(s){return Pc(s,o,e,r)}})}var kc=Gt({prefix:"9",name:"base10",alphabet:"0123456789"});var Dn={};dt(Dn,{base16:()=>Uc,base16upper:()=>Mc});var Uc=Y({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Mc=Y({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Tn={};dt(Tn,{base2:()=>Kc});var Kc=Y({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var On={};dt(On,{base256emoji:()=>zc});var Us=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Fc=Us.reduce((r,t,e)=>(r[e]=t,r),[]),Vc=Us.reduce((r,t,e)=>{let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);return r[n]=e,r},[]);function Hc(r){return r.reduce((t,e)=>(t+=Fc[e],t),"")}function qc(r){let t=[];for(let e of r){let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);let o=Vc[n];if(o==null)throw new Error(`Non-base256emoji character: ${e}`);t.push(o)}return new Uint8Array(t)}var zc=we({prefix:"\u{1F680}",name:"base256emoji",encode:Hc,decode:qc});var Ln={};dt(Ln,{base32:()=>$t,base32hex:()=>Zc,base32hexpad:()=>Wc,base32hexpadupper:()=>Xc,base32hexupper:()=>Yc,base32pad:()=>$c,base32padupper:()=>jc,base32upper:()=>Gc,base32z:()=>Jc});var $t=Y({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Gc=Y({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),$c=Y({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),jc=Y({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Zc=Y({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Yc=Y({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Wc=Y({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Xc=Y({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Jc=Y({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Pn={};dt(Pn,{base36:()=>qe,base36upper:()=>Qc});var qe=Gt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Qc=Gt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Nn={};dt(Nn,{base58btc:()=>W,base58flickr:()=>tf});var W=Gt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),tf=Gt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var kn={};dt(kn,{base64:()=>ef,base64pad:()=>rf,base64url:()=>Rn,base64urlpad:()=>nf});var ef=Y({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),rf=Y({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Rn=Y({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),nf=Y({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Un={};dt(Un,{base8:()=>of});var of=Y({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Mn={};dt(Mn,{identity:()=>sf});var sf=we({prefix:"\0",name:"identity",encode:r=>Cs(r),decode:r=>Is(r)});var Oh=new TextEncoder,Lh=new TextDecoder;var Kn={};dt(Kn,{identity:()=>vt});var Ms=0,ff="identity",Ks=Pt;function uf(r,t){if(t?.truncate!=null&&t.truncate!==r.byteLength){if(t.truncate<0||t.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t.truncate)}return be(Ms,Ks(r))}var vt={code:Ms,name:ff,encode:Ks,digest:uf};function Fs(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return hf(e,Fn(r),t??W.encoder);default:return df(e,Fn(r),t??$t.encoder)}}var Vs=new WeakMap;function Fn(r){let t=Vs.get(r);if(t==null){let e=new Map;return Vs.set(r,e),e}return t}var tt=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,this.version=t,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:e}=this;if(t!==ze)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==pf)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:e}=this.multihash,n=be(t,e);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&Os(t.multihash,n.multihash)}toString(t){return Fs(this,t)}toJSON(){return{"/":Fs(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??Hs(n,o,s.bytes))}else if(e[mf]===!0){let{version:n,multihash:o,code:s}=e,i=He(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(e!==ze)throw new Error(`Version 0 CID must use dag-pb (code: ${ze}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Hs(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,ze,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=Pt(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new ge(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[l,d]=Ve(t.subarray(e));return e+=d,l},o=n(),s=ze;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),u=e+c,f=u-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:f,size:u}}static parse(t,e){let[n,o]=lf(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Fn(s).set(n,t),s}};function lf(r,t){switch(r[0]){case"Q":{let e=t??W;return[W.prefix,e.decode(`${W.prefix}${r}`)]}case W.prefix:{let e=t??W;return[W.prefix,e.decode(r)]}case $t.prefix:{let e=t??$t;return[$t.prefix,e.decode(r)]}case qe.prefix:{let e=t??qe;return[qe.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function hf(r,t,e){let{prefix:n}=e;if(n!==W.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function df(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var ze=112,pf=18;function Hs(r,t,e){let n=ye(r),o=n+ye(t),s=new Uint8Array(o+e.byteLength);return me(r,s,0),me(t,s,n),s.set(e,o),s}var mf=Symbol.for("@ipld/js-cid/CID");var Ge={...Mn,...Tn,...Un,..._n,...Dn,...Ln,...Pn,...Nn,...kn,...On},Wh={...Sn,...Kn};function Nt(r=0){return new Uint8Array(r)}function pt(r=0){return new Uint8Array(r)}function zs(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var qs=zs("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Vn=zs("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=pt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),yf={utf8:qs,"utf-8":qs,hex:Ge.base16,latin1:Vn,ascii:Vn,binary:Vn,...Ge},Sr=yf;function V(r,t="utf8"){let e=Sr[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}function X(r,t="utf8"){let e=Sr[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}async function J(r){let t=r.toMultihash().bytes;return await zt.encode(t)}async function $e(r){return await zt.encode(r)}function Gs(r){return V(r,"base64url")}function $s(r="default"){let t=`/optimystic/${r}/fret/1.0.0`;return{PROTOCOL_NEIGHBORS:`${t}/neighbors`,PROTOCOL_NEIGHBORS_ANNOUNCE:`${t}/neighbors/announce`,PROTOCOL_MAYBE_ACT:`${t}/maybeAct`,PROTOCOL_LEAVE:`${t}/leave`,PROTOCOL_PING:`${t}/ping`}}var Hn="/optimystic/default/fret/1.0.0/neighbors",qn="/optimystic/default/fret/1.0.0/neighbors/announce",zn="/optimystic/default/fret/1.0.0/maybeAct",Gn="/optimystic/default/fret/1.0.0/leave",$n="/optimystic/default/fret/1.0.0/ping";async function Et(r){let t=JSON.stringify(r);return new TextEncoder().encode(t)}async function _t(r){if(r.byteLength===0)throw new Error("empty response");let t=0,e=r.byteLength;for(;t<e&&(r[t]===0||r[t]===9||r[t]===10||r[t]===13||r[t]===32);)t++;for(;e>t&&(r[e-1]===0||r[e-1]===9||r[e-1]===10||r[e-1]===13||r[e-1]===32);)e--;if(e<=t)throw new Error("whitespace response");let n=new TextDecoder().decode(r.subarray(t,e));return JSON.parse(n)}var jt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},Ar=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var Ir=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};function mt(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Rt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=pt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var Zs=Symbol.for("@achingbrain/uint8arraylist");function js(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function Cr(r){return!!r?.[Zs]}var yt=class r{bufs;length;[Zs]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(Cr(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(Cr(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=js(this.bufs,t);return e.buf[e.index]}set(t,e){let n=js(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(Cr(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return Rt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:Rt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let u=t>=a&&t<c,f=e>a&&e<=c;if(u&&f){if(t===a&&e===c){n.push(i);break}let l=t-a;n.push(i.subarray(l,l+(e-t)));break}if(u){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(f){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!Cr(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let l=0;l<s;l++)i[l]=-1;for(let l=0;l<o;l++)i[n[l]]=l;let a=i,c=this.byteLength-n.byteLength,u=n.byteLength-1,f;for(let l=e;l<=c;l+=f){f=0;for(let d=u;d>=0;d--){let x=this.get(l+d);if(n[d]!==x){f=Math.max(1,d-a[x]);break}}if(f===0)return l}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=pt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=Nt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=Nt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=Nt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=pt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=Nt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=Nt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=Nt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=Nt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=Nt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!mt(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};var gf=parseInt("11111",2),jn=parseInt("10000000",2),bf=parseInt("01111111",2),Ys={0:je,1:je,2:xf,3:vf,4:Sf,5:Ef,6:wf,16:je,22:je,48:je};function Zn(r,t={offset:0}){let e=r[t.offset]&gf;if(t.offset++,Ys[e]!=null)return Ys[e](r,t);throw new Error("No decoder for tag "+e)}function Ze(r,t){let e=0;if((r[t.offset]&jn)===jn){let n=r[t.offset]&bf,o="0x";t.offset++;for(let s=0;s<n;s++,t.offset++)o+=r[t.offset].toString(16).padStart(2,"0");e=parseInt(o,16)}else e=r[t.offset],t.offset++;return e}function je(r,t){Ze(r,t);let e=[];for(;!(t.offset>=r.byteLength);){let n=Zn(r,t);if(n===null)break;e.push(n)}return e}function xf(r,t){let e=Ze(r,t),n=t.offset,o=t.offset+e,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return t.offset+=e,Uint8Array.from(s)}function wf(r,t){let e=Ze(r,t),n=t.offset+e,o=r[t.offset];t.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,c=[];for(;t.offset<n;){let u=r[t.offset];if(t.offset++,c.push(u&127),u<128){c.reverse();let f=0;for(let l=0;l<c.length;l++)f+=c[l]<<l*7;a+=`.${f}`,c=[]}}return a}function Ef(r,t){return t.offset++,null}function vf(r,t){let e=Ze(r,t),n=r[t.offset];t.offset++;let o=r.subarray(t.offset,t.offset+e-1);if(t.offset+=e,n!==0)throw new Error("Unused bits in bit string is unimplemented");return o}function Sf(r,t){let e=Ze(r,t),n=r.subarray(t.offset,t.offset+e);return t.offset+=e,n}function Af(r){let t=r.toString(16);t.length%2===1&&(t="0"+t);let e=new yt;for(let n=0;n<t.length;n+=2)e.append(Uint8Array.from([parseInt(`${t[n]}${t[n+1]}`,16)]));return e}function Yn(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let t=Af(r.byteLength);return new yt(Uint8Array.from([t.byteLength|jn]),t)}function Ws(r){let t=new yt,e=128;return(r.subarray()[0]&e)===e&&t.append(Uint8Array.from([0])),t.append(r),new yt(Uint8Array.from([2]),Yn(t),t)}function Xs(r){let t=Uint8Array.from([0]),e=new yt(t,r);return new yt(Uint8Array.from([3]),Yn(e),e)}function Br(r,t=48){let e=new yt;for(let n of r)e.append(n);return new yt(Uint8Array.from([t]),Yn(e),e)}async function Js(r,t,e,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,t,e.subarray());return n?.signal?.throwIfAborted(),s}var If=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Cf=Uint8Array.from([6,5,43,129,4,0,34]),Bf=Uint8Array.from([6,5,43,129,4,0,35]),_f={ext:!0,kty:"EC",crv:"P-256"},Df={ext:!0,kty:"EC",crv:"P-384"},Tf={ext:!0,kty:"EC",crv:"P-521"},Wn=32,Xn=48,Jn=66;function Qs(r){let t=Zn(r);return ti(t)}function ti(r){let t=r[1][1][0],e=1,n,o;if(t.byteLength===Wn*2+1)return n=V(t.subarray(e,e+Wn),"base64url"),o=V(t.subarray(e+Wn),"base64url"),new Ee({..._f,key_ops:["verify"],x:n,y:o});if(t.byteLength===Xn*2+1)return n=V(t.subarray(e,e+Xn),"base64url"),o=V(t.subarray(e+Xn),"base64url"),new Ee({...Df,key_ops:["verify"],x:n,y:o});if(t.byteLength===Jn*2+1)return n=V(t.subarray(e,e+Jn),"base64url"),o=V(t.subarray(e+Jn),"base64url"),new Ee({...Tf,key_ops:["verify"],x:n,y:o});throw new jt(`coordinates were wrong length, got ${t.byteLength}, expected 65, 97 or 133`)}function ei(r){return Br([Ws(Uint8Array.from([1])),Br([Of(r.crv)],160),Br([Xs(new yt(Uint8Array.from([4]),X(r.x??"","base64url"),X(r.y??"","base64url")))],161)]).subarray()}function Of(r){if(r==="P-256")return If;if(r==="P-384")return Cf;if(r==="P-521")return Bf;throw new jt(`Invalid curve ${r}`)}var Ee=class{type="ECDSA";jwk;_raw;constructor(t){this.jwk=t}get raw(){return this._raw==null&&(this._raw=ei(this.jwk)),this._raw}toMultihash(){return vt.digest(ve(this))}toCID(){return tt.createV1(114,this.toMultihash())}toString(){return W.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:mt(this.raw,t.raw)}async verify(t,e,n){return Js(this.jwk,e,t,n)}};function ne(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Dt(r,t=""){if(!Number.isSafeInteger(r)||r<0){let e=t&&`"${t}" `;throw new Error(`${e}expected integer >= 0, got ${r}`)}}function U(r,t,e=""){let n=ne(r),o=r?.length,s=t!==void 0;if(!n||s&&o!==t){let i=e&&`"${e}" `,a=s?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function _r(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Dt(r.outputLen),Dt(r.blockLen)}function Se(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function ni(r,t){U(r,void 0,"digestInto() output");let e=t.outputLen;if(r.length<e)throw new Error('"digestInto() output" expected to be of length >='+e)}function Ut(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}function Dr(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function St(r,t){return r<<32-t|r>>>t}var oi=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Lf=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Mt(r){if(U(r),oi)return r.toHex();let t="";for(let e=0;e<r.length;e++)t+=Lf[r[e]];return t}var kt={_0:48,_9:57,A:65,F:70,a:97,f:102};function ri(r){if(r>=kt._0&&r<=kt._9)return r-kt._0;if(r>=kt.A&&r<=kt.F)return r-(kt.A-10);if(r>=kt.a&&r<=kt.f)return r-(kt.a-10)}function Kt(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(oi)return Uint8Array.fromHex(r);let t=r.length,e=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,s=0;o<e;o++,s+=2){let i=ri(r.charCodeAt(s)),a=ri(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function lt(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];U(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}function Qn(r,t={}){let e=(o,s)=>r(s).update(o).digest(),n=r(void 0);return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=o=>r(o),Object.assign(e,t),Object.freeze(e)}function Ae(r=32){let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(r))}var to=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function si(r,t,e){return r&t^~r&e}function ii(r,t,e){return r&t^r&e^t&e}var Ye=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,e,n,o){this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Dr(this.buffer)}update(t){Se(this),U(t);let{view:e,buffer:n,blockLen:o}=this,s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Dr(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Se(this),ni(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,Ut(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)e[l]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=Dr(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,f[l],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||=new this.constructor,t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.destroyed=i,t.finished=s,t.length=o,t.pos=a,o%e&&t.buffer.set(n),t}clone(){return this._cloneInto()}},Ft=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var st=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Tr=BigInt(4294967295),ai=BigInt(32);function Pf(r,t=!1){return t?{h:Number(r&Tr),l:Number(r>>ai&Tr)}:{h:Number(r>>ai&Tr)|0,l:Number(r&Tr)|0}}function ci(r,t=!1){let e=r.length,n=new Uint32Array(e),o=new Uint32Array(e);for(let s=0;s<e;s++){let{h:i,l:a}=Pf(r[s],t);[n[s],o[s]]=[i,a]}return[n,o]}var eo=(r,t,e)=>r>>>e,ro=(r,t,e)=>r<<32-e|t>>>e,oe=(r,t,e)=>r>>>e|t<<32-e,se=(r,t,e)=>r<<32-e|t>>>e,We=(r,t,e)=>r<<64-e|t>>>e-32,Xe=(r,t,e)=>r>>>e-32|t<<64-e;function Tt(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var fi=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),ui=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,li=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),hi=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,di=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),pi=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var Rf=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]),Zt=new Uint32Array(64),no=class extends Ye{constructor(t){super(64,t,8,!1)}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let l=0;l<16;l++,e+=4)Zt[l]=t.getUint32(e,!1);for(let l=16;l<64;l++){let d=Zt[l-15],x=Zt[l-2],h=St(d,7)^St(d,18)^d>>>3,v=St(x,17)^St(x,19)^x>>>10;Zt[l]=v+Zt[l-7]+h+Zt[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){let d=St(a,6)^St(a,11)^St(a,25),x=f+d+si(a,c,u)+Rf[l]+Zt[l]|0,v=(St(n,2)^St(n,13)^St(n,22))+ii(n,o,s)|0;f=u,u=c,c=a,a=i+x|0,i=s,s=o,o=n,n=x+v|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(n,o,s,i,a,c,u,f)}roundClean(){Ut(Zt)}destroy(){this.set(0,0,0,0,0,0,0,0),Ut(this.buffer)}},oo=class extends no{A=Ft[0]|0;B=Ft[1]|0;C=Ft[2]|0;D=Ft[3]|0;E=Ft[4]|0;F=Ft[5]|0;G=Ft[6]|0;H=Ft[7]|0;constructor(){super(32)}};var mi=ci(["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(r=>BigInt(r))),kf=mi[0],Uf=mi[1],Yt=new Uint32Array(80),Wt=new Uint32Array(80),so=class extends Ye{constructor(t){super(128,t,16,!1)}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:u,El:f,Fh:l,Fl:d,Gh:x,Gl:h,Hh:v,Hl:b}=this;return[t,e,n,o,s,i,a,c,u,f,l,d,x,h,v,b]}set(t,e,n,o,s,i,a,c,u,f,l,d,x,h,v,b){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=f|0,this.Fh=l|0,this.Fl=d|0,this.Gh=x|0,this.Gl=h|0,this.Hh=v|0,this.Hl=b|0}process(t,e){for(let w=0;w<16;w++,e+=4)Yt[w]=t.getUint32(e),Wt[w]=t.getUint32(e+=4);for(let w=16;w<80;w++){let C=Yt[w-15]|0,P=Wt[w-15]|0,R=oe(C,P,1)^oe(C,P,8)^eo(C,P,7),M=se(C,P,1)^se(C,P,8)^ro(C,P,7),S=Yt[w-2]|0,E=Wt[w-2]|0,N=oe(S,E,19)^We(S,E,61)^eo(S,E,6),K=se(S,E,19)^Xe(S,E,61)^ro(S,E,6),T=li(M,K,Wt[w-7],Wt[w-16]),y=hi(T,R,N,Yt[w-7],Yt[w-16]);Yt[w]=y|0,Wt[w]=T|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:u,Dl:f,Eh:l,El:d,Fh:x,Fl:h,Gh:v,Gl:b,Hh:m,Hl:I}=this;for(let w=0;w<80;w++){let C=oe(l,d,14)^oe(l,d,18)^We(l,d,41),P=se(l,d,14)^se(l,d,18)^Xe(l,d,41),R=l&x^~l&v,M=d&h^~d&b,S=di(I,P,M,Uf[w],Wt[w]),E=pi(S,m,C,R,kf[w],Yt[w]),N=S|0,K=oe(n,o,28)^We(n,o,34)^We(n,o,39),T=se(n,o,28)^Xe(n,o,34)^Xe(n,o,39),y=n&s^n&a^s&a,g=o&i^o&c^i&c;m=v|0,I=b|0,v=x|0,b=h|0,x=l|0,h=d|0,{h:l,l:d}=Tt(u|0,f|0,E|0,N|0),u=a|0,f=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let p=fi(N,T,g);n=ui(p,E,K,y),o=p|0}({h:n,l:o}=Tt(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Tt(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Tt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:f}=Tt(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:d}=Tt(this.Eh|0,this.El|0,l|0,d|0),{h:x,l:h}=Tt(this.Fh|0,this.Fl|0,x|0,h|0),{h:v,l:b}=Tt(this.Gh|0,this.Gl|0,v|0,b|0),{h:m,l:I}=Tt(this.Hh|0,this.Hl|0,m|0,I|0),this.set(n,o,s,i,a,c,u,f,l,d,x,h,v,b,m,I)}roundClean(){Ut(Yt,Wt)}destroy(){Ut(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},io=class extends so{Ah=st[0]|0;Al=st[1]|0;Bh=st[2]|0;Bl=st[3]|0;Ch=st[4]|0;Cl=st[5]|0;Dh=st[6]|0;Dl=st[7]|0;Eh=st[8]|0;El=st[9]|0;Fh=st[10]|0;Fl=st[11]|0;Gh=st[12]|0;Gl=st[13]|0;Hh=st[14]|0;Hl=st[15]|0;constructor(){super(64)}};var yi=Qn(()=>new oo,to(1));var gi=Qn(()=>new io,to(3));var co=BigInt(0),ao=BigInt(1);function Vt(r,t=""){if(typeof r!="boolean"){let e=t&&`"${t}" `;throw new Error(e+"expected boolean, got type="+typeof r)}return r}function bi(r){if(typeof r=="bigint"){if(!Or(r))throw new Error("positive bigint expected, got "+r)}else Dt(r);return r}function Je(r){let t=bi(r).toString(16);return t.length&1?"0"+t:t}function xi(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?co:BigInt("0x"+r)}function Ie(r){return xi(Mt(r))}function ie(r){return xi(Mt(Pr(U(r)).reverse()))}function Lr(r,t){Dt(t),r=bi(r);let e=Kt(r.toString(16).padStart(t*2,"0"));if(e.length!==t)throw new Error("number too large");return e}function fo(r,t){return Lr(r,t).reverse()}function Pr(r){return Uint8Array.from(r)}var Or=r=>typeof r=="bigint"&&co<=r;function Mf(r,t,e){return Or(r)&&Or(t)&&Or(e)&&t<=r&&r<e}function Qe(r,t,e,n){if(!Mf(t,e,n))throw new Error("expected valid "+r+": "+e+" <= n < "+n+", got "+t)}function uo(r){let t;for(t=0;r>co;r>>=ao,t+=1);return t}var tr=r=>(ao<<BigInt(r))-ao;function wi(r,t,e){if(Dt(r,"hashLen"),Dt(t,"qByteLen"),typeof e!="function")throw new Error("hmacFn must be a function");let n=b=>new Uint8Array(b),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),u=n(r),f=0,l=()=>{c.fill(1),u.fill(0),f=0},d=(...b)=>e(u,lt(c,...b)),x=(b=o)=>{u=d(s,b),c=d(),b.length!==0&&(u=d(i,b),c=d())},h=()=>{if(f++>=a)throw new Error("drbg: tried max amount of iterations");let b=0,m=[];for(;b<t;){c=d();let I=c.slice();m.push(I),b+=c.length}return lt(...m)};return(b,m)=>{l(),x(b);let I;for(;!(I=m(h()));)x();return l(),I}}function Xt(r,t={},e={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(s,i,a){let c=r[s];if(a&&c===void 0)return;let u=typeof c;if(u!==i||c===null)throw new Error(`param "${s}" is invalid: expected ${i}, got ${u}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(t,!1),o(e,!0)}function Ce(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let s=r(e,...n);return t.set(e,s),s}}var ut=BigInt(0),et=BigInt(1),ae=BigInt(2),Si=BigInt(3),Ai=BigInt(4),Ii=BigInt(5),Kf=BigInt(7),Ci=BigInt(8),Ff=BigInt(9),Bi=BigInt(16);function Q(r,t){let e=r%t;return e>=ut?e:t+e}function z(r,t,e){let n=r;for(;t-- >ut;)n*=n,n%=e;return n}function Ei(r,t){if(r===ut)throw new Error("invert: expected non-zero number");if(t<=ut)throw new Error("invert: expected positive modulus, got "+t);let e=Q(r,t),n=t,o=ut,s=et,i=et,a=ut;for(;e!==ut;){let u=n/e,f=n%e,l=o-i*u,d=s-a*u;n=e,e=f,o=i,s=a,i=l,a=d}if(n!==et)throw new Error("invert: does not exist");return Q(o,t)}function ho(r,t,e){if(!r.eql(r.sqr(t),e))throw new Error("Cannot find square root")}function _i(r,t){let e=(r.ORDER+et)/Ai,n=r.pow(t,e);return ho(r,n,t),n}function Vf(r,t){let e=(r.ORDER-Ii)/Ci,n=r.mul(t,ae),o=r.pow(n,e),s=r.mul(t,o),i=r.mul(r.mul(s,ae),o),a=r.mul(s,r.sub(i,r.ONE));return ho(r,a,t),a}function Hf(r){let t=Be(r),e=Di(r),n=e(t,t.neg(t.ONE)),o=e(t,n),s=e(t,t.neg(n)),i=(r+Kf)/Bi;return(a,c)=>{let u=a.pow(c,i),f=a.mul(u,n),l=a.mul(u,o),d=a.mul(u,s),x=a.eql(a.sqr(f),c),h=a.eql(a.sqr(l),c);u=a.cmov(u,f,x),f=a.cmov(d,l,h);let v=a.eql(a.sqr(f),c),b=a.cmov(u,f,v);return ho(a,b,c),b}}function Di(r){if(r<Si)throw new Error("sqrt is not defined for small field");let t=r-et,e=0;for(;t%ae===ut;)t/=ae,e++;let n=ae,o=Be(r);for(;vi(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(e===1)return _i;let s=o.pow(n,t),i=(t+et)/ae;return function(c,u){if(c.is0(u))return u;if(vi(c,u)!==1)throw new Error("Cannot find square root");let f=e,l=c.mul(c.ONE,s),d=c.pow(u,t),x=c.pow(u,i);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let h=1,v=c.sqr(d);for(;!c.eql(v,c.ONE);)if(h++,v=c.sqr(v),h===f)throw new Error("Cannot find square root");let b=et<<BigInt(f-h-1),m=c.pow(l,b);f=h,l=c.sqr(m),d=c.mul(d,l),x=c.mul(x,m)}return x}}function qf(r){return r%Ai===Si?_i:r%Ci===Ii?Vf:r%Bi===Ff?Hf(r):Di(r)}var Ti=(r,t)=>(Q(r,t)&et)===et,zf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function po(r){let t={ORDER:"bigint",BYTES:"number",BITS:"number"},e=zf.reduce((n,o)=>(n[o]="function",n),t);return Xt(r,e),r}function Gf(r,t,e){if(e<ut)throw new Error("invalid exponent, negatives unsupported");if(e===ut)return r.ONE;if(e===et)return t;let n=r.ONE,o=t;for(;e>ut;)e&et&&(n=r.mul(n,o)),o=r.sqr(o),e>>=et;return n}function er(r,t,e=!1){let n=new Array(t.length).fill(e?r.ZERO:void 0),o=t.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return t.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function vi(r,t){let e=(r.ORDER-et)/ae,n=r.pow(t,e),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function $f(r,t){t!==void 0&&Dt(t);let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}var lo=class{ORDER;BITS;BYTES;isLE;ZERO=ut;ONE=et;_lengths;_sqrt;_mod;constructor(t,e={}){if(t<=ut)throw new Error("invalid field: expected ORDER > 0, got "+t);let n;this.isLE=!1,e!=null&&typeof e=="object"&&(typeof e.BITS=="number"&&(n=e.BITS),typeof e.sqrt=="function"&&(this.sqrt=e.sqrt),typeof e.isLE=="boolean"&&(this.isLE=e.isLE),e.allowedLengths&&(this._lengths=e.allowedLengths?.slice()),typeof e.modFromBytes=="boolean"&&(this._mod=e.modFromBytes));let{nBitLength:o,nByteLength:s}=$f(t,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=t,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(t){return Q(t,this.ORDER)}isValid(t){if(typeof t!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof t);return ut<=t&&t<this.ORDER}is0(t){return t===ut}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}isOdd(t){return(t&et)===et}neg(t){return Q(-t,this.ORDER)}eql(t,e){return t===e}sqr(t){return Q(t*t,this.ORDER)}add(t,e){return Q(t+e,this.ORDER)}sub(t,e){return Q(t-e,this.ORDER)}mul(t,e){return Q(t*e,this.ORDER)}pow(t,e){return Gf(this,t,e)}div(t,e){return Q(t*Ei(e,this.ORDER),this.ORDER)}sqrN(t){return t*t}addN(t,e){return t+e}subN(t,e){return t-e}mulN(t,e){return t*e}inv(t){return Ei(t,this.ORDER)}sqrt(t){return this._sqrt||(this._sqrt=qf(this.ORDER)),this._sqrt(this,t)}toBytes(t){return this.isLE?fo(t,this.BYTES):Lr(t,this.BYTES)}fromBytes(t,e=!1){U(t);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(!n.includes(t.length)||t.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+t.length);let u=new Uint8Array(o);u.set(t,s?0:u.length-t.length),t=u}if(t.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+t.length);let c=s?ie(t):Ie(t);if(a&&(c=Q(c,i)),!e&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(t){return er(this,t)}cmov(t,e,n){return n?e:t}};function Be(r,t={}){return new lo(r,t)}function Oi(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function mo(r){let t=Oi(r);return t+Math.ceil(t/2)}function yo(r,t,e=!1){U(r);let n=r.length,o=Oi(t),s=mo(t);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=e?ie(r):Ie(r),a=Q(i,t-et)+et;return e?fo(a,o):Lr(a,o)}var _e=BigInt(0),ce=BigInt(1);function rr(r,t){let e=t.negate();return r?e:t}function fe(r,t){let e=er(r.Fp,t.map(n=>n.Z));return t.map((n,o)=>r.fromAffine(n.toAffine(e[o])))}function Ri(r,t){if(!Number.isSafeInteger(r)||r<=0||r>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+r)}function go(r,t){Ri(r,t);let e=Math.ceil(t/r)+1,n=2**(r-1),o=2**r,s=tr(r),i=BigInt(r);return{windows:e,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Li(r,t,e){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=e,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=ce);let u=t*n,f=u+Math.abs(a)-1,l=a===0,d=a<0,x=t%2!==0;return{nextN:c,offset:f,isZero:l,isNeg:d,isNegF:x,offsetF:u}}var bo=new WeakMap,ki=new WeakMap;function xo(r){return ki.get(r)||1}function Pi(r){if(r!==_e)throw new Error("invalid wNAF")}var De=class{BASE;ZERO;Fn;bits;constructor(t,e){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=e}_unsafeLadder(t,e,n=this.ZERO){let o=t;for(;e>_e;)e&ce&&(n=n.add(o)),o=o.double(),e>>=ce;return n}precomputeWindow(t,e){let{windows:n,windowSize:o}=go(e,this.bits),s=[],i=t,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let u=1;u<o;u++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(t,e,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=go(t,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:u,isZero:f,isNeg:l,isNegF:d,offsetF:x}=Li(n,a,i);n=c,f?s=s.add(rr(d,e[x])):o=o.add(rr(l,e[u]))}return Pi(n),{p:o,f:s}}wNAFUnsafe(t,e,n,o=this.ZERO){let s=go(t,this.bits);for(let i=0;i<s.windows&&n!==_e;i++){let{nextN:a,offset:c,isZero:u,isNeg:f}=Li(n,i,s);if(n=a,!u){let l=e[c];o=o.add(f?l.negate():l)}}return Pi(n),o}getPrecomputes(t,e,n){let o=bo.get(e);return o||(o=this.precomputeWindow(e,t),t!==1&&(typeof n=="function"&&(o=n(o)),bo.set(e,o))),o}cached(t,e,n){let o=xo(t);return this.wNAF(o,this.getPrecomputes(o,t,n),e)}unsafe(t,e,n,o){let s=xo(t);return s===1?this._unsafeLadder(t,e,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,n),e,o)}createCache(t,e){Ri(e,this.bits),ki.set(t,e),bo.delete(t)}hasCache(t){return xo(t)!==1}};function Ui(r,t,e,n){let o=t,s=r.ZERO,i=r.ZERO;for(;e>_e||n>_e;)e&ce&&(s=s.add(o)),n&ce&&(i=i.add(o)),o=o.double(),e>>=ce,n>>=ce;return{p1:s,p2:i}}function Ni(r,t,e){if(t){if(t.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return po(t),t}else return Be(r,{isLE:e})}function Nr(r,t,e={},n){if(n===void 0&&(n=r==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let u=t[c];if(!(typeof u=="bigint"&&u>_e))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Ni(t.p,e.Fp,n),s=Ni(t.n,e.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:s}}function Rr(r,t){return function(n){let o=r(n);return{secretKey:o,publicKey:t(o)}}}var Jt=BigInt(0),rt=BigInt(1),wo=BigInt(2),jf=BigInt(8);function Zf(r,t,e,n){let o=r.sqr(e),s=r.sqr(n),i=r.add(r.mul(t.a,o),s),a=r.add(r.ONE,r.mul(t.d,r.mul(o,s)));return r.eql(i,a)}function Mi(r,t={}){let e=Nr("edwards",r,t,t.FpFnLE),{Fp:n,Fn:o}=e,s=e.CURVE,{h:i}=s;Xt(t,{},{uvRatio:"function"});let a=wo<<BigInt(o.BYTES*8)-rt,c=b=>n.create(b),u=t.uvRatio||((b,m)=>{try{return{isValid:!0,value:n.sqrt(n.div(b,m))}}catch{return{isValid:!1,value:Jt}}});if(!Zf(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function f(b,m,I=!1){let w=I?rt:Jt;return Qe("coordinate "+b,m,w,a),m}function l(b){if(!(b instanceof h))throw new Error("EdwardsPoint expected")}let d=Ce((b,m)=>{let{X:I,Y:w,Z:C}=b,P=b.is0();m==null&&(m=P?jf:n.inv(C));let R=c(I*m),M=c(w*m),S=n.mul(C,m);if(P)return{x:Jt,y:rt};if(S!==rt)throw new Error("invZ was invalid");return{x:R,y:M}}),x=Ce(b=>{let{a:m,d:I}=s;if(b.is0())throw new Error("bad point: ZERO");let{X:w,Y:C,Z:P,T:R}=b,M=c(w*w),S=c(C*C),E=c(P*P),N=c(E*E),K=c(M*m),T=c(E*c(K+S)),y=c(N+c(I*c(M*S)));if(T!==y)throw new Error("bad point: equation left != right (1)");let g=c(w*C),p=c(P*R);if(g!==p)throw new Error("bad point: equation left != right (2)");return!0});class h{static BASE=new h(s.Gx,s.Gy,rt,c(s.Gx*s.Gy));static ZERO=new h(Jt,rt,rt,Jt);static Fp=n;static Fn=o;X;Y;Z;T;constructor(m,I,w,C){this.X=f("x",m),this.Y=f("y",I),this.Z=f("z",w,!0),this.T=f("t",C),Object.freeze(this)}static CURVE(){return s}static fromAffine(m){if(m instanceof h)throw new Error("extended point not allowed");let{x:I,y:w}=m||{};return f("x",I),f("y",w),new h(I,w,rt,c(I*w))}static fromBytes(m,I=!1){let w=n.BYTES,{a:C,d:P}=s;m=Pr(U(m,w,"point")),Vt(I,"zip215");let R=Pr(m),M=m[w-1];R[w-1]=M&-129;let S=ie(R),E=I?a:n.ORDER;Qe("point.y",S,Jt,E);let N=c(S*S),K=c(N-rt),T=c(P*N-C),{isValid:y,value:g}=u(K,T);if(!y)throw new Error("bad point: invalid y coordinate");let p=(g&rt)===rt,A=(M&128)!==0;if(!I&&g===Jt&&A)throw new Error("bad point: x=0 and x_0=1");return A!==p&&(g=c(-g)),h.fromAffine({x:g,y:S})}static fromHex(m,I=!1){return h.fromBytes(Kt(m),I)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,I=!0){return v.createCache(this,m),I||this.multiply(wo),this}assertValidity(){x(this)}equals(m){l(m);let{X:I,Y:w,Z:C}=this,{X:P,Y:R,Z:M}=m,S=c(I*M),E=c(P*C),N=c(w*M),K=c(R*C);return S===E&&N===K}is0(){return this.equals(h.ZERO)}negate(){return new h(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:m}=s,{X:I,Y:w,Z:C}=this,P=c(I*I),R=c(w*w),M=c(wo*c(C*C)),S=c(m*P),E=I+w,N=c(c(E*E)-P-R),K=S+R,T=K-M,y=S-R,g=c(N*T),p=c(K*y),A=c(N*y),B=c(T*K);return new h(g,p,B,A)}add(m){l(m);let{a:I,d:w}=s,{X:C,Y:P,Z:R,T:M}=this,{X:S,Y:E,Z:N,T:K}=m,T=c(C*S),y=c(P*E),g=c(M*w*K),p=c(R*N),A=c((C+P)*(S+E)-T-y),B=p-g,D=p+g,O=c(y-I*T),_=c(A*B),L=c(D*O),k=c(A*O),$=c(B*D);return new h(_,L,$,k)}subtract(m){return this.add(m.negate())}multiply(m){if(!o.isValidNot0(m))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:I,f:w}=v.cached(this,m,C=>fe(h,C));return fe(h,[I,w])[0]}multiplyUnsafe(m,I=h.ZERO){if(!o.isValid(m))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return m===Jt?h.ZERO:this.is0()||m===rt?this:v.unsafe(this,m,w=>fe(h,w),I)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return v.unsafe(this,s.n).is0()}toAffine(m){return d(this,m)}clearCofactor(){return i===rt?this:this.multiplyUnsafe(i)}toBytes(){let{x:m,y:I}=this.toAffine(),w=n.toBytes(I);return w[w.length-1]|=m&rt?128:0,w}toHex(){return Mt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let v=new De(h,o.BITS);return h.BASE.precompute(8),h}function Ki(r,t,e={}){if(typeof t!="function")throw new Error('"hash" function param is required');Xt(e,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=e,{BASE:o,Fp:s,Fn:i}=r,a=e.randomBytes||Ae,c=e.adjustScalarBytes||(S=>S),u=e.domain||((S,E,N)=>{if(Vt(N,"phflag"),E.length||N)throw new Error("Contexts/pre-hash are not supported");return S});function f(S){return i.create(ie(S))}function l(S){let E=w.secretKey;U(S,w.secretKey,"secretKey");let N=U(t(S),2*E,"hashedSecretKey"),K=c(N.slice(0,E)),T=N.slice(E,2*E),y=f(K);return{head:K,prefix:T,scalar:y}}function d(S){let{head:E,prefix:N,scalar:K}=l(S),T=o.multiply(K),y=T.toBytes();return{head:E,prefix:N,scalar:K,point:T,pointBytes:y}}function x(S){return d(S).pointBytes}function h(S=Uint8Array.of(),...E){let N=lt(...E);return f(t(u(N,U(S,void 0,"context"),!!n)))}function v(S,E,N={}){S=U(S,void 0,"message"),n&&(S=n(S));let{prefix:K,scalar:T,pointBytes:y}=d(E),g=h(N.context,K,S),p=o.multiply(g).toBytes(),A=h(N.context,p,y,S),B=i.create(g+A*T);if(!i.isValid(B))throw new Error("sign failed: invalid s");let D=lt(p,i.toBytes(B));return U(D,w.signature,"result")}let b={zip215:!0};function m(S,E,N,K=b){let{context:T,zip215:y}=K,g=w.signature;S=U(S,g,"signature"),E=U(E,void 0,"message"),N=U(N,w.publicKey,"publicKey"),y!==void 0&&Vt(y,"zip215"),n&&(E=n(E));let p=g/2,A=S.subarray(0,p),B=ie(S.subarray(p,g)),D,O,_;try{D=r.fromBytes(N,y),O=r.fromBytes(A,y),_=o.multiplyUnsafe(B)}catch{return!1}if(!y&&D.isSmallOrder())return!1;let L=h(T,O.toBytes(),D.toBytes(),E);return O.add(D.multiplyUnsafe(L)).subtract(_).clearCofactor().is0()}let I=s.BYTES,w={secretKey:I,publicKey:I,signature:2*I,seed:I};function C(S=a(w.seed)){return U(S,w.seed,"seed")}function P(S){return ne(S)&&S.length===i.BYTES}function R(S,E){try{return!!r.fromBytes(S,E)}catch{return!1}}let M={getExtendedPublicKey:d,randomSecretKey:C,isValidSecretKey:P,isValidPublicKey:R,toMontgomery(S){let{y:E}=r.fromBytes(S),N=w.publicKey,K=N===32;if(!K&&N!==57)throw new Error("only defined for 25519 and 448");let T=K?s.div(rt+E,rt-E):s.div(E-rt,E+rt);return s.toBytes(T)},toMontgomerySecret(S){let E=w.secretKey;U(S,E);let N=t(S.subarray(0,E));return c(N).subarray(0,E)}};return Object.freeze({keygen:Rr(C,x),getPublicKey:x,sign:v,verify:m,utils:M,Point:r,lengths:w})}var Yf=BigInt(1),Fi=BigInt(2);var Wf=BigInt(5),Xf=BigInt(8),Eo=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Jf={p:Eo,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Xf,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Qf(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=Eo,a=r*r%s*r%s,c=z(a,Fi,s)*a%s,u=z(c,Yf,s)*r%s,f=z(u,Wf,s)*u%s,l=z(f,t,s)*f%s,d=z(l,e,s)*l%s,x=z(d,n,s)*d%s,h=z(x,o,s)*x%s,v=z(h,o,s)*x%s,b=z(v,t,s)*f%s;return{pow_p_5_8:z(b,Fi,s)*r%s,b2:a}}function tu(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var Vi=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function eu(r,t){let e=Eo,n=Q(t*t*t,e),o=Q(n*n*t,e),s=Qf(r*o).pow_p_5_8,i=Q(r*n*s,e),a=Q(t*i*i,e),c=i,u=Q(i*Vi,e),f=a===r,l=a===Q(-r,e),d=a===Q(-r*Vi,e);return f&&(i=c),(l||d)&&(i=u),Ti(i,e)&&(i=Q(-i,e)),{isValid:f||l,value:i}}var ru=Mi(Jf,{uvRatio:eu});function nu(r){return Ki(ru,gi,Object.assign({adjustScalarBytes:tu},r))}var Hi=nu({});var nr=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},kr=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var qi={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new kr("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 t}};var Ur=qi;var Mr=32;var vo,ou=(async()=>{try{return await Ur.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function su(r,t,e){if(r.buffer instanceof ArrayBuffer){let n=await Ur.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Ur.get().subtle.verify({name:"Ed25519"},n,t,e instanceof Uint8Array?e:e.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function iu(r,t,e){return Hi.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}async function zi(r,t,e){return vo==null&&(vo=await ou),vo?su(r,t,e):iu(r,t,e)}function Kr(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Fr=class{type="Ed25519";raw;constructor(t){this.raw=So(t,Mr)}toMultihash(){return vt.digest(ve(this))}toCID(){return tt.createV1(114,this.toMultihash())}toString(){return W.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:mt(this.raw,t.raw)}verify(t,e,n){n?.signal?.throwIfAborted();let o=zi(this.raw,e,t);return Kr(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function $i(r){return r=So(r,Mr),new Fr(r)}function So(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new jt(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}var cu=Math.pow(2,7),fu=Math.pow(2,14),uu=Math.pow(2,21),Ao=Math.pow(2,28),Io=Math.pow(2,35),Co=Math.pow(2,42),Bo=Math.pow(2,49),G=128,ct=127;function Ot(r){if(r<cu)return 1;if(r<fu)return 2;if(r<uu)return 3;if(r<Ao)return 4;if(r<Io)return 5;if(r<Co)return 6;if(r<Bo)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function or(r,t,e=0){switch(Ot(r)){case 8:t[e++]=r&255|G,r/=128;case 7:t[e++]=r&255|G,r/=128;case 6:t[e++]=r&255|G,r/=128;case 5:t[e++]=r&255|G,r/=128;case 4:t[e++]=r&255|G,r>>>=7;case 3:t[e++]=r&255|G,r>>>=7;case 2:t[e++]=r&255|G,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function _o(r,t){let e=r[t],n=0;if(n+=e&ct,e<G||(e=r[t+1],n+=(e&ct)<<7,e<G)||(e=r[t+2],n+=(e&ct)<<14,e<G)||(e=r[t+3],n+=(e&ct)<<21,e<G)||(e=r[t+4],n+=(e&ct)*Ao,e<G)||(e=r[t+5],n+=(e&ct)*Io,e<G)||(e=r[t+6],n+=(e&ct)*Co,e<G)||(e=r[t+7],n+=(e&ct)*Bo,e<G))return n;throw new RangeError("Could not decode varint")}function lu(r,t){let e=r.get(t),n=0;if(n+=e&ct,e<G||(e=r.get(t+1),n+=(e&ct)<<7,e<G)||(e=r.get(t+2),n+=(e&ct)<<14,e<G)||(e=r.get(t+3),n+=(e&ct)<<21,e<G)||(e=r.get(t+4),n+=(e&ct)*Ao,e<G)||(e=r.get(t+5),n+=(e&ct)*Io,e<G)||(e=r.get(t+6),n+=(e&ct)*Co,e<G)||(e=r.get(t+7),n+=(e&ct)*Bo,e<G))return n;throw new RangeError("Could not decode varint")}function Do(r,t=0){return r instanceof Uint8Array?_o(r,t):lu(r,t)}var To=new Float32Array([-0]),Qt=new Uint8Array(To.buffer);function ji(r,t,e){To[0]=r,t[e]=Qt[0],t[e+1]=Qt[1],t[e+2]=Qt[2],t[e+3]=Qt[3]}function Zi(r,t){return Qt[0]=r[t],Qt[1]=r[t+1],Qt[2]=r[t+2],Qt[3]=r[t+3],To[0]}var Oo=new Float64Array([-0]),ft=new Uint8Array(Oo.buffer);function Yi(r,t,e){Oo[0]=r,t[e]=ft[0],t[e+1]=ft[1],t[e+2]=ft[2],t[e+3]=ft[3],t[e+4]=ft[4],t[e+5]=ft[5],t[e+6]=ft[6],t[e+7]=ft[7]}function Wi(r,t){return ft[0]=r[t],ft[1]=r[t+1],ft[2]=r[t+2],ft[3]=r[t+3],ft[4]=r[t+4],ft[5]=r[t+5],ft[6]=r[t+6],ft[7]=r[t+7],Oo[0]}var du=BigInt(Number.MAX_SAFE_INTEGER),pu=BigInt(Number.MIN_SAFE_INTEGER),gt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return ue;if(t<du&&t>pu)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>Xi&&(o=0n,++n>Xi&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return ue;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):ue}},ue=new gt(0,0);ue.toBigInt=function(){return 0n};ue.zzEncode=ue.zzDecode=function(){return this};ue.length=function(){return 1};var Xi=4294967296n;function Ji(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Qi(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Lo(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function At(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function Vr(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Po=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,At(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw At(this,4);return Vr(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw At(this,4);return Vr(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw At(this,4);let t=Zi(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw At(this,4);let t=Wi(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw At(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Qi(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw At(this,t);this.pos+=t}else do if(this.pos>=this.len)throw At(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new gt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw At(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw At(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw At(this,8);let t=Vr(this.buf,this.pos+=4),e=Vr(this.buf,this.pos+=4);return new gt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=_o(this.buf,this.pos);return this.pos+=Ot(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function No(r){return new Po(r instanceof Uint8Array?r:r.subarray())}function Hr(r,t,e){let n=No(r);return t.decode(n,void 0,e)}function Ro(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return pt(i);o+i>t&&(n=pt(t),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var le=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function ko(){}var Mo=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},mu=Ro();function yu(r){return globalThis.Buffer!=null?pt(r):mu(r)}var ir=class{len;head;tail;states;constructor(){this.len=0,this.head=new le(ko,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new le(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Ko((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(qr,10,gt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=gt.fromBigInt(t);return this._push(qr,e.length(),e)}uint64Number(t){return this._push(or,Ot(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=gt.fromBigInt(t).zzEncode();return this._push(qr,e.length(),e)}sint64Number(t){let e=gt.fromNumber(t).zzEncode();return this._push(qr,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Uo,1,t?1:0)}fixed32(t){return this._push(sr,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=gt.fromBigInt(t);return this._push(sr,4,e.lo)._push(sr,4,e.hi)}fixed64Number(t){let e=gt.fromNumber(t);return this._push(sr,4,e.lo)._push(sr,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(ji,4,t)}double(t){return this._push(Yi,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Uo,1,0):this.uint32(e)._push(bu,e,t)}string(t){let e=Ji(t);return e!==0?this.uint32(e)._push(Lo,e,t):this._push(Uo,1,0)}fork(){return this.states=new Mo(this),this.head=this.tail=new le(ko,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new le(ko,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=yu(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Uo(r,t,e){t[e]=r&255}function gu(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Ko=class extends le{next;constructor(t,e){super(gu,t,e),this.next=void 0}};function qr(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function sr(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function bu(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(ir.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(xu,t,r),this},ir.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(wu,t,r),this});function xu(r,t,e){t.set(r,e)}function wu(r,t,e){r.length<40?Lo(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(X(r),e)}function Fo(){return new ir}function zr(r,t){let e=Fo();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Te;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Te||(Te={}));function Gr(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function Vo(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(s,i){let a=t(s);i.int32(a)},n=function(s){let i=s.int32();return t(i)};return Gr("enum",Te.VARINT,e,n)}function $r(r,t){return Gr("message",Te.LENGTH_DELIMITED,r,t)}var bt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(bt||(bt={}));var Ho;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(Ho||(Ho={}));(function(r){r.codec=()=>Vo(Ho)})(bt||(bt={}));var ar;(function(r){let t;r.codec=()=>(t==null&&(t=$r((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),bt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=bt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>zr(e,r.codec()),r.decode=(e,n)=>Hr(e,r.codec(),n)})(ar||(ar={}));var qo;(function(r){let t;r.codec=()=>(t==null&&(t=$r((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),bt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=bt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>zr(e,r.codec()),r.decode=(e,n)=>Hr(e,r.codec(),n)})(qo||(qo={}));var jr=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(t,e){if(_r(t),U(e,void 0,"key"),this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,o=new Uint8Array(n);o.set(e.length>n?t.create().update(e).digest():e);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=t.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Ut(o)}update(t){return Se(this),this.iHash.update(t),this}digestInto(t){Se(this),U(t,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||=Object.create(Object.getPrototypeOf(this),{});let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},zo=(r,t,e)=>new jr(r,t).update(e).digest();zo.create=(r,t)=>new jr(r,t);var ea=(r,t)=>(r+(r>=0?t:-t)/ra)/t;function vu(r,t,e){let[[n,o],[s,i]]=t,a=ea(i*r,e),c=ea(-o*r,e),u=r-a*n-c*s,f=-a*o-c*i,l=u<Ht,d=f<Ht;l&&(u=-u),d&&(f=-f);let x=tr(Math.ceil(uo(e)/2))+Oe;if(u<Ht||u>=x||f<Ht||f>=x)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:l,k1:u,k2neg:d,k2:f}}function $o(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Go(r,t){let e={};for(let n of Object.keys(t))e[n]=r[n]===void 0?t[n]:r[n];return Vt(e.lowS,"lowS"),Vt(e.prehash,"prehash"),e.format!==void 0&&$o(e.format),e}var jo=class extends Error{constructor(t=""){super(t)}},te={Err:jo,_tlv:{encode:(r,t)=>{let{Err:e}=te;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=Je(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?Je(o.length/2|128):"";return Je(r)+s+o+t},decode(r,t){let{Err:e}=te,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let u=t.subarray(n,n+c);if(u.length!==c)throw new e("tlv.decode: length bytes not complete");if(u[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let f of u)i=i<<8|f;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=te;if(r<Ht)throw new t("integer: negative integers are not allowed");let e=Je(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected DER parsing assertion: unpadded hex");return e},decode(r){let{Err:t}=te;if(r[0]&128)throw new t("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("invalid signature integer: unnecessary leading zero");return Ie(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=te,o=U(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:u,l:f}=n.decode(2,c);if(f.length)throw new t("invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(u)}},hexFromSig(r){let{_tlv:t,_int:e}=te,n=t.encode(2,e.encode(r.r)),o=t.encode(2,e.encode(r.s)),s=n+o;return t.encode(48,s)}},Ht=BigInt(0),Oe=BigInt(1),ra=BigInt(2),Zr=BigInt(3),Su=BigInt(4);function na(r,t={}){let e=Nr("weierstrass",r,t),{Fp:n,Fn:o}=e,s=e.CURVE,{h:i,n:a}=s;Xt(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=t;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=sa(n,o);function f(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(T,y,g){let{x:p,y:A}=y.toAffine(),B=n.toBytes(p);if(Vt(g,"isCompressed"),g){f();let D=!n.isOdd(A);return lt(oa(D),B)}else return lt(Uint8Array.of(4),B,n.toBytes(A))}function d(T){U(T,void 0,"Point");let{publicKey:y,publicKeyUncompressed:g}=u,p=T.length,A=T[0],B=T.subarray(1);if(p===y&&(A===2||A===3)){let D=n.fromBytes(B);if(!n.isValid(D))throw new Error("bad point: is not on curve, wrong x");let O=v(D),_;try{_=n.sqrt(O)}catch($){let q=$ instanceof Error?": "+$.message:"";throw new Error("bad point: is not on curve, sqrt error"+q)}f();let L=n.isOdd(_);return(A&1)===1!==L&&(_=n.neg(_)),{x:D,y:_}}else if(p===g&&A===4){let D=n.BYTES,O=n.fromBytes(B.subarray(0,D)),_=n.fromBytes(B.subarray(D,D*2));if(!b(O,_))throw new Error("bad point: is not on curve");return{x:O,y:_}}else throw new Error(`bad point: got length ${p}, expected compressed=${y} or uncompressed=${g}`)}let x=t.toBytes||l,h=t.fromBytes||d;function v(T){let y=n.sqr(T),g=n.mul(y,T);return n.add(n.add(g,n.mul(T,s.a)),s.b)}function b(T,y){let g=n.sqr(y),p=v(T);return n.eql(g,p)}if(!b(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let m=n.mul(n.pow(s.a,Zr),Su),I=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(m,I)))throw new Error("bad curve params: a or b");function w(T,y,g=!1){if(!n.isValid(y)||g&&n.is0(y))throw new Error(`bad point coordinate ${T}`);return y}function C(T){if(!(T instanceof E))throw new Error("Weierstrass Point expected")}function P(T){if(!c||!c.basises)throw new Error("no endo");return vu(T,c.basises,o.ORDER)}let R=Ce((T,y)=>{let{X:g,Y:p,Z:A}=T;if(n.eql(A,n.ONE))return{x:g,y:p};let B=T.is0();y==null&&(y=B?n.ONE:n.inv(A));let D=n.mul(g,y),O=n.mul(p,y),_=n.mul(A,y);if(B)return{x:n.ZERO,y:n.ZERO};if(!n.eql(_,n.ONE))throw new Error("invZ was invalid");return{x:D,y:O}}),M=Ce(T=>{if(T.is0()){if(t.allowInfinityPoint&&!n.is0(T.Y))return;throw new Error("bad point: ZERO")}let{x:y,y:g}=T.toAffine();if(!n.isValid(y)||!n.isValid(g))throw new Error("bad point: x or y not field elements");if(!b(y,g))throw new Error("bad point: equation left != right");if(!T.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function S(T,y,g,p,A){return g=new E(n.mul(g.X,T),g.Y,g.Z),y=rr(p,y),g=rr(A,g),y.add(g)}class E{static BASE=new E(s.Gx,s.Gy,n.ONE);static ZERO=new E(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(y,g,p){this.X=w("x",y),this.Y=w("y",g,!0),this.Z=w("z",p),Object.freeze(this)}static CURVE(){return s}static fromAffine(y){let{x:g,y:p}=y||{};if(!y||!n.isValid(g)||!n.isValid(p))throw new Error("invalid affine point");if(y instanceof E)throw new Error("projective point not allowed");return n.is0(g)&&n.is0(p)?E.ZERO:new E(g,p,n.ONE)}static fromBytes(y){let g=E.fromAffine(h(U(y,void 0,"point")));return g.assertValidity(),g}static fromHex(y){return E.fromBytes(Kt(y))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,g=!0){return K.createCache(this,y),g||this.multiply(Zr),this}assertValidity(){M(this)}hasEvenY(){let{y}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(y)}equals(y){C(y);let{X:g,Y:p,Z:A}=this,{X:B,Y:D,Z:O}=y,_=n.eql(n.mul(g,O),n.mul(B,A)),L=n.eql(n.mul(p,O),n.mul(D,A));return _&&L}negate(){return new E(this.X,n.neg(this.Y),this.Z)}double(){let{a:y,b:g}=s,p=n.mul(g,Zr),{X:A,Y:B,Z:D}=this,O=n.ZERO,_=n.ZERO,L=n.ZERO,k=n.mul(A,A),$=n.mul(B,B),q=n.mul(D,D),F=n.mul(A,B);return F=n.add(F,F),L=n.mul(A,D),L=n.add(L,L),O=n.mul(y,L),_=n.mul(p,q),_=n.add(O,_),O=n.sub($,_),_=n.add($,_),_=n.mul(O,_),O=n.mul(F,O),L=n.mul(p,L),q=n.mul(y,q),F=n.sub(k,q),F=n.mul(y,F),F=n.add(F,L),L=n.add(k,k),k=n.add(L,k),k=n.add(k,q),k=n.mul(k,F),_=n.add(_,k),q=n.mul(B,D),q=n.add(q,q),k=n.mul(q,F),O=n.sub(O,k),L=n.mul(q,$),L=n.add(L,L),L=n.add(L,L),new E(O,_,L)}add(y){C(y);let{X:g,Y:p,Z:A}=this,{X:B,Y:D,Z:O}=y,_=n.ZERO,L=n.ZERO,k=n.ZERO,$=s.a,q=n.mul(s.b,Zr),F=n.mul(g,B),j=n.mul(p,D),ot=n.mul(A,O),Ct=n.add(g,p),Z=n.add(B,D);Ct=n.mul(Ct,Z),Z=n.add(F,j),Ct=n.sub(Ct,Z),Z=n.add(g,A);let at=n.add(B,O);return Z=n.mul(Z,at),at=n.add(F,ot),Z=n.sub(Z,at),at=n.add(p,A),_=n.add(D,O),at=n.mul(at,_),_=n.add(j,ot),at=n.sub(at,_),k=n.mul($,Z),_=n.mul(q,ot),k=n.add(_,k),_=n.sub(j,k),k=n.add(j,k),L=n.mul(_,k),j=n.add(F,F),j=n.add(j,F),ot=n.mul($,ot),Z=n.mul(q,Z),j=n.add(j,ot),ot=n.sub(F,ot),ot=n.mul($,ot),Z=n.add(Z,ot),F=n.mul(j,Z),L=n.add(L,F),F=n.mul(at,Z),_=n.mul(Ct,_),_=n.sub(_,F),F=n.mul(Ct,j),k=n.mul(at,k),k=n.add(k,F),new E(_,L,k)}subtract(y){return this.add(y.negate())}is0(){return this.equals(E.ZERO)}multiply(y){let{endo:g}=t;if(!o.isValidNot0(y))throw new Error("invalid scalar: out of range");let p,A,B=D=>K.cached(this,D,O=>fe(E,O));if(g){let{k1neg:D,k1:O,k2neg:_,k2:L}=P(y),{p:k,f:$}=B(O),{p:q,f:F}=B(L);A=$.add(F),p=S(g.beta,k,q,D,_)}else{let{p:D,f:O}=B(y);p=D,A=O}return fe(E,[p,A])[0]}multiplyUnsafe(y){let{endo:g}=t,p=this;if(!o.isValid(y))throw new Error("invalid scalar: out of range");if(y===Ht||p.is0())return E.ZERO;if(y===Oe)return p;if(K.hasCache(this))return this.multiply(y);if(g){let{k1neg:A,k1:B,k2neg:D,k2:O}=P(y),{p1:_,p2:L}=Ui(E,p,B,O);return S(g.beta,_,L,A,D)}else return K.unsafe(p,y)}toAffine(y){return R(this,y)}isTorsionFree(){let{isTorsionFree:y}=t;return i===Oe?!0:y?y(E,this):K.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:y}=t;return i===Oe?this:y?y(E,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(y=!0){return Vt(y,"isCompressed"),this.assertValidity(),x(E,this,y)}toHex(y=!0){return Mt(this.toBytes(y))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let N=o.BITS,K=new De(E,t.endo?Math.ceil(N/2):N);return E.BASE.precompute(8),E}function oa(r){return Uint8Array.of(r?2:3)}function sa(r,t){return{secretKey:t.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Au(r,t={}){let{Fn:e}=r,n=t.randomBytes||Ae,o=Object.assign(sa(r.Fp,e),{seed:mo(e.ORDER)});function s(x){try{let h=e.fromBytes(x);return e.isValidNot0(h)}catch{return!1}}function i(x,h){let{publicKey:v,publicKeyUncompressed:b}=o;try{let m=x.length;return h===!0&&m!==v||h===!1&&m!==b?!1:!!r.fromBytes(x)}catch{return!1}}function a(x=n(o.seed)){return yo(U(x,o.seed,"seed"),e.ORDER)}function c(x,h=!0){return r.BASE.multiply(e.fromBytes(x)).toBytes(h)}function u(x){let{secretKey:h,publicKey:v,publicKeyUncompressed:b}=o;if(!ne(x)||"_lengths"in e&&e._lengths||h===v)return;let m=U(x,void 0,"key").length;return m===v||m===b}function f(x,h,v=!0){if(u(x)===!0)throw new Error("first arg must be private key");if(u(h)===!1)throw new Error("second arg must be public key");let b=e.fromBytes(x);return r.fromBytes(h).multiply(b).toBytes(v)}let l={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},d=Rr(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:d,Point:r,utils:l,lengths:o})}function ia(r,t,e={}){_r(t),Xt(e,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),e=Object.assign({},e);let n=e.randomBytes||Ae,o=e.hmac||((g,p)=>zo(t,g,p)),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:u,getPublicKey:f,getSharedSecret:l,utils:d,lengths:x}=Au(r,e),h={prehash:!0,lowS:typeof e.lowS=="boolean"?e.lowS:!0,format:"compact",extraEntropy:!1},v=a*ra<s.ORDER;function b(g){let p=a>>Oe;return g>p}function m(g,p){if(!i.isValidNot0(p))throw new Error(`invalid signature ${g}: out of range 1..Point.Fn.ORDER`);return p}function I(){if(v)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function w(g,p){$o(p);let A=x.signature,B=p==="compact"?A:p==="recovered"?A+1:void 0;return U(g,B)}class C{r;s;recovery;constructor(p,A,B){if(this.r=m("r",p),this.s=m("s",A),B!=null){if(I(),![0,1,2,3].includes(B))throw new Error("invalid recovery id");this.recovery=B}Object.freeze(this)}static fromBytes(p,A=h.format){w(p,A);let B;if(A==="der"){let{r:L,s:k}=te.toSig(U(p));return new C(L,k)}A==="recovered"&&(B=p[0],A="compact",p=p.subarray(1));let D=x.signature/2,O=p.subarray(0,D),_=p.subarray(D,D*2);return new C(i.fromBytes(O),i.fromBytes(_),B)}static fromHex(p,A){return this.fromBytes(Kt(p),A)}assertRecovery(){let{recovery:p}=this;if(p==null)throw new Error("invalid recovery id: must be present");return p}addRecoveryBit(p){return new C(this.r,this.s,p)}recoverPublicKey(p){let{r:A,s:B}=this,D=this.assertRecovery(),O=D===2||D===3?A+a:A;if(!s.isValid(O))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let _=s.toBytes(O),L=r.fromBytes(lt(oa((D&1)===0),_)),k=i.inv(O),$=R(U(p,void 0,"msgHash")),q=i.create(-$*k),F=i.create(B*k),j=r.BASE.multiplyUnsafe(q).add(L.multiplyUnsafe(F));if(j.is0())throw new Error("invalid recovery: point at infinify");return j.assertValidity(),j}hasHighS(){return b(this.s)}toBytes(p=h.format){if($o(p),p==="der")return Kt(te.hexFromSig(this));let{r:A,s:B}=this,D=i.toBytes(A),O=i.toBytes(B);return p==="recovered"?(I(),lt(Uint8Array.of(this.assertRecovery()),D,O)):lt(D,O)}toHex(p){return Mt(this.toBytes(p))}}let P=e.bits2int||function(p){if(p.length>8192)throw new Error("input is too large");let A=Ie(p),B=p.length*8-c;return B>0?A>>BigInt(B):A},R=e.bits2int_modN||function(p){return i.create(P(p))},M=tr(c);function S(g){return Qe("num < 2^"+c,g,Ht,M),i.toBytes(g)}function E(g,p){return U(g,void 0,"message"),p?U(t(g),void 0,"prehashed message"):g}function N(g,p,A){let{lowS:B,prehash:D,extraEntropy:O}=Go(A,h);g=E(g,D);let _=R(g),L=i.fromBytes(p);if(!i.isValidNot0(L))throw new Error("invalid private key");let k=[S(L),S(_)];if(O!=null&&O!==!1){let j=O===!0?n(x.secretKey):O;k.push(U(j,void 0,"extraEntropy"))}let $=lt(...k),q=_;function F(j){let ot=P(j);if(!i.isValidNot0(ot))return;let Ct=i.inv(ot),Z=r.BASE.multiply(ot).toAffine(),at=i.create(Z.x);if(at===Ht)return;let yr=i.create(Ct*i.create(q+at*L));if(yr===Ht)return;let Es=(Z.x===at?0:2)|Number(Z.y&Oe),vs=yr;return B&&b(yr)&&(vs=i.neg(yr),Es^=1),new C(at,vs,v?void 0:Es)}return{seed:$,k2sig:F}}function K(g,p,A={}){let{seed:B,k2sig:D}=N(g,p,A);return wi(t.outputLen,i.BYTES,o)(B,D).toBytes(A.format)}function T(g,p,A,B={}){let{lowS:D,prehash:O,format:_}=Go(B,h);if(A=U(A,void 0,"publicKey"),p=E(p,O),!ne(g)){let L=g instanceof C?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+L)}w(g,_);try{let L=C.fromBytes(g,_),k=r.fromBytes(A);if(D&&L.hasHighS())return!1;let{r:$,s:q}=L,F=R(p),j=i.inv(q),ot=i.create(F*j),Ct=i.create($*j),Z=r.BASE.multiplyUnsafe(ot).add(k.multiplyUnsafe(Ct));return Z.is0()?!1:i.create(Z.x)===$}catch{return!1}}function y(g,p,A={}){let{prehash:B}=Go(A,h);return p=E(p,B),C.fromBytes(g,"recovered").recoverPublicKey(p).toBytes()}return Object.freeze({keygen:u,getPublicKey:f,getSharedSecret:l,utils:d,lengths:x,Point:r,sign:K,verify:T,recoverPublicKey:y,Signature:C,hash:t})}var Yo={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Iu={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var aa=BigInt(2);function Cu(r){let t=Yo.p,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),u=r*r*r%t,f=u*u*r%t,l=z(f,e,t)*f%t,d=z(l,e,t)*f%t,x=z(d,aa,t)*u%t,h=z(x,o,t)*x%t,v=z(h,s,t)*h%t,b=z(v,a,t)*v%t,m=z(b,c,t)*b%t,I=z(m,a,t)*v%t,w=z(I,e,t)*f%t,C=z(w,i,t)*h%t,P=z(C,n,t)*u%t,R=z(P,aa,t);if(!Zo.eql(Zo.sqr(R),r))throw new Error("Cannot find square root");return R}var Zo=Be(Yo.p,{sqrt:Cu}),Bu=na(Yo,{Fp:Zo,endo:Iu}),Le=ia(Bu,yi);function ca(r,t,e,n){let o=zt.digest(e instanceof Uint8Array?e:e.subarray());if(Kr(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Le.verify(t,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new nr(String(s))});try{return n?.signal?.throwIfAborted(),Le.verify(t,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new nr(String(s))}}var Yr=class{type="secp256k1";raw;_key;constructor(t){this._key=ua(t),this.raw=fa(this._key)}toMultihash(){return vt.digest(ve(this))}toCID(){return tt.createV1(114,this.toMultihash())}toString(){return W.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:mt(this.raw,t.raw)}verify(t,e,n){return ca(this._key,e,t,n)}};function la(r){return new Yr(r)}function fa(r){return Le.Point.fromBytes(r).toBytes()}function ua(r){try{return Le.Point.fromBytes(r),r}catch(t){throw new Ar(String(t))}}function ha(r){let{Type:t,Data:e}=ar.decode(r.digest),n=e??new Uint8Array;switch(t){case bt.Ed25519:return $i(n);case bt.secp256k1:return la(n);case bt.ECDSA:return Qs(n);default:throw new Ir}}function ve(r){return ar.encode({Type:bt[r.type],Data:r.raw})}var Wo=Symbol.for("@libp2p/peer-id");var Wr=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}};var Xr=class extends Error{static name="InvalidCIDError";constructor(t="Invalid CID"){super(t),this.name="InvalidCIDError"}},Jr=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var da=Symbol.for("nodejs.util.inspect.custom"),_u=114,cr=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Wo]=!0;toString(){return this.string==null&&(this.string=W.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return tt.createV1(_u,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return mt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return mt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[da](){return`PeerId(${this.toString()})`}},Qr=class extends cr{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},tn=class extends cr{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},en=class extends cr{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Du=2336,fr=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=vt.digest(X(this.url))}[da](){return`PeerId(${this.url})`}[Wo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return tt.createV1(Du,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=V(t)),t.toString()===this.toString())}};var Tu=114,pa=2336;function H(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=He(W.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Ou(tt.parse(r));if(t==null)throw new Wr('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=He(t.decode(r))}return ma(e)}function ma(r){if(Pu(r))return new Qr({multihash:r});if(Lu(r))try{let t=ha(r);if(t.type==="Ed25519")return new tn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new en({multihash:r,publicKey:t})}catch{let e=V(r.digest);return new fr(new URL(e))}throw new Jr("Supplied PeerID Multihash is invalid")}function Ou(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Tu&&r.code!==pa)throw new Xr("Supplied PeerID CID is invalid");if(r.code===pa){let t=V(r.multihash.digest);return new fr(new URL(t))}return ma(r.multihash)}function Lu(r){return r.code===vt.code}function Pu(r){return r.code===zt.code}var Ea=cc(wa(),1),$u="optimystic:fret";function ee(r){return(0,Ea.default)(`${$u}:${r}`)}var Xo=ee("rpc:neighbors");function va(r,t,e,n={PROTOCOL_NEIGHBORS:Hn,PROTOCOL_NEIGHBORS_ANNOUNCE:qn}){r.handle(n.PROTOCOL_NEIGHBORS,async({stream:o})=>{try{let s=await t();await o.sink((async function*(){yield await Et(s)})());try{o.close?.()}catch{}}catch(s){console.error("neighbors handler error:",s)}}),e&&r.handle(n.PROTOCOL_NEIGHBORS_ANNOUNCE,async({stream:o})=>{try{let s=await Aa(o),i=await _t(s);e(i.from,i),await o.sink((async function*(){yield await Et({ok:!0})})());try{o.close?.()}catch{}}catch(s){console.error("neighbors announce handler error:",s)}})}async function Sa(r,t,e=Hn){let n=H(t),o=r.getConnections?.(n)??[];if(!Array.isArray(o)||o.length===0||typeof o[0]?.newStream!="function")return{v:1,from:t,timestamp:Date.now(),successors:[],predecessors:[],sig:""};let s;try{s=await o[0].newStream([e]);let i=await Aa(s);return await _t(i)}catch(i){return Xo("fetchNeighbors decode failed for %s - %o",t,i),{v:1,from:t,timestamp:Date.now(),successors:[],predecessors:[],sig:""}}finally{if(s)try{await s.close()}catch{}}}async function Jo(r,t,e,n=qn){let o=H(t),s=r.getConnections?.(o)??[];if(!Array.isArray(s)||s.length===0||typeof s[0]?.newStream!="function")return;let i;try{i=await s[0].newStream([n]),await i.sink((async function*(){yield await Et(e)})())}catch(a){Xo("announceNeighbors failed to %s - %o",t,a)}finally{if(i)try{await i.close()}catch{}}}function ju(r){if(r instanceof Uint8Array)return r;let t=r;if(typeof t?.subarray=="function")try{return t.subarray(0)}catch(e){Xo("toBytes subarray failed - %o",e)}if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unsupported chunk type in neighbors read")}async function Aa(r){let t=[];for await(let s of r.source)t.push(ju(s));let e=0;for(let s of t)e+=s.length;let n=new Uint8Array(e),o=0;for(let s of t)n.set(s,o),o+=s.length;return n}function Ia(r,t,e=zn){r.handle(e,async({stream:n})=>{try{let o=await Ba(n),s=await _t(o),i=await t(s);await n.sink((async function*(){yield await Et(i)})())}catch(o){console.error("maybeAct handler error:",o)}})}async function Ca(r,t,e,n=zn){let o=H(t),s=r.getConnections?.(o)??[],i;try{Array.isArray(s)&&s.length>0&&typeof s[0]?.newStream=="function"?i=await s[0].newStream([n]):i=await r.dialProtocol(o,[n]),await i.sink((async function*(){yield await Et(e)})());let a=await Ba(i);return await _t(a)}finally{if(i)try{await i.close()}catch{}}}function Zu(r){if(r instanceof Uint8Array)return r;let t=r;if(typeof t?.subarray=="function")return t.subarray(0);throw new Error("Unsupported chunk type in maybeAct read")}async function Ba(r){let t=[];for await(let s of r.source)t.push(Zu(s));let e=0;for(let s of t)e+=s.length;let n=new Uint8Array(e),o=0;for(let s of t)n.set(s,o),o+=s.length;return n}function _a(r,t,e=Gn){r.handle(e,async({stream:n})=>{try{let o=await Wu(n),s=await _t(o);await t(s),await n.sink((async function*(){yield await Et({ok:!0})})())}catch(o){console.error("leave handler error:",o)}})}async function Da(r,t,e,n=Gn){let o=H(t),s=r.getConnections?.(o)??[],i;try{Array.isArray(s)&&s.length>0&&typeof s[0]?.newStream=="function"?i=await s[0].newStream([n]):i=await r.dialProtocol(o,[n]),await i.sink((async function*(){yield await Et(e)})())}finally{if(i)try{await i.close()}catch{}}}function Yu(r){if(r instanceof Uint8Array)return r;let t=r;if(typeof t?.subarray=="function")return t.subarray(0);throw new Error("Unsupported chunk type in leave read")}async function Wu(r){let t=[];for await(let s of r.source)t.push(Yu(s));let e=0;for(let s of t)e+=s.length;let n=new Uint8Array(e),o=0;for(let s of t)n.set(s,o),o+=s.length;return n}var Qo=ee("rpc:ping");function Ta(r,t=$n,e){r.handle(t,async({stream:n})=>{let o={ok:!0,ts:Date.now()};if(e)try{let s=await e();s.size_estimate!==void 0&&(o.size_estimate=s.size_estimate,o.confidence=s.confidence)}catch(s){Qo("getSizeEstimate failed - %o",s)}await n.sink((async function*(){yield await Et(o)})())})}async function ur(r,t,e=$n){let n=Date.now(),o=H(t),s;try{try{let u=r.getConnections?.(o)??[];if(Array.isArray(u)&&u.length>0&&typeof u[0]?.newStream=="function")s=await u[0].newStream([e]);else{let f=await r.dialProtocol(o,[e]);s=f.stream??f}}catch{let f=await r.dialProtocol(o,[e]);s=f.stream??f}let i=null;for await(let u of s.source)if(u!=null)try{if(u instanceof Uint8Array){i=u;break}if(typeof u.subarray=="function"){let f=u.subarray();if(f instanceof Uint8Array){i=f;break}if(ArrayBuffer.isView(f)){i=new Uint8Array(f.buffer,f.byteOffset,f.byteLength);break}}if(ArrayBuffer.isView(u)){i=new Uint8Array(u.buffer,u.byteOffset,u.byteLength);break}}catch(f){Qo("sendPing chunk handling failed - %o",f)}let a=Math.max(0,Date.now()-n);if(!i||i.length===0)return{ok:!1,rttMs:a};let c=new TextDecoder().decode(i).trim();if(!c||c[0]!=="{"||!c.endsWith("}"))return{ok:!1,rttMs:a};try{let u=await _t(i);return{ok:!!u.ok,rttMs:a,size_estimate:u.size_estimate,confidence:u.confidence}}catch(u){return Qo("sendPing decode failed - %o",u),{ok:!1,rttMs:a}}}finally{if(s)try{await s.close()}catch{}}}function Xu(r){let t=0n;for(let e=0;e<r.length;e++)t=t<<8n|BigInt(r[e]);return t}function Ju(r){if(r.length===0)return 0n;let t=[...r].sort((n,o)=>n<o?-1:n>o?1:0),e=Math.floor(t.length/2);return t.length%2===0?(t[e-1]+t[e])/2n:t[e]}function on(r,t){let e=r.list(),n=e.length;if(n===0)return{n:0,confidence:0};if(n===1)return{n:1,confidence:.2};let o=1n<<256n,s=e.map(b=>Xu(b.coord)).sort((b,m)=>b<m?-1:b>m?1:0),i=[];for(let b=1;b<s.length;b++)i.push(s[b]-s[b-1]);i.push(s[0]+o-s[s.length-1]);let a=Ju(i),c=a>0n?a:o/BigInt(Math.max(1,n)),u=o/c,f=Math.max(1,Math.min(Number(u),1e9)),l=i[0],d=i[0];for(let b of i)b<l&&(l=b),b>d&&(d=b);let x=Math.min(1,n/Math.max(1,t*2)),h=d===0n?0:Number(l)/Number(d),v=Math.max(.05,Math.min(1,.5*x+.5*h));return{n:f,confidence:v}}var ke=class{capacity;refillPerSec;tokens;last;constructor(t,e){this.capacity=t,this.refillPerSec=e,this.tokens=t,this.last=Date.now()}tryTake(t=1){return this.refill(),this.tokens>=t?(this.tokens-=t,!0):!1}retryAfterMs(t=1){if(this.refill(),this.tokens>=t)return 0;let n=(t-this.tokens)/this.refillPerSec;return Math.ceil(n*1e3)}refill(){let t=Date.now(),e=(t-this.last)/1e3;e>0&&(this.tokens=Math.min(this.capacity,this.tokens+e*this.refillPerSec),this.last=t)}};var it=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},qt=class extends Error{static name="ValidationError";name="ValidationError"},lr=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},sn=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var an=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",u=2**(8*o)-1;for(;;){let f=this.readAtomically(()=>{let l=this.readChar();if(l===void 0)return;let d=Number.parseInt(l,t);if(!Number.isNaN(d))return d});if(f===void 0)break;if(s*=t,s+=f,s>u||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Qu=45,tl=15,cn=new an;function ts(r){if(!(r.length>tl))return cn.new(r).parseWith(()=>cn.readIPv4Addr())}function es(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Qu))return cn.new(r).parseWith(()=>cn.readIPv6Addr())}function fn(r){return!!ts(r)}function La(r){return!!es(r)}function ns(r){return t=>V(t,r)}function os(r){return t=>X(t,r)}function Ue(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function de(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(t)}function Pa(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=X(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=de(n);return Rt([e,o],e.length+o.length)}function Na(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=$t.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let o=de(n);return Rt([e,o],e.length+o.length)}function ss(r){let t=r.subarray(0,r.length-2),e=r.subarray(r.length-2),n=V(t,"base32"),o=Ue(e);return`${n}:${o}`}var is=function(r){r=r.toString().trim();let t=new Uint8Array(4);return r.split(/\./g).forEach((e,n)=>{let o=parseInt(e,10);if(isNaN(o)||o<0||o>255)throw new it("Invalid byte value in IP address");t[n]=o}),t},Ra=function(r){let t=0;r=r.toString().trim();let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=fn(e[n]),i;s&&(i=is(e[n]),e[n]=V(i.subarray(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,V(i.subarray(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){e[n]===""&&(e[n]="0");let s=parseInt(e[n],16);if(isNaN(s)||s<0||s>65535)throw new it("Invalid byte value in IP address");o[t++]=s>>8&255,o[t++]=s&255}return o},ka=function(r){if(r.byteLength!==4)throw new it("IPv4 address was incorrect length");let t=[];for(let e=0;e<r.byteLength;e++)t.push(r[e]);return t.join(".")},Ua=function(r){if(r.byteLength!==16)throw new it("IPv6 address was incorrect length");let t=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;t.push(i)}let e=t.join(":");try{let n=new URL(`http://[${e}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new it(`Invalid IPv6 address "${e}"`)}};function Ma(r){try{let t=new URL(`http://[${r}]`);return t.hostname.substring(1,t.hostname.length-1)}catch{throw new it(`Invalid IPv6 address "${r}"`)}}var rs=Object.values(Ge).map(r=>r.decoder),el=(function(){let r=rs[0].or(rs[1]);return rs.slice(2).forEach(t=>r=r.or(t)),r})();function Ka(r){return el.decode(r)}function Fa(r){return t=>r.encoder.encode(t)}function rl(r){if(parseInt(r).toString()!==r)throw new qt("Value must be an integer")}function nl(r){if(r<0)throw new qt("Value must be a positive integer, or zero")}function ol(r){return t=>{if(t>r)throw new qt(`Value must be smaller than or equal to ${r}`)}}function sl(...r){return t=>{for(let e of r)e(t)}}var hr=sl(rl,nl,ol(65535));var nt=-1,as=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(t){let e;if(typeof t=="string"?e=this.protocolsByName.get(t):e=this.protocolsByCode.get(t),e==null)throw new sn(`Protocol ${t} was unknown`);return e}addProtocol(t){this.protocolsByCode.set(t.code,t),this.protocolsByName.set(t.name,t),t.aliases?.forEach(e=>{this.protocolsByName.set(e,t)})}removeProtocol(t){let e=this.protocolsByCode.get(t);e!=null&&(this.protocolsByCode.delete(e.code),this.protocolsByName.delete(e.name),e.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},xt=new as,Rl=[{code:4,name:"ip4",size:32,valueToBytes:is,bytesToValue:ka,validate:r=>{if(!fn(r))throw new qt(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:de,bytesToValue:Ue,validate:hr},{code:273,name:"udp",size:16,valueToBytes:de,bytesToValue:Ue,validate:hr},{code:33,name:"dccp",size:16,valueToBytes:de,bytesToValue:Ue,validate:hr},{code:41,name:"ip6",size:128,valueToBytes:Ra,bytesToValue:Ua,stringToValue:Ma,validate:r=>{if(!La(r))throw new qt(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:nt},{code:43,name:"ipcidr",size:8,bytesToValue:ns("base10"),valueToBytes:os("base10")},{code:53,name:"dns",size:nt,resolvable:!0},{code:54,name:"dns4",size:nt,resolvable:!0},{code:55,name:"dns6",size:nt,resolvable:!0},{code:56,name:"dnsaddr",size:nt,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:de,bytesToValue:Ue,validate:hr},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:nt,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:nt,bytesToValue:ns("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?os("base58btc")(r):tt.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:ss,valueToBytes:Pa},{code:445,name:"onion3",size:296,bytesToValue:ss,valueToBytes:Na},{code:446,name:"garlic64",size:nt},{code:447,name:"garlic32",size:nt},{code:448,name:"tls"},{code:449,name:"sni",size:nt},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:nt,bytesToValue:Fa(Rn),valueToBytes:Ka},{code:480,name:"http"},{code:481,name:"http-path",size:nt,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:nt}];Rl.forEach(r=>{xt.addProtocol(r)});function Va(r){let t=[],e=0;for(;e<r.length;){let n=Do(r,e),o=xt.getProtocol(n),s=Ot(n),i=kl(o,r,e+s),a=0;i>0&&o.size===nt&&(a=Ot(i));let c=s+a+i,u={code:n,name:o.name,bytes:r.subarray(e,e+c)};if(i>0){let f=e+s+a,l=r.subarray(f,f+i);u.value=o.bytesToValue?.(l)??V(l)}t.push(u),e+=c}return t}function Ha(r){let t=0,e=[];for(let n of r){if(n.bytes==null){let o=xt.getProtocol(n.code),s=Ot(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??X(n.value),a=i.byteLength,o.size===nt&&(c=Ot(a)));let u=new Uint8Array(s+c+a),f=0;or(n.code,u,f),f+=s,i!=null&&(o.size===nt&&(or(a,u,f),f+=c),u.set(i,f)),n.bytes=u}e.push(n.bytes),t+=n.bytes.byteLength}return Rt(e,t)}function qa(r){if(r.charAt(0)!=="/")throw new it('String multiaddr must start with "/"');let t=[],e="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(e==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=xt.getProtocol(o);if(e==="protocol"){if(c.size==null||c.size===0){t.push({code:c.code,name:c.name}),n="",o="",e="protocol";continue}else if(a)throw new it(`Component ${o} was missing value`);e="value"}else if(e==="value"){let u={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new it(`Component ${o} was missing value`);u.value=c.stringToValue?.(n)??n}t.push(u),n="",o="",e="protocol"}}}if(o!==""&&n!=="")throw new it("Incomplete multiaddr");return t}function za(r){return`/${r.flatMap(t=>{if(t.value==null)return t.name;let e=xt.getProtocol(t.code);if(e==null)throw new it(`Unknown protocol code ${t.code}`);return[t.name,e.valueToString?.(t.value)??t.value]}).join("/")}`}function kl(r,t,e){return r.size==null||r.size===0?0:r.size>0?r.size/8:Do(t,e)}var Ul=Symbol.for("nodejs.util.inspect.custom"),ms=Symbol.for("@multiformats/multiaddr"),Ml=[53,54,55,56],ps=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}};function Kl(r){if(r==null&&(r="/"),$a(r))return r.getComponents();if(r instanceof Uint8Array)return Va(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),qa(r);if(Array.isArray(r))return r;throw new it("Must be a string, Uint8Array, Component[], or another Multiaddr")}var pn=class r{[ms]=!0;#t;#e;#r;constructor(t="/",e={}){this.#t=Kl(t),e.validate!==!1&&Fl(this)}get bytes(){return this.#r==null&&(this.#r=Ha(this.#t)),this.#r}toString(){return this.#e==null&&(this.#e=za(this.#t)),this.#e}toJSON(){return this.toString()}toOptions(){let t,e,n,o,s="";for(let{code:a,name:c,value:u}of this.#t)a===42&&(s=`%${u??""}`),Ml.includes(a)&&(e="tcp",o=443,n=`${u??""}${s}`,t=a===55?6:4),(a===6||a===273)&&(e=c==="tcp"?"tcp":"udp",o=parseInt(u??"")),(a===4||a===41)&&(e="tcp",n=`${u??""}${s}`,t=a===41?6:4);if(t==null||e==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:o}}getComponents(){return[...this.#t]}protos(){return this.#t.map(({code:t,value:e})=>{let n=xt.getProtocol(t);return{code:t,size:n.size??0,name:n.name,resolvable:!!n.resolvable,path:!!n.path}})}protoCodes(){return this.#t.map(({code:t})=>t)}protoNames(){return this.#t.map(({name:t})=>t)}tuples(){return this.#t.map(({code:t,value:e})=>{if(e==null)return[t];let n=xt.getProtocol(t),o=[t];return e!=null&&o.push(n.valueToBytes?.(e)??X(e)),o})}stringTuples(){return this.#t.map(({code:t,value:e})=>e==null?[t]:[t,e])}encapsulate(t){let e=new r(t);return new r([...this.#t,...e.getComponents()],{validate:!1})}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new lr(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o),{validate:!1})}decapsulateCode(t){let e;for(let n=this.#t.length-1;n>-1;n--)if(this.#t[n].code===t){e=n;break}return new r(this.#t.slice(0,e),{validate:!1})}getPeerId(){try{let t=[];this.#t.forEach(({code:n,value:o})=>{n===421&&t.push([n,o]),n===290&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?V(W.decode(`z${n}`),"base58btc"):V(tt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let t of this.#t)if(xt.getProtocol(t.code).path)return t.value??null;return null}equals(t){return mt(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=Ga.get(e.name);if(n==null)throw new ps(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>pr(s))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(){return!(this.#t.length!==2||this.#t[0].code!==4&&this.#t[0].code!==41||this.#t[1].code!==6&&this.#t[1].code!==273)}[Ul](){return`Multiaddr(${this.toString()})`}};function Fl(r){r.getComponents().forEach(t=>{let e=xt.getProtocol(t.code);t.value!=null&&e.validate?.(t.value)})}var Yy=parseInt("0xFFFF",16),Wy=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);var Ga=new Map;function $a(r){return!!r?.[ms]}function pr(r){return new pn(r)}function mn(r,t){let e=Math.max(r.length,t.length),n=new Uint8Array(e);for(let o=0;o<e;o++){let s=r[r.length-1-o]??0,i=t[t.length-1-o]??0;n[e-1-o]=s^i}return n}function ys(r,t){let e=Math.max(r.length,t.length);for(let n=0;n<e;n++){let o=r[n]??0,s=t[n]??0;if(o<s)return!0;if(o>s)return!1}return!1}function Ya(r){for(let t=0;t<r.length;t++)if(r[t]!==0)return t;return Number.POSITIVE_INFINITY}function Gl(r,t){if(r.length!==t.length)return!1;for(let e=0;e<r.length;e++)if(r[e]!==t[e])return!1;return!0}function Wa(r,t,e,n){return ys(t,n)?!0:ys(n,t)?!1:r<e}function yn(r,t,e,n,o,s=1){let i,a=[];for(let f of e){let l=r.getById(f);if(!l)continue;let d=mn(l.coord,t),x=n(f),h=(x?1:0)+.25*o(f);a.push({id:f,dist:d,connected:x,score:h}),(!i||Wa(f,d,i.id,i.dist))&&(i={id:f,dist:d})}if(!i)return;let c=Ya(i.dist),u;for(let f of a){if(!f.connected)continue;if(Ya(f.dist)<=c+s){if(!u){u={id:f.id,dist:f.dist,score:f.score};continue}Wa(f.id,f.dist,u.id,u.dist)?u={id:f.id,dist:f.dist,score:f.score}:Gl(f.dist,u.dist)&&(f.score>u.score||f.score===u.score&&f.id<u.id)&&(u={id:f.id,dist:f.dist,score:f.score})}}return u?.id??i.id}function Xa(r=12,t=.08,e=.03,n=.6,o=.7,s=1.8,i=1e-6){let a=[];for(let c=0;c<r;c++)a.push((c+.5)/r);return{centers:a,occupancy:new Float64Array(r),alpha:e,sigma:t,beta:n,sMin:o,sMax:s,eps:i}}function gn(r,t){let e=mn(r,t),n=0;for(let s=0;s<e.length;s++){let i=e[s]??0;if(i===0){n+=8;continue}let a=7-Math.floor(Math.log2(i));n+=a;break}return 1-Math.min(256,n)/256}function Ja(r,t){let e=r/Math.max(1e-9,t);return Math.exp(-.5*e*e)}function gs(r,t){for(let e=0;e<r.centers.length;e++){let n=Ja(Math.abs(t-r.centers[e]),r.sigma);r.occupancy[e]=(1-r.alpha)*r.occupancy[e]+r.alpha*n}}function bs(r,t){let e=0,n=0;for(let i=0;i<r.centers.length;i++){let a=Ja(Math.abs(t-r.centers[i]),r.sigma);e+=r.occupancy[i]*a,n+=1*a}let o=(n+r.eps)/(e+r.eps),s=Math.pow(o,r.beta);return Math.max(r.sMin,Math.min(r.sMax,s))}function $l(r,t){let e=Math.max(0,t-r.lastAccess),o=Math.log(2)/Math.max(1,6e4);return Math.exp(-o*e)}function jl(r){return Math.log1p(r.accessCount)/5}function Zl(r){let t=r.successCount+r.failureCount,e=t>0?r.successCount/t:.5,n=r.avgLatencyMs>0?Math.min(1,r.avgLatencyMs/1e3):.5,o=.5*e+.5*(1-n);return Math.max(0,o)}function xs(r,t){return .4*$l(r,t)+.2*jl(r)+.4*Zl(r)}function ws(r,t){return{...r,...t}}function Qa(r,t,e,n=Date.now()){gs(e,t);let o=xs(r,n),s=bs(e,t),i=o*s;return ws(r,{lastAccess:n,relevance:i,accessCount:r.accessCount+1})}function tc(r,t,e,n,o=Date.now()){gs(n,e);let s=.2,i=r.avgLatencyMs>0?(1-s)*r.avgLatencyMs+s*t:t,a=xs({...r,avgLatencyMs:i,successCount:r.successCount+1},o),c=bs(n,e),u=a*c;return ws(r,{lastAccess:o,relevance:u,successCount:r.successCount+1,avgLatencyMs:i})}function ec(r,t,e,n=Date.now()){gs(e,t);let o=xs({...r,failureCount:r.failureCount+1},n)*.7,s=bs(e,t),i=o*s;return ws(r,{lastAccess:n,relevance:i,failureCount:r.failureCount+1})}var It=ee("service:fret"),re=class{mode="passive";store=new Er;cfg;node;stabilizing=!1;inflightAct=0;bucketNeighbors;bucketMaybeAct;bucketDiscovery;announcedIds=new Map;postBootstrapAnnounced=!1;sparsity=Xa();cachedSelfCoord=null;preconnectRunning=!1;protocols;metadata;diag={peersDiscovered:0,snapshotsFetched:0,announcementsSent:0,pingsSent:0,pingsOk:0,pingsFail:0,maybeActForwarded:0,evictions:0};networkObservations=[];maxObservations=100;observationWindowMs=3e5;constructor(t,e){this.node=t,this.cfg={k:e?.k??15,m:e?.m??Math.ceil((e?.k??15)/2),capacity:e?.capacity??2048,profile:e?.profile??"core",bootstraps:e?.bootstraps??[],networkName:e?.networkName??"default"},this.protocols=$s(this.cfg.networkName),this.bucketDiscovery=new ke(this.cfg.profile==="core"?50:10,this.cfg.profile==="core"?25:3),this.bucketNeighbors=new ke(this.cfg.profile==="core"?20:8,this.cfg.profile==="core"?10:4),this.bucketMaybeAct=new ke(this.cfg.profile==="core"?32:8,this.cfg.profile==="core"?16:4)}getDiagnostics(){return this.diag}async selfCoord(){return this.cachedSelfCoord?this.cachedSelfCoord:(this.cachedSelfCoord=await J(this.node.peerId),this.cachedSelfCoord)}enforceCapacity(){let t=Math.max(1,this.cfg.capacity);if(this.store.size()<=t)return;let e=this.cachedSelfCoord;if(!e)return;let n=this.store.protectedIdsAround(e,Math.max(2,this.cfg.m)),o=this.store.list();o.sort((s,i)=>s.relevance-i.relevance);for(let s of o){if(this.store.size()<=t)break;n.has(s.id)||this.store.remove(s.id)}}async applyTouch(t,e){let n=this.store.getById(t)??this.store.upsert(t,e),o=gn(await this.selfCoord(),e),s=Qa(n,o,this.sparsity);this.store.update(t,{lastAccess:s.lastAccess,relevance:s.relevance,accessCount:s.accessCount})}async applySuccess(t,e,n){let o=this.store.getById(t)??this.store.upsert(t,e),s=gn(await this.selfCoord(),e),i=tc(o,n,s,this.sparsity);this.store.update(t,{lastAccess:i.lastAccess,relevance:i.relevance,successCount:i.successCount,avgLatencyMs:i.avgLatencyMs})}async applyFailure(t,e){let n=this.store.getById(t)??this.store.upsert(t,e),o=gn(await this.selfCoord(),e),s=ec(n,o,this.sparsity);this.store.update(t,{lastAccess:s.lastAccess,relevance:s.relevance,failureCount:s.failureCount})}async start(){await this.seedFromPeerStore(),this.registerRpcHandlers(),await this.proactiveAnnounceOnStart(),this.startStabilizationLoop(),this.mode==="active"&&this.preconnectNeighbors(),this.node.addEventListener("peer:connect",async t=>{if(!this.postBootstrapAnnounced){this.postBootstrapAnnounced=!0;try{await this.announceNeighborsBounded(8)}catch(e){It("postBootstrap announce failed - %o",e)}}}),this.node.addEventListener("peer:connect",async t=>{try{let e=t?.detail?.id?.toString?.();if(!e)return;let n=this.store.getById(e)?.coord??await J(H(e));this.store.setState(e,"connected"),await this.applyTouch(e,n)}catch(e){It("peer:connect handler failed - %o",e)}}),this.node.addEventListener("peer:disconnect",async t=>{try{let e=t?.detail?.id?.toString?.();if(!e)return;let n=this.store.getById(e)?.coord??await J(H(e));this.store.setState(e,"disconnected"),await this.applyFailure(e,n)}catch(e){It("peer:disconnect handler failed - %o",e)}})}async stop(){this.stabilizing=!1;try{await this.sendLeaveToNeighbors()}catch(t){console.warn("sendLeaveToNeighbors failed",t)}}setMode(t){this.mode=t,t==="active"&&!this.preconnectRunning&&this.startActivePreconnectLoop()}async ready(){}registerRpcHandlers(){va(this.node,async()=>this.handleNeighborsRequest(),(t,e)=>{this.mergeAnnounceSnapshot(t,e)},this.protocols),Ia(this.node,async t=>this.handleMaybeAct(t),this.protocols.PROTOCOL_MAYBE_ACT),_a(this.node,async t=>this.handleLeave(t.from),this.protocols.PROTOCOL_LEAVE),Ta(this.node,this.protocols.PROTOCOL_PING,()=>this.getNetworkSizeEstimate())}async handleNeighborsRequest(){return this.bucketNeighbors.tryTake()?await this.snapshot():{v:1,from:this.node.peerId.toString(),timestamp:Date.now(),successors:[],predecessors:[],sig:""}}async handleMaybeAct(t){if(t.ttl<=0)return await this.nearAnchorOnly(t);if(t.activity&&t.activity.length>128*1024)return await this.nearAnchorOnly(t);if(!this.bucketMaybeAct.tryTake())return await this.nearAnchorOnly(t);let e=this.cfg.profile==="core"?16:4;if(this.inflightAct>=e)return this.nearAnchorOnly(t);this.inflightAct++;try{return await this.routeAct(t)}catch(n){return console.error("routeAct failed:",n),await this.nearAnchorOnly(t)}finally{this.inflightAct--}}isConnected(t){try{return this.node.getConnections(H(t)).length>0}catch{return!1}}hasAddresses(t){try{let e=this.node.getMultiaddrsForPeer?.(H(t))??[];return Array.isArray(e)&&e.length>0}catch{return!1}}async proactiveAnnounceOnStart(){try{await this.announceNeighborsBounded(8)}catch(t){console.warn("proactiveAnnounceOnStart failed",t)}}async announceNeighborsBounded(t){let e=await J(this.node.peerId),n=this.node.peerId.toString(),o=Array.from(new Set([...this.getNeighbors(e,"right",this.cfg.m),...this.getNeighbors(e,"left",this.cfg.m)])).filter(i=>i!==n).slice(0,t),s=await this.snapshot();for(let i of o)if(this.isConnected(i)||this.hasAddresses(i))try{await Jo(this.node,i,s,this.protocols.PROTOCOL_NEIGHBORS_ANNOUNCE),this.diag.announcementsSent++}catch(a){console.warn("announce failed",i,a)}}async preconnectNeighbors(){try{let t=await J(this.node.peerId),e=this.node.peerId.toString(),n=Array.from(new Set([...this.getNeighbors(t,"right",Math.min(6,this.cfg.m)),...this.getNeighbors(t,"left",Math.min(6,this.cfg.m))])).filter(o=>o!==e);for(let o of n)if(this.isConnected(o)||this.hasAddresses(o))try{await ur(this.node,o,this.protocols.PROTOCOL_PING),this.diag.pingsSent++}catch(s){It("preconnectNeighbors ping failed for %s - %o",o,s)}}catch(t){It("preconnectNeighbors outer failed - %o",t)}}startActivePreconnectLoop(){if(this.preconnectRunning)return;this.preconnectRunning=!0;let t=async()=>{if(!this.preconnectRunning||this.mode!=="active"){this.preconnectRunning=!1;return}try{let e=await this.selfCoord(),n=this.node.peerId.toString(),o=this.cfg.profile==="core"?6:3,s=Array.from(new Set([...this.getNeighbors(e,"right",Math.min(12,this.cfg.m)),...this.getNeighbors(e,"left",Math.min(12,this.cfg.m))])).filter(i=>i!==n).slice(0,o);for(let i of s)if(this.isConnected(i)||this.hasAddresses(i))try{await ur(this.node,i,this.protocols.PROTOCOL_PING),this.diag.pingsSent++}catch(a){It("active preconnect ping failed for %s - %o",i,a)}}catch(e){It("active preconnect tick failed - %o",e)}setTimeout(t,1e3)};t()}async sendLeaveToNeighbors(){try{let t=await J(this.node.peerId),e=this.node.peerId.toString(),n=Array.from(new Set([...this.getNeighbors(t,"right",this.cfg.m),...this.getNeighbors(t,"left",this.cfg.m)])).filter(s=>s!==e).slice(0,8),o={v:1,from:this.node.peerId.toString(),timestamp:Date.now()};for(let s of n)try{await Da(this.node,s,o,this.protocols.PROTOCOL_LEAVE)}catch(i){It("sendLeave failed for %s - %o",s,i)}}catch(t){It("sendLeaveToNeighbors outer failed - %o",t)}}async handleLeave(t){try{let e=null,n=this.store.getById(t);if(n)e=n.coord;else try{e=await J(H(t))}catch(u){console.warn("handleLeave: could not hash departing peer id",t,u)}if(this.store.remove(t),e)try{await this.applyFailure(t,e)}catch{}if(!e)return;let o=Array.from(new Set([...this.store.neighborsRight(e,this.cfg.m),...this.store.neighborsLeft(e,this.cfg.m)])),s=this.expandCohort(o,e,Math.max(2,Math.ceil(this.cfg.m/2))),i=new Set(o),a=s.filter(u=>!i.has(u)),c=a.slice(0,Math.min(a.length,6));for(let u of c)try{if(await ur(this.node,u,this.protocols.PROTOCOL_PING),!this.isConnected(u)){let f=await this.snapshot();await Jo(this.node,u,f,this.protocols.PROTOCOL_NEIGHBORS_ANNOUNCE)}}catch(f){console.warn("warm/announce failed for",u,f)}await this.mergeNeighborSnapshots(c.slice(0,4))}catch(e){console.error("handleLeave failed for",t,e)}}async mergeAnnounceSnapshot(t,e){try{let n=H(t),o=await J(n),s=[];this.store.getById(t)||s.push(t),this.store.upsert(t,o),await this.applyTouch(t,o),e.metadata&&this.store.update(t,{metadata:e.metadata});for(let i of[...e.successors??[],...e.predecessors??[]])try{let a=await J(H(i));this.store.getById(i)||s.push(i),this.store.upsert(i,a),await this.applyTouch(i,a)}catch(a){console.warn("mergeAnnounceSnapshot: failed for",i,a)}for(let i of e.sample??[])try{let a=X(i.coord,"base64url");this.store.getById(i.id)||s.push(i.id),this.store.upsert(i.id,a),await this.applyTouch(i.id,a)}catch(a){It("mergeAnnounceSnapshot sample upsert failed for %s - %o",i.id,a)}this.enforceCapacity(),this.emitDiscovered(s)}catch(n){console.warn("mergeAnnounceSnapshot failed for",t,n)}}async seedFromPeerStore(){try{let t=this.node.peerStore?.getPeers?.()??[],e=[];for(let n of t)try{let o=await J(n.id),s=n.id.toString();this.store.getById(s)||e.push(s),this.store.upsert(s,o)}catch(o){console.warn("failed to add peer from peerStore",n?.id?.toString?.(),o)}try{let n=await J(this.node.peerId),o=this.node.peerId.toString();this.store.getById(o)||e.push(o),this.store.upsert(o,n)}catch(n){console.error("failed to add self to store",n)}this.enforceCapacity(),this.emitDiscovered(e)}catch(t){console.error("seedFromPeerStore failed:",t)}}startStabilizationLoop(){if(this.stabilizing)return;this.stabilizing=!0;let t=async()=>{if(this.stabilizing)try{await this.seedFromPeerStore(),await this.seedFromBootstraps(),await this.stabilizeOnce()}catch(e){console.error("stabilize tick failed:",e)}finally{let e=this.mode==="active"?300:1500;setTimeout(t,e)}};t()}async seedFromBootstraps(){if(!this.cfg.bootstraps||this.cfg.bootstraps.length===0)return;let t=[];for(let e of this.cfg.bootstraps.slice(0,8))try{let n=e;if(e.startsWith("/"))try{let a=pr(e).getPeerId();a&&(n=a)}catch{}let o=H(n),s=await J(o);this.store.getById(n)||t.push(n),this.store.upsert(n,s),await this.applyTouch(n,s)}catch(n){console.warn("seedFromBootstraps failed for",e,n)}this.enforceCapacity(),this.emitDiscovered(t)}async stabilizeOnce(){let t=await J(this.node.peerId),e=this.node.peerId.toString(),o=this.getNeighbors(t,"both",Math.max(2,this.cfg.m)).filter(s=>s!==e&&(this.isConnected(s)||this.hasAddresses(s)));await this.probeNeighborsLatency(o.slice(0,4)),await this.mergeNeighborSnapshots(o.slice(0,4))}async probeNeighborsLatency(t){for(let e of t)try{let n=await ur(this.node,e,this.protocols.PROTOCOL_PING);if(this.diag.pingsSent++,n.ok){let o=this.store.getById(e)?.coord??await J(H(e));await this.applySuccess(e,o,n.rttMs),this.diag.pingsOk++}else{let o=this.store.getById(e)?.coord??await J(H(e));await this.applyFailure(e,o),this.diag.pingsFail++}}catch{try{let o=this.store.getById(e)?.coord??await J(H(e));await this.applyFailure(e,o),this.diag.pingsFail++}catch{}}}async mergeNeighborSnapshots(t){let e=[];for(let n of t)try{let o=await Sa(this.node,n,this.protocols.PROTOCOL_NEIGHBORS);this.diag.snapshotsFetched++;let s=this.cfg.profile==="core"?16:8,i=this.cfg.profile==="core"?16:8,a=(o.successors??[]).slice(0,s),c=(o.predecessors??[]).slice(0,i);for(let f of[...a,...c])try{let l=await J(H(f));this.store.getById(f)||e.push(f),this.store.upsert(f,l),await this.applyTouch(f,l)}catch(l){console.warn("failed to merge neighbor",f,l)}let u=this.cfg.profile==="core"?8:6;for(let f of(o.sample??[]).slice(0,u))try{let l=X(f.coord,"base64url");this.store.getById(f.id)||e.push(f.id),this.store.upsert(f.id,l),await this.applyTouch(f.id,l)}catch(l){It("mergeNeighborSnapshots sample upsert failed for %s - %o",f.id,l)}}catch(o){console.warn("fetchNeighbors failed for",n,o)}this.enforceCapacity(),this.emitDiscovered(e)}async snapshot(){let t=await J(this.node.peerId),{n:e,confidence:n}=on(this.store,this.cfg.m),o=this.cfg.profile==="core"?12:6,s=this.cfg.profile==="core"?12:6,i=this.cfg.profile==="core"?8:6,a=this.getNeighbors(t,"right",this.cfg.m),c=this.getNeighbors(t,"left",this.cfg.m),u=a.slice(0,o),f=c.slice(0,s),l=Array.from(new Set([...u.slice(0,4),...f.slice(0,4)])).slice(0,i),d=await Promise.all(l.map(async x=>{let h=this.store.getById(x);return h?{id:x,coord:Gs(h.coord),relevance:h.relevance}:{id:x,coord:"",relevance:0}}));return{v:1,from:this.node.peerId.toString(),timestamp:Date.now(),successors:u,predecessors:f,sample:d,size_estimate:e,confidence:n,sig:"",metadata:this.metadata}}neighborDistance(t,e,n){let o=new Set,s=Math.max(1,n),a=this.assembleCohort(e,s,o).findIndex(c=>c===t);return a>=0?a:Number.POSITIVE_INFINITY}getNeighbors(t,e,n){let o=[];return(e==="right"||e==="both")&&o.push(...this.store.neighborsRight(t,n)),(e==="left"||e==="both")&&o.push(...this.store.neighborsLeft(t,n)),Array.from(new Set(o)).slice(0,n)}nextSuccessor(t,e){let n=e.findIndex(o=>o.id===t.id);return e[(n+1)%e.length]}nextPredecessor(t,e){let n=e.findIndex(o=>o.id===t.id);return e[(n-1+e.length)%e.length]}assembleCohort(t,e,n){let o=[],s=n??new Set,i=this.store.neighborsRight(t,e*2),a=this.store.neighborsLeft(t,e*2),c=0,u=0;for(;o.length<e&&(c<i.length||u<a.length);)if(o.length%2===0){let f=i[c++];f&&!s.has(f)&&o.push(f)}else{let f=a[u++];f&&!s.has(f)&&o.push(f)}return Array.from(new Set(o)).slice(0,e)}expandCohort(t,e,n,o){let s=new Set(t),i=this.assembleCohort(e,t.length+n,o);for(let a of i)s.add(a);return Array.from(s)}async nearAnchorOnly(t){let e=X(t.key,"base64url"),n=await $e(e),o=this.getNeighbors(n,"right",this.cfg.m),s=this.getNeighbors(n,"left",this.cfg.m);return{v:1,anchors:this.pickAnchors([...o.slice(0,3),...s.slice(0,3)]),cohort_hint:Array.from(new Set([...o.slice(0,2),...s.slice(0,2)])),estimated_cluster_size:this.cfg.k,confidence:.5}}emitDiscovered(t){if(t.length===0)return;let e=Date.now(),n=this.cfg.profile==="core"?10*6e4:30*6e4,o=this.node,s=0;for(let i of Array.from(new Set(t)))if(!((this.announcedIds.get(i)??0)>e)){if(!this.bucketDiscovery.tryTake())break;try{let c=H(i);o.dispatchEvent?.(new CustomEvent("peer:discovery",{detail:{id:c,multiaddrs:[]}})),this.announcedIds.set(i,e+n),s++}catch(c){console.warn("emitDiscovered failed for",i,c)}}if(s>0&&this.announcedIds.size>4096)for(let[i,a]of this.announcedIds)a<=e&&this.announcedIds.delete(i)}pickAnchors(t){let e=Array.from(new Set(t));if(e.length===0)return[];let n=c=>.5,o=new Uint8Array(32),s=yn(this.store,o,e,c=>this.isConnected(c),n),i=e.filter(c=>c!==s),a=yn(this.store,o,i,c=>this.isConnected(c),n);return[s,a].filter(c=>!!c)}async routeAct(t){let e=X(t.key,"base64url"),n=await $e(e),o=this.node.peerId.toString();if(this.neighborDistance(o,n,2)>1&&t.ttl>0){let l=new Set([...t.breadcrumbs??[],o]),d=this.assembleCohort(n,Math.max(4,this.cfg.m)).filter(v=>!l.has(v)),x=v=>.5,h=yn(this.store,n,d,v=>this.isConnected(v),x);if(h){let v={...t,ttl:t.ttl-1,breadcrumbs:[...t.breadcrumbs??[],o]};try{return await Ca(this.node,h,v,this.protocols.PROTOCOL_MAYBE_ACT)}catch(b){console.warn("forward maybeAct failed to",h,b)}}}let{n:i,confidence:a}=on(this.store,this.cfg.m),c=this.getNeighbors(n,"right",this.cfg.m),u=this.getNeighbors(n,"left",this.cfg.m);return{v:1,anchors:this.pickAnchors([...c.slice(0,4),...u.slice(0,4)]),cohort_hint:Array.from(new Set([...c.slice(0,4),...u.slice(0,4)])),estimated_cluster_size:Math.max(this.cfg.k,i),confidence:a}}report(t){}reportNetworkSize(t,e,n="external"){let o=Date.now();this.networkObservations.push({estimate:t,confidence:e,timestamp:o,source:n});let s=o-this.observationWindowMs;this.networkObservations=this.networkObservations.filter(i=>i.timestamp>s),this.networkObservations.length>this.maxObservations&&(this.networkObservations=this.networkObservations.slice(-this.maxObservations))}getNetworkSizeEstimate(){let t=on(this.store,this.cfg.m),e=Date.now(),n=[{estimate:t.n,confidence:t.confidence,timestamp:e,source:"fret"},...this.networkObservations];if(n.length===0)return{size_estimate:0,confidence:0,sources:0};let o=0,s=0,i=0;for(let u of n){let f=e-u.timestamp,l=Math.exp(-f/(this.observationWindowMs/3)),d=l*u.confidence;s+=u.estimate*d,i+=u.confidence*l,o+=d}if(o===0)return{size_estimate:0,confidence:0,sources:0};let a=Math.round(s/o),c=i/n.length;return{size_estimate:a,confidence:Math.min(1,c),sources:n.length}}getNetworkChurn(){if(this.networkObservations.length<2)return 0;let t=Date.now(),e=this.observationWindowMs/2,n=t-e,o=this.networkObservations.filter(u=>u.timestamp>n),s=this.networkObservations.filter(u=>u.timestamp<=n);if(o.length===0||s.length===0)return 0;let i=o.reduce((u,f)=>u+f.estimate,0)/o.length,a=s.reduce((u,f)=>u+f.estimate,0)/s.length;return(i-a)/e*6e4}detectPartition(){if(this.networkObservations.length<10)return!1;let t=this.getNetworkSizeEstimate();if(t.confidence<.3)return!1;let e=Date.now()-3e4,n=this.networkObservations.filter(c=>c.timestamp<e);if(n.length<3)return!1;let o=n.slice(-5).reduce((c,u)=>c+u.estimate,0)/Math.min(5,n.length);if(t.size_estimate/o<.5)return!0;let i=Math.abs(this.getNetworkChurn()),a=t.size_estimate*.1;return i>a}setMetadata(t){this.metadata=t}getMetadata(t){return this.store.getById(t)?.metadata}listPeers(){return this.store.list().map(t=>({id:t.id,metadata:t.metadata}))}};var Yl=ee("service:discovery");function bn(r,t){let e=r;for(let n of t.list())try{let o=H(n.id);e.dispatchEvent?.(new CustomEvent("peer:discovery",{detail:{id:o,multiaddrs:[]}}))}catch(o){Yl("seedDiscovery failed for %s - %o",n.id,o)}}var mr=class{components;cfg;inner=null;nodeRef=null;constructor(t,e){this.components=t,this.cfg=e}get[Symbol.toStringTag](){return"@optimystic/fret"}setLibp2p(t){this.nodeRef=t}ensure(){if(!this.inner){if(!this.nodeRef)throw new Error("Libp2pFretService: libp2p node not injected");this.inner=new re(this.nodeRef,this.cfg)}return this.inner}async start(){if(this.ensure(),!this.nodeRef)throw new Error("Libp2pFretService.start: libp2p node not injected");bn(this.nodeRef,this.inner?.store??{}),await this.ensure().start()}async stop(){await this.inner?.stop()}async routeAct(t){return await this.ensure().routeAct(t)}getNeighborsForKey(t,e,n){return this.ensure().getNeighbors(t,e,n)}assembleCohortForKey(t,e){return this.ensure().assembleCohort(t,e)}getDiagnostics(){return this.ensure().getDiagnostics?.()}neighborDistance(t,e,n){return this.ensure().neighborDistance(t,e,n)}getNeighbors(t,e,n){return this.ensure().getNeighbors(t,e,n)}assembleCohort(t,e,n){return this.ensure().assembleCohort(t,e,n)}expandCohort(t,e,n,o){return this.ensure().expandCohort(t,e,n,o)}async ready(){await this.ensure().ready()}setMode(t){this.ensure().setMode(t)}setMetadata(t){this.ensure().setMetadata(t)}report(t){this.ensure().report(t)}getMetadata(t){return this.ensure().getMetadata(t)}listPeers(){return this.ensure().listPeers()}};function rc(r){return t=>new mr(t,r)}function Wl(r,t){return new re(r,t)}return fc(Xl);})();
3
+ /*! Bundled license information:
4
+
5
+ @noble/hashes/utils.js:
6
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
7
+
8
+ @noble/curves/utils.js:
9
+ @noble/curves/abstract/modular.js:
10
+ @noble/curves/abstract/curve.js:
11
+ @noble/curves/abstract/edwards.js:
12
+ @noble/curves/ed25519.js:
13
+ @noble/curves/abstract/weierstrass.js:
14
+ @noble/curves/secp256k1.js:
15
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
16
+ */
17
+ return P2PFret}));
18
+ //# sourceMappingURL=index.min.js.map